query
stringlengths
8
6.75k
document
stringlengths
9
1.89M
negatives
listlengths
19
19
metadata
dict
Retrieves the bypass state of the DSP unit. If a unit is bypassed, it will still process its inputs, unlike "DSP.SetActive" (when set to false) which causes inputs to stop processing as well.
func (d *DSP) Bypass() (bool, error) { var bypass C.FMOD_BOOL res := C.FMOD_DSP_GetBypass(d.cptr, &bypass) return setBool(bypass), errs[res] }
[ "func (d *DSP) SetBypass(bypass bool) error {\n\tres := C.FMOD_DSP_SetBypass(d.cptr, getBool(bypass))\n\treturn errs[res]\n}", "func GetBypass(conn io.ReadWriter) (bypass Bypass, err error) {\n\n\tresp, err := getQuery(getBypass, conn)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn *resp.(*Bypass), err\n}", "func (o *FullHealthCheck) GetPassing() bool {\n\tif o == nil {\n\t\tvar ret bool\n\t\treturn ret\n\t}\n\n\treturn o.Passing\n}", "func (m *AndroidGeneralDeviceConfiguration) GetPowerOffBlocked()(*bool) {\n val, err := m.GetBackingStore().Get(\"powerOffBlocked\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func (d *Device) Off() {\n\turl := fmt.Sprintf(\"%s?token=%s\", d.AppServerURL, token)\n\n\tpassThroughRequest := PassThroughRequest{\n\t\tMethod: \"passthrough\",\n\t\tParams: PassThroughRequestParams{\n\t\t\tDeviceID: d.DeviceID,\n\t\t\tRequestData: `{\"system\":{\"set_relay_state\":{\"state\":0}}}`,\n\t\t},\n\t}\n\n\tpayload, _ := json.Marshal(passThroughRequest)\n\n\treq, _ := http.NewRequest(\"POST\", url, bytes.NewReader(payload))\n\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\n\tres, _ := http.DefaultClient.Do(req)\n\n\tdefer res.Body.Close()\n}", "func (r *DeviceManagementScriptDeviceStateRequest) Get(ctx context.Context) (resObj *DeviceManagementScriptDeviceState, err error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\terr = r.JSONRequest(ctx, \"GET\", query, nil, &resObj)\n\treturn\n}", "func (d *DSP) Idle() (bool, error) {\n\tvar idle C.FMOD_BOOL\n\tres := C.FMOD_DSP_GetIdle(d.cptr, &idle)\n\treturn setBool(idle), errs[res]\n}", "func (s *Flee) Get() *SteeringOutput {\n\tsteering := NewSteeringOutput()\n\t// Get the direction to the target\n\tsteering.Linear = s.entity.Data.Position.Clone().Sub(s.target.Data.Position)\n\t// Go full speed ahead\n\tsteering.Linear.Normalize().Scale(s.entity.Data.MaxAcceleration)\n\treturn steering\n}", "func (m *TenantSetupInfo) GetSkipSetup()(*bool) {\n val, err := m.GetBackingStore().Get(\"skipSetup\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func (m *DeviceComplianceScriptDeviceState) GetDetectionState()(*RunState) {\n val, err := m.GetBackingStore().Get(\"detectionState\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*RunState)\n }\n return nil\n}", "func (p *PhoneConnectionWebrtc) GetStun() (value bool) {\n\treturn p.Flags.Has(1)\n}", "func (o *SyntheticsAPITestResultShortResult) GetPassed() bool {\n\tif o == nil || o.Passed == nil {\n\t\tvar ret bool\n\t\treturn ret\n\t}\n\treturn *o.Passed\n}", "func (unitImpl *UnitImpl) Shield() int64 {\n\treturn unitImpl.shieldImpl\n}", "func (m *DirectRoutingLogRow) GetMediaBypassEnabled()(*bool) {\n return m.mediaBypassEnabled\n}", "func (r *DeviceHealthScriptDeviceStateRequest) Get(ctx context.Context) (resObj *DeviceHealthScriptDeviceState, err error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\terr = r.JSONRequest(ctx, \"GET\", query, nil, &resObj)\n\treturn\n}", "func DUTActive(ctx context.Context, servoInst *servo.Servo) (bool, error) {\n\tstate, err := servoInst.GetECSystemPowerState(ctx)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"failed to get ec_system_power_state\")\n\t}\n\ttesting.ContextLog(ctx, \"state: \", state)\n\tif state == \"S0\" {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}", "func (m *WindowsMalwareInformation) GetDeviceMalwareStates()([]MalwareStateForWindowsDeviceable) {\n val, err := m.GetBackingStore().Get(\"deviceMalwareStates\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]MalwareStateForWindowsDeviceable)\n }\n return nil\n}", "func (m *AndroidWorkProfileGeneralDeviceConfiguration) GetPasswordBlockFingerprintUnlock()(*bool) {\n return m.passwordBlockFingerprintUnlock\n}", "func (d *DspConnection) Input() (DSP, error) {\n\tvar input DSP\n\tres := C.FMOD_DSPConnection_GetInput(d.cptr, &input.cptr)\n\treturn input, errs[res]\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the wet/dry scale of a DSP effect, through the 'wet' mix, which is the postprocessed signal and the 'dry' mix which is the preprocessed signal. The dry signal path is silent by default, because dsp effects transform the input and pass the newly processed result to the output. It does not add to the input.
func (d *DSP) WetDryMix() (float64, float64, float64, error) { var prewet, postwet, dry C.float res := C.FMOD_DSP_GetWetDryMix(d.cptr, &prewet, &postwet, &dry) return float64(prewet), float64(postwet), float64(dry), errs[res] }
[ "func wate(freq float64, fx, wtx []float64, lband int, filterType FilterType) float64 {\n\tif filterType != Differentiator {\n\t\treturn wtx[lband]\n\t}\n\tif fx[lband] >= 0.0001 {\n\t\treturn wtx[lband] / freq\n\t}\n\treturn wtx[lband]\n}", "func (_V1 *V1Caller) Dry(opts *bind.CallOpts, swapper1 common.Address, swapper2 common.Address, val *big.Int, forth []common.Address, back []common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _V1.contract.Call(opts, &out, \"dry\", swapper1, swapper2, val, forth, back)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func NewDry(screen *ui.Screen, env *drydocker.DockerEnv) (*Dry, error) {\n\td, err := drydocker.ConnectToDaemon(env)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newDry(screen, d)\n}", "func isDry(arguments map[string]interface{}) bool {\n\tdry := false\n\tif isDry, ok := arguments[\"--dry\"].(bool); ok {\n\t\tdry = isDry\n\t} else {\n\t\tif isD, ok := arguments[\"-d\"].(bool); ok {\n\t\t\tdry = isD\n\t\t}\n\t}\n\treturn dry\n}", "func (m *Message) DSP() (*DSP, error) {\n\tps, err := m.Parse(\"DSP\")\n\tpst, ok := ps.(*DSP)\n\tif ok {\n\t\treturn pst, err\n\t}\n\treturn nil, err\n}", "func NewDry(screen *ui.Screen, cfg Config) (*Dry, error) {\n\n\td, err := docker.ConnectToDaemon(cfg.dockerEnv())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdry, err := newDry(screen, d)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif cfg.MonitorMode {\n\t\tdry.changeView(Monitor)\n\t\twidgets.Monitor.RefreshRate(cfg.MonitorRefreshRate)\n\t}\n\treturn dry, nil\n}", "func (b BaseDefender) GetShieldPower(researches Researches) int64 {\n\treturn int64(float64(b.ShieldPower) * (1 + float64(researches.ShieldingTechnology)*0.1))\n}", "func (_CraftingI *CraftingICaller) GetWeaponDc(opts *bind.CallOpts, _item_id *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _CraftingI.contract.Call(opts, &out, \"get_weapon_dc\", _item_id)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (p *Pump) WavBitDepth() int {\n\treturn p.wavBitDepth\n}", "func (d *DSP) Bypass() (bool, error) {\n\tvar bypass C.FMOD_BOOL\n\tres := C.FMOD_DSP_GetBypass(d.cptr, &bypass)\n\treturn setBool(bypass), errs[res]\n}", "func (m *WTWWSWMediator) TransferWater(amount float64) {\n\tamount = m.WTW.OutputToStorage(amount)\n\tm.WSW.InputFromWTW(amount)\n}", "func SpewFormater(req interface{}, resp interface{}, err error) []byte {\n\tbf := new(bytes.Buffer)\n\n\twriteHeader(bf, \"Request\")\n\tspew.Fdump(bf, req)\n\n\twriteHeader(bf, \"Response\")\n\tspew.Fdump(bf, resp)\n\n\twriteHeader(bf, \"error\")\n\tspew.Fdump(bf, err)\n\n\treturn bf.Bytes()\n}", "func (s *Sum) Soft(val VarSet, key string) float64 {\n\tif _lv, ok := s.Stored(key); ok && s.stores {\n\t\treturn _lv\n\t}\n\n\tv, n := 0.0, len(s.ch)\n\tfor i := 0; i < n; i++ {\n\t\tp := s.ch[i].Soft(val, key)\n\t\tv += s.w[i] * p\n\t\t//if s.root {\n\t\t//fmt.Printf(\"Root %f * %f = %f\\n\", s.w[i], p, s.w[i]*p)\n\t\t//}\n\t}\n\n\ts.Store(key, v)\n\treturn v\n}", "func (o GetSrvRecordRecordOutput) Weight() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GetSrvRecordRecord) int { return v.Weight }).(pulumi.IntOutput)\n}", "func (p *Pump) WavSampleRate() phono.SampleRate {\n\treturn p.wavSampleRate\n}", "func (s *Service) GetSignalStrength(ctx context.Context) (uint8, error) {\n\tprops, err := s.GetProperties(ctx)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"unable to get properties\")\n\t}\n\tstrength, err := props.GetUint8(shillconst.ServicePropertyStrength)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"unable to get strength from properties\")\n\t}\n\treturn strength, nil\n}", "func (ind *Indicator) Soft(val VarSet, key string) float64 {\n\tif _lv, ok := ind.Stored(key); ok && ind.stores {\n\t\treturn _lv\n\t}\n\n\tv, ok := val[ind.varid]\n\tvar l float64\n\tif !ok || v == ind.setting {\n\t\tl = 1.0\n\t}\n\n\tind.Store(key, l)\n\treturn l\n}", "func ExampleVaropt_GetOriginalWeight() {\n\t// Number of points.\n\tconst totalCount = 1e6\n\n\t// Relative size of the sample.\n\tconst sampleRatio = 0.01\n\n\t// Ensure this test is deterministic.\n\trnd := rand.New(rand.NewSource(104729))\n\n\t// Construct a timeseries consisting of three colored signals,\n\t// for x=0 to x=60 seconds.\n\tvar points []point\n\n\t// origCounts stores the original signals at second granularity.\n\torigCounts := make([][]int, len(colors))\n\tfor i := range colors {\n\t\torigCounts[i] = make([]int, 60)\n\t}\n\n\t// Construct the signals by choosing a random color, then\n\t// using its Gaussian to compute a timestamp.\n\tfor len(points) < totalCount {\n\t\tchoose := rnd.Intn(len(colors))\n\t\tseries := colors[choose]\n\t\txvalue := rnd.NormFloat64()*series.stddev + series.mean\n\n\t\tif xvalue < 0 || xvalue > 60 {\n\t\t\tcontinue\n\t\t}\n\t\torigCounts[choose][int(math.Floor(xvalue))]++\n\t\tpoints = append(points, point{\n\t\t\tcolor: choose,\n\t\t\txvalue: xvalue,\n\t\t})\n\t}\n\n\t// Compute the total number of points per second. This will be\n\t// used to establish the per-second probability.\n\txcount := make([]int, 60)\n\tfor _, point := range points {\n\t\txcount[int(math.Floor(point.xvalue))]++\n\t}\n\n\t// Compute the sample with using the inverse probability as a\n\t// weight. This ensures a uniform distribution of points in each\n\t// second.\n\tsampleSize := int(sampleRatio * float64(totalCount))\n\tsampler := varopt.New(sampleSize, rnd)\n\tfor _, point := range points {\n\t\tsecond := int(math.Floor(point.xvalue))\n\t\tprob := float64(xcount[second]) / float64(totalCount)\n\t\tsampler.Add(point, 1/prob)\n\t}\n\n\t// sampleCounts stores the reconstructed signals.\n\tsampleCounts := make([][]float64, len(colors))\n\tfor i := range colors {\n\t\tsampleCounts[i] = make([]float64, 60)\n\t}\n\n\t// pointCounts stores the number of points per second.\n\tpointCounts := make([]int, 60)\n\n\t// Reconstruct the signals using the output sample weights.\n\t// The effective count of each sample point is its output\n\t// weight divided by its original weight.\n\tfor i := 0; i < sampler.Size(); i++ {\n\t\tsample, weight := sampler.Get(i)\n\t\torigWeight := sampler.GetOriginalWeight(i)\n\t\tpoint := sample.(point)\n\t\tsecond := int(math.Floor(point.xvalue))\n\t\tsampleCounts[point.color][second] += (weight / origWeight)\n\t\tpointCounts[second]++\n\t}\n\n\t// Compute standard deviation of sample points per second.\n\tsum := 0.0\n\tmean := float64(sampleSize) / 60\n\tfor s := 0; s < 60; s++ {\n\t\te := float64(pointCounts[s]) - mean\n\t\tsum += e * e\n\t}\n\tstddev := math.Sqrt(sum / (60 - 1))\n\n\tfmt.Printf(\"Samples per second mean %.2f\\n\", mean)\n\tfmt.Printf(\"Samples per second standard deviation %.2f\\n\", stddev)\n\n\t// Compute mean absolute percentage error between sampleCounts\n\t// and origCounts for each signal.\n\tfor c := range colors {\n\t\tmae := 0.0\n\t\tfor s := 0; s < 60; s++ {\n\t\t\tmae += math.Abs(sampleCounts[c][s]-float64(origCounts[c][s])) / float64(origCounts[c][s])\n\t\t}\n\t\tmae /= 60\n\t\tfmt.Printf(\"Mean absolute percentage error (%s) = %.2f%%\\n\", colors[c].color, mae*100)\n\t}\n\n\t// Output:\n\t// Samples per second mean 166.67\n\t// Samples per second standard deviation 13.75\n\t// Mean absolute percentage error (red) = 25.16%\n\t// Mean absolute percentage error (green) = 14.30%\n\t// Mean absolute percentage error (blue) = 14.23%\n}", "func (toneAnalyzer *ToneAnalyzerV3) ToneWithContext(ctx context.Context, toneOptions *ToneOptions) (result *ToneAnalysis, response *core.DetailedResponse, err error) {\n\terr = core.ValidateNotNil(toneOptions, \"toneOptions cannot be nil\")\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.ValidateStruct(toneOptions, \"toneOptions\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif toneOptions.ToneInput != nil && toneOptions.ContentType == nil {\n\t\ttoneOptions.SetContentType(\"application/json\")\n\t}\n\n\tbuilder := core.NewRequestBuilder(core.POST)\n\tbuilder = builder.WithContext(ctx)\n\tbuilder.EnableGzipCompression = toneAnalyzer.GetEnableGzipCompression()\n\t_, err = builder.ResolveRequestURL(toneAnalyzer.Service.Options.URL, `/v3/tone`, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor headerName, headerValue := range toneOptions.Headers {\n\t\tbuilder.AddHeader(headerName, headerValue)\n\t}\n\n\tsdkHeaders := common.GetSdkHeaders(\"tone_analyzer\", \"V3\", \"Tone\")\n\tfor headerName, headerValue := range sdkHeaders {\n\t\tbuilder.AddHeader(headerName, headerValue)\n\t}\n\tbuilder.AddHeader(\"Accept\", \"application/json\")\n\tif toneOptions.ContentType != nil {\n\t\tbuilder.AddHeader(\"Content-Type\", fmt.Sprint(*toneOptions.ContentType))\n\t}\n\tif toneOptions.ContentLanguage != nil {\n\t\tbuilder.AddHeader(\"Content-Language\", fmt.Sprint(*toneOptions.ContentLanguage))\n\t}\n\tif toneOptions.AcceptLanguage != nil {\n\t\tbuilder.AddHeader(\"Accept-Language\", fmt.Sprint(*toneOptions.AcceptLanguage))\n\t}\n\n\tbuilder.AddQuery(\"version\", fmt.Sprint(*toneAnalyzer.Version))\n\tif toneOptions.Sentences != nil {\n\t\tbuilder.AddQuery(\"sentences\", fmt.Sprint(*toneOptions.Sentences))\n\t}\n\tif toneOptions.Tones != nil {\n\t\tbuilder.AddQuery(\"tones\", strings.Join(toneOptions.Tones, \",\"))\n\t}\n\n\t_, err = builder.SetBodyContent(core.StringNilMapper(toneOptions.ContentType), toneOptions.ToneInput, nil, toneOptions.Body)\n\tif err != nil {\n\t\treturn\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 = toneAnalyzer.Service.Request(request, &rawResponse)\n\tif err != nil {\n\t\treturn\n\t}\n\tif rawResponse != nil {\n\t\terr = core.UnmarshalModel(rawResponse, \"\", &result, UnmarshalToneAnalysis)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tresponse.Result = result\n\t}\n\n\treturn\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the signal format of a dsp unit so that the signal is processed on the speakers specified. Also defines the number of channels in the unit that a read callback will process, and the output signal of the unit. channelmask: A series of bits specified by "ChannelMask" to determine which speakers are represented by the channels in the signal. numchannels: The number of channels to be processed on this unit and sent to the outputs connected to it. Maximum of FMOD_MAX_CHANNEL_WIDTH. source_speakermode: The source speaker mode where the signal came from. Setting the number of channels on a unit will force a down or up mix to that channel count before processing the DSP read callback. This channelcount is then sent to the outputs of the unit. source_speakermode is informational, when channelmask describes what bits are active, and numchannels describes how many channels are in a buffer, source_speakermode describes where the channels originated from. For example if numchannels = 2 then this could describe for the DSP if the original signal started from a stereo signal or a 5.1 signal. It could also describe the signal as all monaural, for example if numchannels was 16 and the speakermode was FMOD_SPEAKERMODE_MONO.
func (d *DSP) SetChannelFormat(channelmask ChannelMask, numchannels int, source_speakermode SpeakerMode) error { res := C.FMOD_DSP_SetChannelFormat(d.cptr, C.FMOD_CHANNELMASK(channelmask), C.int(numchannels), C.FMOD_SPEAKERMODE(source_speakermode)) return errs[res] }
[ "func (d *DSP) ChannelFormat() (ChannelMask, int, SpeakerMode, error) {\n\tvar channelmask C.FMOD_CHANNELMASK\n\tvar numchannels C.int\n\tvar source_speakermode C.FMOD_SPEAKERMODE\n\tres := C.FMOD_DSP_GetChannelFormat(d.cptr, &channelmask, &numchannels, &source_speakermode)\n\treturn ChannelMask(channelmask), int(numchannels), SpeakerMode(source_speakermode), errs[res]\n}", "func (s *System) SetSoftwareFormat(samplerate int, speakermode SpeakerMode, numrawspeakers int) error {\n\tres := C.FMOD_System_SetSoftwareFormat(s.cptr, C.int(samplerate), C.FMOD_SPEAKERMODE(speakermode), C.int(numrawspeakers))\n\treturn errs[res]\n}", "func (d *DSP) OutputChannelFormat(inmask ChannelMask, inchannels int, inspeakermode SpeakerMode) (ChannelMask, int, SpeakerMode, error) {\n\tvar outmask C.FMOD_CHANNELMASK\n\tvar outchannels C.int\n\tvar outspeakermode C.FMOD_SPEAKERMODE\n\tres := C.FMOD_DSP_GetOutputChannelFormat(d.cptr, C.FMOD_CHANNELMASK(inmask), C.int(inchannels), C.FMOD_SPEAKERMODE(inspeakermode), &outmask, &outchannels, &outspeakermode)\n\treturn ChannelMask(outmask), int(outchannels), SpeakerMode(outspeakermode), errs[res]\n}", "func (e *Engine) SetInputChannels(numberOfChannels int) error {\n\tif !e.initialized {\n\t\treturn errorEngineNotInitialized\n\t}\n\t// return error if the input device does not exist\n\tif e.streamParameters.Input.Device == nil {\n\t\treturn errorDeviceDoesNotExist\n\t}\n\t// error if numberOfChannels is not mono or stereo\n\t// or if we are assigning stereo to a mono only device\n\tunsupportedNumberOfChannels := (numberOfChannels < 1) || (numberOfChannels > 2) ||\n\t\t(numberOfChannels == 2 && e.streamParameters.Input.Device.MaxInputChannels == 1)\n\tif unsupportedNumberOfChannels {\n\t\treturn errorUnsupportedNumberOfChannels\n\t}\n\t// successfully assign (a correct) number of channels\n\te.streamParameters.Input.Channels = numberOfChannels\n\treturn nil\n}", "func (e *encoder) writeFmtChunk() error {\n\t// Chunk header\n\theader := fmtChunkHeader\n\tcopy(e.fmt.Header[:], header)\n\n\t// Size of this chunk\n\tsize := uint64(fmtChunkSize)\n\tbinary.LittleEndian.PutUint64(e.fmt.Size[:], size)\n\n\t// Format version\n\tformatVersion := uint32(fmtVersion)\n\tbinary.LittleEndian.PutUint32(e.fmt.Version[:], formatVersion)\n\n\t// Format id\n\tformatId := uint32(fmtIdentifier)\n\tbinary.LittleEndian.PutUint32(e.fmt.Identifier[:], formatId)\n\n\t// Channel type\n\tvar channelType uint32\n\tfor key, order := range fmtChannelOrder {\n\t\tif reflect.DeepEqual(e.audio.ChannelOrder, order) {\n\t\t\tchannelType = key\n\t\t}\n\t}\n\tif channelType == 0 {\n\t\tvar s string\n\t\tfor i, channel := range e.audio.ChannelOrder {\n\t\t\tif i < len(e.audio.ChannelOrder)-1 {\n\t\t\t\ts += channel.String() + \", \"\n\t\t\t} else {\n\t\t\t\ts += channel.String()\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"fmt: unsupported channel ordering: %v\", s)\n\t}\n\tchannelTypeString, _ := fmtChannelType[channelType]\n\tbinary.LittleEndian.PutUint32(e.fmt.ChannelType[:], channelType)\n\n\t// Channel num\n\tchannelNum := uint32(e.audio.NumChannels)\n\tif channelNum > 1 && (channelNum != uint32(len(e.audio.ChannelOrder))) {\n\t\treturn fmt.Errorf(\"fmt: mismatch between num channels and channel order: %v, %v\", channelNum, e.audio.ChannelOrder)\n\t}\n\tbinary.LittleEndian.PutUint32(e.fmt.ChannelNum[:], channelNum)\n\n\t// SamplingFrequency\n\tsamplingFrequency := uint32(e.audio.SamplingFrequency)\n\tsamplingFrequencyString, ok := fmtSamplingFrequency[samplingFrequency]\n\tif !ok {\n\t\treturn fmt.Errorf(\"fmt: unsupported sampling frequency: %v\", samplingFrequency)\n\t}\n\tbinary.LittleEndian.PutUint32(e.fmt.SamplingFrequency[:], samplingFrequency)\n\n\t// Bits per sample\n\tbitsPerSample := uint32(e.audio.BitsPerSample)\n\t_, ok = fmtBitsPerSample[bitsPerSample]\n\tif !ok {\n\t\treturn fmt.Errorf(\"fmt: unsupported bits per sample: %v\", bitsPerSample)\n\t}\n\tbinary.LittleEndian.PutUint32(e.fmt.BitsPerSample[:], bitsPerSample)\n\n\t// SampleCount\n\n\t// Log the fields of the chunk (only active if a log output has been set)\n\te.logger.Print(\"\\nFmt Chunk\\n=========\\n\")\n\te.logger.Printf(\"Chunk header: %q\\n\", header)\n\te.logger.Printf(\"Size of this chunk: %v\\n\", size)\n\te.logger.Printf(\"Format version: %v\\n\", formatVersion)\n\te.logger.Printf(\"Format id: %v\\n\", formatId)\n\te.logger.Printf(\"Channel type: %v (%s)\\n\", channelType, channelTypeString)\n\te.logger.Printf(\"Channel num: %v\\n\", channelNum)\n\tif len(e.audio.ChannelOrder) > 1 {\n\t\tvar s string\n\t\tfor i, channel := range e.audio.ChannelOrder {\n\t\t\tif i < len(e.audio.ChannelOrder)-1 {\n\t\t\t\ts += channel.String() + \", \"\n\t\t\t} else {\n\t\t\t\ts += channel.String()\n\t\t\t}\n\t\t}\n\t\te.logger.Printf(\"Channel order: %v\\n\", s)\n\t}\n\te.logger.Printf(\"Sampling frequency: %vHz (%s)\\n\", samplingFrequency, samplingFrequencyString)\n\te.logger.Printf(\"Bits per sample: %v\\n\", bitsPerSample)\n\n\t// Write the entire chunk in one go\n\terr := binary.Write(e.writer, binary.LittleEndian, &e.fmt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func RecordChannels(m proto.ChannelMap) RecordOption {\n\tif len(m) == 0 {\n\t\tpanic(\"pulse: invalid channel map\")\n\t}\n\treturn func(r *RecordStream) {\n\t\tr.createRequest.ChannelMap = m\n\t\tr.createRequest.Channels = byte(len(m))\n\t}\n}", "func NewPCM16Sound(channels int, sampleRate int) Sound {\n\tres := wavSound16{wavSound{NewHeader(), []Sample{}}}\n\tres.header.Format.BitsPerSample = 16\n\tres.header.Format.BlockAlign = uint16(channels * 2)\n\tres.header.Format.ByteRate = uint32(sampleRate * channels * 2)\n\tres.header.Format.SampleRate = uint32(sampleRate)\n\tres.header.Format.NumChannels = uint16(channels)\n\treturn &res\n}", "func (s *System) SoftwareFormat() (int, SpeakerMode, int, error) {\n\tvar samplerate C.int\n\tvar speakermode C.FMOD_SPEAKERMODE\n\tvar numrawspeakers C.int\n\tres := C.FMOD_System_GetSoftwareFormat(s.cptr, &samplerate, &speakermode, &numrawspeakers)\n\treturn int(samplerate), SpeakerMode(speakermode), int(numrawspeakers), errs[res]\n}", "func wrapper_audioFreq(t *eval.Thread, in []eval.Value, out []eval.Value) {\n\tif uiSettings.Terminated() {\n\t\treturn\n\t}\n\n\tfreq := uint(in[0].(eval.UintValue).Get(t))\n\n\tmutex.Lock()\n\tuiSettings.SetAudioFreq(freq)\n\tmutex.Unlock()\n}", "func NewChannelMixer(channels int, mixer mixer.ChannelMixer) TransformFunc {\n\treturn func(r Reader) Reader {\n\t\treturn ReaderFunc(func() (wave.Audio, func(), error) {\n\t\t\tbuff, _, err := r.Read()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, func() {}, err\n\t\t\t}\n\t\t\tci := buff.ChunkInfo()\n\t\t\tif ci.Channels == channels {\n\t\t\t\treturn buff, func() {}, nil\n\t\t\t}\n\n\t\t\tci.Channels = channels\n\n\t\t\tvar mixed wave.Audio\n\t\t\tswitch buff.(type) {\n\t\t\tcase *wave.Int16Interleaved:\n\t\t\t\tmixed = wave.NewInt16Interleaved(ci)\n\t\t\tcase *wave.Int16NonInterleaved:\n\t\t\t\tmixed = wave.NewInt16NonInterleaved(ci)\n\t\t\tcase *wave.Float32Interleaved:\n\t\t\t\tmixed = wave.NewFloat32Interleaved(ci)\n\t\t\tcase *wave.Float32NonInterleaved:\n\t\t\t\tmixed = wave.NewFloat32NonInterleaved(ci)\n\t\t\t}\n\t\t\tif err := mixer.Mix(mixed, buff); err != nil {\n\t\t\t\treturn nil, func() {}, err\n\t\t\t}\n\t\t\treturn mixed, func() {}, nil\n\t\t})\n\t}\n}", "func Write(fname string, format Format, rate uint32, slice interface{}) error {\n\tvar wf *File\n\tbuf := new(bytes.Buffer)\n\tswitch x := slice.(type) {\n\tcase []float64:\n\t\tif format == Float {\n\t\t\terr := binary.Write(buf, binary.LittleEndian, x)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\twf = NewFile(format, 1, rate, 64, len(x))\n\t\t} else if format == PCM {\n\t\t\tfor _, xn := range x {\n\t\t\t\txn16 := float64toInt16(xn)\n\t\t\t\terr := binary.Write(buf, binary.LittleEndian, xn16)\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\twf = NewFile(format, 1, rate, 16, len(x))\n\t\t}\n\tcase []float32:\n\t\tif format == Float {\n\t\t\terr := binary.Write(buf, binary.LittleEndian, x)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\twf = NewFile(format, 1, rate, 32, len(x))\n\t\t} else if format == PCM {\n\t\t\tfor _, xn := range x {\n\t\t\t\txn16 := float64toInt16(float64(xn))\n\t\t\t\terr := binary.Write(buf, binary.LittleEndian, xn16)\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\twf = NewFile(format, 1, rate, 16, len(x))\n\t\t}\n\tcase []int16:\n\t\tif format == PCM {\n\t\t\terr := binary.Write(buf, binary.LittleEndian, x)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\twf = NewFile(format, 1, rate, 16, len(x))\n\t\t}\n\t}\n\tif wf == nil {\n\t\treturn fmt.Errorf(\"Write %s: conversion from %T to %s not supported\",\n\t\t\tfname, slice, format)\n\t}\n\tcopy(wf.Data, buf.Bytes())\n\treturn wf.Write(fname)\n}", "func (d *DspConnection) SetMixMatrix(matrix *C.float, outchannels, inchannels, inchannel_hop C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSPConnection_SetMixMatrix (FMOD_DSPCONNECTION *dspconnection, float *matrix, int outchannels, int inchannels, int inchannel_hop);\n\treturn ErrNoImpl\n}", "func (d *Detector) SetSampleRate(x int) error {\n\terrno := C.fvad_set_sample_rate(d.fvad, C.int(x))\n\tif errno != 0 {\n\t\treturn fmt.Errorf(\"invalid sample rate: %v\", x)\n\t}\n\treturn nil\n}", "func NewFormat(chans int, freq freq.T, sc sample.Codec) *Format {\n\treturn &Format{\n\t\tchannels: chans,\n\t\tfreq: freq,\n\t\tCodec: sc}\n}", "func (d *Decoder) SetRawDataSize(frames int32) {\n\td.maxRawdataSize = frames\n\td.rawdataBuf = [][]int16{\n\t\tmake([]int16, frames),\n\t}\n\tpocketsphinx.SetRawdataSize(d.dec, frames*2)\n}", "func DecodeWithSampleRate(sampleRate int, src io.Reader) (*Stream, error) {\n\td, err := mp3.NewDecoder(src)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar r *convert.Resampling\n\tif d.SampleRate() != sampleRate {\n\t\tr = convert.NewResampling(d, d.Length(), d.SampleRate(), sampleRate)\n\t}\n\ts := &Stream{\n\t\torig: d,\n\t\tresampling: r,\n\t}\n\treturn s, nil\n}", "func (d *Dev) SetPwmFreq(freqHz float32) error {\n\tprescaleval := float32(25 * physic.MegaHertz)\n\tprescaleval /= 4096.0 //# 12-bit\n\tprescaleval /= (freqHz * float32(physic.Hertz))\n\tprescaleval -= 1.0\n\n\tprescale := int(math.Floor(float64(prescaleval + 0.5)))\n\n\tvar oldmode byte\n\terr := d.dev.Tx([]byte{Mode1}, []byte{oldmode})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewmode := (byte)((oldmode & 0x7F) | 0x10) // sleep\n\td.dev.Write([]byte{Mode1, newmode}) // go to sleep\n\td.dev.Write([]byte{Prescale, byte(prescale)})\n\td.dev.Write([]byte{Mode1, oldmode})\n\n\ttime.Sleep(100 * time.Millisecond)\n\n\td.dev.Write([]byte{Mode1, (byte)(oldmode | 0x80)})\n\treturn nil\n}", "func (e *Engine) SetDevices(inputDeviceInfo, outputDeviceInfo *portaudio.DeviceInfo) error {\n\tif !e.initialized {\n\t\treturn errorEngineNotInitialized\n\t}\n\t// create a new (low latency) stream parameter configuration.\n\t// Hopefully you (at least) passed in an output device, otherwise\n\t// Start() will blow up later)\n\tstreamParameters := portaudio.LowLatencyParameters(inputDeviceInfo, outputDeviceInfo)\n\t// copy the relevant old stream parameter values into the new stream\n\t// parameter values\n\tstreamParameters.SampleRate = e.streamParameters.SampleRate\n\tstreamParameters.FramesPerBuffer = e.streamParameters.FramesPerBuffer\n\t// force stereo output. NB, the output device *must* support stereo\n\t// (otherwise this entire library will not work) if it doesn't support\n\t// stereo, well, you'll find out when Start() is called won't you\n\tstreamParameters.Output.Channels = 2\n\t// if we acquired an input device\n\tif streamParameters.Input.Device != nil {\n\t\t// prefer stereo input (if it has >2 possible channels)\n\t\tif streamParameters.Input.Device.MaxInputChannels >= 2 {\n\t\t\tstreamParameters.Input.Channels = 2\n\t\t}\n\t\t// else there's only mono input, and it's set already (I think)\n\t}\n\t// update the stream parameters\n\te.streamParameters = streamParameters\n\treturn nil\n}", "func (b *PCMBuffer) PCMFormat() *Format {\n\tif b == nil {\n\t\treturn nil\n\t}\n\treturn b.Format\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the input signal format for a dsp units read/process callback, to determine which speakers the signal will be processed on and how many channels will be processed. source_speakermode is informational, when channelmask describes what bits are active, and numchannels describes how many channels are in a buffer, source_speakermode describes where the channels originated from. For example if numchannels = 2 then this could describe for the DSP if the original signal started from a stereo signal or a 5.1 signal. In the 5.1 signal the channels described might only represent 2 surround speakers for example.
func (d *DSP) ChannelFormat() (ChannelMask, int, SpeakerMode, error) { var channelmask C.FMOD_CHANNELMASK var numchannels C.int var source_speakermode C.FMOD_SPEAKERMODE res := C.FMOD_DSP_GetChannelFormat(d.cptr, &channelmask, &numchannels, &source_speakermode) return ChannelMask(channelmask), int(numchannels), SpeakerMode(source_speakermode), errs[res] }
[ "func (d *DSP) OutputChannelFormat(inmask ChannelMask, inchannels int, inspeakermode SpeakerMode) (ChannelMask, int, SpeakerMode, error) {\n\tvar outmask C.FMOD_CHANNELMASK\n\tvar outchannels C.int\n\tvar outspeakermode C.FMOD_SPEAKERMODE\n\tres := C.FMOD_DSP_GetOutputChannelFormat(d.cptr, C.FMOD_CHANNELMASK(inmask), C.int(inchannels), C.FMOD_SPEAKERMODE(inspeakermode), &outmask, &outchannels, &outspeakermode)\n\treturn ChannelMask(outmask), int(outchannels), SpeakerMode(outspeakermode), errs[res]\n}", "func determineFormat(channels int) int {\n\tswitch channels {\n\tcase 1:\n\t\treturn gl.RED\n\tcase 2:\n\t\treturn gl.RG\n\tcase 3:\n\t\treturn gl.RGB\n\tcase 4:\n\t\treturn gl.RGBA\n\t}\n\treturn gl.RGBA\n}", "func (s *System) SoftwareFormat() (int, SpeakerMode, int, error) {\n\tvar samplerate C.int\n\tvar speakermode C.FMOD_SPEAKERMODE\n\tvar numrawspeakers C.int\n\tres := C.FMOD_System_GetSoftwareFormat(s.cptr, &samplerate, &speakermode, &numrawspeakers)\n\treturn int(samplerate), SpeakerMode(speakermode), int(numrawspeakers), errs[res]\n}", "func (r *DynResampler) Channels() int {\n\treturn r.ct.src.Channels()\n}", "func readHeaderFormat(reader *bytes.Reader) (*formatHeader, error) {\n\thdrFormat := formatHeader{}\n\terr := binary.Read(reader, binary.LittleEndian, &hdrFormat)\n\n\t/*\n\t * Check if format header was read.\n\t */\n\tif err != nil {\n\t\tmsg := err.Error()\n\t\treturn nil, fmt.Errorf(\"Failed to read format header: %s\", msg)\n\t} else {\n\t\tchunkId := hdrFormat.ChunkID\n\t\tchannelCount := hdrFormat.ChannelCount\n\t\tbitDepth := hdrFormat.BitDepth\n\t\tsampleRate := hdrFormat.SampleRate\n\t\tframeSize := channelCount * bitDepth\n\t\texpectedBlockAlign32 := uint32(frameSize / BITS_PER_BYTE)\n\t\texpectedBlockAlign16 := uint16(expectedBlockAlign32)\n\t\texpectedByteRate := expectedBlockAlign32 * sampleRate\n\t\tchunkSize := hdrFormat.ChunkSize\n\t\tchunkSize64 := int64(chunkSize)\n\t\tnumBytesSkip := chunkSize64 - MIN_CHUNK_SIZE_FORMAT\n\t\taudioFormat := hdrFormat.AudioFormat\n\t\tbyteRate := hdrFormat.ByteRate\n\t\tblockAlign := hdrFormat.BlockAlign\n\n\t\t/*\n\t\t * Skip optional fields in the format header.\n\t\t */\n\t\tif numBytesSkip > 0 {\n\n\t\t\t/*\n\t\t\t * If this is even, we need to skip one more.\n\t\t\t */\n\t\t\tif (numBytesSkip % 2) == 0 {\n\t\t\t\tnumBytesSkip += 1\n\t\t\t}\n\n\t\t\tamount := uint64(numBytesSkip)\n\t\t\tskipData(reader, amount)\n\t\t}\n\n\t\t/*\n\t\t * Check format header for validity.\n\t\t */\n\t\tif chunkId != ID_FORMAT {\n\t\t\treturn nil, fmt.Errorf(\"Format header contains invalid chunk id. Expected %#08x, found %#08x.\", ID_FORMAT, chunkId)\n\t\t} else if chunkSize < MIN_CHUNK_SIZE_FORMAT {\n\t\t\treturn nil, fmt.Errorf(\"Format header contains invalid chunk size. Expected at least %#08x, found %#08x.\", MIN_CHUNK_SIZE_FORMAT, chunkSize)\n\t\t} else if audioFormat != AUDIO_PCM && audioFormat != AUDIO_IEEE_FLOAT {\n\t\t\treturn nil, fmt.Errorf(\"Format header contains invalid audio format. Expected %#04x or %#04x, found %#04x.\", AUDIO_PCM, AUDIO_IEEE_FLOAT, audioFormat)\n\t\t} else if byteRate != expectedByteRate {\n\t\t\treturn nil, fmt.Errorf(\"Format header contains invalid byte rate. Expected %#08x, found %#08x.\", expectedByteRate, byteRate)\n\t\t} else if blockAlign != expectedBlockAlign16 {\n\t\t\treturn nil, fmt.Errorf(\"Format header contains invalid block align. Expected %#04x, found %#04x.\", expectedBlockAlign16, blockAlign)\n\t\t} else if audioFormat == AUDIO_PCM && bitDepth != 8 && bitDepth != 16 && bitDepth != 24 && bitDepth != 32 {\n\t\t\treturn nil, fmt.Errorf(\"Format header contains invalid bit depth for PCM format. Expected %#04x or %#04x or %#04x or %#04x, found %#04x.\", 8, 16, 24, 32, bitDepth)\n\t\t} else if audioFormat == AUDIO_IEEE_FLOAT && bitDepth != 32 && bitDepth != 64 {\n\t\t\treturn nil, fmt.Errorf(\"Format header contains invalid bit depth for IEEE floating-point format. Expected %#04x or %#04x, found %#04x.\", 32, 64, bitDepth)\n\t\t} else {\n\t\t\treturn &hdrFormat, nil\n\t\t}\n\n\t}\n\n}", "func (obj *Device) GetStreamSourceFreq(\n\tstreamNumber uint,\n) (divider uint32, err Error) {\n\tret, _, _ := syscall.Syscall(\n\t\tobj.vtbl.GetStreamSourceFreq,\n\t\t3,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(streamNumber),\n\t\tuintptr(unsafe.Pointer(&divider)),\n\t)\n\terr = toErr(ret)\n\treturn\n}", "func (d *DSP) SetChannelFormat(channelmask ChannelMask, numchannels int, source_speakermode SpeakerMode) error {\n\tres := C.FMOD_DSP_SetChannelFormat(d.cptr, C.FMOD_CHANNELMASK(channelmask), C.int(numchannels), C.FMOD_SPEAKERMODE(source_speakermode))\n\treturn errs[res]\n}", "func NewAudioSource(c *Config) (*AudioSource, error) {\n\t// create the command and start it, but don't read from the stdout yet.\n\t// not until we attach the listener\n\t// should we do the spectrum analysis here? or raw samples.\n\t// we need to support time-based analysis or just frequency\n\t// based. I only want frequency, but maybe the \"Sample\"\n\t// type should actually be a type with methods for \"TimeDomainAnalysis\"\n\t// and \"FrequencyDomainAnalysis\" and we just call whichever one...\n\t// that way I can implement the FrequencyDomainAnalysis first.\n\t// but first.\n\n\t// we can\n\tcmd := exec.Command(c.FFMpegPath,\n\t\t\"-i\", c.AudioFile, //our audio file\n\t\t\"-vn\", // no video\n\t\t\"-ar\", strconv.Itoa(samplingRate), // get sampling rate\n\t\t\"-ac\", \"1\", //mono\n\t\t\"-f\", \"f64be\", // raw f64 output\n\t\t\"-c:a\", \"pcm_f64be\", // we can get ffmpeg to output float64 data!\n\t\t\"-\", // output to stdout\n\t)\n\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tas := &AudioSource{\n\t\tCmd: cmd,\n\t\tsamplesPerFrame: samplingRate / c.FPS,\n\t\tstdout: stdout,\n\t}\n\n\treturn as, cmd.Start()\n}", "func (info TrackInfo) NChannels() int {\n\t// bit 28 - 1 = stereo audio; 0 = mono audio\n\tif info&0x10000000 != 0 {\n\t\t// stero audio.\n\t\treturn 2\n\t}\n\t// mono audio.\n\treturn 1\n}", "func (c *Sound) GetFormat() int {\n\treturn c.Format\n}", "func NewChannelMixer(channels int, mixer mixer.ChannelMixer) TransformFunc {\n\treturn func(r Reader) Reader {\n\t\treturn ReaderFunc(func() (wave.Audio, func(), error) {\n\t\t\tbuff, _, err := r.Read()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, func() {}, err\n\t\t\t}\n\t\t\tci := buff.ChunkInfo()\n\t\t\tif ci.Channels == channels {\n\t\t\t\treturn buff, func() {}, nil\n\t\t\t}\n\n\t\t\tci.Channels = channels\n\n\t\t\tvar mixed wave.Audio\n\t\t\tswitch buff.(type) {\n\t\t\tcase *wave.Int16Interleaved:\n\t\t\t\tmixed = wave.NewInt16Interleaved(ci)\n\t\t\tcase *wave.Int16NonInterleaved:\n\t\t\t\tmixed = wave.NewInt16NonInterleaved(ci)\n\t\t\tcase *wave.Float32Interleaved:\n\t\t\t\tmixed = wave.NewFloat32Interleaved(ci)\n\t\t\tcase *wave.Float32NonInterleaved:\n\t\t\t\tmixed = wave.NewFloat32NonInterleaved(ci)\n\t\t\t}\n\t\t\tif err := mixer.Mix(mixed, buff); err != nil {\n\t\t\t\treturn nil, func() {}, err\n\t\t\t}\n\t\t\treturn mixed, func() {}, nil\n\t\t})\n\t}\n}", "func extractSampleRate(data []byte) uint32 {\n\t// Skip 40 bits (28 of the OGG header + 12 of the Opus header) and read the\n\t// next 4 bits to extract the sample rate as an int.\n\tif len(data) < 44 {\n\t\tlog.Panicf(\"unexpected data length: %v\", len(data))\n\t}\n\n\treturn binary.LittleEndian.Uint32(data[40:44])\n}", "func (dev *Device) CaptureChannels() uint32 {\n\treturn uint32(dev.cptr().capture.channels)\n}", "func (audio *Audio) Channels() int {\n\treturn audio.channels\n}", "func (dev *Device) PlaybackChannels() uint32 {\n\treturn uint32(dev.cptr().playback.channels)\n}", "func (e *Engine) SetInputChannels(numberOfChannels int) error {\n\tif !e.initialized {\n\t\treturn errorEngineNotInitialized\n\t}\n\t// return error if the input device does not exist\n\tif e.streamParameters.Input.Device == nil {\n\t\treturn errorDeviceDoesNotExist\n\t}\n\t// error if numberOfChannels is not mono or stereo\n\t// or if we are assigning stereo to a mono only device\n\tunsupportedNumberOfChannels := (numberOfChannels < 1) || (numberOfChannels > 2) ||\n\t\t(numberOfChannels == 2 && e.streamParameters.Input.Device.MaxInputChannels == 1)\n\tif unsupportedNumberOfChannels {\n\t\treturn errorUnsupportedNumberOfChannels\n\t}\n\t// successfully assign (a correct) number of channels\n\te.streamParameters.Input.Channels = numberOfChannels\n\treturn nil\n}", "func (b *PCMBuffer) PCMFormat() *Format {\n\tif b == nil {\n\t\treturn nil\n\t}\n\treturn b.Format\n}", "func (p *Pump) WavNumChannels() phono.NumChannels {\n\treturn p.wavNumChannels\n}", "func convert(s *C.SDL_AudioSpec, data *C.Uint8, len C.Uint32) (*C.Uint8, C.Uint32, error) {\n\tvar cvt C.SDL_AudioCVT\n\to := openedSpec\n\tswitch C.SDL_BuildAudioCVT(&cvt, s.format, s.channels, s.freq, o.format, o.channels, o.freq) {\n\tcase -1:\n\t\treturn nil, 0, errors.New(\"Cannot convert audio\")\n\tcase 0:\n\t\treturn data, len, nil\n\t}\n\n\tbuf := C.malloc(C.size_t(len) * C.size_t(cvt.len_mult))\n\tcvt.buf = (*C.Uint8)(buf)\n\tcvt.len = C.int(len)\n\tC.memcpy(buf, unsafe.Pointer(data), C.size_t(len))\n\tC.free(unsafe.Pointer(data))\n\n\tif C.SDL_ConvertAudio(&cvt) < 0 {\n\t\treturn nil, 0, sdlError()\n\t}\n\treturn cvt.buf, C.Uint32(cvt.len), nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call the DSP process function to retrieve the output signal format for a DSP based on input values. inmask: Channel bitmask representing the speakers enabled for the incoming signal. For example a 5.1 signal could have inchannels 2 that represent CHANNELMASK_SURROUND_LEFT and CHANNELMASK_SURROUND_RIGHT. inchannels: Number of channels for the incoming signal. inspeakermode: Speaker mode for the incoming signal. A DSP unit may be an up mixer or down mixer for example. In this case if you specified 6 in for a downmixer, it may provide you with 2 out for example. Generally the input values will be reproduced for the output values, but some DSP units will want to alter the output format.
func (d *DSP) OutputChannelFormat(inmask ChannelMask, inchannels int, inspeakermode SpeakerMode) (ChannelMask, int, SpeakerMode, error) { var outmask C.FMOD_CHANNELMASK var outchannels C.int var outspeakermode C.FMOD_SPEAKERMODE res := C.FMOD_DSP_GetOutputChannelFormat(d.cptr, C.FMOD_CHANNELMASK(inmask), C.int(inchannels), C.FMOD_SPEAKERMODE(inspeakermode), &outmask, &outchannels, &outspeakermode) return ChannelMask(outmask), int(outchannels), SpeakerMode(outspeakermode), errs[res] }
[ "func (this *signalGenerator) Process(in []float64, out []float64, sampleRate uint32) {\n\tthis.mutex.RLock()\n\tinputAmplitude, _ := this.getNumericValue(\"input_amplitude\")\n\tinputGain, _ := this.getNumericValue(\"input_gain\")\n\tsignalType, _ := this.getDiscreteValue(\"signal_type\")\n\tsignalFrequency, _ := this.getNumericValue(\"signal_frequency\")\n\tsignalAmplitude, _ := this.getNumericValue(\"signal_amplitude\")\n\tsignalGain, _ := this.getNumericValue(\"signal_gain\")\n\tthis.mutex.RUnlock()\n\tinputAmplitudeFloat := float64(inputAmplitude)\n\tfacInputGain := decibelsToFactor(inputGain)\n\tfacInput := (0.01 * inputAmplitudeFloat) * facInputGain\n\tfacSignalGain := decibelsToFactor(signalGain)\n\tsignalAmplitudeFloat := float64(signalAmplitude)\n\tfacSignal := (0.01 * signalAmplitudeFloat) * facSignalGain\n\tphase := this.phase\n\tsignalFrequencyFloat := float64(signalFrequency)\n\tsampleRateFloat := float64(sampleRate)\n\tphaseIncrement := MATH_TWO_PI * (signalFrequencyFloat / sampleRateFloat)\n\ttwoOverPi := 2.0 / math.Pi\n\tn := len(in)\n\tnFloat := float64(n)\n\n\t/*\n\t * Generate the appropriate signal.\n\t */\n\tswitch signalType {\n\tcase \"sine\":\n\n\t\t/*\n\t\t * Process each sample.\n\t\t */\n\t\tfor i, sample := range in {\n\t\t\tiFloat := float64(i)\n\t\t\tupdatedPhase := phase + (iFloat * phaseIncrement)\n\t\t\tcurrentPhase := math.Mod(updatedPhase, MATH_TWO_PI)\n\t\t\tsignal := math.Sin(currentPhase)\n\t\t\tout[i] = (facInput * sample) + (facSignal * signal)\n\t\t}\n\n\t\tphase += nFloat * phaseIncrement\n\t\tphase = math.Mod(phase, MATH_TWO_PI)\n\t\tbreak\n\tcase \"triangle\":\n\n\t\t/*\n\t\t * Process each sample.\n\t\t */\n\t\tfor i, sample := range in {\n\t\t\tiFloat := float64(i)\n\t\t\tupdatedPhase := phase + (iFloat * phaseIncrement)\n\t\t\tcurrentPhase := math.Mod(updatedPhase, MATH_TWO_PI)\n\t\t\tsignal := 0.0\n\n\t\t\t/*\n\t\t\t * Check whether the waveform is rising or falling.\n\t\t\t */\n\t\t\tif currentPhase < math.Pi {\n\t\t\t\tsignal = (twoOverPi * currentPhase) - 1.0\n\t\t\t} else {\n\t\t\t\tsignal = 3.0 - (twoOverPi * currentPhase)\n\t\t\t}\n\n\t\t\tout[i] = (facInput * sample) + (facSignal * signal)\n\t\t}\n\n\t\tphase += nFloat * phaseIncrement\n\t\tphase = math.Mod(phase, MATH_TWO_PI)\n\t\tbreak\n\tcase \"square\":\n\n\t\t/*\n\t\t * Process each sample.\n\t\t */\n\t\tfor i, sample := range in {\n\t\t\tiFloat := float64(i)\n\t\t\tupdatedPhase := phase + (iFloat * phaseIncrement)\n\t\t\tcurrentPhase := math.Mod(updatedPhase, MATH_TWO_PI)\n\t\t\tsignal := signFloat(math.Pi - currentPhase)\n\t\t\tout[i] = (facInput * sample) + (facSignal * signal)\n\t\t}\n\n\t\tphase += nFloat * phaseIncrement\n\t\tphase = math.Mod(phase, MATH_TWO_PI)\n\t\tbreak\n\tcase \"sawtooth\":\n\n\t\t/*\n\t\t * Process each sample.\n\t\t */\n\t\tfor i, sample := range in {\n\t\t\tiFloat := float64(i)\n\t\t\tupdatedPhase := phase + (iFloat * phaseIncrement)\n\t\t\tcurrentPhase := math.Mod(updatedPhase, MATH_TWO_PI)\n\t\t\tsignal := currentPhase / math.Pi\n\n\t\t\t/*\n\t\t\t * Check whether we're after the phase jump.\n\t\t\t */\n\t\t\tif currentPhase > math.Pi {\n\t\t\t\tsignal -= 2.0\n\t\t\t}\n\n\t\t\tout[i] = (facInput * sample) + (facSignal * signal)\n\t\t}\n\n\t\tphase += nFloat * phaseIncrement\n\t\tphase = math.Mod(phase, MATH_TWO_PI)\n\t\tbreak\n\tcase \"noise\":\n\t\tprng := this.prng\n\n\t\t/*\n\t\t * Check if pseudo-random number generator is initialized.\n\t\t */\n\t\tif prng == nil {\n\t\t\tprng = random.CreatePRNG(1337)\n\t\t\tthis.prng = prng\n\t\t}\n\n\t\t/*\n\t\t * Process each sample.\n\t\t */\n\t\tfor i, sample := range in {\n\t\t\tr := prng.NextFloat()\n\t\t\tuniform := (1.0 - (2.0 * r))\n\t\t\tout[i] = (facInput * sample) + (facSignal * uniform)\n\t\t}\n\n\t\tbreak\n\t}\n\n\tthis.phase = phase\n}", "func (_HbSwap *HbSwapFilterer) WatchInputmask(opts *bind.WatchOpts, sink chan<- *HbSwapInputmask) (event.Subscription, error) {\n\n\tlogs, sub, err := _HbSwap.contract.WatchLogs(opts, \"Inputmask\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn event.NewSubscription(func(quit <-chan struct{}) error {\n\t\tdefer sub.Unsubscribe()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase log := <-logs:\n\t\t\t\t// New log arrived, parse the event and forward to the user\n\t\t\t\tevent := new(HbSwapInputmask)\n\t\t\t\tif err := _HbSwap.contract.UnpackLog(event, \"Inputmask\", log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tevent.Raw = log\n\n\t\t\t\tselect {\n\t\t\t\tcase sink <- event:\n\t\t\t\tcase err := <-sub.Err():\n\t\t\t\t\treturn err\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase err := <-sub.Err():\n\t\t\t\treturn err\n\t\t\tcase <-quit:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}), nil\n}", "func (j *JustAddPowerReciever) AudioVideoInputs(ctx context.Context) (map[string]string, error) {\n\ttoReturn := make(map[string]string)\n\n\tipAddress, err := net.ResolveIPAddr(\"ip\", j.Address)\n\tipAddress.IP = ipAddress.IP.To4()\n\n\tj.Log.Debug(\"ip address\", zap.Any(\"IP\", ipAddress.IP))\n\n\tif err != nil {\n\t\treturn toReturn, fmt.Errorf(\"Error when resolving IP Address [%s]: %w\", j.Address, err)\n\t}\n\n\tresult, err := justAddPowerRequest(fmt.Sprintf(\"http://%s/cgi-bin/api/details/channel\", j.Address), \"\", \"GET\")\n\n\tif err != nil {\n\t\tj.Log.Debug(\"error when making request\", zap.Error(err))\n\t\treturn toReturn, fmt.Errorf(\"error when making request: %w\", err)\n\t}\n\n\tvar jsonResult JustAddPowerChannelIntResult\n\tgerr := json.Unmarshal(result, &jsonResult)\n\tif gerr != nil {\n\t\tj.Log.Debug(\"error unmarshaling response\", zap.Error(gerr))\n\t\treturn toReturn, fmt.Errorf(\"error when unmarshaling response: %w\", gerr)\n\t}\n\n\tj.Log.Debug(\"Result\", zap.Any(\"result\", result), zap.Any(\"jsonResult\", jsonResult))\n\tj.Log.Debug(\"len of IP\", zap.Int(\"lenght\", len(ipAddress.IP)))\n\n\ttransmissionChannel := fmt.Sprintf(\"%v.%v.%v.%v\",\n\t\tipAddress.IP[0], ipAddress.IP[1], ipAddress.IP[2], jsonResult.Data)\n\n\ttoReturn[\"\"] = transmissionChannel\n\treturn toReturn, nil\n}", "func ProcessOutChannel(wg *sync.WaitGroup, scConfig *common.SCConfiguration) {\n\t//qdr throws out the data on this channel ,listen to data coming out of qdrEventOutCh\n\t//Send back the acknowledgement to publisher\n\tpostProcessFn := func(address string, status channel.Status) {\n\t\tif pub, ok := scConfig.PubSubAPI.HasPublisher(address); ok {\n\t\t\tif status == channel.SUCCESS {\n\t\t\t\tlocalmetrics.UpdateEventAckCount(address, localmetrics.SUCCESS)\n\t\t\t} else {\n\t\t\t\tlocalmetrics.UpdateEventAckCount(address, localmetrics.FAILED)\n\t\t\t}\n\t\t\tif pub.EndPointURI != nil {\n\t\t\t\tlog.Debugf(\"posting event status %s to publisher %s\", channel.Status(status), pub.Resource)\n\t\t\t\trestClient := restclient.New()\n\t\t\t\t_ = restClient.Post(pub.EndPointURI,\n\t\t\t\t\t[]byte(fmt.Sprintf(`{eventId:\"%s\",status:\"%s\"}`, pub.ID, status)))\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Warnf(\"could not send ack to publisher ,`publisher` for address %s not found\", address)\n\t\t\tlocalmetrics.UpdateEventAckCount(address, localmetrics.FAILED)\n\t\t}\n\t}\n\tpostHandler := func(err error, endPointURI *types.URI, address string) {\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"error posting request at %s : %s\", endPointURI, err)\n\t\t\tlocalmetrics.UpdateEventReceivedCount(address, localmetrics.FAILED)\n\t\t} else {\n\t\t\tlocalmetrics.UpdateEventReceivedCount(address, localmetrics.SUCCESS)\n\t\t}\n\t}\n\n\tfor { //nolint:gosimple\n\t\tselect { //nolint:gosimple\n\t\tcase d := <-scConfig.EventOutCh: // do something that is put out by QDR\n\t\t\tswitch d.Data.Type() {\n\t\t\tcase channel.HWEvent:\n\t\t\t\tevent, err := v1hwevent.GetCloudNativeEvents(*d.Data)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"error marshalling event data when reading from amqp %v\\n %#v\", err, d)\n\t\t\t\t\tlog.Infof(\"data %#v\", d.Data)\n\t\t\t\t} else if d.Type == channel.EVENT {\n\t\t\t\t\tif d.Status == channel.NEW {\n\t\t\t\t\t\tif d.ProcessEventFn != nil { // always leave event to handle by default method for events\n\t\t\t\t\t\t\tif err := d.ProcessEventFn(event); err != nil {\n\t\t\t\t\t\t\t\tlog.Errorf(\"error processing data %v\", err)\n\t\t\t\t\t\t\t\tlocalmetrics.UpdateEventReceivedCount(d.Address, localmetrics.FAILED)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if sub, ok := scConfig.PubSubAPI.HasSubscription(d.Address); ok {\n\t\t\t\t\t\t\tif sub.EndPointURI != nil {\n\t\t\t\t\t\t\t\trestClient := restclient.New()\n\t\t\t\t\t\t\t\tevent.ID = sub.ID // set ID to the subscriptionID\n\t\t\t\t\t\t\t\terr := restClient.PostHwEvent(sub.EndPointURI, event)\n\t\t\t\t\t\t\t\tpostHandler(err, sub.EndPointURI, d.Address)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tlog.Warnf(\"endpoint uri not given, posting event to log %#v for address %s\\n\", event, d.Address)\n\t\t\t\t\t\t\t\tlocalmetrics.UpdateEventReceivedCount(d.Address, localmetrics.SUCCESS)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlog.Warnf(\"subscription not found, posting event %#v to log for address %s\\n\", event, d.Address)\n\t\t\t\t\t\t\tlocalmetrics.UpdateEventReceivedCount(d.Address, localmetrics.FAILED)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if d.Status == channel.SUCCESS || d.Status == channel.FAILED { // event sent ,ack back to publisher\n\t\t\t\t\t\tpostProcessFn(d.Address, d.Status)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tevent, err := v1event.GetCloudNativeEvents(*d.Data)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"error marshalling event data when reading from amqp %v\\n %#v\", err, d)\n\t\t\t\t\tlog.Infof(\"data %#v\", d.Data)\n\t\t\t\t} else if d.Type == channel.EVENT {\n\t\t\t\t\tif d.Status == channel.NEW {\n\t\t\t\t\t\tif d.ProcessEventFn != nil { // always leave event to handle by default method for events\n\t\t\t\t\t\t\tif err := d.ProcessEventFn(event); err != nil {\n\t\t\t\t\t\t\t\tlog.Errorf(\"error processing data %v\", err)\n\t\t\t\t\t\t\t\tlocalmetrics.UpdateEventReceivedCount(d.Address, localmetrics.FAILED)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if sub, ok := scConfig.PubSubAPI.HasSubscription(d.Address); ok {\n\t\t\t\t\t\t\tif sub.EndPointURI != nil {\n\t\t\t\t\t\t\t\trestClient := restclient.New()\n\t\t\t\t\t\t\t\tevent.ID = sub.ID // set ID to the subscriptionID\n\t\t\t\t\t\t\t\terr := restClient.PostEvent(sub.EndPointURI, event)\n\t\t\t\t\t\t\t\tpostHandler(err, sub.EndPointURI, d.Address)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tlog.Warnf(\"endpoint uri not given, posting event to log %#v for address %s\\n\", event, d.Address)\n\t\t\t\t\t\t\t\tlocalmetrics.UpdateEventReceivedCount(d.Address, localmetrics.SUCCESS)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlog.Warnf(\"subscription not found, posting event %#v to log for address %s\\n\", event, d.Address)\n\t\t\t\t\t\t\tlocalmetrics.UpdateEventReceivedCount(d.Address, localmetrics.FAILED)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if d.Status == channel.SUCCESS || d.Status == channel.FAILED { // event sent ,ack back to publisher\n\t\t\t\t\t\tpostProcessFn(d.Address, d.Status)\n\t\t\t\t\t}\n\t\t\t\t} else if d.Type == channel.STATUS {\n\t\t\t\t\tif d.Status == channel.SUCCESS {\n\t\t\t\t\t\tlocalmetrics.UpdateStatusAckCount(d.Address, localmetrics.SUCCESS)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Errorf(\"failed to receive status request to address %s\", d.Address)\n\t\t\t\t\t\tlocalmetrics.UpdateStatusAckCount(d.Address, localmetrics.FAILED)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} // end switch\n\t\tcase <-scConfig.CloseCh:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (d *DSP) ChannelFormat() (ChannelMask, int, SpeakerMode, error) {\n\tvar channelmask C.FMOD_CHANNELMASK\n\tvar numchannels C.int\n\tvar source_speakermode C.FMOD_SPEAKERMODE\n\tres := C.FMOD_DSP_GetChannelFormat(d.cptr, &channelmask, &numchannels, &source_speakermode)\n\treturn ChannelMask(channelmask), int(numchannels), SpeakerMode(source_speakermode), errs[res]\n}", "func convert(c *cli.Context) error {\n\tif isPipe() {\n\n\t\tvar annotatedSequence AnnotatedSequence\n\n\t\t// logic for determining input format, then parses accordingly.\n\t\tif c.String(\"i\") == \"json\" {\n\t\t\tjson.Unmarshal([]byte(stdinToString(os.Stdin)), &annotatedSequence)\n\t\t} else if c.String(\"i\") == \"gbk\" || c.String(\"i\") == \"gb\" {\n\t\t\tannotatedSequence = ParseGbk(stdinToString(os.Stdin))\n\t\t} else if c.String(\"i\") == \"gff\" {\n\t\t\tannotatedSequence = ParseGff(stdinToString(os.Stdin))\n\t\t}\n\n\t\tvar output []byte\n\n\t\t// logic for chosing output format, then builds string to be output.\n\t\tif c.String(\"o\") == \"json\" {\n\t\t\toutput, _ = json.MarshalIndent(annotatedSequence, \"\", \" \")\n\t\t} else if c.String(\"o\") == \"gff\" {\n\t\t\toutput = BuildGff(annotatedSequence)\n\t\t}\n\n\t\t// output to stdout\n\t\tfmt.Print(string(output))\n\n\t\t//\n\t} else {\n\n\t\tvar matches []string\n\n\t\t//take all args and get their pattern matches.\n\t\tfor argIndex := 0; argIndex < c.Args().Len(); argIndex++ {\n\t\t\tmatch, _ := filepath.Glob(c.Args().Get(argIndex))\n\t\t\tmatches = append(matches, match...)\n\t\t}\n\n\t\t//filtering pattern matches for duplicates.\n\t\tmatches = uniqueNonEmptyElementsOf(matches)\n\n\t\t// TODO write basic check to see if input flag or all paths have accepted file extensions.\n\n\t\t// TODO write basic check for reduduncy. I.E converting gff to gff, etc.\n\n\t\t// declaring wait group outside loop\n\t\tvar wg sync.WaitGroup\n\n\t\t// concurrently iterate through each pattern match, read the file, output to new format.\n\t\tfor _, match := range matches {\n\n\t\t\t// incrementing wait group for Go routine\n\t\t\twg.Add(1)\n\n\t\t\t// executing Go routine.\n\t\t\tgo func(match string) {\n\t\t\t\textension := filepath.Ext(match)\n\t\t\t\tvar annotatedSequence AnnotatedSequence\n\n\t\t\t\t// determining which reader to use and parse into AnnotatedSequence struct.\n\t\t\t\tif extension == \".gff\" || c.String(\"i\") == \"gff\" {\n\t\t\t\t\tannotatedSequence = ReadGff(match)\n\t\t\t\t} else if extension == \".gbk\" || extension == \".gb\" || c.String(\"i\") == \"gbk\" || c.String(\"i\") == \"gb\" {\n\t\t\t\t\tannotatedSequence = ReadGbk(match)\n\t\t\t\t} else if extension == \".json\" || c.String(\"i\") == \"json\" {\n\t\t\t\t\tannotatedSequence = ReadJSON(match)\n\t\t\t\t} else {\n\t\t\t\t\t// TODO put default error handling here.\n\t\t\t\t}\n\n\t\t\t\t// determining output format and name, then writing out to name.\n\t\t\t\toutputPath := match[0 : len(match)-len(extension)]\n\t\t\t\tif c.String(\"o\") == \"json\" {\n\t\t\t\t\tWriteJSON(annotatedSequence, outputPath+\".json\")\n\t\t\t\t} else if c.String(\"o\") == \"gff\" {\n\t\t\t\t\tWriteGff(annotatedSequence, outputPath+\".gff\")\n\t\t\t\t}\n\n\t\t\t\t// decrementing wait group.\n\t\t\t\twg.Done()\n\n\t\t\t}(match) // passing match to Go routine anonymous function.\n\n\t\t\t// TODO add delete flag with confirmation.\n\n\t\t}\n\n\t\t// waiting outside for loop for Go routines so they can run concurrently.\n\t\twg.Wait()\n\t}\n\n\treturn nil\n}", "func inFunc(signal uint32) *volatile.Register32 {\n\treturn (*volatile.Register32)(unsafe.Add(unsafe.Pointer(&esp.GPIO.FUNC0_IN_SEL_CFG), uintptr(signal)*4))\n}", "func (d *DSP) Info(name *C.char, version *C.uint, channels, configwidth, configheight *C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetInfo(FMOD_DSP *dsp, char *name, unsigned int *version, int *channels, int *configwidth, int *configheight);\n\treturn ErrNoImpl\n}", "func (fan _Fan) FanIn(done <-chan bool) Pipeline {\n\tvar wg sync.WaitGroup\n\tout := make(chan X)\n\n\toutput := func(pl Pipeline) {\n\t\tdefer wg.Done()\n\t\tfor val := range pl {\n\t\t\tselect {\n\t\t\tcase out <- val:\n\t\t\tcase <-done:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\twg.Add(len(fan))\n\tfor _, val := range fan {\n\t\tgo output(val)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(out)\n\t}()\n\n\treturn out\n}", "func FFTIn(vs ...string) predicate.Form {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Form(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldFFT), v...))\n\t})\n}", "func ProcessInChannel(wg *sync.WaitGroup, scConfig *common.SCConfiguration) {\n\tdefer wg.Done()\n\tfor { //nolint:gosimple\n\t\tselect {\n\t\tcase d := <-scConfig.EventInCh:\n\t\t\tif d.Type == channel.LISTENER {\n\t\t\t\tlog.Warnf(\"amqp disabled,no action taken: request to create listener address %s was called,but transport is not enabled\", d.Address)\n\t\t\t} else if d.Type == channel.SENDER {\n\t\t\t\tlog.Warnf(\"no action taken: request to create sender for address %s was called,but transport is not enabled\", d.Address)\n\t\t\t} else if d.Type == channel.EVENT && d.Status == channel.NEW {\n\t\t\t\tif e, err := v1event.GetCloudNativeEvents(*d.Data); err != nil {\n\t\t\t\t\tlog.Warnf(\"error marshalling event data\")\n\t\t\t\t} else {\n\t\t\t\t\tlog.Warnf(\"amqp disabled,no action taken(can't send to a desitination): logging new event %s\\n\", e.String())\n\t\t\t\t}\n\t\t\t\tout := channel.DataChan{\n\t\t\t\t\tAddress: d.Address,\n\t\t\t\t\tData: d.Data,\n\t\t\t\t\tStatus: channel.SUCCESS,\n\t\t\t\t\tType: channel.EVENT,\n\t\t\t\t\tProcessEventFn: d.ProcessEventFn,\n\t\t\t\t}\n\t\t\t\tif d.OnReceiveOverrideFn != nil {\n\t\t\t\t\tif err := d.OnReceiveOverrideFn(*d.Data, &out); err != nil {\n\t\t\t\t\t\tlog.Errorf(\"error onReceiveOverrideFn %s\", err)\n\t\t\t\t\t\tout.Status = channel.FAILED\n\t\t\t\t\t} else {\n\t\t\t\t\t\tout.Status = channel.SUCCESS\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tscConfig.EventOutCh <- &out\n\t\t\t} else if d.Type == channel.STATUS && d.Status == channel.NEW {\n\t\t\t\tlog.Warnf(\"amqp disabled,no action taken(can't send to a destination): logging new status check %v\\n\", d)\n\t\t\t\tout := channel.DataChan{\n\t\t\t\t\tAddress: d.Address,\n\t\t\t\t\tData: d.Data,\n\t\t\t\t\tStatus: channel.SUCCESS,\n\t\t\t\t\tType: channel.EVENT,\n\t\t\t\t\tProcessEventFn: d.ProcessEventFn,\n\t\t\t\t}\n\t\t\t\tif d.OnReceiveOverrideFn != nil {\n\t\t\t\t\tif err := d.OnReceiveOverrideFn(*d.Data, &out); err != nil {\n\t\t\t\t\t\tlog.Errorf(\"error onReceiveOverrideFn %s\", err)\n\t\t\t\t\t\tout.Status = channel.FAILED\n\t\t\t\t\t} else {\n\t\t\t\t\t\tout.Status = channel.SUCCESS\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-scConfig.CloseCh:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (e *Engine) streamCallback(in, out []float32) {\n\n\tvar left, right float64\n\n\t// if there are new playback events recently encountered append\n\t// them to the active playback events set\n\t//\n\t// NB. for some reason, we can only access activePlaybackEvents at a\n\t// rate of SampleRate / FramesPerBuffer hz (and more confusinhgly\n\t// FramesPerBuffer can vary with each call). This effectively creates\n\t// unlistenably amounts of stutter if the FramesPerBuffer is too high\n\t// (greater than 512 for 44100hz sample rate is already pushing it)\n\tfor i := 0; i < len(e.newPlaybackEvents); i++ {\n\t\te.activePlaybackEvents[<-e.newPlaybackEvents] = true\n\t}\n\n\t// for each (stereo interleaved) output frame\n\tfor n := 0; n < len(out); n += 2 {\n\t\t// clear the current output frame (to avoid explosive accumulation)\n\t\tout[n] = 0.0\n\t\tout[n+1] = 0.0\n\t\t// for each event in the active playback events\n\t\tfor playbackEvent, _ := range e.activePlaybackEvents {\n\t\t\t// accumulate a frame of audio from the event\n\t\t\t// into the output buffer's current frame\n\t\t\tleft, right = playbackEvent.tick()\n\t\t\tout[n] += float32(left)\n\t\t\tout[n+1] += float32(right)\n\t\t}\n\t}\n\n\t// monitor audio input (if not muted and device exists)\n\tif e.inputAmplitude != 0 && e.streamParameters.Input.Device != nil {\n\t\tswitch e.streamParameters.Input.Channels {\n\t\tcase 1:\n\t\t\t// mono\n\t\t\tfor n := 0; n < len(in); n++ {\n\t\t\t\tout[2*n] += in[n] * e.inputAmplitude\n\t\t\t\tout[2*n+1] += in[n] * e.inputAmplitude\n\t\t\t}\n\t\tcase 2:\n\t\t\t// stereo\n\t\t\tfor n := 0; n < len(in); n += 2 {\n\t\t\t\tout[n] += in[n] * e.inputAmplitude\n\t\t\t\tout[n+1] += in[n+1] * e.inputAmplitude\n\t\t\t}\n\t\t}\n\t}\n\n}", "func (d *Demodulator) Process(input []byte) (power, ddm, sdm, ident float64) {\n\tiqToComplex128(input, d.iqData)\n\tmult(d.iqData, d.nco, d.lpfIn[history:history+d.n])\n\t//lowpass(d.lpfIn, d.lpfOut)\n\tmult(d.iqData, d.nco, d.lpfOut[history:history+d.n])\n\t// TODO: subsample lpfOut here?\n\tabs(d.lpfOut[history:history+d.n], d.fftData) // Demodulate the AM signal\n\ts := d.fft.Transform(d.fftData)\n\tcarrier := cmplx.Abs(s[0])\n\tmod150 := (cmplx.Abs(s[15]) + cmplx.Abs(s[len(s)-15])) / carrier * 100\n\tmod90 := (cmplx.Abs(s[9]) + cmplx.Abs(s[len(s)-9])) / carrier * 100\n\tddm = (mod150 - mod90) // 150 Hz dominance (DDM > 0): Fly UP/LEFT\n\tsdm = (mod150 + mod90)\n\tident = (cmplx.Abs(s[102]) + cmplx.Abs(s[len(s)-102])) / carrier * 100\n\tcarrier = carrier / float64(len(s))\n\tpower = 20 * math.Log10(carrier) // Carrier power in dBFS\n\treturn\n}", "func processAudio(out []float32) {\n\tfor i := range out {\n\t\tout[i] = 0\n\t\tfor _, t := range toneMap {\n\t\t\tout[i] += t.next()\n\t\t}\n\t}\n}", "func (sine *Sine) ProcessAudio(out [][2]float32) {\n\tfor i := range out {\n\t\tout[i][0] = float32(math.Sin(2 * math.Pi * sine.phaseL))\n\t\t_, sine.phaseL = math.Modf(sine.phaseL + sine.stepL)\n\t\tout[i][1] = float32(math.Sin(2 * math.Pi * sine.phaseR))\n\t\t_, sine.phaseR = math.Modf(sine.phaseR + sine.stepR)\n\t}\n}", "func (m *Message) DSP() (*DSP, error) {\n\tps, err := m.Parse(\"DSP\")\n\tpst, ok := ps.(*DSP)\n\tif ok {\n\t\treturn pst, err\n\t}\n\treturn nil, err\n}", "func (_HbSwap *HbSwapCallerSession) InputmaskCnt() (*big.Int, error) {\n\treturn _HbSwap.Contract.InputmaskCnt(&_HbSwap.CallOpts)\n}", "func Input(c *cli.Context) error {\n\tvar file string\n\tfmt.Println(\"Enter the output file name\")\n\tfmt.Scan(&file)\n\tif file == \"\" {\n\t\tfile = inputFileName\n\t}\n\n\tvar str string\n\tfmt.Println(\"Enter the music you want to play\")\n\tfmt.Scan(&str)\n\n\tvar score []uint8\n\tfor _, t := range str {\n\t\tscore = append(score, values.Scale(fmt.Sprintf(\"%c\", t)))\n\t}\n\n\tdivision, err := smf.NewDivision(ticks, smf.NOSMTPE)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmidi, err := smf.NewSMF(smf.Format0, *division)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttrack := &smf.Track{}\n\terr = midi.AddTrack(track)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar list []*smf.MIDIEvent\n\tfor i, t := range score {\n\t\tvar d uint32\n\t\tif i != 0 {\n\t\t\td = onDeltaTime\n\t\t}\n\t\ttoneOn, err := smf.NewMIDIEvent(d, smf.NoteOnStatus, 0x00, t, 0x64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlist = append(list, toneOn)\n\t\ttoneOff, err := smf.NewMIDIEvent(offDeltaTime, smf.NoteOffStatus, 0x00, t, 0x64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlist = append(list, toneOff)\n\t}\n\n\tfor _, l := range list {\n\t\tif err := track.AddEvent(l); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tmetaEvent, err := smf.NewMetaEvent(21, smf.MetaEndOfTrack, []byte{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := track.AddEvent(metaEvent); err != nil {\n\t\treturn err\n\t}\n\n\toutputMidi, err := os.Create(fmt.Sprintf(\"./%s.mid\", file))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer outputMidi.Close()\n\n\twriter := bufio.NewWriter(outputMidi)\n\tsmfio.Write(writer, midi)\n\treturn writer.Flush()\n}", "func (d *Driver) Ins() (ins []drivers.In, err error) {\n\tvar num int\n\tfor i := 0; i < portmidi.CountDevices(); i++ {\n\t\tinfo := portmidi.Info(portmidi.DeviceID(i))\n\t\tif info != nil && info.IsInputAvailable {\n\t\t\tins = append(ins, newIn(d, portmidi.DeviceID(i), num, info.Name))\n\t\t\tnum++\n\t\t}\n\t}\n\treturn\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calls the DSP unit's reset function, which will clear internal buffers and reset the unit back to an initial state. Calling this function is useful if the DSP unit relies on a history to process itself (ie an echo filter). If you disconnected the unit and reconnected it to a different part of the network with a different sound, you would want to call this to reset the units state (ie clear and reset the echo filter) so that you dont get left over artifacts from the place it used to be connected.
func (d *DSP) Reset() error { res := C.FMOD_DSP_Reset(d.cptr) return errs[res] }
[ "func Reset() {\n\tDefaultBus.Reset()\n}", "func (arg1 *UConverter) Reset()", "func (g *M3Collector) Reset() {}", "func (e *Engine) Reset() error {\n\treturn e.graph.Reset(e.fadeIn, e.frameSize, e.backend.SampleRate())\n}", "func (s *State)Reset(){\n s.operations = 0\n}", "func (ko *Knockoff) Reset() {\n\tko.chunk = -1\n\tko.data.Reset()\n}", "func (self *PhysicsP2) Reset() {\n self.Object.Call(\"reset\")\n}", "func Reset() {\n\tfdState.reset()\n}", "func Reset() {\n\treset.Set(true)\n}", "func (u *Unit) Reset() {\n\tu.pru.wr(u.ctlBase+c_CONTROL, 0)\n}", "func (eng *engine) Reset() {\n\tif eng.root() != nil {\n\t\teng.disposePov(eng.root().id)\n\t}\n\teng.ids.reset()\n\teng.povs.reset()\n\teng.povs.create(eng, eng.ids.create(), nil) // root\n\teng.cams = newCams()\n\teng.models = newModels(eng)\n\teng.lights = newLights()\n\teng.layers = newLayers(eng)\n\teng.sounds = newSounds(eng)\n\teng.sounds.setListener(eng.povs.get(0))\n\teng.bodies = newBodies()\n\teng.frames = newFrames()\n}", "func (device *AirQualityBricklet) Reset() (err error) {\n\tvar buf bytes.Buffer\n\n\tresultBytes, err := device.device.Set(uint8(FunctionReset), buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(resultBytes) > 0 {\n\t\tvar header PacketHeader\n\n\t\theader.FillFromBytes(resultBytes)\n\n\t\tif header.Length != 8 {\n\t\t\treturn fmt.Errorf(\"Received packet of unexpected size %d, instead of %d\", header.Length, 8)\n\t\t}\n\n\t\tif header.ErrorCode != 0 {\n\t\t\treturn DeviceError(header.ErrorCode)\n\t\t}\n\n\t\tbytes.NewBuffer(resultBytes[8:])\n\n\t}\n\n\treturn nil\n}", "func (device *PerformanceDCBricklet) Reset() (err error) {\n\tvar buf bytes.Buffer\n\n\tresultBytes, err := device.device.Set(uint8(FunctionReset), buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(resultBytes) > 0 {\n\t\tvar header PacketHeader\n\n\t\theader.FillFromBytes(resultBytes)\n\n\t\tif header.Length != 8 {\n\t\t\treturn fmt.Errorf(\"Received packet of unexpected size %d, instead of %d\", header.Length, 8)\n\t\t}\n\n\t\tif header.ErrorCode != 0 {\n\t\t\treturn DeviceError(header.ErrorCode)\n\t\t}\n\n\t\tbytes.NewBuffer(resultBytes[8:])\n\n\t}\n\n\treturn nil\n}", "func (buf *Buffer) reset() {\n\tbuf.DNCReports = nil\n\tbuf.DNCReports = make([]DNCReport, 0)\n\tbuf.CNIReports = nil\n\tbuf.CNIReports = make([]CNIReport, 0)\n\tbuf.NPMReports = nil\n\tbuf.NPMReports = make([]NPMReport, 0)\n\tbuf.CNSReports = nil\n\tbuf.CNSReports = make([]CNSReport, 0)\n\tpayloadSize = 0\n}", "func (c *CmdBuff) Reset() {\n\tc.ClearText(true)\n\tc.SetActive(false)\n\tc.fireBufferCompleted(c.GetText(), c.GetSuggestion())\n}", "func (wgs *WavetableGlottalSource) Reset() {\n\twgs.CurrentPosition = 0\n\twgs.FirFilter.Init(FirBeta, FirGamma, FirCutoff)\n}", "func (c *ChannelData) Reset() {\n\tc.Raw = c.Raw[:0]\n\tc.Length = 0\n\tc.Data = c.Data[:0]\n}", "func (bl *EwLogger) Reset() {\n\tbl.Flush()\n\tfor _, l := range bl.outputs {\n\t\tl.Destroy()\n\t}\n\tbl.outputs = nil\n}", "func (s *Statistics) reset() {\n\ts.cycles++\n\ts.totalMessagesCleared += s.messagesCleared\n\n\ts.memoryCleared = 0\n\ts.messagesCleared = 0\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ DSP parameter control. Sets a DSP unit's floating point parameter by index. To find out the parameter names and range, see the see also field. index: Parameter index for this unit. Find the number of parameters with "DSP.NumParameters". value: Floating point parameter value to be passed to the DSP unit. The parameter properties (such as min/max values) can be retrieved with "DSP.ParameterInfo".
func (d *DSP) SetParameterFloat(index int, value float64) error { res := C.FMOD_DSP_SetParameterFloat(d.cptr, C.int(index), C.float(value)) return errs[res] }
[ "func (d *DSP) ParameterFloat(index C.int, value *C.float, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterFloat(FMOD_DSP *dsp, int index, float *value, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func (d *DSP) DataParameterIndex(datatype C.int, index *C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetDataParameterIndex (FMOD_DSP *dsp, int datatype, int *index);\n\treturn ErrNoImpl\n}", "func (d *DSP) ParameterInfo(index C.int, desc **C.FMOD_DSP_PARAMETER_DESC) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterInfo (FMOD_DSP *dsp, int index, FMOD_DSP_PARAMETER_DESC **desc);\n\treturn ErrNoImpl\n}", "func (d *DSP) SetParameterData(index C.int, data *interface{}, length C.uint) error {\n\t//FMOD_RESULT F_API FMOD_DSP_SetParameterData(FMOD_DSP *dsp, int index, void *data, unsigned int length);\n\treturn ErrNoImpl\n}", "func (p *Param) SetValue(value float64) error {\n\tvar ferr C.FMOD_RESULT\n\tbase.Thread(func() {\n\t\tferr = C.FMOD_EventParameter_SetValue(p.param, C.float(value))\n\t})\n\treturn base.ResultToError(ferr)\n}", "func (d *DSP) ParameterInt(index C.int, value *C.int, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterInt(FMOD_DSP *dsp, int index, int *value, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func (d *DSP) ParameterData(index C.int, data **interface{}, length *C.uint, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterData(FMOD_DSP *dsp, int index, void **data, unsigned int *length, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func (b *fixedResolutionValues) SetValueAt(n int, v float64) {\n\tb.values[n] = v\n}", "func (d *DSP) ParameterBool(index C.int, value *C.FMOD_BOOL, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterBool(FMOD_DSP *dsp, int index, FMOD_BOOL *value, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func (d *DSP) SetParameterInt(index, value int) error {\n\tres := C.FMOD_DSP_SetParameterInt(d.cptr, C.int(index), C.int(value))\n\treturn errs[res]\n}", "func FloatVarP(pv *float64, short rune, long string, value float64, description string) {\n\tif err := parseShortAndLongFlag(short, long); err != nil {\n\t\tpanic(err)\n\t}\n\t*pv = value\n\tflags = append(flags, &optionFloat{\n\t\tdescription: description,\n\t\tlong: long,\n\t\tshort: short,\n\t\tpv: pv,\n\t\tdef: value,\n\t})\n}", "func (this *NamedParameterQuery) SetValue(parameterName string, parameterValue interface{}) {\n\n\tfor _, position := range this.positions[parameterName] {\n\t\tthis.parameters[position] = parameterValue\n\t}\n}", "func (d *DSP) SetParameterBool(index int, value bool) error {\n\tres := C.FMOD_DSP_SetParameterBool(d.cptr, C.int(index), getBool(value))\n\treturn errs[res]\n}", "func (uni *Uniform4fv) Set(idx int, v0, v1, v2, v3 float32) {\n\n\tpos := idx * 4\n\tuni.v[pos] = v0\n\tuni.v[pos+1] = v1\n\tuni.v[pos+2] = v2\n\tuni.v[pos+3] = v3\n}", "func (s *Slider) Float(f *Float) *Slider {\n\ts.float = f\n\treturn s\n}", "func (f *Flags) Float(spec string, p *float64, name, usage string) {\n\tf.addOption(spec, name, usage, func(name, value string) error {\n\t\tf, err := strconv.ParseFloat(value, 64)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid %s argument '%s'\", name, value)\n\t\t}\n\t\t*p = f\n\t\treturn nil\n\t})\n}", "func (c *Constructor[_]) FloatVar(ptr *float64, name string, value float64, help string) {\n\t*ptr = value\n\tc.define(name, paramFloat, help).floatptr = ptr\n}", "func FloatVar(pv *float64, flag string, value float64, description string) {\n\tshort, long, err := parseSingleFlag(flag)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t*pv = value\n\tflags = append(flags, &optionFloat{\n\t\tdescription: description,\n\t\tlong: long,\n\t\tshort: short,\n\t\tpv: pv,\n\t\tdef: value,\n\t})\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}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets a DSP unit's integer parameter by index. To find out the parameter names and range, see the see also field. index: Parameter index for this unit. Find the number of parameters with "DSP.NumParameters". value: Integer parameter value to be passed to the DSP unit. The parameter properties (such as min/max values) can be retrieved with "DSP.ParameterInfo".
func (d *DSP) SetParameterInt(index, value int) error { res := C.FMOD_DSP_SetParameterInt(d.cptr, C.int(index), C.int(value)) return errs[res] }
[ "func (d *DSP) ParameterInt(index C.int, value *C.int, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterInt(FMOD_DSP *dsp, int index, int *value, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func (d *DSP) DataParameterIndex(datatype C.int, index *C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetDataParameterIndex (FMOD_DSP *dsp, int datatype, int *index);\n\treturn ErrNoImpl\n}", "func (d *DSP) SetParameterData(index C.int, data *interface{}, length C.uint) error {\n\t//FMOD_RESULT F_API FMOD_DSP_SetParameterData(FMOD_DSP *dsp, int index, void *data, unsigned int length);\n\treturn ErrNoImpl\n}", "func (d *DSP) ParameterInfo(index C.int, desc **C.FMOD_DSP_PARAMETER_DESC) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterInfo (FMOD_DSP *dsp, int index, FMOD_DSP_PARAMETER_DESC **desc);\n\treturn ErrNoImpl\n}", "func (m *TeleconferenceDeviceMediaQuality) SetChannelIndex(value *int32)() {\n err := m.GetBackingStore().Set(\"channelIndex\", value)\n if err != nil {\n panic(err)\n }\n}", "func (b *fixedResolutionValues) SetValueAt(n int, v float64) {\n\tb.values[n] = v\n}", "func (instance *Instance) SetInt(fieldName string, value int) error {\n\tfieldNameCStr := C.CString(fieldName)\n\tdefer C.free(unsafe.Pointer(fieldNameCStr))\n\n\tC.RTIDDSConnector_setNumberIntoSamples(unsafe.Pointer(instance.output.connector.native), instance.output.nameCStr, fieldNameCStr, C.double(value))\n\treturn nil\n}", "func (instance *Instance) SetInt(fieldName string, value int) error {\n\tfieldNameCStr := C.CString(fieldName)\n\tdefer C.free(unsafe.Pointer(fieldNameCStr))\n\n\tretcode := int(C.RTI_Connector_set_number_into_samples(unsafe.Pointer(instance.output.connector.native), instance.output.nameCStr, fieldNameCStr, C.double(value)))\n\treturn checkRetcode(retcode)\n}", "func (c *Client) SetParamInt(key string, val int) error {\n\treq := RequestParamSetInt{\n\t\tCallerID: c.callerID,\n\t\tKey: key,\n\t\tVal: val,\n\t}\n\n\tvar res ResponseSetParam\n\terr := c.xc.Do(\"setParam\", req, &res)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif res.Code != 1 {\n\t\treturn fmt.Errorf(\"server returned an error (%d): %s\", res.Code, res.StatusMessage)\n\t}\n\n\treturn nil\n}", "func (service *GameStateService) SetIntegerVariable(index int, info archive.GameVariableInfo) error {\n\treturn service.registry.Register(cmd.Named(\"SetIntegerVariable\"),\n\t\tcmd.Forward(setVariableTask(service.integerVariables, index, info)),\n\t\tcmd.Reverse(restoreVariableTask(service.integerVariables, index)))\n}", "func (d *DSP) ParameterData(index C.int, data **interface{}, length *C.uint, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterData(FMOD_DSP *dsp, int index, void **data, unsigned int *length, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func (gdt *Array) Set(idx Int, value Variant) {\n\targ0 := gdt.getBase()\n\targ1 := idx.getBase()\n\targ2 := value.getBase()\n\n\tC.go_godot_array_set(GDNative.api, arg0, arg1, arg2)\n}", "func (spriteBatch *SpriteBatch) Set(index int, args ...float32) error {\n\treturn spriteBatch.addv(spriteBatch.texture.getVerticies(), generateModelMatFromArgs(args), index)\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 (v Value) SetIndex(i int, x interface{}) {\n\tpanic(message)\n}", "func (m *RecurrencePattern) SetIndex(value *WeekIndex)() {\n m.index = value\n}", "func SetPort(v string) func(*Manager) error {\n\treturn func(c *Manager) error {\n\t\tport, err := strconv.Atoi(v)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Invalid port; non-number.\")\n\t\t}\n\t\tif port < 65536 && port > -1 {\n\t\t\tc.samport = v\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"Invalid port.\")\n\t}\n}", "func (this *NamedParameterQuery) SetValue(parameterName string, parameterValue interface{}) {\n\n\tfor _, position := range this.positions[parameterName] {\n\t\tthis.parameters[position] = parameterValue\n\t}\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}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets a DSP unit's boolean parameter by index. To find out the parameter names and range, see the see also field. index: Parameter index for this unit. Find the number of parameters with "DSP.NumParameters". value: Boolean parameter value to be passed to the DSP unit. Should be TRUE or FALSE. The parameter properties (such as min/max values) can be retrieved with "DSP.ParameterInfo".
func (d *DSP) SetParameterBool(index int, value bool) error { res := C.FMOD_DSP_SetParameterBool(d.cptr, C.int(index), getBool(value)) return errs[res] }
[ "func (d *DSP) ParameterBool(index C.int, value *C.FMOD_BOOL, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterBool(FMOD_DSP *dsp, int index, FMOD_BOOL *value, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func (service *GameStateService) SetBooleanVariable(index int, info archive.GameVariableInfo) error {\n\treturn service.registry.Register(cmd.Named(\"SetBooleanVariable\"),\n\t\tcmd.Forward(setVariableTask(service.booleanVariables, index, info)),\n\t\tcmd.Reverse(restoreVariableTask(service.booleanVariables, index)))\n}", "func (b *BoolMatrixLinear) SetBool(i, j int, value bool) bool {\n\tif i > b.heigh || j > b.width {\n\t\treturn false\n\t}\n\tb.matrix[i*b.width+j] = value\n\treturn true\n}", "func (instance *Instance) SetBoolean(fieldName string, value bool) error {\n\tfieldNameCStr := C.CString(fieldName)\n\tdefer C.free(unsafe.Pointer(fieldNameCStr))\n\n\tvar intValue int\n\tif value {\n\t\tintValue = 1\n\t} else {\n\t\tintValue = 0\n\t}\n\tC.RTIDDSConnector_setBooleanIntoSamples(unsafe.Pointer(instance.output.connector.native), instance.output.nameCStr, fieldNameCStr, C.int(intValue))\n\treturn nil\n}", "func (sp *shaderProgram) setBool(name *uint8, value bool) {\n\tif value {\n\t\tgl.Uniform1i(gl.GetUniformLocation(sp.program, name), 1)\n\t}\n\n\tgl.Uniform1i(gl.GetUniformLocation(sp.program, name), 0)\n}", "func (instance *Instance) SetBoolean(fieldName string, value bool) error {\n\tfieldNameCStr := C.CString(fieldName)\n\tdefer C.free(unsafe.Pointer(fieldNameCStr))\n\n\tintValue := 0\n\tif value {\n\t\tintValue = 1\n\t}\n\tretcode := int(C.RTI_Connector_set_boolean_into_samples(unsafe.Pointer(instance.output.connector.native), instance.output.nameCStr, fieldNameCStr, C.int(intValue)))\n\treturn checkRetcode(retcode)\n}", "func (c *Client) SetParamBool(key string, val bool) error {\n\treq := RequestParamSetBool{\n\t\tCallerID: c.callerID,\n\t\tKey: key,\n\t\tVal: val,\n\t}\n\n\tvar res ResponseSetParam\n\terr := c.xc.Do(\"setParam\", req, &res)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif res.Code != 1 {\n\t\treturn fmt.Errorf(\"server returned an error (%d): %s\", res.Code, res.StatusMessage)\n\t}\n\n\treturn nil\n}", "func WriteBool(buffer []byte, offset int, value bool) {\n if value {\n buffer[offset] = 1\n } else {\n buffer[offset] = 0\n }\n}", "func (args Arguments) Bool(index int) bool {\n\tvar s bool\n\tvar ok bool\n\tif s, ok = args.Get(index).(bool); !ok {\n\t\tpanic(fmt.Sprintf(\"assert: arguments: Bool(%d) failed because object wasn't correct type: %v\", index, args.Get(index)))\n\t}\n\treturn s\n}", "func (access BoolAccess) Set(row int, val bool) {\n access.rawData[access.indices[row]] = val\n}", "func (s *BoolSetting) SetValue(v interface{}) error {\n\tvar err error\n\t*s.BoolValue, err = cast.ToBoolE(v)\n\treturn err\n}", "func (a *BooleanArchive) SetValue(entryIndex int, value bool) {\n\tif entryIndex >= a.size {\n\t\toutOfBoundsError := errors.New(\"index out of range\")\n\t\tpanic(outOfBoundsError)\n\t}\n\ta.setValueUnchecked(entryIndex, value)\n\ta.resetCache()\n}", "func setSrvConfBool(key string, value string, conf *SrvConf) {\n if value == \"true\" {\n conf.B[key] = true;\n } else if value == \"false\" {\n conf.B[key] = false;\n } else {\n util.PrintTime();\n fmt.Printf(\"Directive %s: expected boolean, got %s\\n\", key, value);\n }\n}", "func WriteBool(p thrift.TProtocol, value bool, name string, field int16) error {\n\treturn WriteBoolWithContext(context.Background(), p, value, name, field)\n}", "func (b *AtomBool) Set(value bool) {\n\tvar i int32 = 0\n\tif value {\n\t\ti = 1\n\t}\n\tatomic.StoreInt32(&(b.flag), int32(i))\n}", "func (r *R1_eg) setBit(idx1 int, value int) {\n\tr.Values[idx1] = value\n}", "func SetBit(b byte, idx uint, flag bool) byte {\n\tif idx < 0 || idx > 7 {\n\t\tlog.Panic(\"the idx must be from 0 to 7\")\n\t}\n\tif flag {\n\t\treturn b | (1 << idx)\n\t}\n\treturn b &^ (1 << idx)\n}", "func TestExecutor_Execute_SetBool(t *testing.T) {\n\tt.Run(\"Basic\", func(t *testing.T) {\n\t\tc := test.MustRunCluster(t, 1)\n\t\tdefer c.Close()\n\t\thldr := test.Holder{Holder: c[0].Server.Holder()}\n\n\t\t// Create fields.\n\t\tindex := hldr.MustCreateIndexIfNotExists(\"i\", pilosa.IndexOptions{})\n\t\tif _, err := index.CreateFieldIfNotExists(\"f\", pilosa.OptFieldTypeBool()); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\t// Set a true bit.\n\t\tif res, err := c[0].API.Query(context.Background(), &pilosa.QueryRequest{Index: \"i\", Query: `Set(100, f=true)`}); err != nil {\n\t\t\tt.Fatal(err)\n\t\t} else if !res.Results[0].(bool) {\n\t\t\tt.Fatalf(\"expected column changed\")\n\t\t}\n\n\t\t// Set the same bit to true again verify nothing changed.\n\t\tif res, err := c[0].API.Query(context.Background(), &pilosa.QueryRequest{Index: \"i\", Query: `Set(100, f=true)`}); err != nil {\n\t\t\tt.Fatal(err)\n\t\t} else if res.Results[0].(bool) {\n\t\t\tt.Fatalf(\"expected column to be unchanged\")\n\t\t}\n\n\t\t// Set the same bit to false.\n\t\tif res, err := c[0].API.Query(context.Background(), &pilosa.QueryRequest{Index: \"i\", Query: `Set(100, f=false)`}); err != nil {\n\t\t\tt.Fatal(err)\n\t\t} else if !res.Results[0].(bool) {\n\t\t\tt.Fatalf(\"expected column changed\")\n\t\t}\n\n\t\t// Ensure that the false row is set.\n\t\tif result, err := c[0].API.Query(context.Background(), &pilosa.QueryRequest{Index: \"i\", Query: `Row(f=false)`}); err != nil {\n\t\t\tt.Fatal(err)\n\t\t} else if columns := result.Results[0].(*pilosa.Row).Columns(); !reflect.DeepEqual(columns, []uint64{100}) {\n\t\t\tt.Fatalf(\"unexpected colums: %+v\", columns)\n\t\t}\n\n\t\t// Ensure that the true row is empty.\n\t\tif result, err := c[0].API.Query(context.Background(), &pilosa.QueryRequest{Index: \"i\", Query: `Row(f=true)`}); err != nil {\n\t\t\tt.Fatal(err)\n\t\t} else if columns := result.Results[0].(*pilosa.Row).Columns(); !reflect.DeepEqual(columns, []uint64{}) {\n\t\t\tt.Fatalf(\"unexpected colums: %+v\", columns)\n\t\t}\n\t})\n\tt.Run(\"Error\", func(t *testing.T) {\n\t\tc := test.MustRunCluster(t, 1)\n\t\tdefer c.Close()\n\t\thldr := test.Holder{Holder: c[0].Server.Holder()}\n\n\t\t// Create fields.\n\t\tindex := hldr.MustCreateIndexIfNotExists(\"i\", pilosa.IndexOptions{})\n\t\tif _, err := index.CreateFieldIfNotExists(\"f\", pilosa.OptFieldTypeBool()); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\t// Set bool using a string value.\n\t\tif _, err := c[0].API.Query(context.Background(), &pilosa.QueryRequest{Index: \"i\", Query: `Set(100, f=\"true\")`}); err == nil {\n\t\t\tt.Fatalf(\"expected invalid bool type error\")\n\t\t}\n\n\t\t// Set bool using an integer.\n\t\tif _, err := c[0].API.Query(context.Background(), &pilosa.QueryRequest{Index: \"i\", Query: `Set(100, f=1)`}); err == nil {\n\t\t\tt.Fatalf(\"expected invalid bool type error\")\n\t\t}\n\n\t})\n}", "func (bl *BitList) SetBit(index int, value bool) {\n\titmIndex := index / 32\n\titmBitShift := 31 - (index % 32)\n\tif value {\n\t\tbl.data[itmIndex] = bl.data[itmIndex] | 1<<uint(itmBitShift)\n\t} else {\n\t\tbl.data[itmIndex] = bl.data[itmIndex] & ^(1 << uint(itmBitShift))\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NOTE: Not implement yet Sets a DSP unit's binary data parameter by index. To find out the parameter names and range, see the see also field. The parameter properties (such as min/max values) can be retrieved with "DSP.ParameterInfo".
func (d *DSP) SetParameterData(index C.int, data *interface{}, length C.uint) error { //FMOD_RESULT F_API FMOD_DSP_SetParameterData(FMOD_DSP *dsp, int index, void *data, unsigned int length); return ErrNoImpl }
[ "func (d *DSP) ParameterData(index C.int, data **interface{}, length *C.uint, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterData(FMOD_DSP *dsp, int index, void **data, unsigned int *length, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func (d *DSP) DataParameterIndex(datatype C.int, index *C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetDataParameterIndex (FMOD_DSP *dsp, int datatype, int *index);\n\treturn ErrNoImpl\n}", "func (d *DSP) ParameterInt(index C.int, value *C.int, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterInt(FMOD_DSP *dsp, int index, int *value, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func (d *DSP) ParameterInfo(index C.int, desc **C.FMOD_DSP_PARAMETER_DESC) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterInfo (FMOD_DSP *dsp, int index, FMOD_DSP_PARAMETER_DESC **desc);\n\treturn ErrNoImpl\n}", "func (b *fixedResolutionValues) SetValueAt(n int, v float64) {\n\tb.values[n] = v\n}", "func (d *DSP) ParameterBool(index C.int, value *C.FMOD_BOOL, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterBool(FMOD_DSP *dsp, int index, FMOD_BOOL *value, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func (d *DSP) SetParameterInt(index, value int) error {\n\tres := C.FMOD_DSP_SetParameterInt(d.cptr, C.int(index), C.int(value))\n\treturn errs[res]\n}", "func (d *DSP) ParameterFloat(index C.int, value *C.float, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterFloat(FMOD_DSP *dsp, int index, float *value, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func (gdt *Array) Set(idx Int, value Variant) {\n\targ0 := gdt.getBase()\n\targ1 := idx.getBase()\n\targ2 := value.getBase()\n\n\tC.go_godot_array_set(GDNative.api, arg0, arg1, arg2)\n}", "func (m *Server) SetParam(w http.ResponseWriter, r *http.Request) {\n\n\tif err := r.ParseForm(); err != nil {\n\t\tfmt.Fprintf(w, \"Error: %v\", err)\n\t\treturn\n\t}\n\n\tif v := r.Form.Get(\"servoDelta\"); v != \"\" {\n\t\tval, _ := strconv.ParseUint(v, 10, 8)\n\t\tm.servoDelta = uint8(val)\n\t}\n\n\tif v := r.Form.Get(\"velocity\"); v != \"\" {\n\t\tval, _ := strconv.ParseInt(v, 10, 16)\n\t\tm.velocity = int16(val)\n\t}\n\n\twriteResponse(w, &response{\n\t\tErr: \"\",\n\t\tData: \"OK\",\n\t})\n}", "func (d *DSP) SetParameterFloat(index int, value float64) error {\n\tres := C.FMOD_DSP_SetParameterFloat(d.cptr, C.int(index), C.float(value))\n\treturn errs[res]\n}", "func (d *DSP) SetParameterBool(index int, value bool) error {\n\tres := C.FMOD_DSP_SetParameterBool(d.cptr, C.int(index), getBool(value))\n\treturn errs[res]\n}", "func (s *f64) SetSample(i int, value float64) {\n\ts.buffer[i] = float64(value)\n}", "func (_BondingManager *BondingManagerTransactor) SetParameters(opts *bind.TransactOpts, _unbondingPeriod uint64, _numTranscoders *big.Int, _numActiveTranscoders *big.Int) (*types.Transaction, error) {\n\treturn _BondingManager.contract.Transact(opts, \"setParameters\", _unbondingPeriod, _numTranscoders, _numActiveTranscoders)\n}", "func (x *NetworkConfig_Parameter) SetValue(v []byte) {\n\tif x != nil {\n\t\tx.Value = v\n\t}\n}", "func (v Vector) Set(n int, data float64) {\n\tv.data[n] = data\n}", "func (opt *Int16) SetValue(val int16) {\n\topt.value = &val\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 (this *NamedParameterQuery) SetValue(parameterName string, parameterValue interface{}) {\n\n\tfor _, position := range this.positions[parameterName] {\n\t\tthis.parameters[position] = parameterValue\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NOTE: Not implement yet Retrieves a DSP unit's floating point parameter by index. To find out the parameter names and range, see the see also field. The parameter properties (such as min/max values) can be retrieved with "DSP.ParameterInfo".
func (d *DSP) ParameterFloat(index C.int, value *C.float, valuestr *C.char, valuestrlen C.int) error { //FMOD_RESULT F_API FMOD_DSP_GetParameterFloat(FMOD_DSP *dsp, int index, float *value, char *valuestr, int valuestrlen); return ErrNoImpl }
[ "func (d *DSP) ParameterInfo(index C.int, desc **C.FMOD_DSP_PARAMETER_DESC) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterInfo (FMOD_DSP *dsp, int index, FMOD_DSP_PARAMETER_DESC **desc);\n\treturn ErrNoImpl\n}", "func (d *DSP) ParameterData(index C.int, data **interface{}, length *C.uint, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterData(FMOD_DSP *dsp, int index, void **data, unsigned int *length, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func (d *DSP) DataParameterIndex(datatype C.int, index *C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetDataParameterIndex (FMOD_DSP *dsp, int datatype, int *index);\n\treturn ErrNoImpl\n}", "func (d *DSP) ParameterInt(index C.int, value *C.int, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterInt(FMOD_DSP *dsp, int index, int *value, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func GetSamplerParameterf(sampler uint32, pname GLenum) []float32 {\n\tparams := make([]float32, 4)\n\n\tC.glGetSamplerParameterfv(C.GLuint(sampler), C.GLenum(pname), (*C.GLfloat)(unsafe.Pointer(&params[0])))\n\n\treturn params\n}", "func (d *DSP) SetParameterFloat(index int, value float64) error {\n\tres := C.FMOD_DSP_SetParameterFloat(d.cptr, C.int(index), C.float(value))\n\treturn errs[res]\n}", "func (st *CMD) GetParamByIndex(index int) (CMDParam, error) {\n\tif index >= len(st.Params) {\n\t\treturn CMDParam{}, fmt.Errorf(\"Index out of bounds: %v\", index)\n\t}\n\n\treturn st.Params[index], nil\n}", "func (p Properties) GetFloat(name string) float64 {\n\tfor _, property := range p {\n\t\tif property.Name == name && property.Type == \"float\" {\n\t\t\tv, err := strconv.ParseFloat(property.Value, 64)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn v\n\t\t}\n\t}\n\treturn 0\n}", "func ParamUnit(name, description string) *float64 {\n\tf := &unitFlag{}\n\tflag.Var(f, name, description)\n\tparamNames = append(paramNames, name)\n\treturn &f.value\n}", "func (p *Param) GetValue() (float64, error) {\n\tvar ferr C.FMOD_RESULT\n\tvar value C.float\n\tbase.Thread(func() {\n\t\tferr = C.FMOD_EventParameter_GetValue(p.param, &value)\n\t})\n\treturn float64(value), base.ResultToError(ferr)\n}", "func (uni *Uniform4fv) Get(idx int) (v0, v1, v2, v3 float32) {\n\n\tpos := idx * 4\n\treturn uni.v[pos], uni.v[pos+1], uni.v[pos+2], uni.v[pos+3]\n}", "func GetUniformfv(program uint32, location int32, params *float32) {\n C.glowGetUniformfv(gpGetUniformfv, (C.GLuint)(program), (C.GLint)(location), (*C.GLfloat)(unsafe.Pointer(params)))\n}", "func SamplerParameterf(sampler uint32, pname GLenum, param float32) {\n\tC.glSamplerParameterf(C.GLuint(sampler), C.GLenum(pname), C.GLfloat(param))\n}", "func (af *filtBase) checkFloatParam(p, low, high float64, name string) (float64, error) {\n\tif low <= p && p <= high {\n\t\treturn p, nil\n\t} else {\n\t\terr := fmt.Errorf(\"parameter %v is not in range <%v, %v>\", name, low, high)\n\t\treturn 0, err\n\t}\n}", "func (f *Field) FloatAt(idx int) (float64, error) {\n\tswitch f.Type() {\n\tcase FieldTypeInt8:\n\t\treturn float64(f.At(idx).(int8)), nil\n\tcase FieldTypeNullableInt8:\n\t\tiv := f.At(idx).(*int8)\n\t\tif iv == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn float64(*iv), nil\n\n\tcase FieldTypeInt16:\n\t\treturn float64(f.At(idx).(int16)), nil\n\tcase FieldTypeNullableInt16:\n\t\tiv := f.At(idx).(*int16)\n\t\tif iv == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn float64(*iv), nil\n\n\tcase FieldTypeInt32:\n\t\treturn float64(f.At(idx).(int32)), nil\n\tcase FieldTypeNullableInt32:\n\t\tiv := f.At(idx).(*int32)\n\t\tif iv == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn float64(*iv), nil\n\n\tcase FieldTypeInt64:\n\t\treturn float64(f.At(idx).(int64)), nil\n\tcase FieldTypeNullableInt64:\n\t\tiv := f.At(idx).(*int64)\n\t\tif iv == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn float64(*iv), nil\n\n\tcase FieldTypeUint8:\n\t\treturn float64(f.At(idx).(uint8)), nil\n\tcase FieldTypeNullableUint8:\n\t\tuiv := f.At(idx).(*uint8)\n\t\tif uiv == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn float64(*uiv), nil\n\n\tcase FieldTypeUint16:\n\t\treturn float64(f.At(idx).(uint16)), nil\n\tcase FieldTypeNullableUint16:\n\t\tuiv := f.At(idx).(*uint16)\n\t\tif uiv == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn float64(*uiv), nil\n\n\tcase FieldTypeUint32:\n\t\treturn float64(f.At(idx).(uint32)), nil\n\tcase FieldTypeNullableUint32:\n\t\tuiv := f.At(idx).(*uint32)\n\t\tif uiv == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn float64(*uiv), nil\n\n\t// TODO: third param for loss of precision?\n\t// Maybe something in math/big can help with this (also see https://github.com/golang/go/issues/29463).\n\tcase FieldTypeUint64:\n\t\treturn float64(f.At(idx).(uint64)), nil\n\tcase FieldTypeNullableUint64:\n\t\tuiv := f.At(idx).(*uint64)\n\t\tif uiv == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn float64(*uiv), nil\n\n\tcase FieldTypeFloat32:\n\t\treturn float64(f.At(idx).(float32)), nil\n\tcase FieldTypeNullableFloat32:\n\t\tfv := f.At(idx).(*float32)\n\t\tif fv == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn float64(*fv), nil\n\n\tcase FieldTypeFloat64:\n\t\treturn f.At(idx).(float64), nil\n\tcase FieldTypeNullableFloat64:\n\t\tfv := f.At(idx).(*float64)\n\t\tif fv == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn *fv, nil\n\n\tcase FieldTypeString:\n\t\ts := f.At(idx).(string)\n\t\tft, err := strconv.ParseFloat(s, 64)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\treturn ft, nil\n\tcase FieldTypeNullableString:\n\t\ts := f.At(idx).(*string)\n\t\tif s == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\tft, err := strconv.ParseFloat(*s, 64)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\treturn ft, nil\n\n\tcase FieldTypeBool:\n\t\tif f.At(idx).(bool) {\n\t\t\treturn 1, nil\n\t\t}\n\t\treturn 0, nil\n\n\tcase FieldTypeNullableBool:\n\t\tb := f.At(idx).(*bool)\n\t\tif b == nil || !*b {\n\t\t\treturn 0, nil\n\t\t}\n\t\treturn 1, nil\n\n\tcase FieldTypeTime:\n\t\treturn float64(f.At(idx).(time.Time).UnixNano() / int64(time.Millisecond)), nil\n\tcase FieldTypeNullableTime:\n\t\tt := f.At(idx).(*time.Time)\n\t\tif t == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn float64(t.UnixNano() / int64(time.Millisecond)), nil\n\t}\n\treturn 0, fmt.Errorf(\"unsupported field type %T\", f.Type())\n}", "func floatParam(op *contentstream.ContentStreamOperation) (float64, error) {\n\tif len(op.Params) != 1 {\n\t\terr := errors.New(\"incorrect parameter count\")\n\t\tcommon.Log.Debug(\"ERROR: %#q should have %d input params, got %d %+v\",\n\t\t\top.Operand, 1, len(op.Params), op.Params)\n\t\treturn 0.0, err\n\t}\n\treturn core.GetNumberAsFloat(op.Params[0])\n}", "func (c *Context) ParamFloat(name string) float64 {\n\tf, _ := strconv.ParseFloat(c.params[name], 64)\n\treturn f\n}", "func (this *parameter) Floats() []float64 {\n\tif this.Values == nil {\n\t\treturn nil\n\t} else {\n\t\tres := make([]float64, this.Count())\n\t\tfor i, v := range this.Values {\n\t\t\tres[i] = reflekt.AsFloat(v)\n\t\t}\n\t\treturn res\n\t}\n}", "func (nrn *Neuron) VarByIndex(idx int) float32 {\n\tfv := (*float32)(unsafe.Pointer(uintptr(unsafe.Pointer(nrn)) + uintptr(NeuronVarStart+4*idx)))\n\treturn *fv\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NOTE: Not implement yet Retrieves a DSP unit's integer parameter by index. To find out the parameter names and range, see the see also field. The parameter properties (such as min/max values) can be retrieved with "DSP.ParameterInfo".
func (d *DSP) ParameterInt(index C.int, value *C.int, valuestr *C.char, valuestrlen C.int) error { //FMOD_RESULT F_API FMOD_DSP_GetParameterInt(FMOD_DSP *dsp, int index, int *value, char *valuestr, int valuestrlen); return ErrNoImpl }
[ "func (d *DSP) ParameterInfo(index C.int, desc **C.FMOD_DSP_PARAMETER_DESC) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterInfo (FMOD_DSP *dsp, int index, FMOD_DSP_PARAMETER_DESC **desc);\n\treturn ErrNoImpl\n}", "func (d *DSP) DataParameterIndex(datatype C.int, index *C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetDataParameterIndex (FMOD_DSP *dsp, int datatype, int *index);\n\treturn ErrNoImpl\n}", "func (d *DSP) ParameterData(index C.int, data **interface{}, length *C.uint, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterData(FMOD_DSP *dsp, int index, void **data, unsigned int *length, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func GetRenderbufferParameteri(target, pname Enum) int {\n\tlog.Println(\"GetRenderbufferParameteri: not yet tested (TODO: remove this after it's confirmed to work. Your feedback is welcome.)\")\n\tvar result int32\n\tgl.GetRenderbufferParameteriv(uint32(target), uint32(pname), &result)\n\treturn int(result)\n}", "func (st *CMD) GetParamByIndex(index int) (CMDParam, error) {\n\tif index >= len(st.Params) {\n\t\treturn CMDParam{}, fmt.Errorf(\"Index out of bounds: %v\", index)\n\t}\n\n\treturn st.Params[index], nil\n}", "func (f *linkFrame) GetParamInt(k string) (i int64, err error) {\n v, ok := f.param[k]\n if ok {\n switch v.(type) {\n case int64:\n i = v.(int64)\n break\n default:\n err = errors.New(\"param value \"+k+\" not int\")\n }\n } else {\n err = errors.New(\"params don't have \"+k)\n }\n return\n}", "func GetSamplerParameterIi(sampler uint32, pname GLenum) []int {\n\tparams := make([]int, 4)\n\n\tC.glGetSamplerParameterIiv(C.GLuint(sampler), C.GLenum(pname), (*C.GLint)(unsafe.Pointer(&params[0])))\n\n\treturn params\n}", "func (samples *Samples) GetInt(index int, fieldName string) (value int) {\n\tfieldNameCStr := C.CString(fieldName)\n\tdefer C.free(unsafe.Pointer(fieldNameCStr))\n\n\tvalue = int(C.RTIDDSConnector_getNumberFromSamples(unsafe.Pointer(samples.input.connector.native), samples.input.nameCStr, C.int(index+1), fieldNameCStr))\n\treturn value\n}", "func (mi *MediaInfo) GetIdx(stream_type int, stream_idx int, param string) (result string) {\n\tp := C.CString(param)\n\tst := C.int(stream_type)\n\tsi := C.int(stream_idx)\n\tr := C.GoMediaInfoGetIdx(mi.handle, si, st, p)\n\tresult = C.GoString(r)\n\tC.free(unsafe.Pointer(p))\n\tC.free(unsafe.Pointer(r))\n\treturn\n}", "func (mi *MediaInfo) GetIntIdx(stream_type int, stream_idx int, param string) (ivalue int64) {\n\tresult := mi.GetIdx(stream_type, stream_idx, param)\n\tif result != \"\" {\n\t\tivalue, _ = strconv.ParseInt(result, 10, 64)\n\t}\n\treturn\n}", "func (r PIDParam) Value() int { return int(r) }", "func (t *Function) Param(i int) *Parameter {\n\tif i < 0 || i >= t.NumParam() {\n\t\tpanic(\"cxxtypes: Param index out of range\")\n\t}\n\treturn &t.Params[i]\n}", "func SamplerParameteri(sampler uint32, pname GLenum, param int) {\n\tC.glSamplerParameteri(C.GLuint(sampler), C.GLenum(pname), C.GLint(param))\n}", "func (d *DSP) SetParameterInt(index, value int) error {\n\tres := C.FMOD_DSP_SetParameterInt(d.cptr, C.int(index), C.int(value))\n\treturn errs[res]\n}", "func getParam(memory []int, ip int, rb int, mode ParamMode) int {\n\tswitch mode {\n\tcase POSITION:\n\t\treturn memory[memory[ip]]\n\tcase IMMEDIATE:\n\t\treturn memory[ip]\n\tcase RELATIVE:\n\t\treturn memory[rb+memory[ip]]\n\tdefault:\n\t\tpanic(fmt.Errorf(\"Unknown parameter mode: %d\", mode))\n\t}\n\treturn 0\n}", "func (samples *Samples) GetUint(index int, fieldName string) (value uint) {\n\tfieldNameCStr := C.CString(fieldName)\n\tdefer C.free(unsafe.Pointer(fieldNameCStr))\n\n\tvalue = uint(C.RTIDDSConnector_getNumberFromSamples(unsafe.Pointer(samples.input.connector.native), samples.input.nameCStr, C.int(index+1), fieldNameCStr))\n\treturn value\n}", "func (samples *Samples) GetInt(index int, fieldName string) (int, error) {\n\tvar retVal C.double\n\terr := samples.getNumber(index, fieldName, &retVal)\n\treturn int(retVal), err\n}", "func intParamMetaIndex(L *lua.LState) int {\n\tdata := checkIntParam(L, 1)\n\tL.CheckTypes(2, lua.LTNumber, lua.LTString)\n\n\tswitch lvalue := L.Get(2); lvalue.Type() {\n\tcase lua.LTNumber:\n\t\tindex := int(lua.LVAsNumber(lvalue))\n\t\tif ok := indexIsInRange(index, data); !ok {\n\t\t\tL.ArgError(2, indexOutMessage)\n\t\t}\n\t\tL.Push(lua.LNumber(data.Get(index)))\n\t\treturn 1\n\tcase lua.LTString:\n\t\tkey := lua.LVAsString(lvalue)\n\t\t// find methods\n\t\tmt := L.GetTypeMetatable(intParamMetaName).(*lua.LTable)\n\t\tif fn := mt.RawGetString(key); fn.Type() == lua.LTFunction {\n\t\t\tL.Push(fn)\n\t\t\treturn 1\n\t\t}\n\n\t\t// find data\n\t\tif val, ok := data.GetByStr(key); ok {\n\t\t\tL.Push(lua.LNumber(val))\n\t\t\treturn 1\n\t\t}\n\t\tL.ArgError(2, key+\" is not found in csv\")\n\t}\n\n\tL.Push(lua.LNil)\n\treturn 1\n}", "func (d *DSP) Input(index int) (DSP, DspConnection, error) {\n\tvar input DSP\n\tvar inputconnection DspConnection\n\tres := C.FMOD_DSP_GetInput(d.cptr, C.int(index), &input.cptr, &inputconnection.cptr)\n\treturn input, inputconnection, errs[res]\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NOTE: Not implement yet Retrieves a DSP unit's boolean parameter by index. To find out the parameter names and range, see the see also field. The parameter properties (such as min/max values) can be retrieved with "DSP.ParameterInfo".
func (d *DSP) ParameterBool(index C.int, value *C.FMOD_BOOL, valuestr *C.char, valuestrlen C.int) error { //FMOD_RESULT F_API FMOD_DSP_GetParameterBool(FMOD_DSP *dsp, int index, FMOD_BOOL *value, char *valuestr, int valuestrlen); return ErrNoImpl }
[ "func (d *DSP) SetParameterBool(index int, value bool) error {\n\tres := C.FMOD_DSP_SetParameterBool(d.cptr, C.int(index), getBool(value))\n\treturn errs[res]\n}", "func (samples *Samples) GetBoolean(index int, fieldName string) bool {\n\tfieldNameCStr := C.CString(fieldName)\n\tdefer C.free(unsafe.Pointer(fieldNameCStr))\n\n\tvalue := int(C.RTIDDSConnector_getBooleanFromSamples(unsafe.Pointer(samples.input.connector.native), samples.input.nameCStr, C.int(index+1), fieldNameCStr))\n\treturn value != 0\n}", "func (d *DSP) ParameterInfo(index C.int, desc **C.FMOD_DSP_PARAMETER_DESC) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterInfo (FMOD_DSP *dsp, int index, FMOD_DSP_PARAMETER_DESC **desc);\n\treturn ErrNoImpl\n}", "func (samples *Samples) GetBoolean(index int, fieldName string) (bool, error) {\n\tfieldNameCStr := C.CString(fieldName)\n\tdefer C.free(unsafe.Pointer(fieldNameCStr))\n\n\tvar retVal C.int\n\n\tretcode := int(C.RTI_Connector_get_boolean_from_sample(unsafe.Pointer(samples.input.connector.native), &retVal, samples.input.nameCStr, C.int(index+1), fieldNameCStr))\n\terr := checkRetcode(retcode)\n\n\treturn (retVal != 0), err\n}", "func (service GameStateService) BooleanVariable(index int) archive.GameVariableInfo {\n\tbaseInfo := service.baseInfoProvider().BooleanVariable(index)\n\tprojInfo, perProject := service.booleanVariables[index]\n\tif perProject {\n\t\tprojInfo.Hardcoded = baseInfo.Hardcoded\n\t\treturn projInfo\n\t}\n\treturn baseInfo\n}", "func parseBoolParam(paramName string, gen config.Generator) (bool, error) {\n\tfor _, param := range gen.Params {\n\t\tif param.Key == paramName {\n\t\t\tresult, err := strconv.ParseBool(param.Value)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\treturn result, nil\n\t\t}\n\t}\n\treturn false, nil\n}", "func (c *Client) GetParamBool(key string) (*ResponseGetParamBool, error) {\n\treq := RequestGetParam{\n\t\tCallerID: c.callerID,\n\t\tKey: key,\n\t}\n\n\tvar res ResponseGetParamBool\n\terr := c.xc.Do(\"getParam\", req, &res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif res.Code != 1 {\n\t\treturn nil, fmt.Errorf(\"server returned an error (%d): %s\", res.Code, res.StatusMessage)\n\t}\n\n\treturn &res, nil\n}", "func QueryParamBool(request *http.Request, name string) (bool, IResponse) {\n\tvalueStr := request.URL.Query().Get(name)\n\tvalue, err := strconv.ParseBool(valueStr)\n\tif err != nil {\n\t\treturn false, BadRequest(request, \"Invalid query param %s (value: '%s'): %s\", name, valueStr, err)\n\t}\n\n\treturn value, nil\n}", "func (args Arguments) Bool(index int) bool {\n\tvar s bool\n\tvar ok bool\n\tif s, ok = args.Get(index).(bool); !ok {\n\t\tpanic(fmt.Sprintf(\"assert: arguments: Bool(%d) failed because object wasn't correct type: %v\", index, args.Get(index)))\n\t}\n\treturn s\n}", "func (f *Form) Bool(param string, defaultValue bool) bool {\n\tvals, ok := f.values[param]\n\tif !ok {\n\t\treturn defaultValue\n\t}\n\tparamVal, err := strconv.ParseBool(vals[0])\n\tif err != nil {\n\t\tf.err = err\n\t\treturn defaultValue\n\t}\n\treturn paramVal\n}", "func (c *Context) ParamBool(name string) bool {\n\tb, _ := strconv.ParseBool(c.params[name])\n\treturn b\n}", "func (c *Context) ParamBool(name string) bool {\n\tb, _ := strconv.ParseBool(c.Param(name))\n\treturn b\n}", "func (c Config) GetParameter(name string) (Parameter, bool) {\n\tfor i, v := range c.Parameters {\n\t\tif v.Name == name {\n\t\t\treturn c.Parameters[i], true\n\t\t}\n\t}\n\treturn Parameter{}, false\n}", "func GetBool(name string) bool {\n\t//params, err := url.ParseQuery(r.URL.RawQuery)\n\t//if err != nil {\n\t//\treturn false\n\t//}\n\n\t//value, ok := params[name]\n\t//if !ok {\n\t//\treturn false\n\t//}\n\n\tstrValue := strings.Join([]string{\"\", \"\"}, \"\")\n\tif strValue == \"\" {\n\t\treturn true\n\t}\n\n\tboolValue, err := strconv.ParseBool(strValue)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn boolValue\n}", "func (d *DSP) ParameterInt(index C.int, value *C.int, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterInt(FMOD_DSP *dsp, int index, int *value, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func Boolean(param interface{}) bool {\n\tvar v bool\n\tif param != nil {\n\t\tv = param.(bool)\n\t}\n\treturn v\n}", "func (attrs ippAttrs) getBool(name string) string {\n\tvals := attrs.getAttr(goipp.TypeBoolean, name)\n\tif vals == nil {\n\t\treturn \"\"\n\t}\n\tif vals[0].(goipp.Boolean) {\n\t\treturn \"T\"\n\t}\n\treturn \"F\"\n}", "func Get(name string, parameters map[string]interface{}) (bool, error) {\n\tfeat, err := inst.getFeature(name)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn feat.IsEnabledForParameters(parameters)\n}", "func (d *DSP) DataParameterIndex(datatype C.int, index *C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetDataParameterIndex (FMOD_DSP *dsp, int datatype, int *index);\n\treturn ErrNoImpl\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NOTE: Not implement yet Retrieves a DSP unit's data block parameter by index. To find out the parameter names and range, see the see also field. The parameter properties (such as min/max values) can be retrieved with "DSP.ParameterInfo".
func (d *DSP) ParameterData(index C.int, data **interface{}, length *C.uint, valuestr *C.char, valuestrlen C.int) error { //FMOD_RESULT F_API FMOD_DSP_GetParameterData(FMOD_DSP *dsp, int index, void **data, unsigned int *length, char *valuestr, int valuestrlen); return ErrNoImpl }
[ "func (d *DSP) ParameterInfo(index C.int, desc **C.FMOD_DSP_PARAMETER_DESC) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterInfo (FMOD_DSP *dsp, int index, FMOD_DSP_PARAMETER_DESC **desc);\n\treturn ErrNoImpl\n}", "func (d *DSP) DataParameterIndex(datatype C.int, index *C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetDataParameterIndex (FMOD_DSP *dsp, int datatype, int *index);\n\treturn ErrNoImpl\n}", "func (d *DSP) ParameterInt(index C.int, value *C.int, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterInt(FMOD_DSP *dsp, int index, int *value, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func (st *CMD) GetParamByIndex(index int) (CMDParam, error) {\n\tif index >= len(st.Params) {\n\t\treturn CMDParam{}, fmt.Errorf(\"Index out of bounds: %v\", index)\n\t}\n\n\treturn st.Params[index], nil\n}", "func (d *DSP) ParameterFloat(index C.int, value *C.float, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterFloat(FMOD_DSP *dsp, int index, float *value, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func (d *DSP) SetParameterData(index C.int, data *interface{}, length C.uint) error {\n\t//FMOD_RESULT F_API FMOD_DSP_SetParameterData(FMOD_DSP *dsp, int index, void *data, unsigned int length);\n\treturn ErrNoImpl\n}", "func GetParam(d []*commands.Data, name string) *commands.Data {\n\tfor _, element := range d {\n\t\tif strings.Compare(element.Name, name) == 0 {\n\t\t\treturn element\n\t\t}\n\t}\n\treturn nil\n}", "func (x SSMAccessor) GetParameter(ctx context.Context, in0 *ssm.GetParameterInput) (*ssm.GetParameterOutput, error) {\n action := func(rawPeer interface{}, span *TracingSpan) ([]interface{}, error) {\n client, peer, err := x.Client(rawPeer)\n if err != nil {\n return nil, err\n }\n in0.Name = &peer.Name\n res := make([]interface{}, 1)\n res[0], err = client.GetParameter(in0)\n return res, err\n }\n execRes, execErr := execute(ctx, x.info.peers, \"GetParameter\", action)\n if execErr != nil {\n return nil, execErr\n }\n return execRes[0].(*ssm.GetParameterOutput), nil\n}", "func (m *Mechanism) Parameter() []byte {\n\treturn m.mechanism.Parameter\n}", "func (repo *Repository) GetOneRawDataByIndex(groupname string, series string, index int) (Values, error) {\n\tdata := []Values{}\n\terr := repo.db.Select(&data, `SELECT seq, value, ind FROM RawData\n\t\tWHERE groupname = ? AND series = ? AND ind = ? \n\t\tLIMIT 1`,\n\t\tgroupname, series, index)\n\tif len(data) == 1 {\n\t\treturn data[0], err\n\t}\n\treturn Values{}, errors.New(\"data not found\")\n}", "func (c *common) Parameters() sbcon.Parameters { return c.params }", "func GetTransactionByBlockNumberAndIndex() {\n\n}", "func (b *Block) Parameters() []*autofunc.Variable {\n\tres := []*autofunc.Variable{b.StartVar}\n\tfor _, e := range b.Entries {\n\t\tres = append(res, e.Output)\n\t\tres = append(res, e.Transitions...)\n\t}\n\treturn res\n}", "func (index *SpecIndex) GetParametersNode() *yaml.Node {\n\treturn index.parametersNode\n}", "func GetParameterSets(sample []byte) (sps [][]byte, pps [][]byte) {\n\tsampleLength := uint32(len(sample))\n\tvar pos uint32 = 0\n\tfor {\n\t\tif pos >= sampleLength {\n\t\t\tbreak\n\t\t}\n\t\tnaluLength := binary.BigEndian.Uint32(sample[pos : pos+4])\n\t\tpos += 4\n\t\tnaluHdr := sample[pos]\n\t\tswitch GetNaluType(naluHdr) {\n\t\tcase NALU_SPS:\n\t\t\tsps = append(sps, sample[pos:pos+naluLength])\n\t\tcase NALU_PPS:\n\t\t\tpps = append(pps, sample[pos:pos+naluLength])\n\t\t}\n\t\tpos += naluLength\n\t}\n\treturn sps, pps\n}", "func (r *BlockSeqFunc) Parameters() []*autofunc.Variable {\n\tif l, ok := r.Block.(sgd.Learner); ok {\n\t\treturn l.Parameters()\n\t} else {\n\t\treturn nil\n\t}\n}", "func (options *Options) Param(pos int) interface{} {\n\tif len(options.params) > pos {\n\t\treturn options.params[pos]\n\t}\n\n\treturn nil\n}", "func (l *Libvirt) DomainGetBlkioParameters(Dom Domain, Nparams int32, Flags uint32) (rParams []TypedParam, rNparams int32, err error) {\n\tvar buf []byte\n\n\targs := DomainGetBlkioParametersArgs {\n\t\tDom: Dom,\n\t\tNparams: Nparams,\n\t\tFlags: Flags,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar r response\n\tr, err = l.requestStream(206, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Return value unmarshaling\n\ttpd := typedParamDecoder{}\n\tct := map[string]xdr.TypeDecoder{\"libvirt.TypedParam\": tpd}\n\trdr := bytes.NewReader(r.Payload)\n\tdec := xdr.NewDecoderCustomTypes(rdr, 0, ct)\n\t// Params: []TypedParam\n\t_, err = dec.Decode(&rParams)\n\tif err != nil {\n\t\treturn\n\t}\n\t// Nparams: int32\n\t_, err = dec.Decode(&rNparams)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (c Config) GetParameter(name string) (Parameter, bool) {\n\tfor i, v := range c.Parameters {\n\t\tif v.Name == name {\n\t\t\treturn c.Parameters[i], true\n\t\t}\n\t}\n\treturn Parameter{}, false\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the number of parameters a DSP unit has to control its behaviour. Use this to enumerate all parameters of a DSP unit with "DSP.ParameterInfo".
func (d *DSP) NumParameters() (int, error) { var numparams C.int res := C.FMOD_DSP_GetNumParameters(d.cptr, &numparams) return int(numparams), errs[res] }
[ "func (p PoissonBinomial) NumParameters() int {\n\treturn len(p.p)\n}", "func (s *Trainer) NumParameters() int {\n\treturn s.outputDim * s.nFeatures\n}", "func (this *parameter) Count() int {\n\treturn len(this.Values)\n}", "func (ps *Parameters) Len() int {\n\treturn len(*ps)\n}", "func (p *Parameters) Len() int {\n\treturn len(p.names)\n}", "func (index *SpecIndex) GetComponentParameterCount() int {\n\tif index.root == nil {\n\t\treturn -1\n\t}\n\n\tif index.componentParamCount > 0 {\n\t\treturn index.componentParamCount\n\t}\n\n\tfor i, n := range index.root.Content[0].Content {\n\t\tif i%2 == 0 {\n\t\t\t// openapi 3\n\t\t\tif n.Value == \"components\" {\n\t\t\t\t_, parametersNode := utils.FindKeyNode(\"parameters\", index.root.Content[0].Content[i+1].Content)\n\t\t\t\tif parametersNode != nil {\n\t\t\t\t\tindex.componentLock.Lock()\n\t\t\t\t\tindex.parametersNode = parametersNode\n\t\t\t\t\tindex.componentParamCount = len(parametersNode.Content) / 2\n\t\t\t\t\tindex.componentLock.Unlock()\n\t\t\t\t}\n\t\t\t}\n\t\t\t// openapi 2\n\t\t\tif n.Value == \"parameters\" {\n\t\t\t\tparametersNode := index.root.Content[0].Content[i+1]\n\t\t\t\tif parametersNode != nil {\n\t\t\t\t\tindex.componentLock.Lock()\n\t\t\t\t\tindex.parametersNode = parametersNode\n\t\t\t\t\tindex.componentParamCount = len(parametersNode.Content) / 2\n\t\t\t\t\tindex.componentLock.Unlock()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn index.componentParamCount\n}", "func (d *DSP) ParameterInfo(index C.int, desc **C.FMOD_DSP_PARAMETER_DESC) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterInfo (FMOD_DSP *dsp, int index, FMOD_DSP_PARAMETER_DESC **desc);\n\treturn ErrNoImpl\n}", "func (model *GLM) NumParams() int {\n\treturn len(model.xpos)\n}", "func (t *Function) NumParam() int {\n\treturn len(t.Params)\n}", "func (o *AddOn) GetParameters() (value *AddOnParameterList, ok bool) {\n\tok = o != nil && o.bitmap_&8192 != 0\n\tif ok {\n\t\tvalue = o.parameters\n\t}\n\treturn\n}", "func (s *System) Parameters() []float32 {\n\treturn s.parametersVector\n}", "func (tr *CapacityProvider) 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 countParameterType(b bindingInterface, i interface{}) (ret int) {\n\tt := reflect.TypeOf(i)\n\tret = 0\n\ta := parameterTypeArray(b, true)\n\tfor _, v := range a {\n\t\tif v == t {\n\t\t\tret++\n\t\t}\n\t}\n\treturn\n}", "func (l *Layer) Parameters() []*autofunc.Variable {\n\treturn []*autofunc.Variable{l.Biases, l.Scales}\n}", "func (p *Parameters) Size() int {\n\treturn p.bytes\n}", "func (m *MouseActor) ParamLen() int {\n\tif m.Discrete {\n\t\treturn 1 + len(m.options())\n\t} else {\n\t\treturn 5\n\t}\n}", "func (o *AddOn) Parameters() *AddOnParameterList {\n\tif o != nil && o.bitmap_&8192 != 0 {\n\t\treturn o.parameters\n\t}\n\treturn nil\n}", "func (s *Statement) Parameters() int {\n\treturn int(C.sqlite3_bind_parameter_count(s.cptr))\n}", "func (tr *Configuration) 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}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NOTE: Not implement yet Retrieve information about a specified parameter within the DSP unit. Use "DSP.NumParameters" to find out the number of parameters for this DSP unit.
func (d *DSP) ParameterInfo(index C.int, desc **C.FMOD_DSP_PARAMETER_DESC) error { //FMOD_RESULT F_API FMOD_DSP_GetParameterInfo (FMOD_DSP *dsp, int index, FMOD_DSP_PARAMETER_DESC **desc); return ErrNoImpl }
[ "func (d *DSP) ParameterData(index C.int, data **interface{}, length *C.uint, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterData(FMOD_DSP *dsp, int index, void **data, unsigned int *length, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func (d *DSP) Info(name *C.char, version *C.uint, channels, configwidth, configheight *C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetInfo(FMOD_DSP *dsp, char *name, unsigned int *version, int *channels, int *configwidth, int *configheight);\n\treturn ErrNoImpl\n}", "func (m *Mechanism) Parameter() []byte {\n\treturn m.mechanism.Parameter\n}", "func (d *DSP) ParameterInt(index C.int, value *C.int, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterInt(FMOD_DSP *dsp, int index, int *value, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func (c *common) Parameters() sbcon.Parameters { return c.params }", "func (x SSMAccessor) GetParameter(ctx context.Context, in0 *ssm.GetParameterInput) (*ssm.GetParameterOutput, error) {\n action := func(rawPeer interface{}, span *TracingSpan) ([]interface{}, error) {\n client, peer, err := x.Client(rawPeer)\n if err != nil {\n return nil, err\n }\n in0.Name = &peer.Name\n res := make([]interface{}, 1)\n res[0], err = client.GetParameter(in0)\n return res, err\n }\n execRes, execErr := execute(ctx, x.info.peers, \"GetParameter\", action)\n if execErr != nil {\n return nil, execErr\n }\n return execRes[0].(*ssm.GetParameterOutput), nil\n}", "func (mi *MediaInfo) AvailableParameters() string {\n\treturn mi.Option(\"Info_Parameters\", \"\")\n}", "func (d *DSP) DataParameterIndex(datatype C.int, index *C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetDataParameterIndex (FMOD_DSP *dsp, int datatype, int *index);\n\treturn ErrNoImpl\n}", "func (opt *GuacamoleConfiguration) GetParameter(name string) string {\n\treturn opt.parameters[name]\n}", "func (xmlmc *XmlmcInstStruct) GetParam() string {\n\n\treturn \"<params>\" + xmlmc.paramsxml + \"</params>\"\n}", "func (l *Layer) Parameters() []*autofunc.Variable {\n\treturn []*autofunc.Variable{l.Biases, l.Scales}\n}", "func (c Config) GetParameter(name string) (Parameter, bool) {\n\tfor i, v := range c.Parameters {\n\t\tif v.Name == name {\n\t\t\treturn c.Parameters[i], true\n\t\t}\n\t}\n\treturn Parameter{}, false\n}", "func (scs *SubCommandStruct) ParameterUsage() ([]*cli.Parameter, string) {\n\tif scs.ParameterSetter != nil {\n\t\treturn scs.ParameterSetter.ParameterUsage()\n\t}\n\treturn nil, \"\"\n}", "func (o BackendCredentialsAuthorizationOutput) Parameter() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BackendCredentialsAuthorization) *string { return v.Parameter }).(pulumi.StringPtrOutput)\n}", "func (d *DSP) ParameterFloat(index C.int, value *C.float, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterFloat(FMOD_DSP *dsp, int index, float *value, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func GetParam(d []*commands.Data, name string) *commands.Data {\n\tfor _, element := range d {\n\t\tif strings.Compare(element.Name, name) == 0 {\n\t\t\treturn element\n\t\t}\n\t}\n\treturn nil\n}", "func (s *System) Parameters() []float32 {\n\treturn s.parametersVector\n}", "func (tr *CapacityProvider) 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 (d *DSP) NumParameters() (int, error) {\n\tvar numparams C.int\n\tres := C.FMOD_DSP_GetNumParameters(d.cptr, &numparams)\n\treturn int(numparams), errs[res]\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NOTE: Not implement yet Retrieve the index of the first data parameter of a particular data type. The return code can therefore be used to check whether the DSP supports specific functionality through data parameters of certain types without the need to pass in 'index'.
func (d *DSP) DataParameterIndex(datatype C.int, index *C.int) error { //FMOD_RESULT F_API FMOD_DSP_GetDataParameterIndex (FMOD_DSP *dsp, int datatype, int *index); return ErrNoImpl }
[ "func (d *DSP) ParameterData(index C.int, data **interface{}, length *C.uint, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterData(FMOD_DSP *dsp, int index, void **data, unsigned int *length, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func intParamMetaIndex(L *lua.LState) int {\n\tdata := checkIntParam(L, 1)\n\tL.CheckTypes(2, lua.LTNumber, lua.LTString)\n\n\tswitch lvalue := L.Get(2); lvalue.Type() {\n\tcase lua.LTNumber:\n\t\tindex := int(lua.LVAsNumber(lvalue))\n\t\tif ok := indexIsInRange(index, data); !ok {\n\t\t\tL.ArgError(2, indexOutMessage)\n\t\t}\n\t\tL.Push(lua.LNumber(data.Get(index)))\n\t\treturn 1\n\tcase lua.LTString:\n\t\tkey := lua.LVAsString(lvalue)\n\t\t// find methods\n\t\tmt := L.GetTypeMetatable(intParamMetaName).(*lua.LTable)\n\t\tif fn := mt.RawGetString(key); fn.Type() == lua.LTFunction {\n\t\t\tL.Push(fn)\n\t\t\treturn 1\n\t\t}\n\n\t\t// find data\n\t\tif val, ok := data.GetByStr(key); ok {\n\t\t\tL.Push(lua.LNumber(val))\n\t\t\treturn 1\n\t\t}\n\t\tL.ArgError(2, key+\" is not found in csv\")\n\t}\n\n\tL.Push(lua.LNil)\n\treturn 1\n}", "func (*System_Cpu_Index_Union_Uint32) Is_System_Cpu_Index_Union() {}", "func (d *DSP) ParameterInfo(index C.int, desc **C.FMOD_DSP_PARAMETER_DESC) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterInfo (FMOD_DSP *dsp, int index, FMOD_DSP_PARAMETER_DESC **desc);\n\treturn ErrNoImpl\n}", "func strParamMetaIndex(L *lua.LState) int {\n\tdata := checkStrParam(L, 1)\n\tL.CheckTypes(2, lua.LTNumber, lua.LTString)\n\n\tswitch lvalue := L.Get(2); lvalue.Type() {\n\tcase lua.LTNumber:\n\t\tindex := int(lua.LVAsNumber(lvalue))\n\t\tif ok := indexIsInRange(index, data); !ok {\n\t\t\tL.ArgError(2, indexOutMessage)\n\t\t}\n\t\tL.Push(lua.LString(data.Get(index)))\n\t\treturn 1\n\tcase lua.LTString:\n\t\tkey := lua.LVAsString(lvalue)\n\t\t// find methods\n\t\tmt := L.GetTypeMetatable(strParamMetaName).(*lua.LTable)\n\t\tif fn := mt.RawGetString(key); fn.Type() == lua.LTFunction {\n\t\t\tL.Push(fn)\n\t\t\treturn 1\n\t\t}\n\n\t\t// find data\n\t\tif val, ok := data.GetByStr(key); ok {\n\t\t\tL.Push(lua.LString(val))\n\t\t\treturn 1\n\t\t}\n\t\tL.ArgError(2, key+\" is not found in csv\")\n\t}\n\n\tL.Push(lua.LNil)\n\treturn 1\n}", "func checkIndexType(prgrm *ast.CXProgram, idxIdx ast.CXTypeSignatureIndex) {\n\tidxTypeSig := prgrm.GetCXTypeSignatureFromArray(idxIdx)\n\tvar idxType string\n\n\tidxType = ast.GetFormattedType(prgrm, idxTypeSig)\n\tif idxType != \"i32\" && idxType != \"i64\" {\n\t\tprintln(ast.CompilationError(idxTypeSig.ArgDetails.FileName, idxTypeSig.ArgDetails.FileLine), fmt.Sprintf(\"wrong index type; expected either 'i32' or 'i64', got '%s'\", idxType))\n\t}\n}", "func DataType(d *dwarf.Data, off dwarf.Offset,) (dwarf.Type, error)", "func (d *DSP) ParameterInt(index C.int, value *C.int, valuestr *C.char, valuestrlen C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterInt(FMOD_DSP *dsp, int index, int *value, char *valuestr, int valuestrlen);\n\treturn ErrNoImpl\n}", "func (c Config) IsDataTypeSupported() bool {\n\tsupported := false\n\tfor _, v := range []string{\"int\", \"float\", \"bool\"} {\n\t\tif v == c.Val {\n\t\t\tsupported = true\n\t\t\tbreak\n\t\t}\n\t}\n\treturn supported\n}", "func (*System_Cpu_Index_Union_E_OpenconfigSystem_Cpu_Index) Is_System_Cpu_Index_Union() {}", "func (*OpenconfigSystem_System_Cpus_Cpu_State_Index_Union_Uint32) Is_OpenconfigSystem_System_Cpus_Cpu_State_Index_Union() {}", "func _1043sqlite3VdbeParameterIndex(tls *crt.TLS, _p uintptr /* *TVdbe */, _zName uintptr /* *int8 */, _nName int32) (r int32) {\n\tif _p != 0 && _zName != 0 {\n\t\tgoto _1\n\t}\n\n\treturn int32(0)\n\n_1:\n\treturn _1235sqlite3VListNameToNum(tls, *(*uintptr)(unsafe.Pointer(_p + 116)), _zName, _nName)\n}", "func Index(i interface{}, f interface{}) int {\n\tv1 := reflectSlice(i)\n\tv2 := reflectFunc(f)\n\n\tfor i := 0; i < v1.Len(); i++ {\n\t\te := v1.Index(i)\n\t\tif v2.Call([]reflect.Value{e})[0].Bool() {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func (a aid) dataType() uint32 { return uint32(a & math.MaxUint32) }", "func IsTypeSupported(dataType string) bool {\n\t_, supported := supportedDataTypes[dataType]\n\treturn supported\n}", "func getNumber(api *StackAPI, index int, numType interface{}) bool {\n\tif !api.IsNumber(index) {\n\t\tapi.ArgTypeError(index, ValueTNumber)\n\t\treturn false\n\t}\n\n\tif num, ok := numType.(*int); ok {\n\t\t*num = int(api.GetNumber(index))\n\t\treturn true\n\t}\n\tpanic(\"assert\")\n}", "func (mi *MediaInfo) GetIdx(stream_type int, stream_idx int, param string) (result string) {\n\tp := C.CString(param)\n\tst := C.int(stream_type)\n\tsi := C.int(stream_idx)\n\tr := C.GoMediaInfoGetIdx(mi.handle, si, st, p)\n\tresult = C.GoString(r)\n\tC.free(unsafe.Pointer(p))\n\tC.free(unsafe.Pointer(r))\n\treturn\n}", "func (*OpenconfigSystem_System_Cpus_Cpu_State_Index_Union_E_OpenconfigSystem_System_Cpus_Cpu_State_Index) Is_OpenconfigSystem_System_Cpus_Cpu_State_Index_Union() {}", "func (sl *Slice) IndexByType(t reflect.Type, embeds bool, startIdx int) (int, bool) {\n\tif embeds {\n\t\treturn sl.IndexByFunc(startIdx, func(ch Ki) bool { return ch.TypeEmbeds(t) })\n\t}\n\treturn sl.IndexByFunc(startIdx, func(ch Ki) bool { return ch.Type() == t })\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NOTE: Not implement yet Display or hide a DSP unit configuration dialog box inside the target window. Dialog boxes are used by DSP plugins that prefer to use a graphical user interface to modify their parameters rather than using the other method of enumerating the parameters and using "DSP.SetParameterFloat" / "DSP.SetParameterInt" / "DSP.SetParameterBool" / "DSP.SetParameterData". These are usually VST plugins. FMOD Studio plugins do not have configuration dialog boxes. To find out what size window to create to store the configuration screen, use "DSP.Info" where you can get the width and height.
func (d *DSP) ShowConfigDialog(hwnd *interface{}, show C.FMOD_BOOL) error { //FMOD_RESULT F_API FMOD_DSP_ShowConfigDialog (FMOD_DSP *dsp, void *hwnd, FMOD_BOOL show); return ErrNoImpl }
[ "func (ss *Sim) ConfigGui() *gi.Window {\n\twidth := 1600\n\theight := 1200\n\n\tgi.SetAppName(\"hip\")\n\tgi.SetAppAbout(`This demonstrates a basic Hippocampus model in Leabra. See <a href=\"https://github.com/emer/emergent\">emergent on GitHub</a>.</p>`)\n\n\twin := gi.NewMainWindow(\"hip\", \"Hippocampus Close-Far\", width, height)\n\tss.Win = win\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\tss.ToolBar = tbar\n\n\tsplit := gi.AddNewSplitView(mfr, \"split\")\n\tsplit.Dim = gi.X\n\tsplit.SetStretchMax()\n\n\tsv := giv.AddNewStructView(split, \"sv\")\n\tsv.SetStruct(ss)\n\n\ttv := gi.AddNewTabView(split, \"tv\")\n\n\tnv := tv.AddNewTab(netview.KiT_NetView, \"NetView\").(*netview.NetView)\n\tnv.Var = \"Act\"\n\t// nv.Params.ColorMap = \"Jet\" // default is ColdHot\n\t// which fares pretty well in terms of discussion here:\n\t// https://matplotlib.org/tutorials/colors/colormaps.html\n\tnv.SetNet(ss.Net)\n\tss.NetView = nv\n\tnv.ViewDefaults()\n\n\tplt := tv.AddNewTab(eplot.KiT_Plot2D, \"TrnTrlPlot\").(*eplot.Plot2D)\n\tss.TrnTrlPlot = ss.ConfigTrnTrlPlot(plt, ss.TrnTrlLog)\n\n\tplt = tv.AddNewTab(eplot.KiT_Plot2D, \"TrnEpcPlot\").(*eplot.Plot2D)\n\tss.TrnEpcPlot = ss.ConfigTrnEpcPlot(plt, ss.TrnEpcLog)\n\n\tplt = tv.AddNewTab(eplot.KiT_Plot2D, \"TstTrlPlot\").(*eplot.Plot2D)\n\tss.TstTrlPlot = ss.ConfigTstTrlPlot(plt, ss.TstTrlLog)\n\n\tplt = tv.AddNewTab(eplot.KiT_Plot2D, \"TstEpcPlot\").(*eplot.Plot2D)\n\tss.TstEpcPlot = ss.ConfigTstEpcPlot(plt, ss.TstEpcLog)\n\n\tplt = tv.AddNewTab(eplot.KiT_Plot2D, \"TstCycPlot\").(*eplot.Plot2D)\n\tss.TstCycPlot = ss.ConfigTstCycPlot(plt, ss.TstCycLog)\n\n\tplt = tv.AddNewTab(eplot.KiT_Plot2D, \"RunPlot\").(*eplot.Plot2D)\n\tss.RunPlot = ss.ConfigRunPlot(plt, ss.RunLog)\n\n\tsplit.SetSplits(.3, .7)\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Init\", Icon: \"update\", Tooltip: \"Initialize everything including network weights, and start over. Also applies current params.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tss.Init()\n\t\tvp.SetNeedsFullRender()\n\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"AllOn\", Icon: \"update\", Tooltip: \"Initialize everything including network weights, and start over. Also applies current params.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tss.AllOn()\n\t})\n\n\tsmen := gi.AddNewMenuButton(tbar, \"load\")\n\tsmen.SetText(\"Load\")\n\n\tsmen.Menu.AddAction(gi.ActOpts{Label: \"LoadSem\", Icon: \"update\", Tooltip: \"Initialize everything including network weights, and start over. Also applies current params.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tss.OpenPatsSem()\n\t})\n\n\tsmen.Menu.AddAction(gi.ActOpts{Label: \"LoadStudy\", Icon: \"update\", Tooltip: \"Initialize everything including network weights, and start over. Also applies current params.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tss.OpenPats()\n\t})\n\n\tsmen.Menu.AddAction(gi.ActOpts{Label: \"LoadRP\", Icon: \"update\", Tooltip: \"Initialize everything including network weights, and start over. Also applies current params.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tss.OpenPatsRP()\n\t})\n\n\tsmen.Menu.AddAction(gi.ActOpts{Label: \"Sleep\", Icon: \"update\", Tooltip: \"Initialize everything including network weights, and start over. Also applies current params.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tss.OpenPatsSleep()\n\t})\n\n\ttrmen := gi.AddNewMenuButton(tbar, \"train\")\n\ttrmen.SetText(\"Train\")\n\n\ttrmen.Menu.AddAction(gi.ActOpts{Label: \"TrainHip\", Icon: \"run\", Tooltip: \"Starts the network training, picking up from wherever it may have left off. If not stopped, training will complete the specified number of Runs through the full number of Epochs of training, with testing automatically occuring at the specified interval.\",\n\t\tUpdateFunc: func(act *gi.Action) {\n\t\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tif !ss.IsRunning {\n\t\t\tss.IsRunning = true\n\t\t\ttbar.UpdateActions()\n\t\t\t// ss.Train()\n\t\t\tgo ss.TrainHip()\n\t\t}\n\t})\n\n\ttrmen.Menu.AddAction(gi.ActOpts{Label: \"TrainSem\", Icon: \"run\", Tooltip: \"Starts the network training, picking up from wherever it may have left off. If not stopped, training will complete the specified number of Runs through the full number of Epochs of training, with testing automatically occuring at the specified interval.\",\n\t\tUpdateFunc: func(act *gi.Action) {\n\t\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tif !ss.IsRunning {\n\t\t\tss.IsRunning = true\n\t\t\ttbar.UpdateActions()\n\t\t\t// ss.Train()\n\t\t\tgo ss.TrainSem()\n\t\t}\n\t})\n\n\ttrmen.Menu.AddAction(gi.ActOpts{Label: \"TrainRP\", Icon: \"run\", Tooltip: \"Starts the network training, picking up from wherever it may have left off. If not stopped, training will complete the specified number of Runs through the full number of Epochs of training, with testing automatically occuring at the specified interval.\",\n\t\tUpdateFunc: func(act *gi.Action) {\n\t\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tif !ss.IsRunning {\n\t\t\tss.IsRunning = true\n\t\t\ttbar.UpdateActions()\n\t\t\t// ss.Train()\n\t\t\tgo ss.TrainRetrievalPractice()\n\t\t}\n\t})\n\n\ttrmen.Menu.AddAction(gi.ActOpts{Label: \"TrainSleep\", Icon: \"run\", Tooltip: \"Starts the network training, picking up from wherever it may have left off. If not stopped, training will complete the specified number of Runs through the full number of Epochs of training, with testing automatically occuring at the specified interval.\",\n\t\tUpdateFunc: func(act *gi.Action) {\n\t\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tif !ss.IsRunning {\n\t\t\tss.IsRunning = true\n\t\t\ttbar.UpdateActions()\n\t\t\t// ss.Train()\n\t\t\tgo ss.TrainSleep()\n\t\t}\n\t})\n\n\texmen := gi.AddNewMenuButton(tbar, \"Exp\")\n\texmen.SetText(\"Exp\")\n\n\texmen.Menu.AddAction(gi.ActOpts{Label: \"CloseUn\", Icon: \"update\", Tooltip: \"Initialize everything including network weights, and start over. Also applies current params.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tif !ss.IsRunning {\n\t\t\tss.IsRunning = true\n\t\t\ttbar.UpdateActions()\n\t\t\t// ss.Train()\n\t\t\tgo ss.CloseUnrelated()\n\t\t}\n\t})\n\n\texmen.Menu.AddAction(gi.ActOpts{Label: \"CloseRe\", Icon: \"update\", Tooltip: \"Initialize everything including network weights, and start over. Also applies current params.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tif !ss.IsRunning {\n\t\t\tss.IsRunning = true\n\t\t\ttbar.UpdateActions()\n\t\t\t// ss.Train()\n\t\t\tgo ss.CloseRelated()\n\t\t}\n\t})\n\n\texmen.Menu.AddAction(gi.ActOpts{Label: \"FarUn\", Icon: \"update\", Tooltip: \"Initialize everything including network weights, and start over. Also applies current params.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tif !ss.IsRunning {\n\t\t\tss.IsRunning = true\n\t\t\ttbar.UpdateActions()\n\t\t\t// ss.Train()\n\t\t\tgo ss.FarUnrelated()\n\t\t}\n\t})\n\n\texmen.Menu.AddAction(gi.ActOpts{Label: \"FarRe\", Icon: \"update\", Tooltip: \"Initialize everything including network weights, and start over. Also applies current params.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tif !ss.IsRunning {\n\t\t\tss.IsRunning = true\n\t\t\ttbar.UpdateActions()\n\t\t\t// ss.Train()\n\t\t\tgo ss.FarRelated()\n\t\t}\n\t})\n\n\texmen.Menu.AddAction(gi.ActOpts{Label: \"FullSet\", Icon: \"update\", Tooltip: \"Initialize everything including network weights, and start over. Also applies current params.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tif !ss.IsRunning {\n\t\t\tss.IsRunning = true\n\t\t\ttbar.UpdateActions()\n\t\t\t// ss.Train()\n\t\t\tss.ViewOn = false\n\t\t\tss.CloseUnrelated()\n\t\t\tss.CloseRelated()\n\t\t\tss.FarUnrelated()\n\t\t\tss.FarRelated()\n\t\t}\n\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Stop\", Icon: \"stop\", Tooltip: \"Interrupts running. Hitting Train again will pick back up where it left off.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tss.Stop()\n\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"StepHip\", Icon: \"step-fwd\", Tooltip: \"Advances one training trial at a time.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tif !ss.IsRunning {\n\t\t\tss.IsRunning = true\n\t\t\tss.TrainTrialHip()\n\t\t\tss.IsRunning = false\n\t\t\tvp.SetNeedsFullRender()\n\t\t}\n\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"StepSem\", Icon: \"step-fwd\", Tooltip: \"Advances one training trial at a time.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tif !ss.IsRunning {\n\t\t\tss.IsRunning = true\n\t\t\tss.TrainTrialSem()\n\t\t\tss.IsRunning = false\n\t\t\tvp.SetNeedsFullRender()\n\t\t}\n\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Step Epoch\", Icon: \"fast-fwd\", Tooltip: \"Advances one epoch (complete set of training patterns) at a time.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tif !ss.IsRunning {\n\t\t\tss.IsRunning = true\n\t\t\ttbar.UpdateActions()\n\t\t\tgo ss.TrainEpoch()\n\t\t}\n\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Step Run\", Icon: \"fast-fwd\", Tooltip: \"Advances one full training Run at a time.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tif !ss.IsRunning {\n\t\t\tss.IsRunning = true\n\t\t\ttbar.UpdateActions()\n\t\t\tgo ss.TrainRun()\n\t\t}\n\t})\n\n\ttbar.AddSeparator(\"test\")\n\n\ttbar.AddAction(gi.ActOpts{Label: \"TestTrialSem\", Icon: \"step-fwd\", Tooltip: \"Runs the next testing trial.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tif !ss.IsRunning {\n\t\t\tss.IsRunning = true\n\t\t\tss.TestTrialSem(false) // don't return on trial -- wrap\n\t\t\tss.IsRunning = false\n\t\t\tvp.SetNeedsFullRender()\n\t\t}\n\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"TestTrialH\", Icon: \"step-fwd\", Tooltip: \"Runs the next testing trial.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tif !ss.IsRunning {\n\t\t\tss.IsRunning = true\n\t\t\tss.TestTrialHip(false) // don't return on trial -- wrap\n\t\t\tss.IsRunning = false\n\t\t\tvp.SetNeedsFullRender()\n\t\t}\n\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Test Item\", Icon: \"step-fwd\", Tooltip: \"Prompts for a specific input pattern name to run, and runs it in testing mode.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tgi.StringPromptDialog(vp, \"\", \"Test Item\",\n\t\t\tgi.DlgOpts{Title: \"Test Item\", Prompt: \"Enter the Name of a given input pattern to test (case insensitive, contains given string.\"},\n\t\t\twin.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\t\tdlg := send.(*gi.Dialog)\n\t\t\t\tif sig == int64(gi.DialogAccepted) {\n\t\t\t\t\tval := gi.StringPromptDialogValue(dlg)\n\t\t\t\t\tidxs := ss.TestEnv.Table.RowsByString(\"Name\", val, true, true) // contains, ignoreCase\n\t\t\t\t\tif len(idxs) == 0 {\n\t\t\t\t\t\tgi.PromptDialog(nil, gi.DlgOpts{Title: \"Name Not Found\", Prompt: \"No patterns found containing: \" + val}, true, false, nil, nil)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif !ss.IsRunning {\n\t\t\t\t\t\t\tss.IsRunning = true\n\t\t\t\t\t\t\tfmt.Printf(\"testing index: %v\\n\", idxs[0])\n\t\t\t\t\t\t\tss.TestItem(idxs[0])\n\t\t\t\t\t\t\tss.IsRunning = false\n\t\t\t\t\t\t\tvp.SetNeedsFullRender()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"TestTrialF\", Icon: \"step-fwd\", Tooltip: \"Runs the next testing trial.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tif !ss.IsRunning {\n\t\t\tss.IsRunning = true\n\t\t\tss.TestTrialFull(false) // don't return on trial -- wrap\n\t\t\tss.IsRunning = false\n\t\t\tvp.SetNeedsFullRender()\n\t\t}\n\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Test AllSem\", Icon: \"fast-fwd\", Tooltip: \"Tests all of the testing trials.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tif !ss.IsRunning {\n\t\t\tss.IsRunning = true\n\t\t\ttbar.UpdateActions()\n\t\t\tgo ss.RunTestAllSem()\n\t\t}\n\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Test AllH\", Icon: \"fast-fwd\", Tooltip: \"Tests all of the testing trials.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tif !ss.IsRunning {\n\t\t\tss.IsRunning = true\n\t\t\ttbar.UpdateActions()\n\t\t\tgo ss.RunTestAllHip()\n\t\t}\n\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Test AllHPure\", Icon: \"fast-fwd\", Tooltip: \"Tests all of the testing trials.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tif !ss.IsRunning {\n\t\t\tss.IsRunning = true\n\t\t\ttbar.UpdateActions()\n\t\t\tgo ss.RunTestAllHipPure()\n\t\t}\n\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Test AllF\", Icon: \"fast-fwd\", Tooltip: \"Tests all of the testing trials.\", UpdateFunc: func(act *gi.Action) {\n\t\tact.SetActiveStateUpdt(!ss.IsRunning)\n\t}}, win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\tif !ss.IsRunning {\n\t\t\tss.IsRunning = true\n\t\t\ttbar.UpdateActions()\n\t\t\tgo ss.RunTestAllFull()\n\t\t}\n\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Env\", Icon: \"gear\", Tooltip: \"select training input patterns: Close or Far.\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgiv.CallMethod(ss, \"SetEnv\", vp)\n\t\t})\n\n\ttbar.AddSeparator(\"log\")\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Reset RunLog\", Icon: \"reset\", Tooltip: \"Reset the accumulated log of all Runs, which are tagged with the ParamSet used\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tss.RunLog.SetNumRows(0)\n\t\t\tss.RunPlot.Update()\n\t\t})\n\n\ttbar.AddSeparator(\"misc\")\n\n\ttbar.AddAction(gi.ActOpts{Label: \"New Seed\", 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\tss.NewRndSeed()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"README\", Icon: \"file-markdown\", Tooltip: \"Opens your browser on the README file that contains instructions for how to run this model.\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgi.OpenURL(\"https://github.com/emer/leabra/blob/master/examples/ra25/README.md\")\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\t// note: Command in shortcuts is automatically translated into Control for\n\t// Linux, Windows or Meta for MacOS\n\t// fmen := win.MainMenu.ChildByName(\"File\", 0).(*gi.Action)\n\t// fmen.Menu.AddAction(gi.ActOpts{Label: \"Open\", Shortcut: \"Command+O\"},\n\t// \twin.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t// \t\tFileViewOpenSVG(vp)\n\t// \t})\n\t// fmen.Menu.AddSeparator(\"csep\")\n\t// fmen.Menu.AddAction(gi.ActOpts{Label: \"Close Window\", Shortcut: \"Command+W\"},\n\t// \twin.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t// \t\twin.Close()\n\t// \t})\n\n\tinQuitPrompt := false\n\tgi.SetQuitReqFunc(func() {\n\t\tif inQuitPrompt {\n\t\t\treturn\n\t\t}\n\t\tinQuitPrompt = true\n\t\tgi.PromptDialog(vp, gi.DlgOpts{Title: \"Really Quit?\",\n\t\t\tPrompt: \"Are you <i>sure</i> you want to quit and lose any unsaved params, weights, logs, etc?\"}, true, true,\n\t\t\twin.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\t\tif sig == int64(gi.DialogAccepted) {\n\t\t\t\t\tgi.Quit()\n\t\t\t\t} else {\n\t\t\t\t\tinQuitPrompt = false\n\t\t\t\t}\n\t\t\t})\n\t})\n\n\t// gi.SetQuitCleanFunc(func() {\n\t// \tfmt.Printf(\"Doing final Quit cleanup here..\\n\")\n\t// })\n\n\tinClosePrompt := false\n\twin.SetCloseReqFunc(func(w *gi.Window) {\n\t\tif inClosePrompt {\n\t\t\treturn\n\t\t}\n\t\tinClosePrompt = true\n\t\tgi.PromptDialog(vp, gi.DlgOpts{Title: \"Really Close Window?\",\n\t\t\tPrompt: \"Are you <i>sure</i> you want to close the window? This will Quit the App as well, losing all unsaved params, weights, logs, etc\"}, true, true,\n\t\t\twin.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\t\tif sig == int64(gi.DialogAccepted) {\n\t\t\t\t\tgi.Quit()\n\t\t\t\t} else {\n\t\t\t\t\tinClosePrompt = false\n\t\t\t\t}\n\t\t\t})\n\t})\n\n\twin.SetCloseCleanFunc(func(w *gi.Window) {\n\t\tgo gi.Quit() // once main window is closed, quit\n\t})\n\n\twin.MainMenuUpdated()\n\treturn win\n}", "func ConfigShow() error {\n\n\tfmt.Printf(\"\\nCurrently saved values:\\n\")\n\n\tif Config.Secure {\n\t\tfmt.Printf(\" -https\\n\")\n\t} else {\n\t\tfmt.Printf(\" -http\\n\")\n\t}\n\n\tif Config.Hub != \"\" && Config.Hub != notehub.DefaultAPIService {\n\t\tfmt.Printf(\" -hub %s\\n\", Config.Hub)\n\t}\n\tif Config.App != \"\" {\n\t\tfmt.Printf(\" -app %s\\n\", Config.App)\n\t}\n\tif Config.Product != \"\" {\n\t\tfmt.Printf(\" -product %s\\n\", Config.Product)\n\t}\n\tif Config.Device != \"\" {\n\t\tfmt.Printf(\" -device %s\\n\", Config.Device)\n\t}\n\tif Config.Root != \"\" {\n\t\tfmt.Printf(\" -root %s\\n\", Config.Root)\n\t}\n\tif Config.Cert != \"\" {\n\t\tfmt.Printf(\" -cert %s\\n\", Config.Cert)\n\t}\n\tif Config.Key != \"\" {\n\t\tfmt.Printf(\" -key %s\\n\", Config.Key)\n\t}\n\tif Config.Interface != \"\" {\n\t\tfmt.Printf(\" -interface %s\\n\", Config.Interface)\n\t\tif Config.Port == \"\" {\n\t\t\tfmt.Printf(\" -port -\\n\")\n\t\t\tfmt.Printf(\" -portconfig -\\n\")\n\t\t} else {\n\t\t\tfmt.Printf(\" -port %s\\n\", Config.Port)\n\t\t\tfmt.Printf(\" -portconfig %d\\n\", Config.PortConfig)\n\t\t}\n\t}\n\n\treturn nil\n\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 (dlg *Dialog) Open(x, y int, avp *Viewport2D, cfgFunc func()) bool {\n\tavp = ValidViewport(avp)\n\tif avp == nil {\n\t\treturn false\n\t}\n\twin := avp.Win\n\tif win == nil {\n\t\treturn false\n\t}\n\n\tupdt := dlg.UpdateStart()\n\tif dlg.Modal {\n\t\tdlg.State = DialogOpenModal\n\t} else {\n\t\tdlg.State = DialogOpenModeless\n\t}\n\n\tif DialogsSepWindow {\n\t\twin = NewDialogWin(dlg.Nm, dlg.Title, 100, 100, dlg.Modal)\n\t\twin.AddChild(dlg)\n\t\twin.Viewport = &dlg.Viewport2D\n\t\t// fmt.Printf(\"new win dpi: %v\\n\", win.LogicalDPI())\n\t}\n\n\tdlg.Win = win\n\n\tif cfgFunc != nil {\n\t\tcfgFunc()\n\t}\n\n\tdlg.Init2DTree()\n\tdlg.Style2DTree() // sufficient to get sizes\n\tdlg.LayData.AllocSize = win.Viewport.LayData.AllocSize // give it the whole vp initially\n\tdlg.Size2DTree(0) // collect sizes\n\tdlg.Win = nil\n\n\tframe := dlg.KnownChildByName(\"frame\", 0).(*Frame)\n\tvar vpsz image.Point\n\n\tif DialogsSepWindow {\n\t\tvpsz = frame.LayData.Size.Pref.ToPoint()\n\t} else {\n\t\tvpsz = frame.LayData.Size.Pref.Min(win.Viewport.LayData.AllocSize).ToPoint()\n\t}\n\n\tstw := int(dlg.Sty.Layout.MinWidth.Dots)\n\tsth := int(dlg.Sty.Layout.MinHeight.Dots)\n\t// fmt.Printf(\"dlg stw %v sth %v dpi %v vpsz: %v\\n\", stw, sth, dlg.Sty.UnContext.DPI, vpsz)\n\tvpsz.X = ints.MaxInt(vpsz.X, stw)\n\tvpsz.Y = ints.MaxInt(vpsz.Y, sth)\n\n\t// note: LowPri allows all other events to be processed before dialog\n\twin.ConnectEvent(dlg.This, oswin.KeyChordEvent, LowPri, func(recv, send ki.Ki, sig int64, d interface{}) {\n\t\tkt := d.(*key.ChordEvent)\n\t\tddlg, _ := recv.Embed(KiT_Dialog).(*Dialog)\n\t\tkf := KeyFun(kt.Chord())\n\t\tswitch kf {\n\t\tcase KeyFunAbort:\n\t\t\tddlg.Cancel()\n\t\t\tkt.SetProcessed()\n\t\t}\n\t})\n\twin.ConnectEvent(dlg.This, oswin.KeyChordEvent, LowRawPri, func(recv, send ki.Ki, sig int64, d interface{}) {\n\t\tkt := d.(*key.ChordEvent)\n\t\tddlg, _ := recv.Embed(KiT_Dialog).(*Dialog)\n\t\tkf := KeyFun(kt.Chord())\n\t\tswitch kf {\n\t\tcase KeyFunAccept:\n\t\t\tddlg.Accept()\n\t\t\tkt.SetProcessed()\n\t\t}\n\t})\n\t// this is not a good idea\n\t// win.ConnectEvent(dlg.This, oswin.MouseEvent, LowRawPri, func(recv, send ki.Ki, sig int64, d interface{}) {\n\t// \tme := d.(*mouse.Event)\n\t// \tddlg, _ := recv.Embed(KiT_Dialog).(*Dialog)\n\t// \tif me.Button == mouse.Left && me.Action == mouse.DoubleClick {\n\t// \t\tddlg.Accept()\n\t// \t\tme.SetProcessed()\n\t// \t}\n\t// })\n\n\tif DialogsSepWindow {\n\t\tdlg.UpdateEndNoSig(updt)\n\t\t// fmt.Printf(\"setsz: %v\\n\", vpsz)\n\t\tif !win.HasGeomPrefs {\n\t\t\twin.SetSize(vpsz)\n\t\t}\n\t\twin.GoStartEventLoop()\n\t} else {\n\t\tif x == 0 && y == 0 {\n\t\t\tx = win.Viewport.Geom.Size.X / 3\n\t\t\ty = win.Viewport.Geom.Size.Y / 3\n\t\t}\n\t\tx = ints.MinInt(x, win.Viewport.Geom.Size.X-vpsz.X) // fit\n\t\ty = ints.MinInt(y, win.Viewport.Geom.Size.Y-vpsz.Y) // fit\n\t\tframe := dlg.KnownChild(0).(*Frame)\n\t\tdlg.StylePart(Node2D(frame)) // use special styles\n\t\tbitflag.Set(&dlg.Flag, int(VpFlagPopup))\n\t\tdlg.Resize(vpsz)\n\t\tdlg.Geom.Pos = image.Point{x, y}\n\t\tdlg.UpdateEndNoSig(updt)\n\t\twin.NextPopup = dlg.This\n\t}\n\treturn true\n}", "func (self *RenderWindow) GetSettings() sfWindowSettings {\n return C.sfRenderWindow_GetSettings(self.Cref)\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 (c *FwGeneral) Show() (Config, error) {\n c.con.LogQuery(\"(show) general settings\")\n return c.details(c.con.Show)\n}", "func ShowInfo(format string, a ...interface{}) {\n\tshowWindow(sdl.MESSAGEBOX_INFORMATION, format, a...)\n}", "func ShowPreferencesDialog(parent gtk.IWindow, onMpdReconnect, onQueueColumnsChanged, onPlayerSettingChanged func()) {\n\t// Create the dialog\n\td := &PrefsDialog{\n\t\tonQueueColumnsChanged: onQueueColumnsChanged,\n\t\tonPlayerSettingChanged: onPlayerSettingChanged,\n\t}\n\n\t// Load the dialog layout and map the widgets\n\tbuilder, err := NewBuilder(prefsGlade)\n\tif err == nil {\n\t\terr = builder.BindWidgets(d)\n\t}\n\n\t// Check for errors\n\tif errCheck(err, \"ShowPreferencesDialog(): failed to initialise dialog\") {\n\t\tutil.ErrorDialog(parent, fmt.Sprint(glib.Local(\"Failed to load UI widgets\"), err))\n\t\treturn\n\t}\n\tdefer d.PreferencesDialog.Destroy()\n\n\t// Set the dialog up\n\td.PreferencesDialog.SetTransientFor(parent)\n\n\t// Remove the 2-pixel \"aura\" around the notebook\n\tif box, err := d.PreferencesDialog.GetContentArea(); err == nil {\n\t\tbox.SetBorderWidth(0)\n\t}\n\n\t// Map the handlers to callback functions\n\tbuilder.ConnectSignals(map[string]interface{}{\n\t\t\"on_PreferencesDialog_map\": d.onMap,\n\t\t\"on_Setting_change\": d.onSettingChange,\n\t\t\"on_MpdReconnect\": onMpdReconnect,\n\t\t\"on_ColumnMoveUpToolButton_clicked\": d.onColumnMoveUp,\n\t\t\"on_ColumnMoveDownToolButton_clicked\": d.onColumnMoveDown,\n\t})\n\n\t// Run the dialog\n\td.PreferencesDialog.Run()\n}", "func (d *DSP) Info(name *C.char, version *C.uint, channels, configwidth, configheight *C.int) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetInfo(FMOD_DSP *dsp, char *name, unsigned int *version, int *channels, int *configwidth, int *configheight);\n\treturn ErrNoImpl\n}", "func (hd *hud) setSize(screenX, screenY, screenWidth, screenHeight int) {\n\thd.x, hd.y, hd.w, hd.h = 0, 0, screenWidth, screenHeight\n\thd.scene.SetOrthographic(0, float64(hd.w), 0, float64(hd.h), 0, 10)\n\thd.cx, hd.cy = hd.center()\n}", "func (g *Gui) initWindow(w, h int) {\n\trand.NewSource(time.Now().UnixNano())\n\n\tg.cfg.angle = 45\n\tg.cfg.color.randR = uint8(random(1, 2))\n\tg.cfg.color.randG = uint8(random(1, 2))\n\tg.cfg.color.randB = uint8(random(1, 2))\n\n\tg.cfg.window.w, g.cfg.window.h = float32(w), float32(h)\n\tg.cfg.x = interval{min: 0, max: float64(w)}\n\tg.cfg.y = interval{min: 0, max: float64(h)}\n\n\tg.cfg.color.background = defaultBkgColor\n\tg.cfg.color.fill = defaultFillColor\n\n\tif !resizeXY {\n\t\tg.cfg.window.w, g.cfg.window.h = g.getWindowSize()\n\t}\n\tg.cfg.window.title = \"Preview\"\n}", "func (self *RenderWindow) SetSize(width uint, height uint) void {\n return C.sfRenderWindow_SetSize(self.Cref, width, height)\n}", "func NewWindow() *Window {\n\tfile := ui.NewFileWithName(\":/widget.ui\")\n\tloader := ui.NewUiLoader()\n\twidget := loader.Load(file)\n\n\t// Init main window\n\twindow := ui.NewMainWindow()\n\twindow.SetCentralWidget(widget)\n\twindow.SetWindowTitle(\"DFSS Demonstrator v\" + dfss.Version)\n\n\tw := &Window{\n\t\tQMainWindow: window,\n\t\tscene: &Scene{},\n\t}\n\tw.InstallEventFilter(w)\n\n\t// Load dynamic elements from driver\n\tw.logField = ui.NewTextEditFromDriver(widget.FindChild(\"logField\"))\n\tw.graphics = ui.NewGraphicsViewFromDriver(widget.FindChild(\"graphicsView\"))\n\tw.progress = ui.NewLabelFromDriver(widget.FindChild(\"progressLabel\"))\n\n\tw.playButton = ui.NewPushButtonFromDriver(widget.FindChild(\"playButton\"))\n\tw.stopButton = ui.NewPushButtonFromDriver(widget.FindChild(\"stopButton\"))\n\tw.replayButton = ui.NewPushButtonFromDriver(widget.FindChild(\"replayButton\"))\n\n\tw.quantumField = ui.NewSpinBoxFromDriver(widget.FindChild(\"quantumField\"))\n\tw.speedSlider = ui.NewSliderFromDriver(widget.FindChild(\"speedSlider\"))\n\n\t// Load pixmaps\n\tw.pixmaps = map[string]*ui.QPixmap{\n\t\t\"ttp\": ui.NewPixmapWithFilenameFormatFlags(\":/images/server_key.png\", \"\", ui.Qt_AutoColor),\n\t\t\"platform\": ui.NewPixmapWithFilenameFormatFlags(\":/images/server_connect.png\", \"\", ui.Qt_AutoColor),\n\t}\n\n\t// Load icons\n\tw.addIcons()\n\n\t// Add actions\n\tw.addActions()\n\tw.initScene()\n\tw.initTimer()\n\n\tw.StatusBar().ShowMessage(\"Ready\")\n\tw.PrintQuantumInformation()\n\treturn w\n}", "func Show(app fyne.App) {\n c := newCalculator()\n c.loadUI(app)\n}", "func createComponentWindow(sX, sY, sW, sH float32) *gui.Window {\n\t// create a window for operating on the component file\n\tcomponentWindow := uiman.NewWindow(\"Component\", sX, sY, sW, sH, func(wnd *gui.Window) {\n\t\tloadComponent, _ := wnd.Button(\"componentFileLoadButton\", \"Load\")\n\t\tsaveComponent, _ := wnd.Button(\"componentFileSaveButton\", \"Save\")\n\t\twnd.Editbox(\"componentFileEditbox\", &flagComponentFile)\n\t\tif saveComponent {\n\t\t\terr := doSaveComponent(&theComponent, flagComponentFile)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Failed to save the component.\\n%v\\n\", err)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Saved the component file: %s\\n\", flagComponentFile)\n\t\t\t}\n\t\t}\n\n\t\tif loadComponent {\n\t\t\t// remove all existing mesh windows\n\t\t\tcloseAllMeshWindows()\n\t\t\t// load the component file again and create mesh windows / renderables\n\t\t\tdoLoadComponentFile(flagComponentFile)\n\t\t}\n\n\t\twnd.Separator()\n\t\twnd.RequestItemWidthMin(textWidth)\n\t\twnd.Text(\"Name\")\n\t\twnd.Editbox(\"componentNameEditbox\", &theComponent.Name)\n\n\t\t// do the user interface for mesh windows\n\t\twnd.Separator()\n\t\twnd.RequestItemWidthMin(textWidth)\n\t\twnd.Text(\"Meshes:\")\n\t\taddMesh, _ := wnd.Button(\"componentFileAddMeshButton\", \"Add Mesh\")\n\t\tif addMesh {\n\t\t\tdoAddMesh()\n\t\t}\n\n\t\tmeshesThatSurvive := theComponent.Meshes[:0]\n\t\tfor compMeshIndex, compMesh := range theComponent.Meshes {\n\t\t\twnd.StartRow()\n\t\t\twnd.RequestItemWidthMin(textWidth)\n\t\t\twnd.Text(fmt.Sprintf(\"%s\", compMesh.Name))\n\t\t\tshowMeshWnd, _ := wnd.Button(fmt.Sprintf(\"buttonShowMesh%d\", compMeshIndex), \"Show\")\n\t\t\thideMeshWnd, _ := wnd.Button(fmt.Sprintf(\"buttonHideMesh%d\", compMeshIndex), \"Hide\")\n\t\t\tdeleteMesh, _ := wnd.Button(fmt.Sprintf(\"buttonDeleteMesh%d\", compMeshIndex), \"Delete\")\n\t\t\tif showMeshWnd {\n\t\t\t\tdoShowMeshWindow(compMesh)\n\t\t\t}\n\t\t\tif hideMeshWnd || deleteMesh {\n\t\t\t\tdoHideMeshWindow(compMesh)\n\t\t\t}\n\t\t\tif !deleteMesh {\n\t\t\t\tmeshesThatSurvive = append(meshesThatSurvive, compMesh)\n\t\t\t} else {\n\t\t\t\tdoDeleteMesh(compMesh.Name)\n\t\t\t}\n\n\t\t}\n\t\t// FIXME: not Destroying renderables for meshes that don't survive\n\t\ttheComponent.Meshes = meshesThatSurvive\n\n\t\t// do the user interface for colliders\n\t\twnd.Separator()\n\t\twnd.RequestItemWidthMin(textWidth)\n\t\twnd.Text(\"Colliders: \")\n\t\taddNewCollider, _ := wnd.Button(\"buttonAddCollider\", \"Add Collider\")\n\t\tif addNewCollider {\n\t\t\tdoAddCollider(&theComponent)\n\t\t}\n\n\t\tcollidersThatSurvive := theComponent.Collisions[:0]\n\t\tvisibleCollidersThatSurvive := visibleColliders[:0]\n\t\tfor colliderIndex, collider := range theComponent.Collisions {\n\t\t\twnd.StartRow()\n\t\t\twnd.RequestItemWidthMin(textWidth)\n\t\t\twnd.Text(fmt.Sprintf(\"Collider %d:\", colliderIndex))\n\n\t\t\tdelCollider, _ := wnd.Button(fmt.Sprintf(\"buttonDeleteCollider%d\", colliderIndex), \"X\")\n\t\t\tprevColliderType, _ := wnd.Button(fmt.Sprintf(\"buttonPrevColliderType%d\", colliderIndex), \"<\")\n\t\t\tnextColliderType, _ := wnd.Button(fmt.Sprintf(\"buttonNextColliderType%d\", colliderIndex), \">\")\n\n\t\t\tif !delCollider {\n\t\t\t\tcollidersThatSurvive = append(collidersThatSurvive, collider)\n\n\t\t\t\tif prevColliderType {\n\t\t\t\t\tdoPrevColliderType(collider)\n\t\t\t\t}\n\t\t\t\tif nextColliderType {\n\t\t\t\t\tdoNextColliderType(collider)\n\t\t\t\t}\n\n\t\t\t\tswitch collider.Type {\n\t\t\t\tcase component.ColliderTypeAABB:\n\t\t\t\t\twnd.Text(\"Axis Aligned Bounding Box\")\n\t\t\t\t\twnd.StartRow()\n\t\t\t\t\twnd.Space(textWidth)\n\t\t\t\t\twnd.RequestItemWidthMin(width4Col)\n\t\t\t\t\twnd.Text(\"Min\")\n\t\t\t\t\tguiAddDragSliderVec3(wnd, width4Col, \"ColliderMin\", colliderIndex, 0.01, &collider.Min)\n\n\t\t\t\t\twnd.StartRow()\n\t\t\t\t\twnd.Space(textWidth)\n\t\t\t\t\twnd.RequestItemWidthMin(width4Col)\n\t\t\t\t\twnd.Text(\"Max\")\n\t\t\t\t\tguiAddDragSliderVec3(wnd, width4Col, \"ColliderMax\", colliderIndex, 0.01, &collider.Max)\n\n\t\t\t\tcase component.ColliderTypeSphere:\n\t\t\t\t\twnd.Text(\"Sphere\")\n\t\t\t\t\twnd.StartRow()\n\t\t\t\t\twnd.Space(textWidth)\n\t\t\t\t\twnd.RequestItemWidthMin(width4Col)\n\t\t\t\t\twnd.Text(\"Offset\")\n\t\t\t\t\tguiAddDragSliderVec3(wnd, width4Col, \"ColliderOffset\", colliderIndex, 0.01, &collider.Offset)\n\n\t\t\t\t\twnd.StartRow()\n\t\t\t\t\twnd.Space(textWidth)\n\t\t\t\t\twnd.RequestItemWidthMin(width4Col)\n\t\t\t\t\twnd.Text(\"Radius\")\n\t\t\t\t\twnd.DragSliderFloat(fmt.Sprintf(\"ColliderRadius%d\", colliderIndex), 0.01, &collider.Radius)\n\t\t\t\tdefault:\n\t\t\t\t\twnd.Text(fmt.Sprintf(\"Unknown collider (%d)!\", collider.Type))\n\t\t\t\t}\n\n\t\t\t\t// see if we need to update the renderable if it exists already\n\t\t\t\tvisibleColliders = doUpdateVisibleCollider(visibleColliders, collider, colliderIndex)\n\t\t\t\tvisibleCollidersThatSurvive = append(visibleCollidersThatSurvive, visibleColliders[colliderIndex])\n\t\t\t}\n\t\t}\n\t\ttheComponent.Collisions = collidersThatSurvive\n\t\tvisibleColliders = visibleCollidersThatSurvive\n\n\t\twnd.Separator()\n\t\twnd.RequestItemWidthMin(textWidth)\n\t\twnd.Text(\"Child Components:\")\n\t\taddChildComponent, _ := wnd.Button(\"addChildComponent\", \"Add Child\")\n\t\tif addChildComponent {\n\t\t\tdoAddChildReference(&theComponent)\n\t\t}\n\n\t\tchildRefsThatSurvive := theComponent.ChildReferences[:0]\n\t\tfor childRefIndex, childRef := range theComponent.ChildReferences {\n\t\t\twnd.StartRow()\n\t\t\twnd.RequestItemWidthMin(textWidth)\n\t\t\twnd.Text(\"File:\")\n\t\t\tremoveReference, _ := wnd.Button(fmt.Sprintf(\"childRefRemove%d\", childRefIndex), \"X\")\n\t\t\tloadChildReference, _ := wnd.Button(fmt.Sprintf(\"childRefLoad%d\", childRefIndex), \"L\")\n\t\t\twnd.Editbox(fmt.Sprintf(\"childRefFileEditbox%d\", childRefIndex), &childRef.File)\n\n\t\t\twnd.StartRow()\n\t\t\twnd.Space(textWidth)\n\t\t\twnd.RequestItemWidthMin(width4Col)\n\t\t\twnd.Text(\"Offset\")\n\t\t\tguiAddDragSliderVec3(wnd, width4Col, \"childRefLocation\", childRefIndex, 0.01, &childRef.Location)\n\n\t\t\twnd.StartRow()\n\t\t\twnd.Space(textWidth)\n\t\t\twnd.RequestItemWidthMin(width4Col)\n\t\t\twnd.Text(\"Scale\")\n\t\t\tguiAddDragSliderVec3(wnd, width4Col, \"childRefScale\", childRefIndex, 0.01, &childRef.Scale)\n\n\t\t\twnd.StartRow()\n\t\t\twnd.Space(textWidth)\n\t\t\twnd.RequestItemWidthMin(width4Col)\n\t\t\twnd.Text(\"Rot Axis\")\n\t\t\tguiAddDragSliderVec3(wnd, width4Col, \"childRefRotAxis\", childRefIndex, 0.01, &childRef.RotationAxis)\n\n\t\t\twnd.StartRow()\n\t\t\twnd.Space(textWidth)\n\t\t\twnd.RequestItemWidthMin(width4Col)\n\t\t\twnd.Text(\"Rot Deg\")\n\t\t\twnd.DragSliderFloat(fmt.Sprintf(\"childRefRotDeg%d\", childRefIndex), 0.1, &childRef.RotationDegrees)\n\n\t\t\tif !removeReference {\n\t\t\t\tchildRefsThatSurvive = append(childRefsThatSurvive, childRef)\n\t\t\t}\n\t\t\tif loadChildReference {\n\t\t\t\tvar err error\n\t\t\t\tchildComponents, err = doLoadChildComponent(childComponents, childRef)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Printf(\"Failed to load child component.\\n%v\\n\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttheComponent.ChildReferences = childRefsThatSurvive\n\n\t\t// remove any visible child components that no longer have a reference\n\t\tchildComponents = removeStaleChildComponents(childComponents, &theComponent, childRefFilenames)\n\t})\n\treturn componentWindow\n}", "func WindowSize(width, height int) CommandLineOption {\n\treturn Flag(\"window-size\", fmt.Sprintf(\"%d,%d\", width, height))\n}", "func newSettings() *settings {\n\ts := new(settings)\n\ts.windowSettings = &graphics.WindowSettings{}\n\ts.windowSettings.SetResolution(800, 600)\n\treturn s\n}", "func (self *RenderWindow) Show(state Bool) void {\n return C.sfRenderWindow_Show(self.Cref, state.Cref)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ DSP attributes. NOTE: Not implement yet TODO: add more docs Retrieves information about the current DSP unit, including name, version, default channels and width and height of configuration dialog box if it exists.
func (d *DSP) Info(name *C.char, version *C.uint, channels, configwidth, configheight *C.int) error { //FMOD_RESULT F_API FMOD_DSP_GetInfo(FMOD_DSP *dsp, char *name, unsigned int *version, int *channels, int *configwidth, int *configheight); return ErrNoImpl }
[ "func (c *FwGeneral) Show() (Config, error) {\n c.con.LogQuery(\"(show) general settings\")\n return c.details(c.con.Show)\n}", "func (*DeviceLispDetails) Descriptor() ([]byte, []int) {\n\treturn file_config_mesh_proto_rawDescGZIP(), []int{1}\n}", "func (d *DSP) ParameterInfo(index C.int, desc **C.FMOD_DSP_PARAMETER_DESC) error {\n\t//FMOD_RESULT F_API FMOD_DSP_GetParameterInfo (FMOD_DSP *dsp, int index, FMOD_DSP_PARAMETER_DESC **desc);\n\treturn ErrNoImpl\n}", "func (d *DSP) ShowConfigDialog(hwnd *interface{}, show C.FMOD_BOOL) error {\n\t//FMOD_RESULT F_API FMOD_DSP_ShowConfigDialog (FMOD_DSP *dsp, void *hwnd, FMOD_BOOL show);\n\treturn ErrNoImpl\n}", "func displayDetails(dev *device.SDRDevice) {\n\n\tfmt.Printf(\"-------------------\\n\")\n\tfmt.Printf(\"Device Information\\n\")\n\tfmt.Printf(\"-------------------\\n\")\n\n\t// Function from identification API\n\tfmt.Printf(\"Identification / DriverKey: %v\\n\", dev.GetDriverKey())\n\tfmt.Printf(\"Identification / HardwareKey: %v\\n\", dev.GetHardwareKey())\n\n\thardwareInfo := dev.GetHardwareInfo()\n\tif len(hardwareInfo) > 0 {\n\t\tfor k, v := range hardwareInfo {\n\t\t\tfmt.Printf(\"Identification / HardwareInfo: {%v:%v}\\n\", k, v)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"Identification / HardwareInfo: [none]\\n\")\n\t}\n\n\t//\n\t// GPIO\n\t//\n\tbanks := dev.ListGPIOBanks()\n\tif len(banks) > 0 {\n\t\tfor i, bank := range banks {\n\t\t\tfmt.Printf(\"GPIO / Bank #%d: %v\\n\", i, bank)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"GPIO / Banks: [none]\\n\")\n\t}\n\n\t//\n\t// Settings\n\t//\n\tsettings := dev.GetSettingInfo()\n\tif len(settings) > 0 {\n\t\tfor i, setting := range settings {\n\t\t\tfmt.Printf(\"Settings / Setting #%d: %v\\n\", i, setting.ToString())\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"Settings: [none]\\n\")\n\t}\n\n\t//\n\t// UARTs\n\t//\n\tuarts := dev.ListUARTs()\n\tif len(settings) > 0 {\n\t\tfor i, uart := range uarts {\n\t\t\tfmt.Printf(\"UARTs #%d: / UART: %v\\n\", i, uart)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"UARTs: [none]\\n\")\n\t}\n\n\t//\n\t// Clocking\n\t//\n\tfmt.Printf(\"MasterClockRate: %v\\n\", dev.GetMasterClockRate())\n\tclockRanges := dev.GetMasterClockRates()\n\tif len(clockRanges) > 0 {\n\t\tfor i, clockRange := range clockRanges {\n\t\t\tfmt.Printf(\"MasterClockRate range #%d: %v\\n\", i, clockRange)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"MasterClockRate ranges: [none]\\n\")\n\t}\n\tclockSources := dev.ListClockSources()\n\tif len(clockSources) > 0 {\n\t\tfor i, clockSource := range clockSources {\n\t\t\tfmt.Printf(\"Clock source #%d: %v\\n\", i, clockSource)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"Clock sources: [none]\\n\")\n\t}\n\n\t//\n\t// Register\n\t//\n\tregisters := dev.ListRegisterInterfaces()\n\tif len(registers) > 0 {\n\t\tfor i, register := range registers {\n\t\t\tfmt.Printf(\"Register #%d: %v\\n\", i, register)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"Registers: [none]\\n\")\n\t}\n\n\t//\n\t// Device Sensor\n\t//\n\tsensors := dev.ListSensors()\n\tif len(sensors) > 0 {\n\t\tfor i, sensor := range sensors {\n\t\t\tfmt.Printf(\"Sensor #%d: %v\\n\", i, sensor)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"Sensors: [none]\\n\")\n\t}\n\n\t//\n\t// TimeSource\n\t//\n\ttimeSources := dev.ListTimeSources()\n\tif len(timeSources) > 0 {\n\t\tfor i, timeSource := range timeSources {\n\t\t\tfmt.Printf(\"Time source #%d: %v\\n\", i, timeSource)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"Time sources: [none]\\n\")\n\t}\n\thasHardwareTime := dev.HasHardwareTime(\"\")\n\tfmt.Printf(\"Time source / Has hardware time: %v\\n\", hasHardwareTime)\n\tif hasHardwareTime {\n\t\tfmt.Printf(\"Time source / Hardware time: %v\\n\", dev.GetHardwareTime(\"\"))\n\t}\n\n\tdisplayDirectionDetails(dev, device.DirectionTX)\n\tdisplayDirectionDetails(dev, device.DirectionRX)\n}", "func (s *System) DSPInfoByPlugin(handle C.uint, description **C.FMOD_DSP_DESCRIPTION) error {\n\t//FMOD_RESULT F_API FMOD_System_GetDSPInfoByPlugin (FMOD_SYSTEM *system, unsigned int handle, const FMOD_DSP_DESCRIPTION **description);\n\treturn ErrNoImpl\n}", "func (mob Mobile) Attributes() {\n\tmob.Product.Attributes()\n\tfmt.Println(\"\\nDisplay Features:\")\n\tfor _, key := range mob.DisplayFeatures {\n\t\tfmt.Println(key)\n\t}\n\tfmt.Println(\"\\nProcessor Features:\")\n\tfor _, key := range mob.ProcessorFeatures {\n\t\tfmt.Println(key)\n\t}\n}", "func ConfigShow() error {\n\n\tfmt.Printf(\"\\nCurrently saved values:\\n\")\n\n\tif Config.Secure {\n\t\tfmt.Printf(\" -https\\n\")\n\t} else {\n\t\tfmt.Printf(\" -http\\n\")\n\t}\n\n\tif Config.Hub != \"\" && Config.Hub != notehub.DefaultAPIService {\n\t\tfmt.Printf(\" -hub %s\\n\", Config.Hub)\n\t}\n\tif Config.App != \"\" {\n\t\tfmt.Printf(\" -app %s\\n\", Config.App)\n\t}\n\tif Config.Product != \"\" {\n\t\tfmt.Printf(\" -product %s\\n\", Config.Product)\n\t}\n\tif Config.Device != \"\" {\n\t\tfmt.Printf(\" -device %s\\n\", Config.Device)\n\t}\n\tif Config.Root != \"\" {\n\t\tfmt.Printf(\" -root %s\\n\", Config.Root)\n\t}\n\tif Config.Cert != \"\" {\n\t\tfmt.Printf(\" -cert %s\\n\", Config.Cert)\n\t}\n\tif Config.Key != \"\" {\n\t\tfmt.Printf(\" -key %s\\n\", Config.Key)\n\t}\n\tif Config.Interface != \"\" {\n\t\tfmt.Printf(\" -interface %s\\n\", Config.Interface)\n\t\tif Config.Port == \"\" {\n\t\t\tfmt.Printf(\" -port -\\n\")\n\t\t\tfmt.Printf(\" -portconfig -\\n\")\n\t\t} else {\n\t\t\tfmt.Printf(\" -port %s\\n\", Config.Port)\n\t\t\tfmt.Printf(\" -portconfig %d\\n\", Config.PortConfig)\n\t\t}\n\t}\n\n\treturn nil\n\n}", "func (frame *AvFrame) GetInfo() (width int, height int, linesize [8]int32, data [8]*uint8) {\n\twidth = int(frame.linesize[0])\n\theight = int(frame.height)\n\tfor i := range linesize {\n\t\tlinesize[i] = int32(frame.linesize[i])\n\t}\n\tfor i := range data {\n\t\tdata[i] = (*uint8)(frame.data[i])\n\t}\n\t// log.Println(\"Linesize is \", frame.linesize, \"Data is\", data)\n\treturn\n}", "func (m *voiceGoom) Info() *core.ModuleInfo {\n\treturn &m.info\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 (*VoiceSelectionParams) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_dialogflow_cx_v3beta1_audio_config_proto_rawDescGZIP(), []int{2}\n}", "func (*AudioInConfig) Descriptor() ([]byte, []int) {\n\treturn file_google_assistant_embedded_v1alpha1_embedded_assistant_proto_rawDescGZIP(), []int{1}\n}", "func (*InputAudioConfig) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_dialogflow_cx_v3beta1_audio_config_proto_rawDescGZIP(), []int{1}\n}", "func (*OutputAudioConfig) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_dialogflow_cx_v3beta1_audio_config_proto_rawDescGZIP(), []int{4}\n}", "func (*AudioOutConfig) Descriptor() ([]byte, []int) {\n\treturn file_google_assistant_embedded_v1alpha1_embedded_assistant_proto_rawDescGZIP(), []int{2}\n}", "func (*SpeechWordInfo) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_dialogflow_cx_v3beta1_audio_config_proto_rawDescGZIP(), []int{0}\n}", "func displayDirectionChannelDetails(dev *device.SDRDevice, direction device.Direction, channel uint) {\n\n\t// Settings\n\tsettings := dev.GetChannelSettingInfo(direction, channel)\n\tif len(settings) > 0 {\n\t\tfor i, setting := range settings {\n\t\t\tfmt.Printf(\"Channel #%d / Setting #%d: / Banks: %v\\n\", channel, i, setting)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"Channel #%d / Settings: [none]\\n\", channel)\n\t}\n\n\t//\n\t// Channel\n\t//\n\n\tchannelInfo := dev.GetChannelInfo(direction, channel)\n\tif len(channelInfo) > 0 {\n\t\tfor k, v := range channelInfo {\n\t\t\tfmt.Printf(\"Channel #%d / ChannelInfo: {%v:%v}\\n\", channel, k, v)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"Channel #%d / ChannelInfo: [none]\\n\", channel)\n\t}\n\n\tfmt.Printf(\"Channel #%d / FullDuplex: %v\\n\", channel, dev.GetFullDuplex(direction, channel))\n\n\t//\n\t// Antenna\n\t//\n\n\tantennas := dev.ListAntennas(direction, channel)\n\tfmt.Printf(\"Channel #%d / NumAntennas: %v\\n\", channel, len(antennas))\n\n\tfor i, antenna := range antennas {\n\t\tfmt.Printf(\"Channel #%d / Antenna #%d: %v\\n\", channel, i, antenna)\n\t}\n\n\t//\n\t// Bandwidth\n\t//\n\n\tfmt.Printf(\"Channel #%d / Baseband filter width Hz: %v Hz\\n\", channel, dev.GetBandwidth(direction, channel))\n\n\tbandwidthRanges := dev.GetBandwidthRanges(direction, channel)\n\tfor i, bandwidthRange := range bandwidthRanges {\n\t\tfmt.Printf(\"Channel #%d / Baseband filter #%d: %v\\n\", channel, i, bandwidthRange)\n\t}\n\n\t//\n\t// Gain\n\t//\n\n\tfmt.Printf(\"Channel #%d / HasGainMode (Automatic gain possible): %v\\n\", channel, dev.HasGainMode(direction, channel))\n\tfmt.Printf(\"Channel #%d / GainMode (Automatic gain enabled): %v\\n\", channel, dev.GetGainMode(direction, channel))\n\tfmt.Printf(\"Channel #%d / Gain: %v\\n\", channel, dev.GetGain(direction, channel))\n\tfmt.Printf(\"Channel #%d / GainRange: %v\\n\", channel, dev.GetGainRange(direction, channel).ToString())\n\n\tgainElements := dev.ListGains(direction, channel)\n\tfmt.Printf(\"Channel #%d / NumGainElements: %v\\n\", channel, len(gainElements))\n\n\tfor i, gainElement := range gainElements {\n\t\tfmt.Printf(\"Channel #%d / Gain Element #%d / Name: %v\\n\", channel, i, gainElement)\n\t\tfmt.Printf(\"Channel #%d / Gain Element #%d / Value: %v\\n\", channel, i, dev.GetGainElement(direction, channel, gainElement))\n\t\tfmt.Printf(\"Channel #%d / Gain Element #%d / Range: %v\\n\", channel, i, dev.GetGainElementRange(direction, channel, gainElement).ToString())\n\t}\n\n\t//\n\t// SampleRate\n\t//\n\n\tfmt.Printf(\"Channel #%d / Sample Rate: %v\\n\", channel, dev.GetSampleRate(direction, channel))\n\tfor i, sampleRateRange := range dev.GetSampleRateRange(direction, channel) {\n\t\tfmt.Printf(\"Channel #%d / Sample Rate Range #%d: %v\\n\", channel, i, sampleRateRange.ToString())\n\t}\n\n\t//\n\t// Frequencies\n\t//\n\n\tfmt.Printf(\"Channel #%d / Frequency: %v\\n\", channel, dev.GetFrequency(direction, channel))\n\tfor i, frequencyRange := range dev.GetFrequencyRange(direction, channel) {\n\t\tfmt.Printf(\"Channel #%d / Frequency Range #%d: %v\\n\", channel, i, frequencyRange.ToString())\n\t}\n\n\tfrequencyArgsInfos := dev.GetFrequencyArgsInfo(direction, channel)\n\tif len(frequencyArgsInfos) > 0 {\n\t\tfor i, argInfo := range frequencyArgsInfos {\n\t\t\tfmt.Printf(\"Channel #%d / Frequency ArgInfo #%d: %v\\n\", channel, i, argInfo.ToString())\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"Channel #%d / Frequency ArgInfo: [none]\\n\", channel)\n\t}\n\n\tfrequencyComponents := dev.ListFrequencies(direction, channel)\n\tfmt.Printf(\"Channel #%d / NumFrequencyComponents: %v\\n\", channel, len(frequencyComponents))\n\n\tfor i, frequencyComponent := range frequencyComponents {\n\t\tfmt.Printf(\"Channel #%d / Frequency Component #%d / Name: %v\\n\", channel, i, frequencyComponent)\n\t\tfmt.Printf(\"Channel #%d / Frequency Component #%d / Frequency: %v\\n\", channel, i, dev.GetFrequencyComponent(direction, channel, frequencyComponent))\n\n\t\tfrequencyRanges := dev.GetFrequencyRangeComponent(direction, channel, frequencyComponent)\n\t\tfor j, frequencyRange := range frequencyRanges {\n\t\t\tfmt.Printf(\"Channel #%d / Frequency Component #%d / Frequency Range #%d: %v\\n\", channel, i, j, frequencyRange.ToString())\n\t\t}\n\t}\n\n\t//\n\t// Stream\n\t//\n\n\tfmt.Printf(\"Channel #%d / Stream / Formats: %v\\n\", channel, dev.GetStreamFormats(direction, channel))\n\tnativeStreamFormat, nativeStreamFullScale := dev.GetNativeStreamFormat(direction, channel)\n\tfmt.Printf(\"Channel #%d / Stream / NativeFormat: %v (fullScale: %v)\\n\", channel, nativeStreamFormat, nativeStreamFullScale)\n\n\tstreamArgsInfos := dev.GetStreamArgsInfo(direction, channel)\n\tif len(streamArgsInfos) > 0 {\n\t\tfor i, argInfo := range streamArgsInfos {\n\t\t\tfmt.Printf(\"Channel #%d / Stream ArgInfo #%d: %v\\n\", channel, i, argInfo.ToString())\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"Channel #%d / Stream ArgInfo: [none]\\n\", channel)\n\t}\n\n\t//\n\t// Front-end correction\n\t//\n\tavailable := dev.HasDCOffsetMode(direction, channel)\n\tfmt.Printf(\"Channel #%d / Stream / Correction / Auto DC correction available: %v\\n\", channel, available)\n\tif available {\n\t\tfmt.Printf(\"Channel #%d / Stream / Correction / Auto DC correction: %v\\n\", channel, dev.GetDCOffsetMode(direction, channel))\n\t}\n\tavailable = dev.HasDCOffset(direction, channel)\n\tfmt.Printf(\"Channel #%d / Stream / Correction / DC correction available: %v\\n\", channel, available)\n\tif available {\n\t\tI, Q, err := dev.GetDCOffset(direction, channel)\n\t\tfmt.Printf(\"Channel #%d / Stream / Correction / DC correction I: %v, Q: %v, err :%v\\n\", channel, I, Q, err)\n\t}\n\tavailable = dev.HasIQBalance(direction, channel)\n\tfmt.Printf(\"Channel #%d / Stream / Correction / IQ Balance available: %v\\n\", channel, available)\n\tif available {\n\t\tI, Q, err := dev.GetIQBalance(direction, channel)\n\t\tfmt.Printf(\"Channel #%d / Stream / Correction / IQ Balance I: %v, Q: %v, err :%v\\n\", channel, I, Q, err)\n\t}\n\tavailable = dev.HasFrequencyCorrection(direction, channel)\n\tfmt.Printf(\"Channel #%d / Stream / Correction / Frequency correction available: %v\\n\", channel, available)\n\tif available {\n\t\tfmt.Printf(\"Channel #%d / Stream / Correction / Frequency correction: %v PPM\\n\", channel, dev.GetFrequencyCorrection(direction, channel))\n\t}\n\n\t//\n\t// Channel Sensor\n\t//\n\tsensors := dev.ListChannelSensors(direction, channel)\n\tif len(sensors) > 0 {\n\t\tfor i, sensor := range sensors {\n\t\t\tfmt.Printf(\"Channel #%d / Sensor #%d: %v\\n\", channel, i, sensor)\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"Channel #%d / Sensors: [none]\\n\", channel)\n\t}\n}", "func (*GetDeviceConfigurationResponse) Descriptor() ([]byte, []int) {\n\treturn file_pkg_pb_protobuf_api_proto_rawDescGZIP(), []int{33}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the predefined type of a FMOD registered DSP unit. This is only valid for built in FMOD effects. Any user plugins will simply return "DSP_TYPE_UNKNOWN".
func (d *DSP) Type() (DSPType, error) { var typ C.FMOD_DSP_TYPE res := C.FMOD_DSP_GetType(d.cptr, &typ) return DSPType(typ), errs[res] }
[ "func getMetricType(short string) (int, error) {\n\tswitch {\n\tcase \"c\" == short:\n\t\treturn MetricTypeCounter, nil\n\tcase \"g\" == short:\n\t\treturn MetricTypeGauge, nil\n\tcase \"s\" == short:\n\t\treturn MetricTypeSet, nil\n\tcase \"ms\" == short:\n\t\treturn MetricTypeTimer, nil\n\t}\n\treturn MetricTypeUnknown, errors.New(\"unknown metric type\")\n}", "func GetDataType(fourCC [4]byte) ResourceDataType {\n\tvalue := string(fourCC[:])\n\tswitch value {\n\tcase \"NULL\":\n\t\treturn DataNull\n\tcase \"RAWD\":\n\t\treturn DataRaw\n\tcase \"TEXT\":\n\t\treturn DataText\n\tcase \"IMGE\":\n\t\treturn DataImage\n\tcase \"WAVE\":\n\t\treturn DataWave\n\tcase \"VRTX\":\n\t\treturn DataVertex\n\tcase \"FNTG\":\n\t\treturn DataFontGlyphs\n\tcase \"LINK\":\n\t\treturn DataLink\n\tcase \"CDIR\":\n\t\treturn DataDirectory\n\tdefault:\n\t\treturn 0\n\t}\n}", "func GetType(entropyName string) uint32 {\n\tswitch strings.ToUpper(entropyName) {\n\n\tcase \"HUFFMAN\":\n\t\treturn HUFFMAN_TYPE\n\n\tcase \"ANS0\":\n\t\treturn ANS0_TYPE\n\n\tcase \"ANS1\":\n\t\treturn ANS1_TYPE\n\n\tcase \"RANGE\":\n\t\treturn RANGE_TYPE\n\n\tcase \"FPAQ\":\n\t\treturn FPAQ_TYPE\n\n\tcase \"CM\":\n\t\treturn CM_TYPE\n\n\tcase \"TPAQ\":\n\t\treturn TPAQ_TYPE\n\n\tcase \"TPAQX\":\n\t\treturn TPAQX_TYPE\n\n\tcase \"NONE\":\n\t\treturn NONE_TYPE\n\n\tdefault:\n\t\tpanic(fmt.Errorf(\"Unsupported entropy codec type: '%s'\", entropyName))\n\t}\n}", "func (s *System) CreateDSPByType(typ DSPType) (*DSP, error) {\n\t// TODO Finalizer\n\tvar dsp DSP\n\tres := C.FMOD_System_CreateDSPByType(s.cptr, C.FMOD_DSP_TYPE(typ), &dsp.cptr)\n\treturn &dsp, errs[res]\n}", "func GetDeviceType(sysObjectID string) (t string) {\n\tt, ok := deviceTypes[sysObjectID]\n\tif false == ok {\n\t\tt = Unknow\n\t}\n\treturn\n}", "func (m *Message) DSP() (*DSP, error) {\n\tps, err := m.Parse(\"DSP\")\n\tpst, ok := ps.(*DSP)\n\tif ok {\n\t\treturn pst, err\n\t}\n\treturn nil, err\n}", "func (inst *InstFMul) Type() types.Type {\n\treturn inst.X.Type()\n}", "func getDeviceType(r apis.RaidGroup) string {\n\tif r.IsReadCache {\n\t\treturn DeviceTypeReadCache\n\t} else if r.IsSpare {\n\t\treturn DeviceTypeSpare\n\t} else if r.IsWriteCache {\n\t\treturn DeviceTypeWriteCache\n\t}\n\treturn DeviceTypeEmpty\n}", "func (m *WindowsInformationProtectionDeviceRegistration) GetDeviceType()(*string) {\n val, err := m.GetBackingStore().Get(\"deviceType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func phpType(smdType string) string {\n\tswitch smdType {\n\tcase smd.String:\n\t\treturn phpString\n\tcase smd.Array:\n\t\treturn phpArray\n\tcase smd.Boolean:\n\t\treturn phpBoolean\n\tcase smd.Float:\n\t\treturn phpFloat\n\tcase smd.Integer:\n\t\treturn phpInt\n\tcase smd.Object:\n\t\treturn phpObject\n\t}\n\treturn \"mixed\"\n}", "func (s Shop) GetShopTypeString() (result string) {\n\treturn shopTypesEnum[s.Type]\n}", "func (inst *InstFMul) Type() types.Type {\n\t// Cache type if not present.\n\tif inst.Typ == nil {\n\t\tinst.Typ = inst.X.Type()\n\t}\n\treturn inst.Typ\n}", "func GetFileType(suffix string) global.FileType {\n\tif suffix == \".txt\" || suffix == \".doc\" || suffix == \".docx\" || suffix == \".html\" || suffix == \".pdf\" ||\n\t\tsuffix == \".xls\" || suffix == \".xlsx\" || suffix == \".ppt\" || suffix == \".pptx\" || suffix == \".md\" {\n\t\treturn global.FileDocumentType\n\t} else if \".bmp\" == suffix || \".gif\" == suffix || \".jpg\" == suffix || \".png\" == suffix || \".jepg\" == suffix ||\n\t\t\".svg\" == suffix || \".tiff\" == suffix || \".psd\" == suffix || \".raw\" == suffix || \".eps\" == suffix {\n\t\treturn global.FilePictureType\n\t} else if \".avi\" == suffix || \".mov\" == suffix || \".mkv\" == suffix || \".asf\" == suffix || \".rmvb\" == suffix ||\n\t\t\".mpeg\" == suffix || \".wmv\" == suffix || \".mp4\" == suffix || \".ts\" == suffix || \".flv\" == suffix {\n\t\treturn global.FileVideoType\n\t} else if \".mp3\" == suffix || \".wma\" == suffix || \".wav\" == suffix || \"aac\" == suffix || \".flac\" == suffix ||\n\t\t\".ape\" == suffix || \".aiff\" == suffix || \".ogg\" == suffix {\n\t\treturn global.FileMusicType\n\t} else {\n\t\treturn global.FileOtherType\n\t}\n}", "func (d DocLanguageHelper) GetLanguageTypeString(pkg *schema.Package, moduleName string, t schema.Type, input bool) string {\n\t// Remove the union with `undefined` for optional types,\n\t// since we will show that information separately anyway.\n\tif optional, ok := t.(*schema.OptionalType); ok {\n\t\tt = optional.ElementType\n\t}\n\n\tmodCtx := &modContext{\n\t\tpkg: pkg.Reference(),\n\t\tmod: moduleName,\n\t}\n\ttypeName := modCtx.typeString(t, input, nil)\n\n\t// Remove any package qualifiers from the type name.\n\ttypeQualifierPackage := \"inputs\"\n\tif !input {\n\t\ttypeQualifierPackage = \"outputs\"\n\t}\n\ttypeName = strings.ReplaceAll(typeName, typeQualifierPackage+\".\", \"\")\n\ttypeName = strings.ReplaceAll(typeName, \"enums.\", \"\")\n\n\treturn typeName\n}", "func TypedefTypeString(t *dwarf.TypedefType,) string", "func Get(ext string) Type {\n\tif tmp, ok := Types.Load(ext); ok {\n\t\tkind := tmp.(Type)\n\t\tif kind.Extension != \"\" {\n\t\t\treturn kind\n\t\t}\n\t}\n\treturn Unknown\n}", "func (d DocLanguageHelper) GetLanguageTypeString(pkg *schema.Package, moduleName string, t schema.Type, input bool) string {\n\ttypeDetails := map[*schema.ObjectType]*typeDetails{}\n\tmod := &modContext{\n\t\tpkg: pkg.Reference(),\n\t\tmod: moduleName,\n\t\ttypeDetails: typeDetails,\n\t}\n\ttypeName := mod.typeString(t, input, false /*acceptMapping*/)\n\n\t// Remove any package qualifiers from the type name.\n\tif !input {\n\t\ttypeName = strings.ReplaceAll(typeName, \"outputs.\", \"\")\n\t}\n\n\t// Remove single quote from type names.\n\ttypeName = strings.ReplaceAll(typeName, \"'\", \"\")\n\n\treturn typeName\n}", "func getInstallationType(installationType string) (string, error) {\n\tswitch installationType {\n\tcase installationTypeServer:\n\t\treturn windowsServerFull, nil\n\tcase installationTypeServerCore:\n\t\treturn windowsServerCore, nil\n\tdefault:\n\t\treturn \"\", errors.Errorf(\"unsupported installation type: %s\", installationType)\n\t}\n}", "func (Phosphorus) GetCategory() string {\n\tvar c categoryType = nonMetal\n\treturn c.get()\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the idle state of a DSP. A DSP is idle when no signal is coming into it. This can be a useful method of determining if a DSP sub branch is finished processing, so it can be disconnected for example. The idle state takes into account things like tails of echo filters, even if a wavetable or dsp has finished generating sound. When all nodes in a graph have finished processing, only then will it set the top level DSP state to idle.
func (d *DSP) Idle() (bool, error) { var idle C.FMOD_BOOL res := C.FMOD_DSP_GetIdle(d.cptr, &idle) return setBool(idle), errs[res] }
[ "func idle() State_t {\n\t\n}", "func (pool *Pool) Idle() int {\n\treturn int(atomic.LoadInt32(&pool.numIdle))\n}", "func (cp *Pool) IdleClosed() int64 {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.IdleClosed()\n}", "func (s *Stream) idleTick() {\n\tif len(s.workCh) == 0 && s.sessST.CAS(active, inactive) {\n\t\ts.workCh <- &Obj{Hdr: ObjHdr{Opcode: opcIdleTick}}\n\t\tif verbose {\n\t\t\tnlog.Infof(\"%s: active => inactive\", s)\n\t\t}\n\t}\n}", "func (c *Client) Idle() (err error) {\n\ttag, err := c.prepareCmd(\"IDLE\")\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer c.cleanCmd()\n\n\terr = c.writeString(tag + \" IDLE\\r\\n\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tc.doneEmitted = false\n\tc.idling = true\n\tdefer func() {\n\t\tc.idling = false\n\t\tc.doneEmitted = false\n\t}()\n\n\trep := <-c.rep\n\tif rep == nil {\n\t\terr = ErrNilRep\n\t\treturn\n\t}\n\tif rep.err != nil {\n\t\terr = rep.err\n\t\treturn\n\t}\n\treturn\n}", "func (s *MsgStream) idleTick() {\n\tif len(s.workCh) == 0 && s.sessST.CAS(active, inactive) {\n\t\ts.workCh <- &Msg{Opcode: opcIdleTick}\n\t\tif verbose {\n\t\t\tnlog.Infof(\"%s: active => inactive\", s)\n\t\t}\n\t}\n}", "func (r *Radio) State() string {\n\treturn \"idle\"\n}", "func assessidle() {\n\tlog.Printf(\"Launching %v for idle state resource usage assessment\", icmd.Path)\n\tlog.Println(\"Trying to determine idle state resource usage (no external traffic)\")\n\ticmd.Run()\n\tf := Findings{}\n\tif icmd.ProcessState != nil {\n\t\tf.MemoryMaxRSS = int64(icmd.ProcessState.SysUsage().(*syscall.Rusage).Maxrss)\n\t\tf.CPUuser = int64(icmd.ProcessState.SysUsage().(*syscall.Rusage).Utime.Usec)\n\t\tf.CPUsys = int64(icmd.ProcessState.SysUsage().(*syscall.Rusage).Stime.Usec)\n\t}\n\tidlef <- f\n}", "func (rp *ResourcePool) IdleClosed() int64 {\n\treturn rp.idleClosed.Load()\n}", "func (c *cpuMonitor) idle() (float32, error) {\n\tcmd := exec.Command(\"top\", \"-b\", \"-n\", \"3\", \"-d\", \"3\")\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tstr := string(out)\n\tlines := strings.Split(str, \"\\n\")\n\tvar cpuline string\n\tfor _, line := range lines {\n\t\tif strings.Contains(line, \"Cpu\") {\n\t\t\tcpuline = line\n\t\t}\n\t}\n\tvar cpu string\n\titems := strings.Split(cpuline, \" \")\n\tfor i, item := range items {\n\t\tif item == \"id,\" && i > 0 {\n\t\t\tcpu = items[i-1]\n\t\t}\n\t}\n\tvar v float32\n\tif n, err := fmt.Sscanf(cpu, \"%f\", &v); n != 1 || err != nil {\n\t\treturn 0, fmt.Errorf(\"failed to parse\")\n\t}\n\treturn v, nil\n}", "func (wp *IOG) Idle() bool {\n\treturn wp.TaskPending() <= 0\n}", "func (c *Client) Idle() (bool, error) {\n\treturn c.GetBoolProperty(\"idle\")\n}", "func NewIdle() *Idle {\n\treturn &Idle{}\n}", "func (op *obcSieve) idleChannel() <-chan struct{} {\n\treturn op.idleChan\n}", "func (t *Tank) IsIdle() bool {\n\treturn t.state == Idle\n}", "func (d *DFA) Initial() State {\n\treturn d.initial\n}", "func (cs *ConnectivityState) SetStateIdle() {\n\tcs.SetState(\"idle\")\n}", "func (c *Client) Idle() bool {\n\treturn c.pendingAsynCall == 0\n}", "func (c *ConnExt) Idle() bool {\n\tif time.Since(c.LastActivity) > c.Config.IdleThresholdSec {\n\t\treturn true\n\t}\n\treturn false\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ Userdata set/get. Sets a user value that the DSP object will store internally. Can be retrieved with "DSP.UserData". This function is primarily used in case the user wishes to 'attach' data to an FMOD object. It can be useful if an FMOD callback passes an object of this type as a parameter, and the user does not know which object it is (if many of these types of objects exist). Using "DSP.UserData" would help in the identification of the object.
func (d *DSP) SetUserData(userdata interface{}) error { data := *(*[]*C.char)(unsafe.Pointer(&userdata)) res := C.FMOD_DSP_SetUserData(d.cptr, unsafe.Pointer(&data)) return errs[res] }
[ "func (s *System) SetUserData(userdata interface{}) error {\n\tdata := *(*[]*C.char)(unsafe.Pointer(&userdata))\n\tres := C.FMOD_System_SetUserData(s.cptr, unsafe.Pointer(&data))\n\treturn errs[res]\n}", "func (r *Reverb3D) SetUserData(userdata interface{}) error {\n\tdata := *(*[]*C.char)(unsafe.Pointer(&userdata))\n\tres := C.FMOD_Reverb3D_SetUserData(r.cptr, unsafe.Pointer(&data))\n\treturn errs[res]\n}", "func (d *DspConnection) SetUserData(userdata interface{}) error {\n\tdata := *(*[]*C.char)(unsafe.Pointer(&userdata))\n\tres := C.FMOD_DSPConnection_SetUserData(d.cptr, unsafe.Pointer(&data))\n\treturn errs[res]\n}", "func (s *SoundGroup) SetUserData(userdata interface{}) error {\n\tdata := *(*[]*C.char)(unsafe.Pointer(&userdata))\n\tres := C.FMOD_SoundGroup_SetUserData(s.cptr, unsafe.Pointer(&data))\n\treturn errs[res]\n}", "func (c *wagonContext) SetUserData(key string, value interface{}) {\n\tc.userData[key] = value\n}", "func (m *Media) SetUserData(userData interface{}) error {\n\tif err := m.assertInit(); err != nil {\n\t\treturn err\n\t}\n\n\t// Set or update user data.\n\tif _, md := m.getUserData(); md != nil {\n\t\tmd.userData = userData\n\t} else {\n\t\tm.setUserData(&mediaData{userData: userData})\n\t}\n\n\treturn nil\n}", "func (d *DSP) UserData() (interface{}, error) {\n\tvar userdata *interface{}\n\tcUserdata := unsafe.Pointer(userdata)\n\tres := C.FMOD_DSP_GetUserData(d.cptr, &cUserdata)\n\treturn *(*interface{})(cUserdata), errs[res]\n}", "func (m *TimeCard) SetUserId(value *string)() {\n err := m.GetBackingStore().Set(\"userId\", value)\n if err != nil {\n panic(err)\n }\n}", "func (p *Processor) SetUserData(userdata unsafe.Pointer) {\n\tC.zbar_processor_set_userdata(p.c_processor, userdata)\n}", "func (m *SecurityActionState) SetUser(value *string)() {\n err := m.GetBackingStore().Set(\"user\", value)\n if err != nil {\n panic(err)\n }\n}", "func (p *Param) SetUserData() error {\n\treturn errors.New(\"Param.SetUserData() has not been implemented yet.\")\n}", "func UserDataValue(u *UserData) Value {\n\treturn Value{iface: u}\n}", "func (s *SoundGroup) UserData() (interface{}, error) {\n\tvar userdata *interface{}\n\tcUserdata := unsafe.Pointer(userdata)\n\tres := C.FMOD_SoundGroup_GetUserData(s.cptr, &cUserdata)\n\treturn *(*interface{})(cUserdata), errs[res]\n}", "func SetUserData(cr *Cairo, key *UserDataKey, userData unsafe.Pointer, destroy DestroyFunc) Status {\n\tccr, _ := (*C.cairo_t)(unsafe.Pointer(cr)), cgoAllocsUnknown\n\tckey, _ := key.PassRef()\n\tcuserData, _ := userData, cgoAllocsUnknown\n\tcdestroy, _ := destroy.PassValue()\n\t__ret := C.cairo_set_user_data(ccr, ckey, cuserData, cdestroy)\n\t__v := (Status)(__ret)\n\treturn __v\n}", "func (s *System) UserData() (interface{}, error) {\n\tvar userdata *interface{}\n\tcUserdata := unsafe.Pointer(userdata)\n\tres := C.FMOD_System_GetUserData(s.cptr, &cUserdata)\n\treturn *(*interface{})(cUserdata), errs[res]\n}", "func (init *SPH_UDF_INIT) setvalue(value uintptr) {\n\t*(*uintptr)(unsafe.Pointer(&init.func_data)) = value\n}", "func (e *Entry) SetUser(key string, value interface{}) error {\n\tglog.Infof(\"setting registry entry %s to %s\", key, value)\n\n\tif !isKeyWritable(key) {\n\t\treturn errors.NewConfigurationError(\"registry key %s cannot be written\", key)\n\t}\n\n\treturn e.Set(Key(key), value)\n}", "func (d UserData) Set(field models.FieldName, value interface{}) m.UserData {\n\treturn &UserData{\n\t\td.ModelData.Set(field, value),\n\t}\n}", "func (d *DspConnection) UserData() (interface{}, error) {\n\tvar userdata *interface{}\n\tcUserdata := unsafe.Pointer(userdata)\n\tres := C.FMOD_DSPConnection_GetUserData(d.cptr, &cUserdata)\n\treturn *(*interface{})(cUserdata), errs[res]\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the user value that that was set by calling the "DSP.SetUserData" function.
func (d *DSP) UserData() (interface{}, error) { var userdata *interface{} cUserdata := unsafe.Pointer(userdata) res := C.FMOD_DSP_GetUserData(d.cptr, &cUserdata) return *(*interface{})(cUserdata), errs[res] }
[ "func (d *DspConnection) UserData() (interface{}, error) {\n\tvar userdata *interface{}\n\tcUserdata := unsafe.Pointer(userdata)\n\tres := C.FMOD_DSPConnection_GetUserData(d.cptr, &cUserdata)\n\treturn *(*interface{})(cUserdata), errs[res]\n}", "func (s *System) UserData() (interface{}, error) {\n\tvar userdata *interface{}\n\tcUserdata := unsafe.Pointer(userdata)\n\tres := C.FMOD_System_GetUserData(s.cptr, &cUserdata)\n\treturn *(*interface{})(cUserdata), errs[res]\n}", "func (m *MPQ) UserData() []byte {\n\tif m.userData == nil {\n\t\treturn nil\n\t}\n\treturn m.userData.data\n}", "func (p *Param) GetUserData() error {\n\treturn errors.New(\"Param.GetUserData() has not been implemented yet.\")\n}", "func (c *wagonContext) GetUserData(key string) interface{} {\n\treturn c.userData[key]\n}", "func (s *SoundGroup) UserData() (interface{}, error) {\n\tvar userdata *interface{}\n\tcUserdata := unsafe.Pointer(userdata)\n\tres := C.FMOD_SoundGroup_GetUserData(s.cptr, &cUserdata)\n\treturn *(*interface{})(cUserdata), errs[res]\n}", "func (r *LaunchConfiguration) UserData() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"userData\"])\n}", "func (r *Reverb3D) UserData() (interface{}, error) {\n\tvar userdata *interface{}\n\tcUserdata := unsafe.Pointer(userdata)\n\tres := C.FMOD_Reverb3D_GetUserData(r.cptr, &cUserdata)\n\treturn *(*interface{})(cUserdata), errs[res]\n}", "func UserDataValue(u *UserData) Value {\n\treturn Value{iface: u}\n}", "func (m *WindowsInformationProtectionDeviceRegistration) GetUserId()(*string) {\n val, err := m.GetBackingStore().Get(\"userId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (option ApplicationCommandInteractionDataOption) UserIDValue() (value string, ok bool) {\n\treturn option.StringValue()\n}", "func (recv *MarkupParseContext) GetUserData() uintptr {\n\tretC := C.g_markup_parse_context_get_user_data((*C.GMarkupParseContext)(recv.native))\n\tretGo := (uintptr)(unsafe.Pointer(retC))\n\n\treturn retGo\n}", "func (m *Media) UserData() (interface{}, error) {\n\tif err := m.assertInit(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Retrieve user data.\n\t_, md := m.getUserData()\n\tif md == nil {\n\t\treturn nil, nil\n\t}\n\n\treturn md.userData, nil\n}", "func (d *DSP) SetUserData(userdata interface{}) error {\n\tdata := *(*[]*C.char)(unsafe.Pointer(&userdata))\n\tres := C.FMOD_DSP_SetUserData(d.cptr, unsafe.Pointer(&data))\n\treturn errs[res]\n}", "func (v *LVal) UserData() *LVal {\n\tif v.Type != LTaggedVal {\n\t\tpanic(\"not tagged: \" + v.Type.String())\n\t}\n\treturn v.Cells[0]\n}", "func (c *taskQueueManagerImpl) GetUserData(ctx context.Context) (*persistencespb.VersionedTaskQueueUserData, chan struct{}, error) {\n\tif c.managesSpecificVersionSet() {\n\t\treturn nil, nil, errNoUserDataOnVersionedTQM\n\t}\n\tif !c.config.LoadUserData() {\n\t\treturn nil, nil, errUserDataDisabled\n\t}\n\treturn c.db.GetUserData(ctx)\n}", "func (m *TimeCard) GetUserId()(*string) {\n val, err := m.GetBackingStore().Get(\"userId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func LightUserDataValue(d LightUserData) Value {\n\treturn Value{iface: d}\n}", "func (p *Processor) GetUserData() unsafe.Pointer {\n\treturn unsafe.Pointer(C.zbar_processor_get_userdata(p.c_processor))\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ Metering. Enable metering for a DSP unit so that "DSP.MeteringInfo" will return metering information, and so that FMOD Studio profiler tool can visualize the levels. inputEnabled: Enable metering for the input signal (preprocessing). Specify true to turn on input level metering, false to turn it off. outputEnabled: Enable metering for the output signal (postprocessing). Specify true to turn on output level metering, false to turn it off. "INIT_PROFILE_METER_ALL" with "System.Init" will automatically turn on metering for all DSP units inside the FMOD mixer graph.
func (d *DSP) SetMeteringEnabled(inputEnabled, outputEnabled bool) error { res := C.FMOD_DSP_SetMeteringEnabled(d.cptr, getBool(inputEnabled), getBool(outputEnabled)) return errs[res] }
[ "func Meter(component interface{}, sampleRate signal.SampleRate) ResetFunc {\n\tt := getType(component)\n\tmetric := components.get(t)\n\tmetric.components.Add(1)\n\treturn func() MeasureFunc {\n\t\tcalledAt := time.Now()\n\t\tvar (\n\t\t\tbufferSize int\n\t\t\tbufferDuration time.Duration\n\t\t)\n\t\treturn func(s int) {\n\t\t\tmetric.latency.set(time.Since(calledAt))\n\t\t\tmetric.messages.Add(1)\n\t\t\tmetric.samples.Add(int64(s))\n\t\t\t// recalculate buffer duration only when buffer size has changed\n\t\t\tif bufferSize != s {\n\t\t\t\tbufferSize = s\n\t\t\t\tbufferDuration = sampleRate.DurationOf(s)\n\t\t\t}\n\t\t\tmetric.duration.add(bufferDuration)\n\t\t\tcalledAt = time.Now()\n\t\t}\n\t}\n}", "func (m *Manager) Meter(delay time.Duration) *Meter {\n\treturn &Meter{\n\t\tm: m,\n\t\tdelay: delay,\n\t\tnext: time.Now(),\n\t}\n}", "func (this *meterStruct) SetEnabled(value bool) {\n\tthis.mutex.Lock()\n\tenabled := this.enabled\n\n\t/*\n\t * Check if value must be changed.\n\t */\n\tif value != enabled {\n\t\tchannelMeters := this.channelMeters\n\n\t\t/*\n\t\t * Enable or disable each channel meter.\n\t\t */\n\t\tfor _, channelMeter := range channelMeters {\n\t\t\tchannelMeter.setEnabled(value)\n\t\t}\n\n\t\tthis.enabled = value\n\t}\n\n\tthis.mutex.Unlock()\n}", "func (this *meterStruct) Enabled() bool {\n\tthis.mutex.RLock()\n\tenabled := this.enabled\n\tthis.mutex.RUnlock()\n\treturn enabled\n}", "func (d *DSP) MeteringInfo() (DSPMeteringInfo, DSPMeteringInfo, error) {\n\tvar cinputInfo, coutputInfo C.FMOD_DSP_METERING_INFO\n\tvar inputInfo, outputInfo DSPMeteringInfo\n\tres := C.FMOD_DSP_GetMeteringInfo(d.cptr, &cinputInfo, &coutputInfo)\n\tinputInfo.fromC(cinputInfo)\n\toutputInfo.fromC(coutputInfo)\n\treturn inputInfo, outputInfo, errs[res]\n}", "func (this *channelMeterStruct) setEnabled(value bool) {\n\tthis.mutex.Lock()\n\tenabled := this.enabled\n\n\t/*\n\t * Check if status of meter must be changed.\n\t */\n\tif value != enabled {\n\n\t\t/*\n\t\t * If level meter should be disabled, clear state.\n\t\t */\n\t\tif !value {\n\t\t\tthis.currentValue = 0.0\n\t\t\tthis.peakValue = 0.0\n\t\t\tthis.sampleCounter = 0\n\t\t}\n\n\t\tthis.enabled = value\n\t}\n\n\tthis.mutex.Unlock()\n}", "func (m *MeterMetric) IsMeter() bool {\n\treturn m.Type == meterMetricType\n}", "func Meter(attrs []htmlgo.Attribute, children ...HTML) HTML {\n\treturn &htmlgo.Tree{Tag: \"meter\", Attributes: attrs, Children: children}\n}", "func InitMeter(db persistence.Conn) func() {\n\tcleanupFunc := func() {}\n\n\tmetricProvider := os.Getenv(\"METRIC_PROVIDER\")\n\tif metricProvider == \"\" {\n\t\tlog(nil, nil).Info(\"METRIC_PROVIDER not set, metrics will not be generated.\")\n\t\treturn cleanupFunc\n\t}\n\n\tvar err error\n\tswitch metricProvider {\n\tcase STDOUT, PRETTY:\n\t\tvar pusher *push.Controller\n\t\tpusher, err = metricstdout.InstallNewPipeline(metricstdout.Config{\n\t\t\tQuantiles: []float64{},\n\t\t\tPrettyPrint: metricProvider == PRETTY,\n\t\t}, push.WithStateful(false))\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tcleanupFunc = pusher.Stop\n\tcase PROMETHEUS:\n\t\tvar exporter *prometheus.Exporter\n\t\texporter, err = prometheus.InstallNewPipeline(prometheus.Config{}, pull.WithStateful(false))\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\thttp.HandleFunc(\"/metrics\", exporter.ServeHTTP)\n\t\tgo func() {\n\t\t\t_ = http.ListenAndServe(\":2222\", nil)\n\t\t}()\n\tdefault:\n\t\tlog(nil, nil).WithField(\"provider\", metricProvider).Fatal(\"Unsupported metric provider\")\n\t}\n\n\tif err != nil {\n\t\tlog(nil, err).WithField(\"provider\", metricProvider).Fatal(\"failed to initialize metric stdout exporter\")\n\t}\n\n\tinitSystemStatsObserver(db)\n\n\treturn cleanupFunc\n}", "func Enable() error {\n\tenabled = true\n\tsampler = nil\n\n\terr := initStats()\n\treturn err\n}", "func NewMeter(name string) metics.Meter {\n\tif !Enabled {\n\t\treturn new(metics.NilMeter)\n\t}\n\treturn metics.GetOrRegisterMeter(name, metics.DefaultRegistry)\n}", "func SetMeter(ch Channel, value MeterLevel) midi.Message {\n\treturn channel.Channel(0).Aftertouch(byte(ch<<4) + byte(value))\n}", "func meterReader(d *db.DB) error {\n\tsect := d.Config.GetSection(\"meter\")\n\tif sect == nil {\n\t\treturn nil\n\t}\n\tvar angle float64\n\ta, err := sect.GetArg(\"rotate\")\n\tif err == nil {\n\t\tangle, err = strconv.ParseFloat(a, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tsource, err := sect.GetArg(\"source\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tr, err := NewReader(sect, d.Trace)\n\tif err != nil {\n\t\treturn err\n\t}\n\td.AddDiff(db.D_IN_POWER, time.Minute*5)\n\td.AddDiff(db.D_OUT_POWER, time.Minute*5)\n\td.AddAccum(db.A_IN_TOTAL, true)\n\td.AddAccum(db.A_OUT_TOTAL, true)\n\td.AddSubAccum(db.A_IMPORT, true)\n\td.AddSubAccum(db.A_IMPORT, true)\n\td.AddSubAccum(db.A_EXPORT, true)\n\td.AddSubAccum(db.A_EXPORT, true)\n\tlog.Printf(\"Registered meter LCD reader\\n\")\n\tgo runReader(d, r, source, angle)\n\treturn nil\n}", "func (m *HistoMetric) IsMeter() bool {\n\treturn m.Type == meterMetricType\n}", "func SetMeterProvider(mp metric.Provider) {\n\tglobalMeter.Store(meterProvider{mp: mp})\n}", "func Enable(enabled bool) {\n\tif enabled {\n\t\tatomic.StoreUint32(&profilingEnabled, 1)\n\t} else {\n\t\tatomic.StoreUint32(&profilingEnabled, 0)\n\t}\n}", "func (site *Site) updateMeter(name string, meter api.Meter, power *float64) error {\n\tvalue, err := meter.CurrentPower()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*power = value // update value if no error\n\n\tsite.log.DEBUG.Printf(\"%s power: %.0fW\", name, *power)\n\tsite.publish(name+\"Power\", *power)\n\n\treturn nil\n}", "func WithMeter(m meter.Meter) Option {\n\treturn func(o *Options) {\n\t\to.Meter = m\n\t}\n}", "func (sd *stackediff) ProfilingEnable() {\n\tsd.profiletimer = profiletimer.StartProfileTimer()\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the metering information for a particular DSP. "INIT_PROFILE_METER_ALL" with "System.Init" will automatically turn on metering for all DSP units inside the FMOD mixer graph.
func (d *DSP) MeteringInfo() (DSPMeteringInfo, DSPMeteringInfo, error) { var cinputInfo, coutputInfo C.FMOD_DSP_METERING_INFO var inputInfo, outputInfo DSPMeteringInfo res := C.FMOD_DSP_GetMeteringInfo(d.cptr, &cinputInfo, &coutputInfo) inputInfo.fromC(cinputInfo) outputInfo.fromC(coutputInfo) return inputInfo, outputInfo, errs[res] }
[ "func InitMeter(db persistence.Conn) func() {\n\tcleanupFunc := func() {}\n\n\tmetricProvider := os.Getenv(\"METRIC_PROVIDER\")\n\tif metricProvider == \"\" {\n\t\tlog(nil, nil).Info(\"METRIC_PROVIDER not set, metrics will not be generated.\")\n\t\treturn cleanupFunc\n\t}\n\n\tvar err error\n\tswitch metricProvider {\n\tcase STDOUT, PRETTY:\n\t\tvar pusher *push.Controller\n\t\tpusher, err = metricstdout.InstallNewPipeline(metricstdout.Config{\n\t\t\tQuantiles: []float64{},\n\t\t\tPrettyPrint: metricProvider == PRETTY,\n\t\t}, push.WithStateful(false))\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tcleanupFunc = pusher.Stop\n\tcase PROMETHEUS:\n\t\tvar exporter *prometheus.Exporter\n\t\texporter, err = prometheus.InstallNewPipeline(prometheus.Config{}, pull.WithStateful(false))\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\thttp.HandleFunc(\"/metrics\", exporter.ServeHTTP)\n\t\tgo func() {\n\t\t\t_ = http.ListenAndServe(\":2222\", nil)\n\t\t}()\n\tdefault:\n\t\tlog(nil, nil).WithField(\"provider\", metricProvider).Fatal(\"Unsupported metric provider\")\n\t}\n\n\tif err != nil {\n\t\tlog(nil, err).WithField(\"provider\", metricProvider).Fatal(\"failed to initialize metric stdout exporter\")\n\t}\n\n\tinitSystemStatsObserver(db)\n\n\treturn cleanupFunc\n}", "func (s *Tplink) GetMeterInto() (SysInfo, error) {\n\tvar (\n\t\tpayload meterInfo\n\t\tjsonResp SysInfo\n\t)\n\n\tj, _ := json.Marshal(payload)\n\n\tdata := encrypt(string(j))\n\tresp, err := send(s.Host, data)\n\tif err != nil {\n\t\treturn jsonResp, err\n\t}\n\n\tif err := json.Unmarshal([]byte(decrypt(resp)), &jsonResp); err != nil {\n\t\treturn jsonResp, err\n\t}\n\treturn jsonResp, nil\n}", "func (m *metricDcgmGpuProfilingSmUtilization) init() {\n\tm.data.SetName(\"dcgm.gpu.profiling.sm_utilization\")\n\tm.data.SetDescription(\"Fraction of time at least one warp was active on a multiprocessor, averaged over all multiprocessors.\")\n\tm.data.SetUnit(\"1\")\n\tm.data.SetEmptyGauge()\n\tm.data.Gauge().DataPoints().EnsureCapacity(m.capacity)\n}", "func (d *SnmpDevice) InitDevSnmpInfo() {\n\n\t//Alloc array\n\td.Measurements = make([]*InfluxMeasurement, 0, 0)\n\td.log.Debugf(\"-----------------Init device %s------------------\", d.cfg.Host)\n\t//for this device get MeasurementGroups and search all measurements\n\n\tfor _, devMeas := range d.cfg.MeasurementGroups {\n\n\t\t//Selecting all Metric Groups that matches with device.MeasurementGroups\n\t\tselGroups := make(map[string]*MGroupsCfg, 0)\n\t\tvar RegExp = regexp.MustCompile(devMeas)\n\t\tfor key, val := range cfg.GetGroups {\n\t\t\tif RegExp.MatchString(key) {\n\t\t\t\tselGroups[key] = val\n\t\t\t}\n\n\t\t}\n\n\t\td.log.Debugf(\"SNMP device %s has this SELECTED GROUPS: %+v\", d.cfg.ID, selGroups)\n\n\t\t//Only For selected Groups we will get all selected measurements and we will remove repeated values\n\n\t\tvar selMeas []string\n\t\tfor key, val := range selGroups {\n\t\t\td.log.Debugln(\"Selecting from group\", key)\n\t\t\tfor _, item := range val.Measurements {\n\t\t\t\td.log.Debugln(\"Selecting measurements\", item, \"from group\", key)\n\t\t\t\tselMeas = append(selMeas, item)\n\t\t\t}\n\t\t}\n\n\t\tselMeasUniq := removeDuplicatesUnordered(selMeas)\n\n\t\t//Now we know what measurements names will send influx from this device\n\n\t\td.log.Debugln(\"DEVICE MEASUREMENT: \", devMeas, \"HOST: \", d.cfg.Host)\n\t\tfor _, val := range selMeasUniq {\n\t\t\t//check if measurement exist\n\t\t\tif mVal, ok := cfg.Measurements[val]; !ok {\n\t\t\t\td.log.Warnln(\"no measurement configured with name \", val, \"in host :\", d.cfg.Host)\n\t\t\t} else {\n\t\t\t\td.log.Debugln(\"MEASUREMENT CFG KEY:\", val, \" VALUE \", mVal.Name)\n\n\t\t\t\t//creating a new measurement runtime object and asigning to array\n\t\t\t\td.Measurements = append(d.Measurements, &InfluxMeasurement{ID: mVal.ID, cfg: mVal, log: d.log, snmpClient: d.snmpClient})\n\t\t\t}\n\t\t}\n\t}\n\n\t/*For each measurement look for filters and Initialize Measurement with this Filter \t*/\n\n\tfor _, m := range d.Measurements {\n\t\t//check for filters asociated with this measurement\n\t\tvar mfilter *MeasFilterCfg\n\t\tfor _, f := range d.cfg.MeasFilters {\n\t\t\t//we seach if exist in the filter Database\n\t\t\tif filter, ok := cfg.MFilters[f]; ok {\n\t\t\t\tif filter.IDMeasurementCfg == m.ID {\n\t\t\t\t\tmfilter = filter\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif mfilter != nil {\n\t\t\td.log.Debugf(\"filters %s found for device %s and measurment %s \", mfilter.ID, d.cfg.ID, m.cfg.ID)\n\n\t\t} else {\n\t\t\td.log.Debugf(\"no filters found for device %s and measurment %s\", d.cfg.ID, m.cfg.ID)\n\t\t}\n\t\terr := m.Init(mfilter)\n\t\tif err != nil {\n\t\t\td.log.Errorf(\"Error on initialize Measurement %s , Error:%s no data will be gathered for this measurement\", m.cfg.ID, err)\n\t\t\t//d.Measurements = append(d.Measurements[:i], d.Measurements[i+1:]...)\n\t\t}\n\n\t}\n\t//Initialize all snmpMetrics objects and OID array\n\t//get data first time\n\t// useful to inicialize counter all value and test device snmp availability\n\td.log.Debugf(\"SNMP Info: %+v\", d.snmpClient)\n\tfor _, m := range d.Measurements {\n\t\t//if m.cfg.GetMode == \"value\" || d.cfg.SnmpVersion == \"1\" {\n\t\tif m.cfg.GetMode == \"value\" {\n\t\t\t_, _, err := m.SnmpGetData()\n\t\t\tif err != nil {\n\t\t\t\td.log.Errorf(\"SNMP First Get Data error for host: %s\", d.cfg.Host)\n\t\t\t}\n\t\t} else {\n\t\t\t_, _, err := m.SnmpWalkData()\n\t\t\tif err != nil {\n\t\t\t\td.log.Errorf(\"SNMP First Get Data error for host: %s\", d.cfg.Host)\n\t\t\t}\n\t\t}\n\t}\n\n}", "func InitGameProfilers() {\r\n\tupdateProfiler = system.NewProfiler(\"update\")\r\n\tcollisionProfiler = system.NewProfiler(\"collision\")\r\n\tmusicProfiler = system.NewProfiler(\"music\")\r\n\tweatherProfiler = system.NewProfiler(\"weather\")\r\n\tgameModeProfiler = system.NewProfiler(\"gameMode\")\r\n\tdrawProfiler = system.NewProfiler(\"draw\")\r\n\tsortRenderProfiler = system.NewProfiler(\"sortRender\")\r\n\tcullRenderProfiler = system.NewProfiler(\"cullRender\")\r\n\tlightingProfiler = system.NewProfiler(\"lighting\")\r\n\tscriptingProfiler = system.NewProfiler(\"scripting\")\r\n\r\n\tframeRateString = \"total time: 0 ms (0 FPS)\"\r\n\totherTimeString = \"measured time: 0 ms\"\r\n}", "func (p *hardwareProfiler) Profile() (*HardwareProfile, error) {\n\tvar err error\n\thwProfile := &HardwareProfile{}\n\tfor profilerType, profiler := range p.profilers {\n\t\tprofileVal, err2 := profiler.Profile()\n\t\terr = multierr.Append(err, err2)\n\t\tif err2 == nil {\n\t\t\tif hwProfile.TimeEnabled == nil {\n\t\t\t\thwProfile.TimeEnabled = &profileVal.TimeEnabled\n\t\t\t}\n\t\t\tif hwProfile.TimeRunning == nil {\n\t\t\t\thwProfile.TimeRunning = &profileVal.TimeRunning\n\t\t\t}\n\t\t\tswitch profilerType {\n\t\t\tcase unix.PERF_COUNT_HW_CPU_CYCLES:\n\t\t\t\thwProfile.CPUCycles = &profileVal.Value\n\t\t\tcase unix.PERF_COUNT_HW_INSTRUCTIONS:\n\t\t\t\thwProfile.Instructions = &profileVal.Value\n\t\t\tcase unix.PERF_COUNT_HW_CACHE_REFERENCES:\n\t\t\t\thwProfile.CacheRefs = &profileVal.Value\n\t\t\tcase unix.PERF_COUNT_HW_CACHE_MISSES:\n\t\t\t\thwProfile.CacheMisses = &profileVal.Value\n\t\t\tcase unix.PERF_COUNT_HW_BRANCH_INSTRUCTIONS:\n\t\t\t\thwProfile.BranchInstr = &profileVal.Value\n\t\t\tcase unix.PERF_COUNT_HW_BRANCH_MISSES:\n\t\t\t\thwProfile.BranchMisses = &profileVal.Value\n\t\t\tcase unix.PERF_COUNT_HW_BUS_CYCLES:\n\t\t\t\thwProfile.BusCycles = &profileVal.Value\n\t\t\tcase unix.PERF_COUNT_HW_STALLED_CYCLES_FRONTEND:\n\t\t\t\thwProfile.StalledCyclesFrontend = &profileVal.Value\n\t\t\tcase unix.PERF_COUNT_HW_STALLED_CYCLES_BACKEND:\n\t\t\t\thwProfile.StalledCyclesBackend = &profileVal.Value\n\t\t\tcase unix.PERF_COUNT_HW_REF_CPU_CYCLES:\n\t\t\t\thwProfile.RefCPUCycles = &profileVal.Value\n\t\t\t}\n\t\t}\n\t}\n\tif len(multierr.Errors(err)) == len(p.profilers) {\n\t\treturn nil, err\n\t}\n\n\treturn hwProfile, nil\n}", "func (s *DevStat) Init(id string, tm map[string]string, l *logrus.Logger) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\ts.id = id\n\ts.TagMap = tm\n\ts.log = l\n\ts.Counters = make([]interface{}, DevStatTypeSize)\n\ts.Counters[SnmpGetQueries] = 0\n\ts.Counters[SnmpWalkQueries] = 0\n\ts.Counters[SnmpGetErrors] = 0\n\ts.Counters[SnmpWalkErrors] = 0\n\ts.Counters[SnmpQueryTimeouts] = 0\n\ts.Counters[SnmpOIDGetAll] = 0\n\ts.Counters[SnmpOIDGetProcessed] = 0\n\ts.Counters[SnmpOIDGetErrors] = 0\n\ts.Counters[EvalMetricsAll] = 0\n\ts.Counters[EvalMetricsOk] = 0\n\ts.Counters[EvalMetricsErrors] = 0\n\ts.Counters[MetricSent] = 0\n\ts.Counters[MeasurementSent] = 0\n\ts.Counters[MetricSentErrors] = 0\n\ts.Counters[MeasurementSentErrors] = 0\n\ts.Counters[CycleGatherStartTime] = 0\n\ts.Counters[CycleGatherDuration] = 0.0\n\ts.Counters[FilterStartTime] = 0\n\ts.Counters[FilterDuration] = 0.0\n\ts.Counters[BackEndSentStartTime] = 0\n\ts.Counters[BackEndSentDuration] = 0.0\n\ts.Counters[DeviceActive] = 0\n\ts.Counters[DeviceConnected] = 0\n}", "func Meter(component interface{}, sampleRate signal.SampleRate) ResetFunc {\n\tt := getType(component)\n\tmetric := components.get(t)\n\tmetric.components.Add(1)\n\treturn func() MeasureFunc {\n\t\tcalledAt := time.Now()\n\t\tvar (\n\t\t\tbufferSize int\n\t\t\tbufferDuration time.Duration\n\t\t)\n\t\treturn func(s int) {\n\t\t\tmetric.latency.set(time.Since(calledAt))\n\t\t\tmetric.messages.Add(1)\n\t\t\tmetric.samples.Add(int64(s))\n\t\t\t// recalculate buffer duration only when buffer size has changed\n\t\t\tif bufferSize != s {\n\t\t\t\tbufferSize = s\n\t\t\t\tbufferDuration = sampleRate.DurationOf(s)\n\t\t\t}\n\t\t\tmetric.duration.add(bufferDuration)\n\t\t\tcalledAt = time.Now()\n\t\t}\n\t}\n}", "func (c *switchBotCollector) init() error {\n\tdevices, _, err := c.client.Device().List(context.Background())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, d := range devices {\n\t\tswitch d.Type {\n\t\tcase switchbot.Meter:\n\t\t\tc.meters = append(c.meters, d)\n\t\t\tlog.Printf(\"adding meter with device id: %s, name: %s\\n\", d.ID, d.Name)\n\t\t}\n\t}\n\n\treturn nil\n}", "func GetMeter(w http.ResponseWriter, r *http.Request) {\n\t// Assume if we've reach this far, we can access the meter\n\t// context because this handler is a child of the MeterCtx\n\t// middleware. The worst case, the recoverer middleware will save us.\n\tmeter := r.Context().Value(\"meter\").(*Meter)\n\n\tif err := render.Render(w, r, NewMeterResponse(meter)); err != nil {\n\t\trender.Render(w, r, ErrRender(err))\n\t\treturn\n\t}\n}", "func (m *Manager) Meter(delay time.Duration) *Meter {\n\treturn &Meter{\n\t\tm: m,\n\t\tdelay: delay,\n\t\tnext: time.Now(),\n\t}\n}", "func (d *SnmpDevice) Gather(wg *sync.WaitGroup) {\n\t//client := d.snmpClient\n\t//debug := false\n\tif d.DeviceActive && d.snmpClient != nil {\n\t\td.log.Infof(\"Begin first InidevInfo\")\n\t\tstartSnmp := time.Now()\n\t\td.InitDevSnmpInfo()\n\t\telapsedSnmp := time.Since(startSnmp)\n\t\td.log.Infof(\"snmpdevice [%s] snmp INIT runtime measurments/filters took [%s] \", d.cfg.ID, elapsedSnmp)\n\t} else {\n\t\td.log.Infof(\"Can not initialize this device: Is Active: %t | Conection Active: %t \", d.DeviceActive, d.snmpClient != nil)\n\t}\n\n\td.log.Infof(\"Beginning gather process for device %s (%s)\", d.cfg.ID, d.cfg.Host)\n\n\ts := time.Tick(time.Duration(d.cfg.Freq) * time.Second)\n\tfor {\n\t\t//if active\n\t\tif d.DeviceActive {\n\t\t\t//check if device is online\n\t\t\tif d.snmpClient == nil {\n\t\t\t\tclient, err := snmpClient(d)\n\t\t\t\tif err != nil {\n\t\t\t\t\td.log.Errorf(\"Client connect error to device: %s error :%s\", d.cfg.ID, err)\n\t\t\t\t} else {\n\t\t\t\t\td.snmpClient = client\n\t\t\t\t\td.log.Infof(\"SNMP connection stablished initializing SnmpDevice\")\n\t\t\t\t\tstartSnmp := time.Now()\n\t\t\t\t\td.InitDevSnmpInfo()\n\t\t\t\t\telapsedSnmp := time.Since(startSnmp)\n\t\t\t\t\td.log.Infof(\"snmpdevice [%s] snmp INIT runtime measurments/filters took [%s] \", d.cfg.ID, elapsedSnmp)\n\t\t\t\t\t//device not initialized\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t//TODO: review if necesary this Sleep and what is the exact goal for the Timeout\n\t\t\t\t//time.Sleep(time.Duration(d.cfg.Timeout) * time.Second)\n\n\t\t\t\tbpts := d.Influx.BP()\n\t\t\t\tstartSnmp := time.Now()\n\t\t\t\tfor _, m := range d.Measurements {\n\t\t\t\t\td.log.Debugf(\"----------------Processing measurement : %s\", m.cfg.ID)\n\t\t\t\t\tvar nGets, nErrors int64\n\t\t\t\t\t//if m.cfg.GetMode == \"value\" || d.cfg.SnmpVersion == \"1\" {\n\t\t\t\t\tif m.cfg.GetMode == \"value\" {\n\t\t\t\t\t\tnGets, nErrors, _ = m.SnmpGetData()\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnGets, nErrors, _ = m.SnmpWalkData()\n\t\t\t\t\t}\n\t\t\t\t\tif nGets > 0 {\n\t\t\t\t\t\td.addGets(nGets)\n\t\t\t\t\t}\n\t\t\t\t\tif nErrors > 0 {\n\t\t\t\t\t\td.addErrors(nErrors)\n\t\t\t\t\t}\n\t\t\t\t\t//prepare batchpoint\n\t\t\t\t\tpoints := m.GetInfluxPoint(d.TagMap)\n\t\t\t\t\t(*bpts).AddPoints(points)\n\n\t\t\t\t}\n\t\t\t\telapsedSnmp := time.Since(startSnmp)\n\t\t\t\td.log.Infof(\"snmpdevice [%s] snmp pooling took [%s] \", d.cfg.ID, elapsedSnmp)\n\t\t\t\tstartInflux := time.Now()\n\t\t\t\td.Influx.Send(bpts)\n\t\t\t\telapsedInflux := time.Since(startInflux)\n\t\t\t\td.log.Infof(\"snmpdevice [%s] influx send took [%s]\", d.cfg.ID, elapsedInflux)\n\t\t\t\t// pause for interval period and have optional debug toggling\n\t\t\t}\n\t\t} else {\n\t\t\td.log.Infof(\"snmpdevice [%s] Gather process is dissabled\", d.cfg.ID)\n\t\t}\n\tLOOP:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-s:\n\t\t\t\tbreak LOOP\n\t\t\tcase debug := <-d.chDebug:\n\t\t\t\td.StateDebug = debug\n\t\t\t\td.log.Infof(\"DEBUG ACTIVE %s [%t] \", d.cfg.ID, debug)\n\t\t\t\tif debug {\n\t\t\t\t\td.log.Info(\"Activating snmp debug for this device\")\n\t\t\t\t\td.snmpClient.Logger = d.DebugLog()\n\t\t\t\t} else {\n\t\t\t\t\td.log.Info(\"De Activating snmp debug for this device\")\n\t\t\t\t\td.snmpClient.Logger = olog.New(ioutil.Discard, \"\", 0)\n\t\t\t\t}\n\t\t\tcase status := <-d.chEnabled:\n\t\t\t\td.DeviceActive = status\n\t\t\t\td.log.Infof(\"STATUS ACTIVE %s [%t] \", d.cfg.ID, status)\n\t\t\tcase level := <-d.chLogLevel:\n\t\t\t\tl, err := logrus.ParseLevel(level)\n\t\t\t\tif err != nil {\n\t\t\t\t\td.log.Warnf(\"ERROR on Changing LOGLEVEL in %s to [%t] \", d.cfg.ID, level)\n\t\t\t\t}\n\t\t\t\td.log.Level = l\n\t\t\t\td.log.Infof(\"CHANGED LOGLEVEL %s [%s] \", d.cfg.ID, level)\n\t\t\t}\n\t\t}\n\t}\n\twg.Done()\n}", "func (s *DevStat) Init(id string, tm map[string]string, l *logrus.Logger) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\ts.id = id\n\ts.TagMap = tm\n\ts.log = l\n\ts.Counters = make([]interface{}, DevStatTypeSize)\n\ts.Counters[SnmpGetQueries] = 0\n\ts.Counters[SnmpWalkQueries] = 0\n\ts.Counters[SnmpGetErrors] = 0\n\ts.Counters[SnmpWalkErrors] = 0\n\ts.Counters[SnmpQueryTimeouts] = 0\n\ts.Counters[SnmpOIDGetAll] = 0\n\ts.Counters[SnmpOIDGetProcessed] = 0\n\ts.Counters[SnmpOIDGetErrors] = 0\n\ts.Counters[EvalMetricsAll] = 0\n\ts.Counters[EvalMetricsOk] = 0\n\ts.Counters[EvalMetricsErrors] = 0\n\ts.Counters[MetricSent] = 0\n\ts.Counters[MeasurementSent] = 0\n\ts.Counters[MetricSentErrors] = 0\n\ts.Counters[MeasurementSentErrors] = 0\n\ts.Counters[CicleGatherStartTime] = 0\n\ts.Counters[CicleGatherDuration] = 0.0\n\ts.Counters[FilterStartTime] = 0\n\ts.Counters[FilterDuration] = 0.0\n\ts.Counters[BackEndSentStartTime] = 0\n\ts.Counters[BackEndSentDuration] = 0.0\n}", "func (s *System) DSPInfoByPlugin(handle C.uint, description **C.FMOD_DSP_DESCRIPTION) error {\n\t//FMOD_RESULT F_API FMOD_System_GetDSPInfoByPlugin (FMOD_SYSTEM *system, unsigned int handle, const FMOD_DSP_DESCRIPTION **description);\n\treturn ErrNoImpl\n}", "func Init(conf *config.Config) error {\n\tlog := logger.New().With().Int(\"pid\", os.Getpid()).Logger()\n\n\tdriver := registry.GetDriver(conf.MetricsDataDriverType)\n\n\tif driver == nil {\n\t\tlog.Info().Msg(\"No metrics are being recorded.\")\n\t\t// No error but just don't proceed with metrics\n\t\treturn nil\n\t}\n\n\t// configure the driver\n\terr := driver.Configure(conf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm := &Metrics{\n\t\tdataDriver: driver,\n\t\tNumUsersMeasure: stats.Int64(\"cs3_org_sciencemesh_site_total_num_users\", \"The total number of users within this site\", stats.UnitDimensionless),\n\t\tNumGroupsMeasure: stats.Int64(\"cs3_org_sciencemesh_site_total_num_groups\", \"The total number of groups within this site\", stats.UnitDimensionless),\n\t\tAmountStorageMeasure: stats.Int64(\"cs3_org_sciencemesh_site_total_amount_storage\", \"The total amount of storage used within this site\", stats.UnitBytes),\n\t}\n\n\tif err := view.Register(\n\t\tm.getNumUsersView(),\n\t\tm.getNumGroupsView(),\n\t\tm.getAmountStorageView(),\n\t); err != nil {\n\t\treturn err\n\t}\n\n\t// periodically record metrics data\n\tgo func() {\n\t\tfor {\n\t\t\tif err := m.recordMetrics(); err != nil {\n\t\t\t\tlog.Error().Err(err).Msg(\"Metrics recording failed.\")\n\t\t\t}\n\t\t\t<-time.After(time.Millisecond * time.Duration(conf.MetricsRecordInterval))\n\t\t}\n\t}()\n\n\treturn nil\n}", "func (ct *cpuTracker) getMeter(vdr ids.ShortID) uptime.Meter {\n\tmeter, exists := ct.cpuSpenders[vdr]\n\tif exists {\n\t\treturn meter\n\t}\n\n\tnewMeter := ct.factory.New(ct.halflife)\n\tct.cpuSpenders[vdr] = newMeter\n\treturn newMeter\n}", "func (m *metricDcgmGpuProfilingDramUtilization) init() {\n\tm.data.SetName(\"dcgm.gpu.profiling.dram_utilization\")\n\tm.data.SetDescription(\"Fraction of cycles data was being sent or received from GPU memory.\")\n\tm.data.SetUnit(\"1\")\n\tm.data.SetEmptyGauge()\n\tm.data.Gauge().DataPoints().EnsureCapacity(m.capacity)\n}", "func MeterProvider() metric.Provider {\n\tif gp := globalMeter.Load(); gp != nil {\n\t\treturn gp.(meterProvider).mp\n\t}\n\treturn metric.NoopProvider{}\n}", "func meterReader(d *db.DB) error {\n\tsect := d.Config.GetSection(\"meter\")\n\tif sect == nil {\n\t\treturn nil\n\t}\n\tvar angle float64\n\ta, err := sect.GetArg(\"rotate\")\n\tif err == nil {\n\t\tangle, err = strconv.ParseFloat(a, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tsource, err := sect.GetArg(\"source\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tr, err := NewReader(sect, d.Trace)\n\tif err != nil {\n\t\treturn err\n\t}\n\td.AddDiff(db.D_IN_POWER, time.Minute*5)\n\td.AddDiff(db.D_OUT_POWER, time.Minute*5)\n\td.AddAccum(db.A_IN_TOTAL, true)\n\td.AddAccum(db.A_OUT_TOTAL, true)\n\td.AddSubAccum(db.A_IMPORT, true)\n\td.AddSubAccum(db.A_IMPORT, true)\n\td.AddSubAccum(db.A_EXPORT, true)\n\td.AddSubAccum(db.A_EXPORT, true)\n\tlog.Printf(\"Registered meter LCD reader\\n\")\n\tgo runReader(d, r, source, angle)\n\treturn nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TestGetMgmtPortsSortedCost covers both GetMgmtPortsSortedCost and GetAllPortsSortedCost.
func TestGetMgmtPortsSortedCost(t *testing.T) { testMatrix := map[string]struct { deviceNetworkStatus DeviceNetworkStatus rotate int expectedMgmtValue []string expectedAllValue []string }{ "Test single": { deviceNetworkStatus: DeviceNetworkStatus{ Version: DPCIsMgmt, Ports: []NetworkPortStatus{ {IfName: "port1", IsMgmt: true, Cost: 0}, }, }, expectedMgmtValue: []string{"port1"}, expectedAllValue: []string{"port1"}, }, "Test single rotate": { deviceNetworkStatus: DeviceNetworkStatus{ Version: DPCIsMgmt, Ports: []NetworkPortStatus{ {IfName: "port1", IsMgmt: true, Cost: 0}, }, }, rotate: 14, expectedMgmtValue: []string{"port1"}, expectedAllValue: []string{"port1"}, }, "Test empty": { deviceNetworkStatus: DeviceNetworkStatus{}, expectedMgmtValue: []string{}, expectedAllValue: []string{}, }, "Test no management": { deviceNetworkStatus: DeviceNetworkStatus{ Version: DPCIsMgmt, Ports: []NetworkPortStatus{ {IfName: "port1", IsMgmt: false, Cost: 0}, }, }, rotate: 14, expectedMgmtValue: []string{}, expectedAllValue: []string{"port1"}, }, "Test duplicates": { deviceNetworkStatus: DeviceNetworkStatus{ Version: DPCIsMgmt, Ports: []NetworkPortStatus{ {IfName: "port1", IsMgmt: true, Cost: 17}, {IfName: "port2", IsMgmt: true, Cost: 1}, {IfName: "port3", IsMgmt: true, Cost: 17}, {IfName: "port4", IsMgmt: true, Cost: 1}, }, }, expectedMgmtValue: []string{"port2", "port4", "port1", "port3"}, expectedAllValue: []string{"port2", "port4", "port1", "port3"}, }, "Test duplicates rotate": { deviceNetworkStatus: DeviceNetworkStatus{ Version: DPCIsMgmt, Ports: []NetworkPortStatus{ {IfName: "port1", IsMgmt: true, Cost: 17}, {IfName: "port2", IsMgmt: true, Cost: 1}, {IfName: "port3", IsMgmt: true, Cost: 17}, {IfName: "port4", IsMgmt: true, Cost: 1}, }, }, rotate: 1, expectedMgmtValue: []string{"port4", "port2", "port3", "port1"}, expectedAllValue: []string{"port4", "port2", "port3", "port1"}, }, "Test duplicates some management": { deviceNetworkStatus: DeviceNetworkStatus{ Version: DPCIsMgmt, Ports: []NetworkPortStatus{ {IfName: "port1", IsMgmt: false, Cost: 17}, {IfName: "port2", IsMgmt: false, Cost: 1}, {IfName: "port3", IsMgmt: true, Cost: 17}, {IfName: "port4", IsMgmt: true, Cost: 1}, }, }, expectedMgmtValue: []string{"port4", "port3"}, expectedAllValue: []string{"port2", "port4", "port1", "port3"}, }, "Test reverse": { deviceNetworkStatus: DeviceNetworkStatus{ Version: DPCIsMgmt, Ports: []NetworkPortStatus{ {IfName: "port1", IsMgmt: true, Cost: 2}, {IfName: "port2", IsMgmt: true, Cost: 1}, {IfName: "port3", IsMgmt: true, Cost: 0}, }, }, expectedMgmtValue: []string{"port3", "port2", "port1"}, expectedAllValue: []string{"port3", "port2", "port1"}, }, "Test reverse some management": { deviceNetworkStatus: DeviceNetworkStatus{ Version: DPCIsMgmt, Ports: []NetworkPortStatus{ {IfName: "port1", IsMgmt: true, Cost: 2}, {IfName: "port2", IsMgmt: false, Cost: 1}, {IfName: "port3", IsMgmt: true, Cost: 0}, }, }, expectedMgmtValue: []string{"port3", "port1"}, expectedAllValue: []string{"port3", "port2", "port1"}, }, } for testname, test := range testMatrix { t.Logf("Running test case %s", testname) value := GetMgmtPortsSortedCost(test.deviceNetworkStatus, test.rotate) assert.Equal(t, test.expectedMgmtValue, value) value = GetAllPortsSortedCost(test.deviceNetworkStatus, test.rotate) assert.Equal(t, test.expectedAllValue, value) } }
[ "func (m *MockTCPRuleDao) GetUsedPortsByIP(ip string) ([]*model.TCPRule, error) {\n\tret := m.ctrl.Call(m, \"GetUsedPortsByIP\", ip)\n\tret0, _ := ret[0].([]*model.TCPRule)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (no *NetworkOverhead) sortNetworkTopologyCosts(networkTopology *ntv1alpha1.NetworkTopology) {\n\tif no.weightsName != ntv1alpha1.NetworkTopologyNetperfCosts { // Manual weights were selected\n\t\tfor _, w := range networkTopology.Spec.Weights {\n\t\t\t// Sort Costs by TopologyKey, might not be sorted since were manually defined\n\t\t\tsort.Sort(networkawareutil.ByTopologyKey(w.TopologyList))\n\t\t}\n\t}\n}", "func sortNodesByUsage(nodes []NodeInfo, resourceToWeightMap sorter.ResourceToWeightMap, ascending bool) {\n\tscorer := sorter.ResourceUsageScorer(resourceToWeightMap)\n\tsort.Slice(nodes, func(i, j int) bool {\n\t\tvar iNodeUsage, jNodeUsage corev1.ResourceList\n\t\tif nodeMetric := nodes[i].nodeMetric.Status.NodeMetric; nodeMetric != nil {\n\t\t\tiNodeUsage = nodeMetric.NodeUsage.ResourceList\n\t\t}\n\t\tif nodeMetric := nodes[j].nodeMetric.Status.NodeMetric; nodeMetric != nil {\n\t\t\tjNodeUsage = nodeMetric.NodeUsage.ResourceList\n\t\t}\n\n\t\tiScore := scorer(iNodeUsage, nodes[i].node.Status.Allocatable)\n\t\tjScore := scorer(jNodeUsage, nodes[j].node.Status.Allocatable)\n\t\tif ascending {\n\t\t\treturn iScore < jScore\n\t\t}\n\t\treturn iScore > jScore\n\t})\n}", "func (m *MockTenantServiceLBMappingPortDao) GetLBPortsASC() ([]*model.TenantServiceLBMappingPort, error) {\n\tret := m.ctrl.Call(m, \"GetLBPortsASC\")\n\tret0, _ := ret[0].([]*model.TenantServiceLBMappingPort)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (r *Report) SortedUsersByTotalCost() UserList {\n\ttype tempUser struct {\n\t\tname string\n\t\ttotalCost float64\n\t\tdetailedCosts map[string]float64\n\t}\n\tuserMap := make(map[string]*tempUser)\n\t// Go through all ReportItems\n\tfor _, item := range r.Items {\n\t\t// Group by AccountId\n\t\tif user, ok := userMap[item.Owner]; ok {\n\t\t\tuser.totalCost += item.Cost\n\t\t\t// Group by Description\n\t\t\tif cost, ok := user.detailedCosts[item.Description]; ok {\n\t\t\t\tuser.detailedCosts[item.Description] = cost + item.Cost\n\t\t\t} else {\n\t\t\t\tuser.detailedCosts[item.Description] = item.Cost\n\t\t\t}\n\t\t} else {\n\t\t\tcosts := make(map[string]float64)\n\t\t\tcosts[item.Description] = item.Cost\n\t\t\tuserMap[item.Owner] = &tempUser{item.Owner, item.Cost, costs}\n\t\t}\n\t}\n\n\tuserList := make(UserList, 0, len(userMap))\n\tfor _, user := range userMap {\n\t\t// omit users with low TotalCost\n\t\tif user.totalCost < MinimumTotalCost {\n\t\t\tcontinue\n\t\t}\n\t\t// convert detailedCosts into sorted CostLists\n\t\tdetailedCostList := convertCostMapToSortedList(user.detailedCosts)\n\t\t// add generated User to userList\n\t\tuserList = append(userList, User{user.name, user.totalCost, detailedCostList})\n\t}\n\n\tsort.Sort(sort.Reverse(userList))\n\treturn userList\n}", "func TestPortaniaGetPorts(t *testing.T) {\n\n\ttestSuite := map[string]struct {\n\t\tportRange string\n\t\tportList []string\n\t\terr string\n\t\tports []int\n\t}{\n\t\t\"getPorts should throw an error due to nil values\": {\n\t\t\terr: \"no ports found to parse\",\n\t\t},\n\t\t\"getPorts using portList should return the ports 80,443,8080\": {\n\t\t\tportList: []string{\"80\", \"443\", \"8080\"},\n\t\t\tports: []int{80, 443, 8080},\n\t\t},\n\t\t\"getPorts using portRange should return the ports 80-85\": {\n\t\t\tportRange: \"80-85\",\n\t\t\tports: []int{80, 81, 82, 83, 84, 85},\n\t\t},\n\t}\n\tfor testName, testCase := range testSuite {\n\n\t\tt.Logf(\"Running test %v\\n\", testName)\n\t\tports, err := getPorts(testCase.portList, testCase.portRange)\n\t\tif err != nil && err.Error() != testCase.err {\n\t\t\tt.Errorf(\"expected getPorts to fail with %v but received %v.\", testCase.err, err.Error())\n\t\t} else {\n\t\t\tt.Logf(\"received the expected error result %v\", testCase.err)\n\t\t}\n\n\t\tif len(testCase.ports) != 0 {\n\n\t\t\tfor _, p := range testCase.ports {\n\n\t\t\t\tmatch := false\n\t\t\t\tfor _, x := range ports {\n\t\t\t\t\tif p == x {\n\t\t\t\t\t\tmatch = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif match == false {\n\t\t\t\t\tt.Errorf(\"%v was not found in the returned slice from getPorts\", p)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func convertToTotalConnectionCapacityPerPortResponse(tccs []models.TotalConnectionCapacityPerPort) (tccList []messages.TotalConnectionCapacityPerPortResponse) {\n\ttccList = []messages.TotalConnectionCapacityPerPortResponse{}\n\tfor _, vTcc := range tccs {\n\t\ttcc := messages.TotalConnectionCapacityPerPortResponse{}\n\t\ttcc.Protocol = vTcc.Protocol\n\t\ttcc.Port = vTcc.Port\n\t\tif vTcc.Connection > 0 {\n\t\t\ttcc.Connection = &vTcc.Connection\n\t\t}\n\t\tif vTcc.ConnectionClient > 0 {\n\t\t\ttcc.ConnectionClient = &vTcc.ConnectionClient\n\t\t}\n\t\tif vTcc.Embryonic > 0 {\n\t\t\ttcc.Embryonic = &vTcc.Embryonic\n\t\t}\n\t\tif vTcc.EmbryonicClient > 0 {\n\t\t\ttcc.EmbryonicClient = &vTcc.EmbryonicClient\n\t\t}\n\t\tif vTcc.ConnectionPs > 0 {\n\t\t\ttcc.ConnectionPs = &vTcc.ConnectionPs\n\t\t}\n\t\tif vTcc.ConnectionClientPs > 0 {\n\t\t\ttcc.ConnectionClientPs = &vTcc.ConnectionClientPs\n\t\t}\n\t\tif vTcc.RequestPs > 0 {\n\t\t\ttcc.RequestPs = &vTcc.RequestPs\n\t\t}\n\t\tif vTcc.RequestClientPs > 0 {\n\t\t\ttcc.RequestClientPs = &vTcc.RequestClientPs\n\t\t}\n\t\tif vTcc.PartialRequestPs > 0 {\n\t\t\ttcc.PartialRequestPs = &vTcc.PartialRequestPs\n\t\t}\n\t\tif vTcc.PartialRequestClientPs > 0 {\n\t\t\ttcc.PartialRequestClientPs = &vTcc.PartialRequestClientPs\n\t\t}\n\t\ttccList = append(tccList, tcc)\n\t}\n\treturn\n}", "func SortService(elements []int) {\n\tif len(elements) < 10000 {\n\t\tsortfunction.BubbleSort(elements)\n\t\treturn\n\t}\n\tsortfunction.PackageSort(elements)\n}", "func (a *BitlinksApiService) GetSortedBitlinks(ctx _context.Context, groupGuid string, sort string) ApiGetSortedBitlinksRequest {\n\treturn ApiGetSortedBitlinksRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tgroupGuid: groupGuid,\n\t\tsort: sort,\n\t}\n}", "func (c *APCtl) GetPortStats(dpID uint64, portID uint32, names []string, stream fibcapi.FIBCApApi_GetPortStatsServer) error {\n\tc.stats.Inc(APStatsGetPortStats)\n\n\tc.log.Debugf(\"PortStats: dpid:%d port:%d names:%v\", dpID, portID, names)\n\n\tif len(names) == 0 {\n\t\tnames = apCtlPortStatsNames\n\n\t\tc.log.Debugf(\"PortStats: use default stats list.\")\n\t}\n\n\tw := NewDBMpWaiter()\n\txid := c.db.Waiters().Register(w)\n\tdefer c.db.Waiters().Unregister(xid)\n\n\tcmd := fibcapi.FFPortStats_GET\n\tmsg := NewDPMonitorReplyMpPort(dpID, portID, names, cmd, xid)\n\tif err := c.db.SendDPMonitorReply(dpID, msg); err != nil {\n\t\tc.stats.Inc(APStatsGetPortStatsErr)\n\n\t\tc.log.Errorf(\"GetPortStats: send monitor reply error. %s\", err)\n\t\treturn err\n\t}\n\n\tc.log.Debugf(\"PortStats: wait... xid:%d\", xid)\n\n\tif err := w.Wait(c.psTimeout); err != nil {\n\t\tc.stats.Inc(APStatsGetPortStatsErr)\n\n\t\tc.log.Errorf(\"GetPortStats: xid:%d %s\", xid, err)\n\t\treturn err\n\t}\n\n\tc.log.Debugf(\"PortStats: wait...done. xid:%d\", xid)\n\n\tportReply := w.Reply.GetPort()\n\tif portReply == nil {\n\t\tc.stats.Inc(APStatsGetPortStatsErr)\n\n\t\tc.log.Errorf(\"GetPortStats: invaid reply from dp. %d\", xid)\n\t\treturn fmt.Errorf(\"invalid reply from dp. %d\", xid)\n\t}\n\n\tc.extendPortStats(dpID, portReply.Stats)\n\n\tfor _, stats := range portReply.Stats {\n\t\tif err := stream.Send(stats); err != nil {\n\t\t\tc.stats.Inc(APStatsGetPortStatsErr)\n\n\t\t\tc.log.Errorf(\"GetPortStats: send error. %s\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (solver *MapSolver)GetMinCostAfterRegreting(node *data.MachineNode, regretArcList []int)(int, []int, []int, error){\n\tif regretArcList == nil || len(regretArcList) == 0{\n\t\tpanic(\"GetMinCostAfterRegreting's regretArcList can't be empty\")\n\t}\n\tcostSum := 0\n\tcostList := make([]int, len(regretArcList))\n\tscheduledMachineIdList := make([]int, len(regretArcList)) // store machineNode id for each preemted task finally schedulation\n\tscheduledMachineArcList := make([]int, len(regretArcList)) // store arc index of data.ArcList for every task's templateNode to machienNode\n\tfor i, _ := range scheduledMachineIdList{ // initial all task to -1 machine\n\t\tscheduledMachineIdList[i] = -1\n\t}\n\tfor i, _:= range regretArcList {\n\t\tnode := data.ArcList[regretArcList[i]].DstNode\n\t\ttemplateNode, err := node.(*data.TemplateNode)\n\t\tif !err {\n\t\t\tpanic(\"regretArc's dstNode must be templateNode\")\n\t\t}\n\t\ttask := templateNode.SourceTasks[0]\n\n\n\t\t// we only need to iterate by TaskMinCostArcIdList's order\n\t\t// TODO we only need to iterate by TaskMinCostArcIdList's order\n\t\tminCost := data.MAXINTVALUE\n\t\tfor _, arc := range data.TaskMinCostArcIdList[templateNode.SourceTasks[0].Index]{\n\t\t\t// the new machine can't be the old machine\n\t\t\tif(solver.HasScheduled(arc)){\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttargetNode := arc.DstNode\n\t\t\ttargetMachineNode, err := targetNode.(*data.MachineNode)\n\t\t\tif !err {\n\t\t\t\tpanic(\"templateNode can only connect to machineNode on its right\")\n\t\t\t}\n\t\t\tj := targetMachineNode.Machine.Index\n\t\t\t// 1. the new machine has less cost\n\t\t\t// 2. the new machine has enough capacity\n\t\t\t// 3. the new machine can't be mutexed with task\n\t\t\t// check its capacity and its mutexed tag\n\t\t\thasEnoughCapacity := false\n\t\t\tisMutexed := false\n\n\t\t\ttoMachine := data.ClusterMachineList[j]\n\t\t\ttoMachineNode := toMachine.Node\n\n\t\t\t// check if mutexed\n\t\t\tfor _,tag := range task.ExclusiveTag{\n\t\t\t\tif _, isExsit := toMachineNode.ScheduledTasks[tag]; isExsit {\n\t\t\t\t\tisMutexed = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif isMutexed {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// check if has enough capacity\n\t\t\tarcToEnd := toMachineNode.GetRightOutArcs()[0]\n\t\t\tsumCapacity := make([]int, len(arcToEnd.Capacity))\n\t\t\tdata.ListAdd(sumCapacity, arcToEnd.Capacity)\n\t\t\tfor k:=0; k<i; k++ { // check if this machine has been used for previous task schedulation\n\t\t\t\tif arc.DstNode.GetID() == scheduledMachineIdList[k] {\n\t\t\t\t\tnode_ := data.ArcList[regretArcList[k]].DstNode\n\t\t\t\t\ttemplateNode_ := node_.(*data.TemplateNode)\n\t\t\t\t\ttask_ := templateNode_.SourceTasks[0]\n\t\t\t\t\tdata.ListSub(sumCapacity, task_.GetCapacity())\n\t\t\t\t}\n\t\t\t}\n\t\t\tif solver.HasEnoughCapacityForTask(sumCapacity, task){\n\t\t\t\thasEnoughCapacity = true\n\t\t\t}\n\t\t\tif !hasEnoughCapacity{\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// update minCost and scheduledMachineList\n\n\t\t\tscheduledMachineIdList[i] = arc.DstNode.GetID()\n\t\t\tscheduledMachineArcList[i] = arc.ID\n\t\t\tminCost = arc.Cost\n\t\t\tbreak\n\n\t\t}\n\t\tif minCost == data.MAXINTVALUE{ // there is no machine for this task to be scheduled, we droped this task(or we can get another preemptedArcList)\n\t\t\treturn 0, nil, nil, errors.New(\"no machine suitable for preempted task\")\n\t\t}\n\t\tcostList[i] = -minCost\n\n\t}\n\t// get sumCost\n\tfor i,_ := range regretArcList {\n\t\tcostSum += (data.ArcList[regretArcList[i]].Cost - costList[i])\n\t}\n\n\n\treturn costSum, costList, scheduledMachineArcList, nil\n}", "func (no *NetworkOverhead) getAccumulatedCost(scheduledList networkawareutil.ScheduledList, dependencyList []agv1alpha1.DependenciesInfo, nodeName string, region string,\n\tzone string, costMap map[networkawareutil.CostKey]int64) (int64, error) {\n\n\t// keep track of the accumulated cost\n\tvar cost int64 = 0\n\n\t// calculate accumulated shortest path\n\tfor _, podAllocated := range scheduledList { // For each pod already allocated\n\t\tfor _, d := range dependencyList { // For each pod dependency\n\t\t\t// If the pod allocated is not an established dependency, continue.\n\t\t\tif podAllocated.Selector != d.Workload.Selector {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif podAllocated.Hostname == nodeName { // If the Pod hostname is the node being scored\n\t\t\t\tcost += SameHostname\n\t\t\t} else { // If Nodes are not the same\n\t\t\t\t// Get NodeInfo from pod Hostname\n\t\t\t\tpodNodeInfo, err := no.handle.SnapshotSharedLister().NodeInfos().Get(podAllocated.Hostname)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.ErrorS(nil, \"getting pod hostname %q from Snapshot: %v\", podNodeInfo, err)\n\t\t\t\t\treturn cost, err\n\t\t\t\t}\n\t\t\t\t// Get zone and region from Pod Hostname\n\t\t\t\tregionPodNodeInfo := networkawareutil.GetNodeRegion(podNodeInfo.Node())\n\t\t\t\tzonePodNodeInfo := networkawareutil.GetNodeZone(podNodeInfo.Node())\n\n\t\t\t\tif regionPodNodeInfo == \"\" && zonePodNodeInfo == \"\" { // Node has no zone and region defined\n\t\t\t\t\tcost += MaxCost\n\t\t\t\t} else if region == regionPodNodeInfo { // If Nodes belong to the same region\n\t\t\t\t\tif zone == zonePodNodeInfo { // If Nodes belong to the same zone\n\t\t\t\t\t\tcost += SameZone\n\t\t\t\t\t} else { // belong to a different zone\n\t\t\t\t\t\tvalue, ok := costMap[networkawareutil.CostKey{ // Retrieve the cost from the map (origin: zone, destination: pod zoneHostname)\n\t\t\t\t\t\t\tOrigin: zone, // Time Complexity: O(1)\n\t\t\t\t\t\t\tDestination: zonePodNodeInfo,\n\t\t\t\t\t\t}]\n\t\t\t\t\t\tif ok {\n\t\t\t\t\t\t\tcost += value // Add the cost to the sum\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcost += MaxCost\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else { // belong to a different region\n\t\t\t\t\tvalue, ok := costMap[networkawareutil.CostKey{ // Retrieve the cost from the map (origin: region, destination: pod regionHostname)\n\t\t\t\t\t\tOrigin: region, // Time Complexity: O(1)\n\t\t\t\t\t\tDestination: regionPodNodeInfo,\n\t\t\t\t\t}]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tcost += value // Add the cost to the sum\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcost += MaxCost\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn cost, nil\n}", "func (no *NetworkOverhead) populateCostMap(costMap map[networkawareutil.CostKey]int64, networkTopology *ntv1alpha1.NetworkTopology, region string, zone string) {\n\tfor _, w := range networkTopology.Spec.Weights { // Check the weights List\n\t\tif w.Name != no.weightsName { // If it is not the Preferred algorithm, continue\n\t\t\tcontinue\n\t\t}\n\n\t\tif region != \"\" { // Add Region Costs\n\t\t\t// Binary search through CostList: find the Topology Key for region\n\t\t\ttopologyList := networkawareutil.FindTopologyKey(w.TopologyList, ntv1alpha1.NetworkTopologyRegion)\n\n\t\t\tif no.weightsName != ntv1alpha1.NetworkTopologyNetperfCosts {\n\t\t\t\t// Sort Costs by origin, might not be sorted since were manually defined\n\t\t\t\tsort.Sort(networkawareutil.ByOrigin(topologyList))\n\t\t\t}\n\n\t\t\t// Binary search through TopologyList: find the costs for the given Region\n\t\t\tcosts := networkawareutil.FindOriginCosts(topologyList, region)\n\n\t\t\t// Add Region Costs\n\t\t\tfor _, c := range costs {\n\t\t\t\tcostMap[networkawareutil.CostKey{ // Add the cost to the map\n\t\t\t\t\tOrigin: region,\n\t\t\t\t\tDestination: c.Destination}] = c.NetworkCost\n\t\t\t}\n\t\t}\n\t\tif zone != \"\" { // Add Zone Costs\n\t\t\t// Binary search through CostList: find the Topology Key for zone\n\t\t\ttopologyList := networkawareutil.FindTopologyKey(w.TopologyList, ntv1alpha1.NetworkTopologyZone)\n\n\t\t\tif no.weightsName != ntv1alpha1.NetworkTopologyNetperfCosts {\n\t\t\t\t// Sort Costs by origin, might not be sorted since were manually defined\n\t\t\t\tsort.Sort(networkawareutil.ByOrigin(topologyList))\n\t\t\t}\n\n\t\t\t// Binary search through TopologyList: find the costs for the given Region\n\t\t\tcosts := networkawareutil.FindOriginCosts(topologyList, zone)\n\n\t\t\t// Add Zone Costs\n\t\t\tfor _, c := range costs {\n\t\t\t\tcostMap[networkawareutil.CostKey{ // Add the cost to the map\n\t\t\t\t\tOrigin: zone,\n\t\t\t\t\tDestination: c.Destination}] = c.NetworkCost\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *MockTenantServicesPortDao) GetDepUDPPort(serviceID string) ([]*model.TenantServicesPort, error) {\n\tret := m.ctrl.Call(m, \"GetDepUDPPort\", serviceID)\n\tret0, _ := ret[0].([]*model.TenantServicesPort)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (client *HammerspaceClient) GetDataPortals(nodeID string) ([]common.DataPortal, error) {\n req, err := client.generateRequest(\"GET\", \"/data-portals/\", \"\")\n statusCode, respBody, _, err := client.doRequest(*req)\n\n if err != nil {\n log.Error(err)\n return nil, err\n }\n if statusCode != 200 {\n return nil, errors.New(fmt.Sprintf(common.UnexpectedHSStatusCode, statusCode, 200))\n }\n\n var portals []common.DataPortal\n err = json.Unmarshal([]byte(respBody), &portals)\n if err != nil {\n log.Error(\"Error parsing JSON response: \" + err.Error())\n return nil, err\n }\n\n // filter dataportals\n var filteredPortals []common.DataPortal\n for _, p := range portals {\n if p.OperState == \"UP\" && p.AdminState == \"UP\" && p.DataPortalType == \"NFS_V3\" {\n filteredPortals = append(filteredPortals, p)\n }\n }\n\n // sort dataportals\n var colocatedPortals []common.DataPortal\n var otherPortals []common.DataPortal\n //// Find colocated node portals\n for _, p := range filteredPortals {\n if p.Node.Name == nodeID {\n colocatedPortals = append(colocatedPortals, p)\n log.Infof(\"Found co-located data-portal, %s, with node name, %s\", p.Uoid[\"uuid\"], p.Node.Name)\n } else {\n otherPortals = append(otherPortals, p)\n }\n }\n\n sortedPortals := append(colocatedPortals, otherPortals...)\n\n return sortedPortals, nil\n}", "func ShowCalcDurationBySort(sortable Sortable, target []int) {\n\t_, duration := SortWithDuration(sortable, target)\n\tfmt.Printf(\"call took %v to run by %v\\n\", duration, reflect.TypeOf(sortable))\n}", "func (a *UsageMeteringApi) GetCostByOrg(ctx _context.Context, startMonth time.Time, o ...GetCostByOrgOptionalParameters) (CostByOrgResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarReturnValue CostByOrgResponse\n\t\toptionalParams GetCostByOrgOptionalParameters\n\t)\n\n\tif len(o) > 1 {\n\t\treturn localVarReturnValue, nil, datadog.ReportError(\"only one argument of type GetCostByOrgOptionalParameters is allowed\")\n\t}\n\tif len(o) == 1 {\n\t\toptionalParams = o[0]\n\t}\n\n\tlocalBasePath, err := a.Client.Cfg.ServerURLWithContext(ctx, \"v2.UsageMeteringApi.GetCostByOrg\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, datadog.GenericOpenAPIError{ErrorMessage: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v2/usage/cost_by_org\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tlocalVarQueryParams.Add(\"start_month\", datadog.ParameterToString(startMonth, \"\"))\n\tif optionalParams.EndMonth != nil {\n\t\tlocalVarQueryParams.Add(\"end_month\", datadog.ParameterToString(*optionalParams.EndMonth, \"\"))\n\t}\n\tlocalVarHeaderParams[\"Accept\"] = \"application/json;datetime-format=rfc3339\"\n\n\tdatadog.SetAuthKeys(\n\t\tctx,\n\t\t&localVarHeaderParams,\n\t\t[2]string{\"apiKeyAuth\", \"DD-API-KEY\"},\n\t\t[2]string{\"appKeyAuth\", \"DD-APPLICATION-KEY\"},\n\t)\n\treq, err := a.Client.PrepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, nil)\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 := datadog.ReadBody(localVarHTTPResponse)\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := datadog.GenericOpenAPIError{\n\t\t\tErrorBody: localVarBody,\n\t\t\tErrorMessage: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 || localVarHTTPResponse.StatusCode == 403 || localVarHTTPResponse.StatusCode == 429 {\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\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.ErrorModel = 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 := datadog.GenericOpenAPIError{\n\t\t\tErrorBody: localVarBody,\n\t\t\tErrorMessage: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (test *Test) GetPorts(projectName string, ip string) ([]models.Port, error) {\n\treturn tests.NormalPorts, nil\n}", "func (suite *BuilderTestSuite) TestPortTasks() {\n\tportToRole := map[uint32]string{\n\t\t1000: \"*\",\n\t\t1002: \"*\",\n\t\t1004: \"role\",\n\t\t1006: \"role\",\n\t}\n\n\tnumTasks := 2\n\t// add more scalar resource to make sure we are only bound by ports.\n\tresourceTasks := 4\n\tresources := suite.getResources(resourceTasks)\n\tresources = append(resources, util.CreatePortResources(portToRole)...)\n\n\tbuilder := NewBuilder(resources)\n\tsuite.Equal(\n\t\tmap[string]scalar.Resources{\n\t\t\t\"*\": {\n\t\t\t\tCPU: float64(resourceTasks * _cpu),\n\t\t\t\tMem: float64(resourceTasks * _mem),\n\t\t\t\tDisk: float64(resourceTasks * _disk),\n\t\t\t},\n\t\t},\n\t\tbuilder.scalars)\n\tsuite.Equal(\n\t\tmap[uint32]string{\n\t\t\t1000: \"*\",\n\t\t\t1002: \"*\",\n\t\t\t1004: \"role\",\n\t\t\t1006: \"role\",\n\t\t},\n\t\tbuilder.portToRoles)\n\ttid := suite.createTestTaskIDs(2)\n\ttaskConfig := createTestTaskConfigs(1)[0]\n\t// Requires 3 ports, 1 static and 2 dynamic ones.\n\ttaskConfig.Ports = []*task.PortConfig{\n\t\t{\n\t\t\tName: \"static\",\n\t\t\tValue: 80,\n\t\t\tEnvName: \"STATIC_PORT\",\n\t\t},\n\t\t{\n\t\t\tName: \"dynamic_env\",\n\t\t\tEnvName: \"DYNAMIC_ENV\",\n\t\t},\n\t\t{\n\t\t\tName: \"dynamic_env_port\",\n\t\t\tEnvName: \"DYNAMIC_ENV_PORT\",\n\t\t},\n\t}\n\ttaskConfig.Labels = []*peloton.Label{\n\t\t{\n\t\t\tKey: _tmpLabelKey,\n\t\t\tValue: _tmpLabelValue,\n\t\t},\n\t}\n\tselectedDynamicPorts := []map[string]uint32{\n\t\t{\n\t\t\t\"dynamic_env\": 1000,\n\t\t\t\"dynamic_env_port\": 1002,\n\t\t},\n\t\t{\n\t\t\t\"dynamic_env\": 1004,\n\t\t\t\"dynamic_env_port\": 1006,\n\t\t},\n\t}\n\n\tdiscoveryPortSet := make(map[uint32]bool)\n\tfor i := 0; i < numTasks; i++ {\n\t\ttask := &hostsvc.LaunchableTask{\n\t\t\tTaskId: tid[i],\n\t\t\tConfig: taskConfig,\n\t\t\tPorts: selectedDynamicPorts[i],\n\t\t}\n\t\tinfo, err := builder.Build(task)\n\t\tsuite.NoError(err)\n\t\tsuite.Equal(tid[i], info.GetTaskId())\n\t\tsc := scalar.FromMesosResources(info.GetResources())\n\t\tsuite.Equal(\n\t\t\tscalar.Resources{CPU: _cpu, Mem: _mem, Disk: _disk},\n\t\t\tsc)\n\t\tdiscoveryInfo := info.GetDiscovery()\n\t\tsuite.NotNil(discoveryInfo)\n\t\tsuite.Equal(_testJobID, discoveryInfo.GetName()) // job id\n\t\tmesosPorts := discoveryInfo.GetPorts().GetPorts()\n\t\tsuite.Equal(3, len(mesosPorts))\n\n\t\tvar staticFound uint32\n\t\tportsInDiscovery := make(map[string]uint32)\n\t\tfor _, mp := range mesosPorts {\n\t\t\tif mp.GetName() == \"static\" {\n\t\t\t\tstaticFound = mp.GetNumber()\n\t\t\t} else {\n\t\t\t\tportsInDiscovery[mp.GetName()] = mp.GetNumber()\n\t\t\t\tdiscoveryPortSet[mp.GetNumber()] = true\n\t\t\t}\n\t\t}\n\n\t\tsuite.Equal(\n\t\t\tuint32(80),\n\t\t\tstaticFound,\n\t\t\t\"static port is not found in %v\", mesosPorts)\n\n\t\tenvVars := info.GetCommand().GetEnvironment().GetVariables()\n\t\tsuite.Equal(6, len(envVars))\n\n\t\tenvMap := make(map[string]string)\n\t\tfor _, envVar := range envVars {\n\t\t\tenvMap[envVar.GetName()] = envVar.GetValue()\n\t\t}\n\t\tsuite.Equal(6, len(envMap))\n\t\tsuite.Contains(envMap, \"DYNAMIC_ENV_PORT\")\n\t\tp, err := strconv.Atoi(envMap[\"DYNAMIC_ENV_PORT\"])\n\t\tsuite.NoError(err)\n\t\tsuite.Contains(portToRole, uint32(p))\n\t\tsuite.Contains(envMap, \"STATIC_PORT\")\n\t\tsuite.Equal(\"80\", envMap[\"STATIC_PORT\"])\n\n\t\tsuite.Equal(\n\t\t\tstrconv.Itoa(int(portsInDiscovery[\"dynamic_env\"])),\n\t\t\tenvMap[\"DYNAMIC_ENV\"])\n\n\t\tsuite.Equal(\n\t\t\t_testJobID,\n\t\t\tenvMap[hostmgrutil.LabelKeyToEnvVarName(PelotonJobIDLabelKey)],\n\t\t)\n\t\tsuite.Equal(\n\t\t\tfmt.Sprint(i),\n\t\t\tenvMap[hostmgrutil.LabelKeyToEnvVarName(PelotonInstanceIDLabelKey)],\n\t\t)\n\t\tsuite.Equal(\n\t\t\tfmt.Sprint(_testJobID+\"-\", i),\n\t\t\tenvMap[hostmgrutil.LabelKeyToEnvVarName(PelotonTaskIDLabelKey)],\n\t\t)\n\n\t\tsuite.Equal(&mesos.Labels{\n\t\t\tLabels: []*mesos.Label{\n\t\t\t\t{\n\t\t\t\t\tKey: &_tmpLabelKey,\n\t\t\t\t\tValue: &_tmpLabelValue,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tKey: util.PtrPrintf(PelotonJobIDLabelKey),\n\t\t\t\t\tValue: util.PtrPrintf(_testJobID),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tKey: util.PtrPrintf(PelotonInstanceIDLabelKey),\n\t\t\t\t\tValue: util.PtrPrintf(fmt.Sprint(i)),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tKey: util.PtrPrintf(PelotonTaskIDLabelKey),\n\t\t\t\t\tValue: util.PtrPrintf(fmt.Sprint(_testJobID+\"-\", i)),\n\t\t\t\t},\n\t\t\t},\n\t\t}, info.Labels)\n\t}\n\n\tsuite.Len(discoveryPortSet, 4)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NewBuildClient creates a new BuildClient instance that is set to the initial state (i.e., being idle).
func NewBuildClient(scheduler remoteworker.OperationQueueClient, buildExecutor BuildExecutor, filePool filesystem.FilePool, clock clock.Clock, workerID map[string]string, instanceNamePrefix digest.InstanceName, platform *remoteexecution.Platform, sizeClass uint32) *BuildClient { return &BuildClient{ scheduler: scheduler, buildExecutor: buildExecutor, filePool: filePool, clock: clock, instanceNamePrefix: instanceNamePrefix, instanceNamePatcher: digest.NewInstanceNamePatcher(digest.EmptyInstanceName, instanceNamePrefix), request: remoteworker.SynchronizeRequest{ WorkerId: workerID, InstanceNamePrefix: instanceNamePrefix.String(), Platform: platform, SizeClass: sizeClass, CurrentState: &remoteworker.CurrentState{ WorkerState: &remoteworker.CurrentState_Idle{ Idle: &emptypb.Empty{}, }, }, }, nextSynchronizationAt: clock.Now(), } }
[ "func NewBuild(state *builder.Dispatcher, log logrus.FieldLogger, ghIntClient *ghIntegr.Client) *Build {\n\treturn &Build{\n\t\tstate: state,\n\t\tlog: log,\n\t\tgithubIntegrationClient: ghIntClient,\n\t}\n}", "func (c *cookRun) newBuildUpdater() (*buildUpdater, error) {\n\thttpClient, err := c.systemAuth.Authenticator().Client()\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to create a system-auth HTTP client for updating build state on the server\").Err()\n\t}\n\treturn &buildUpdater{\n\t\tannAddr: &c.AnnotationURL,\n\t\tbuildID: c.BuildbucketBuildID,\n\t\tbuildToken: c.buildSecrets.BuildToken,\n\t\tclient: buildbucketpb.NewBuildsPRPCClient(&prpc.Client{\n\t\t\tHost: c.BuildbucketHostname,\n\t\t\tC: httpClient,\n\t\t}),\n\t\tannotations: make(chan []byte),\n\t}, nil\n}", "func BuildClient(creds *config.CircleConfiguration) *circleci.Client {\n\treturn &circleci.Client{Token: creds.Token}\n}", "func NewOSClientBuildClient(client osclient.Interface) *OSClientBuildClient {\n\treturn &OSClientBuildClient{Client: client}\n}", "func NewBuildVersionClient() *BuildVersionClient {\n\treturn &BuildVersionClient{\n\t\tjobCacheClient: &defaultJobCacheClient{},\n\t\tgithubClient: &defaultGithubClient{},\n\t\ttestGridClient: &defaultTestGridClient{},\n\t}\n}", "func (o *OAuth) BuildClient(accessToken *AccessToken) *http.Client {\n\treturn &http.Client{\n\t\tTransport: &RoundTripper{\n\t\t\tdebug: utils.IsDebug(),\n\t\t\toauth: o,\n\t\t\ttoken: accessToken,\n\t\t},\n\t}\n}", "func (c *Client) Build(params map[string]interface{}) (api.ClientAPI, error) {\n\t// tenantName, _ := params[\"name\"].(string)\n\n\tidentity, _ := params[\"identity\"].(map[string]interface{})\n\tcompute, _ := params[\"compute\"].(map[string]interface{})\n\t// network, _ := params[\"network\"].(map[string]interface{})\n\n\tusername, _ := identity[\"Username\"].(string)\n\tpassword, _ := identity[\"Password\"].(string)\n\tdomainName, _ := identity[\"UserDomainName\"].(string)\n\n\tregion, _ := compute[\"Region\"].(string)\n\tprojectName, _ := compute[\"ProjectName\"].(string)\n\tprojectID, _ := compute[\"ProjectID\"].(string)\n\tdefaultImage, _ := compute[\"DefaultImage\"].(string)\n\n\treturn AuthenticatedClient(\n\t\tAuthOptions{\n\t\t\tUsername: username,\n\t\t\tPassword: password,\n\t\t\tRegion: region,\n\t\t\tDomainName: domainName,\n\t\t\tProjectName: projectName,\n\t\t\tProjectID: projectID,\n\t\t},\n\t\topenstack.CfgOptions{\n\t\t\tDefaultImage: defaultImage,\n\t\t},\n\t)\n}", "func (a *ClientArgs) BuildClient() (bus_api.ControllerBusServiceClient, error) {\n\tif a.client != nil {\n\t\treturn a.client, nil\n\t}\n\n\tif a.DialAddr == \"\" {\n\t\treturn nil, errors.New(\"dial address is not set\")\n\t}\n\n\tclientConn, err := grpc.Dial(a.DialAddr, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ta.client = bus_api.NewControllerBusServiceClient(clientConn)\n\treturn a.client, nil\n}", "func BuildClient() (*buildv1.BuildV1Client, error) {\n\tif buildClient == nil && buildClientError == nil {\n\t\tbuildClient, buildClientError = newBuildClient()\n\t}\n\treturn buildClient, buildClientError\n}", "func newBuildConfigs(c *Client, namespace string) *buildConfigs {\n\treturn &buildConfigs{\n\t\tr: c,\n\t\tns: namespace,\n\t}\n}", "func newBuildConfig(cfg rest.Config, stop chan struct{}) (*buildConfig, error) {\n\tbc, err := buildset.NewForConfig(&cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Assume watches receive updates, but resync every 30m in case something wonky happens\n\tbif := buildinfo.NewSharedInformerFactory(bc, time.Minute)\n\tgo bif.Start(stop)\n\treturn &buildConfig{\n\t\tclient: bc,\n\t\tinformer: bif.Build().V1alpha1().Builds(),\n\t}, nil\n}", "func BuildClient(path string) (*Client, error) {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tscheme := defaultScheme\n\tif os.Getenv(\"SCHEME\") != \"\" {\n\t\tscheme = os.Getenv(\"SCHEME\")\n\t}\n\n\thost := defaultHost\n\tif os.Getenv(\"HOST\") != \"\" {\n\t\thost = os.Getenv(\"HOST\")\n\t}\n\n\tidHeader := defaultIDHeader\n\tif os.Getenv(\"IDENTITY\") != \"\" {\n\t\tidHeader = os.Getenv(\"IDENTITY\")\n\t}\n\n\tport := defaultPort\n\tif os.Getenv(\"PORT\") != \"\" {\n\t\tvar err error\n\t\tport, err = strconv.Atoi(os.Getenv(\"PORT\"))\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Invalid Port '%s'.\\n\", os.Getenv(\"PORT\"))\n\t\t\tport = defaultPort\n\t\t}\n\t}\n\n\t// Timeout should be an integer in milliseconds.\n\ttimeout := defaultTimeout\n\tif os.Getenv(\"TIMEOUT\") != \"\" {\n\t\tvar err error\n\t\ttimeout, err = strconv.Atoi(os.Getenv(\"TIMEOUT\"))\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Invalid Timeout '%s'.\\n\", os.Getenv(\"TIMEOUT\"))\n\t\t\ttimeout = defaultTimeout\n\t\t}\n\t}\n\n\tsc := Client{}\n\tsc.Scheme = scheme\n\tsc.Hostname = host\n\tsc.IdentityHeader = idHeader\n\tsc.Port = port\n\tsc.Timeout = timeout\n\n\tsc.Client = &http.Client{\n\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\tif sc.FollowRedirects {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn http.ErrUseLastResponse\n\t\t},\n\t\tTimeout: time.Duration(sc.Timeout) * time.Millisecond,\n\t}\n\n\tsc.load(data)\n\n\treturn &sc, nil\n}", "func (c *Client) Build(params map[string]interface{}) (api.ClientAPI, error) {\n\tUsername, _ := params[\"Username\"].(string)\n\tPassword, _ := params[\"Password\"].(string)\n\tTenantName, _ := params[\"TenantName\"].(string)\n\tRegion, _ := params[\"Region\"].(string)\n\treturn AuthenticatedClient(AuthOptions{\n\t\tUsername: Username,\n\t\tPassword: Password,\n\t\tTenantName: TenantName,\n\t\tRegion: Region,\n\t})\n}", "func (bow *Browser) buildClient() *http.Client {\n\treturn &http.Client{\n\t\tCheckRedirect: bow.shouldRedirect,\n\t}\n}", "func NewBuildingClient(c config) *BuildingClient {\n\treturn &BuildingClient{config: c}\n}", "func newClient() (client *Client) {\n\n\tclient = new(Client)\n\n\tid := <-uuidBuilder\n\tclient.Id = id.String()\n\tclient.subscriptions = make(map[string]bool)\n\n\tclients[client.Id] = client\n\n\tlog.WithField(\"clientID\", id.String()).Info(\"Created new Client\")\n\treturn\n}", "func (client *Client) Build(params map[string]interface{}) (api.ClientAPI, error) {\n\ttenantName, _ := params[\"name\"].(string)\n\n\tidentity, _ := params[\"identity\"].(map[string]interface{})\n\tcompute, _ := params[\"compute\"].(map[string]interface{})\n\t// network, _ := params[\"network\"].(map[string]interface{})\n\n\tidentityEndpoint, _ := identity[\"Endpoint\"].(string)\n\tusername, _ := identity[\"Username\"].(string)\n\tpassword, _ := identity[\"Password\"].(string)\n\n\tregion, _ := compute[\"Region\"].(string)\n\tfloatingIPPool, _ := compute[\"FloatingIPPool\"].(string)\n\tdefaultImage, _ := compute[\"DefaultImage\"]\n\n\treturn AuthenticatedClient(\n\t\tAuthOptions{\n\t\t\tIdentityEndpoint: identityEndpoint,\n\t\t\tUsername: username,\n\t\t\tPassword: password,\n\t\t\tTenantName: tenantName,\n\t\t\tRegion: region,\n\t\t\tFloatingIPPool: floatingIPPool,\n\t\t},\n\t\tCfgOptions{\n\t\t\tProviderNetwork: \"public\",\n\t\t\tUseFloatingIP: true,\n\t\t\tUseLayer3Networking: true,\n\t\t\tAutoHostNetworkInterfaces: true,\n\t\t\tVolumeSpeeds: map[string]VolumeSpeed.Enum{\n\t\t\t\t\"standard\": VolumeSpeed.COLD,\n\t\t\t\t\"performant\": VolumeSpeed.HDD,\n\t\t\t},\n\t\t\tDNSList: []string{\"185.23.94.244\", \"185.23.94.244\"},\n\t\t\tDefaultImage: defaultImage.(string),\n\t\t},\n\t)\n}", "func NewBuildServiceClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*BuildServiceClient, error) {\n\tcl, err := arm.NewClient(moduleName+\".BuildServiceClient\", moduleVersion, credential, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &BuildServiceClient{\n\t\tsubscriptionID: subscriptionID,\n\t\tinternal: cl,\n\t}\n\treturn client, nil\n}", "func GetBuildMockClient() MockClient {\n\tmc := NewMockClient()\n\n\tmc.AddData(buildHead)\n\tmc.AddData(buildPost)\n\tmc.AddData(buildGet1)\n\tmc.AddData(buildGet2)\n\tmc.AddData(buildGetTasks)\n\tmc.AddData(buildGetTask0Logs)\n\tmc.AddData(buildGetTask1Logs)\n\tmc.AddData(buildGetTask2Logs)\n\tmc.AddData(buildGetTask3Logs)\n\tmc.AddData(buildGetTask4Logs)\n\tmc.AddData(buildGetTask5Logs)\n\tmc.AddData(buildGetTask6Logs)\n\tmc.AddData(buildGetTask7Logs)\n\tmc.AddData(buildGetTask8Logs)\n\tmc.AddData(buildGetTask9Logs)\n\tmc.AddData(buildGetTask10Logs)\n\tmc.AddData(buildGetTask11Logs)\n\tmc.AddData(buildGetTask12Logs)\n\tmc.AddData(buildGetTask0Result)\n\tmc.AddData(buildGetTask1Result)\n\tmc.AddData(buildGetTask2Result)\n\tmc.AddData(buildGetTask3Result)\n\tmc.AddData(buildGetTask4Result)\n\tmc.AddData(buildGetTask5Result)\n\tmc.AddData(buildGetTask6Result)\n\tmc.AddData(buildGetTask7Result)\n\tmc.AddData(buildGetTask8Result)\n\tmc.AddData(buildGetTask9Result)\n\tmc.AddData(buildGetTask10Result)\n\tmc.AddData(buildGetTask11Result)\n\tmc.AddData(buildGetTask12Result)\n\tmc.AddData(buildGetTask11ResultMedia)\n\tmc.AddData(buildGetValues)\n\n\treturn mc\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
InExecutingState returns true if the worker is executing an action, or still needs to successfully synchronize against the scheduler to communicate the completion of an action. If this function returns false, it is safe for the worker to stop synchronizing against the scheduler without causing any operations to fail.
func (bc *BuildClient) InExecutingState() bool { return bc.inExecutingState }
[ "func (i *invocation) isActive() bool {\n\treturn i.queuedOperations.Len() > 0 || i.executingWorkersCount > 0\n}", "func (proc *syncProcess) IsSyncInProgress() {}", "func (s *Scheduler) Running() bool {\n\ts.mutex.RLock()\n\tdefer s.mutex.RUnlock()\n\treturn s.running\n}", "func (task *Task) Running() bool {\n\ttask.lock.Lock()\n\trunning := task.running\n\ttask.lock.Unlock()\n\treturn running\n}", "func (cr *ChampionshipEvent) InProgress() bool {\n\treturn !cr.StartedTime.IsZero() && cr.CompletedTime.IsZero()\n}", "func (m *Market) Running() bool {\n\tm.runMtx.RLock()\n\tdefer m.runMtx.RUnlock()\n\tselect {\n\tcase <-m.running:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (sts *StateTransferState) InProgress() bool {\n\treturn sts.asynchronousTransferInProgress\n}", "func (fexec *FlowExecutor) isRunning() bool {\n\tstate, err := fexec.getRequestState()\n\tif err != nil {\n\t\tfexec.log(\"[request `%s`] failed to obtain pipeline state\\n\", fexec.id)\n\t\treturn false\n\t}\n\n\treturn state == STATE_RUNNING\n}", "func (co *CompositeOperator) IsSuspended(ctx context.Context, obj client.Object) bool {\n\tctx, span, _, _ := co.inst.Start(ctx, \"IsSuspended\")\n\tdefer span.End()\n\n\treturn co.isSuspended(ctx, obj)\n}", "func (t *task) IsRunning() bool {\n\treturn t.running\n}", "func (t ResolvedPipelineRunTask) IsRunning() bool {\n\tif t.IsCustomTask() {\n\t\tif t.Run == nil {\n\t\t\treturn false\n\t\t}\n\t} else {\n\t\tif t.TaskRun == nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn !t.IsSuccessful() && !t.IsFailure() && !t.IsCancelled()\n}", "func (p *TaskRunner) isRunning() bool {\n\treturn atomic.LoadUint32(&p.state) == startedState\n}", "func (t Task) IsWaived() bool {\n\treturn t.Status == 3\n}", "func (s *scheduler) IsRunning() bool {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\treturn s.isRunning\n}", "func (w *worker) isRunning() bool {\n\treturn atomic.LoadInt32(&w.running) == 1\n}", "func (t *QueueTracker) IsWorking() bool {\n\treturn t.JobWorking\n}", "func (s *SegmentUpdateWorker) IsRunning() bool {\n\treturn s.lifecycle.IsRunning()\n}", "func (f *Future) IsRunning() bool {\n\tresponse := false\n\n\tlock, err := f.Condition.Aquire(true)\n\n\tif lock && err == nil {\n\t\tif f.State == Running {\n\t\t\tresponse = true\n\t\t}\n\t}\n\n\tif err != nil {\n\t\tfmt.Println(\"Some error occured: \", err)\n\t}\n\tf.Condition.Release()\n\n\treturn response\n}", "func (sc *ConditionsScraper) Running() bool {\n\treturn sc.running\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NewGetDeviceHealthParams creates a new GetDeviceHealthParams object with the default values initialized.
func NewGetDeviceHealthParams() *GetDeviceHealthParams { var () return &GetDeviceHealthParams{ timeout: cr.DefaultTimeout, } }
[ "func NewDeviceHealth()(*DeviceHealth) {\n m := &DeviceHealth{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func MockDeviceHealth(ctrlr *Controller) DeviceHealth {\n\th := MockDeviceHealthPB()\n\treturn DeviceHealth{\n\t\tTemp: h.Temp,\n\t\tTempWarnTime: h.Tempwarn,\n\t\tTempCritTime: h.Tempcrit,\n\t\tCtrlBusyTime: h.Ctrlbusy,\n\t\tPowerCycles: h.Powercycles,\n\t\tPowerOnHours: h.Poweronhours,\n\t\tUnsafeShutdowns: h.Unsafeshutdowns,\n\t\tMediaErrors: h.Mediaerrors,\n\t\tErrorLogEntries: h.Errorlogs,\n\t\tTempWarn: h.Tempwarning,\n\t\tAvailSpareWarn: h.Availspare,\n\t\tReliabilityWarn: h.Reliability,\n\t\tReadOnlyWarn: h.Readonly,\n\t\tVolatileWarn: h.Volatilemem,\n\t}\n}", "func NewDeviceHealthAttestationState()(*DeviceHealthAttestationState) {\n m := &DeviceHealthAttestationState{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func NewHealth() Health {\n\th := Health{\n\t\tInfo: make(map[string]interface{}),\n\t}\n\n\th.Unknown()\n\n\treturn h\n}", "func NewHealth(status string, version string) Health {\n\treturn Health{\n\t\tStatus: status,\n\t\tVersion: version,\n\t}\n}", "func NewGetHealthRequest(server string, params *GetHealthParams) (*http.Request, error) {\n\tvar err error\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/health\")\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"GET\", queryUrl.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif params.ZapTraceSpan != nil {\n\t\tvar headerParam0 string\n\n\t\theaderParam0, err = runtime.StyleParam(\"simple\", false, \"Zap-Trace-Span\", *params.ZapTraceSpan)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treq.Header.Add(\"Zap-Trace-Span\", headerParam0)\n\t}\n\n\treturn req, nil\n}", "func (m *Cndev) GetDeviceHealth(arg0 uint) (uint, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetDeviceHealth\", arg0)\n\tret0, _ := ret[0].(uint)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewGetDevicesParams() *GetDevicesParams {\n\tvar ()\n\treturn &GetDevicesParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func New() *Health {\n\treturn &Health{\n\t\tStatus: StatusUnknown,\n\t\tDetails: make(map[string]interface{}),\n\t}\n}", "func NewHealth() *Health {\n\treturn &Health{\n\t\tcomponents: map[interface{}]*HealthComponentStatus{},\n\t}\n}", "func NewHealth(r router) *Health {\n\treturn &Health{\n\t\trouter: r,\n\t}\n}", "func NewHealth(\n\tstate Status,\n\tmessage string,\n) Health {\n\treturn Health{\n\t\tStatus: state,\n\t\tUrgency: UNKNOWN, // set by the owning Monitor\n\t\tTime: time.Now(),\n\t\tMessage: Message(message),\n\t\tDuration: 0,\n\t}\n}", "func NewHealthGetOK() *HealthGetOK {\n\n\treturn &HealthGetOK{}\n}", "func NewGetHealthOK() *GetHealthOK {\n\n\treturn &GetHealthOK{}\n}", "func NewGetDevicesAllParams() *GetDevicesAllParams {\n\tvar ()\n\treturn &GetDevicesAllParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func NewGetHardwaresParams() *GetHardwaresParams {\n\tvar ()\n\treturn &GetHardwaresParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func NewHealthCheck(opt ...Option) *HealthCheck {\n\topts := GetOpts(opt...)\n\n\th := &HealthCheck{\n\t\tstatus: &healthStatus{},\n\t}\n\tif e, ok := opts[optionWithEngine].(*gin.Engine); ok {\n\t\th.Engine = e\n\t}\n\tif path, ok := opts[optionWithHealthPath].(string); ok {\n\t\th.HealthPath = path\n\t} else {\n\t\th.HealthPath = \"/ready\"\n\t}\n\tif handler, ok := opts[optionWithHealthHandler].(gin.HandlerFunc); ok {\n\t\th.Handler = handler\n\t} else {\n\t\th.Handler = h.DefaultHealthHandler()\n\t}\n\n\tif ticker, ok := opts[optionHealthTicker].(*time.Ticker); ok {\n\t\th.metricTicker = ticker\n\t} else {\n\t\th.metricTicker = time.NewTicker(DefaultHealthTickerDuration)\n\t}\n\n\treturn h\n}", "func NewTeamworkSoftwareUpdateHealth()(*TeamworkSoftwareUpdateHealth) {\n m := &TeamworkSoftwareUpdateHealth{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func newMockHealthSetter() *mockHealthSetter {\n\treturn &mockHealthSetter{\n\t\thealthCh: make(chan allocHealth, 1),\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
palindromeIndex returns the index whose deletion would cause in s becoming a palindrome. 1 is returned if s is already a palindrome.
func palindromeIndex(s string) int { n := len(s) for i := 0; i < n/2; i++ { // problem, find which index // is at fault. if s[i] != s[n-i-1] { if palindrome(s[:i] + s[i+1:]) { return i } else { return n - i - 1 } } } return -1 }
[ "func palindromeIndex(s string) int32 {\n\tl := len(s) - 1\n\tfor i := 0; i <= l; i, l = i+1, l-1 {\n\t\tif s[i] == s[l] {\n\t\t\tcontinue\n\t\t}\n\t\tif palindrome(s[i+1 : l+1]) {\n\t\t\treturn int32(i)\n\t\t}\n\t\tif palindrome(s[i:l]) {\n\t\t\treturn int32(l)\n\t\t}\n\t\treturn -1\n\t}\n\treturn -1\n}", "func isPalindrome(s string) bool {\n\t// defer timeTrack(time.Now(), \"isPalindrome()\")\n\n\tfor i := 0; i < len(s)/2; i++ {\n\t\tif s[i] != s[len(s)-1-i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func IsPalindrome(s string) bool {\n\t// Make case insensitive by converting \"s\" into lower case\n\ts = strings.ToLower(s)\n\n\tsLen := len(s)\n\tfor i := 0; i < sLen/2; i++ {\n\t\tif s[i] != s[sLen-1-i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func IsPalindrome(s sort.Interface) bool {\n\tif s.Len() == 0 {\n\t\treturn false\n\t}\n\tleft := 0\n\tright := s.Len() - 1\n\tfor left < right {\n\t\tif s.Less(left, right) || s.Less(right, left) {\n\t\t\treturn false\n\t\t}\n\t\tleft++\n\t\tright--\n\t}\n\treturn true\n}", "func isPalindrome(n int) bool {\n\ts := strconv.Itoa(n)\n\n\tfor i := 0; i < len(s)/2; i++ {\n\t\tif s[i] != s[len(s)-i-1] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func PalindromesFast(text string) (int, int) {\n\tlengths := make([]int, 2*len(text)+1)\n\ti, j, d, s, e, plen, k := 0, 0, 0, 0, 0, 0, 0\n\tfor i < len(text) {\n\t\t// is the string so far a palindrome ?\n\t\tif i > plen && text[i-plen-1] == text[i] {\n\t\t\t// yes, so we extend the current found palindrome length\n\t\t\t// and keep checking forward else ...\n\t\t\tplen += 2\n\t\t\ti++\n\t\t\tcontinue\n\t\t}\n\t\t// ... we have reached the end of the current found palindrome\n\t\t// so we set the current palindrome length etc. ...\n\t\tlengths[k] = plen\n\t\tk++\n\t\ts = k - 2\n\t\te = s - plen\n\t\t// ... then backtrack over the last found palindrome to see ...\n\t\tb := true\n\t\tfor j = s; j > e; j-- {\n\t\t\td = j - e - 1\n\t\t\t// ... if we have a reflection of the same length ...\n\t\t\tif lengths[j] == d {\n\t\t\t\t// ... yes, so we set new palindrome length ...\n\t\t\t\tplen = d\n\t\t\t\t// ... and stop backtracking.\n\t\t\t\tb = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// ... no, so we take the smaller length,\n\t\t\t// update the lengths and continue backtracking.\n\t\t\tlengths[k] = MinInt(d, lengths[j])\n\t\t\tk++\n\t\t}\n\t\t// if we we're backtracking then reset palindrome length\n\t\t// and move on.\n\t\tif b {\n\t\t\tplen = 1\n\t\t\ti++\n\t\t}\n\t}\n\t// we're done scanning the text so we perform\n\t// one last backtrack.\n\tlengths[k] = plen\n\tk++\n\ts = k - 2\n\te = s - (2*len(text) + 1 - k)\n\tfor i := s; i > e; i-- {\n\t\td = i - e - 1\n\t\tlengths[k] = MinInt(d, lengths[i])\n\t\tk++\n\t}\n\treturn LargestStartEnd(lengths)\n}", "func palindrome(n int) int {\n\tst := int(math.Pow10(n)) - 1\n\tmx := 0\n\tfor i := st; i > 0; i-- {\n\t\tif i*st <= mx {\n\t\t\tbreak\n\t\t}\n\t\tfor j := st; j > 0; j-- {\n\t\t\tpd := i * j\n\t\t\tif pd < mx {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif pd > mx && isPalindrome(pd) {\n\t\t\t\tmx = pd\n\t\t\t}\n\t\t}\n\t}\n\treturn mx\n}", "func isPalindromeRecursive(value string, i int) bool {\n\tif i < len(value) /2 {\n\t\tvar firstIndex = i\n\t\tvar lastIndex = len(value) - i -1\n\t\t//compare per index\n\t\tfmt.Println(string(value[firstIndex]) , \" : \" , string(value[lastIndex]))\n\n\t\tif string(value[firstIndex]) != string(value[lastIndex]) {\n\t\t\tfmt.Println(\"Palindrome recursive false\")\n\t\t\treturn false\n\t\t} else {\n\t\t\t//if true call again the recursive, and add 1 for i var\n\t\t\treturn isPalindromeRecursive(value, i+1)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"Palindrome recursive true\")\n\t\treturn true\n\t}\n}", "func IsPalindrome(s string) bool {\n\tvar letters []rune\n\tfor _, r := range s {\n\t\tif unicode.IsLetter(r) {\n\t\t\tletters = append(letters, unicode.ToLower(r))\n\t\t}\n\t}\n\tfor i := range letters {\n\t\tif letters[i] != letters[len(letters)-1-i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func validPalindrome(s string) bool {\n return validPalindromeDeleted(s, false)\n}", "func IsPalindrome(s sort.Interface) bool {\n\t// TODO\n\treturn false\n}", "func IsPalindrome(num int) bool {\n\tstr := strconv.Itoa(num)\n\tlast := len(str) - 1\n\tfor i := 0; i < len(str)/2; i++ {\n\t\tif str[i] != str[last-i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func CheckPalindrome(str string) bool {\n\tlength := len(str) - 1\n\tfor i := range str {\n\t\tif str[i] != str[length-i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func CheckPalindrome(inputString string) bool {\n\t// We don't need to use Floor, because integer division does that automatically (I guess)\n\t// terminus := int(math.Floor(float64(len(inputString)) / float64(2)))\n\n\tfor i := 0; i < len(inputString)/2; i++ {\n\t\tif string(inputString[i]) != string(inputString[len(inputString)-1-i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func IsPalindromeString(input string) bool {\n\tvar size = len(input)\n\tfor i := 0; i < size>>1; i++ {\n\t\tif input[i] != input[size-1-i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func isPalindrome(s string) bool {\n\ts = strings.ToLower(s)\n\tvar str []rune\n\tfor _, ch := range s {\n\t\tif unicode.IsLetter(ch) || unicode.IsDigit(ch) {\n\t\t\tstr = append(str, ch)\n\t\t}\n\t}\n\n\tfor i := 0; i < len(str)/2; i++ {\n\t\tif str[i] != str[len(str)-i-1] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func IsPalindrome(x int) bool {\n\ty, t := 0, x\n\tfor t > 0 {\n\t\ty = y*10 + t%10\n\t\tt = t / 10\n\t}\n\treturn x == y\n}", "func isPalindrome(input string) bool {\n\n\tletters := splitInput(input)\n\n\tleftPointer := 0\n\trightPointer := len(letters) - 1\n\tres := true\n\tfor true {\n\t\tif leftPointer >= rightPointer {\n\t\t\tbreak\n\t\t}\n\n\t\tif letters[leftPointer] == letters[rightPointer] {\n\t\t\tleftPointer++\n\t\t\trightPointer--\n\t\t} else {\n\t\t\tres = false\n\t\t\tbreak\n\t\t}\n\n\t}\n\treturn res\n}", "func longestPalindromSubstring(s string) (int, string) {\n\tl := len(s)\n\tif l == 0 {\n\t\treturn 0, \"\"\n\t}\n\t// A table array stores false at table[i][j] if the substring from index i to j is not\n\t// a palindrome and true otherwise.\n\ttable := make([][]bool, l)\n\tfor i := range table {\n\t\ttable[i] = make([]bool, l)\n\t}\n\n\t// Substring of length 1 is always a palindrome.\n\tmaxLength := 1\n\tfor i := range table {\n\t\ttable[i][i] = true\n\t}\n\n\tstart := 0\n\t// Substring of length 2.\n\tfor i := 0; i < l-1; i++ {\n\t\tif s[i] == s[i+1] {\n\t\t\ttable[i][i+1] = true\n\t\t\tstart = i\n\t\t\tmaxLength = 2\n\t\t}\n\t}\n\n\t// Substring of higher length\n\t// Let k keep the substring length\n\tfor k := 3; k <= l; k++ {\n\t\tfor i := 0; i < l-k+1; i++ {\n\t\t\t// Get the ending index.\n\t\t\tj := i + k - 1\n\t\t\t// Checking for sub-string from ith index to jth index iff s[i + 1] to s[(j-1)] is\n\t\t\t// a palindrome.\n\t\t\tif table[i+1][j-1] && s[i] == s[j] {\n\t\t\t\ttable[i][j] = true\n\t\t\t\tif k > maxLength {\n\t\t\t\t\tstart = i\n\t\t\t\t\tmaxLength = k\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// fmt.Printf(\"%#v\\n\", table)\n\treturn maxLength, string(s[start : start+maxLength])\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ToggleBluetoothFromBluetoothSettings tests that a user can successfully toggle the Bluetooth state using the Bluetooth toggle within the Bluetooth Settings subpage.
func ToggleBluetoothFromBluetoothSettings(ctx context.Context, s *testing.State) { cr := s.FixtValue().(*bluetooth.ChromeLoggedInWithBluetoothEnabled).Chrome tconn, err := cr.TestAPIConn(ctx) if err != nil { s.Fatal("Failed to create Test API connection: ", err) } // Reserve ten seconds for cleanup. cleanupCtx := ctx ctx, cancel := ctxutil.Shorten(ctx, 10*time.Second) defer cancel() bt := s.FixtValue().(*bluetooth.ChromeLoggedInWithBluetoothEnabled).Impl app, err := ossettings.NavigateToBluetoothSettingsPage(ctx, tconn, bt) defer app.Close(cleanupCtx) defer faillog.DumpUITreeWithScreenshotOnError(cleanupCtx, s.OutDir(), s.HasError, cr, "ui_tree") if err != nil { s.Fatal("Failed to show the Bluetooth Settings sub-page: ", err) } ui := uiauto.New(tconn) if err := ui.WaitUntilExists(bluetoothSettingsBluetoothToggleButton)(ctx); err != nil { s.Fatal("Failed to find the Bluetooth toggle: ", err) } state := false const iterations = 20 for i := 0; i < iterations; i++ { s.Logf("Toggling Bluetooth (iteration %d of %d)", i+1, iterations) if err := ui.LeftClick(bluetoothSettingsBluetoothToggleButton)(ctx); err != nil { s.Fatal("Failed to click the Bluetooth toggle: ", err) } if err := bt.PollForAdapterState(ctx, state); err != nil { s.Fatal("Failed to toggle Bluetooth state: ", err) } state = !state } }
[ "func ToggleBluetoothFromOSSettings(ctx context.Context, s *testing.State) {\n\tcr := s.FixtValue().(*bluetooth.ChromeLoggedInWithBluetoothEnabled).Chrome\n\n\ttconn, err := cr.TestAPIConn(ctx)\n\tif err != nil {\n\t\ts.Fatal(\"Failed to create Test API connection: \", err)\n\t}\n\n\tapp, err := ossettings.Launch(ctx, tconn)\n\tdefer app.Close(ctx)\n\n\tif err != nil {\n\t\ts.Fatal(\"Failed to launch OS Settings: \", err)\n\t}\n\n\tbt := s.FixtValue().(*bluetooth.ChromeLoggedInWithBluetoothEnabled).Impl\n\n\tif err := bt.Enable(ctx); err != nil {\n\t\ts.Fatal(\"Failed to enable Bluetooth: \", err)\n\t}\n\n\tui := uiauto.New(tconn)\n\n\tif err := ui.WaitUntilExists(ossettings.OsSettingsBluetoothToggleButton)(ctx); err != nil {\n\t\ts.Fatal(\"Failed to find the Bluetooth toggle: \", err)\n\t}\n\n\tstate := false\n\tconst iterations = 20\n\tfor i := 0; i < iterations; i++ {\n\t\ts.Logf(\"Toggling Bluetooth (iteration %d of %d)\", i+1, iterations)\n\n\t\tif err := ui.LeftClick(ossettings.OsSettingsBluetoothToggleButton)(ctx); err != nil {\n\t\t\ts.Fatal(\"Failed to click the Bluetooth toggle: \", err)\n\t\t}\n\t\tif err := bt.PollForAdapterState(ctx, state); err != nil {\n\t\t\ts.Fatal(\"Failed to toggle Bluetooth state: \", err)\n\t\t}\n\t\tstate = !state\n\t}\n}", "func ToggleBluetooth() error {\n\tfmt.Sprintf(\"Toggle bluetooth\")\n\terr := TurnOffBluetooth()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn TurnOnBluetooth()\n}", "func TurnOffBluetooth() error {\n\tfmt.Sprintf(\"Turn OFF bluetooth\")\n\treturn TurnOffAdapter(\"bluetooth\")\n}", "func TurnOnBluetooth() error {\n\tfmt.Sprintf(\"Turn ON bluetooth\")\n\treturn TurnOnAdapter(\"bluetooth\")\n}", "func DisableBluetooth(ctx context.Context) (CleanupCallback, error) {\n\treturn Nested(ctx, \"disable bluetooth\", func(s *Setup) error {\n\t\tadapters, err := bluez.Adapters(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, adapter := range adapters {\n\t\t\ts.Add(disableBluetoothAdapter(ctx, adapter))\n\t\t}\n\t\treturn nil\n\t})\n}", "func testBackupToggle(ctx context.Context, arcDevice *androidui.Device) error {\n\tconst backupID = \"android:id/switch_widget\"\n\tconst oldBackupID = \"com.google.android.gms:id/switchWidget\"\n\tbackupToggle := arcDevice.Object(androidui.ID(backupID))\n\n\t// Turn on backup in case if it is off which is the expectation for this test.\n\tbackupToggleOn := arcDevice.Object(androidui.ClassName(\"android.widget.Button\"), androidui.TextMatches(\"(?i)Turn on\"), androidui.Enabled(true))\n\tif err := backupToggleOn.WaitForExists(ctx, time.Second*10); err != nil {\n\t\ttesting.ContextLog(ctx, \"Turn on button doesn't exist\")\n\t} else if err := backupToggleOn.Click(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"failed to click Turn on button\")\n\t}\n\n\toldBackupUI := false\n\t// backupStatus will check for toggle on/off.\n\tbackupStatus, err := arcDevice.Object(androidui.ID(backupID)).IsChecked(ctx)\n\tif err != nil {\n\t\ttesting.ContextLog(ctx, \"Old backup UI\")\n\t\tbackupToggle = arcDevice.Object(androidui.ID(oldBackupID))\n\t\tbackupStatus, err = arcDevice.Object(androidui.ID(oldBackupID)).IsChecked(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\toldBackupUI = true\n\t}\n\n\tif backupStatus == true {\n\t\t// Turn Backup OFF.\n\t\tif err := backupToggle.Click(ctx); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to click backup toggle\")\n\t\t}\n\n\t\tturnOffBackup := arcDevice.Object(androidui.ClassName(\"android.widget.Button\"), androidui.TextMatches(\"(?i)turn off & delete\"), androidui.Enabled(true))\n\t\tif err := turnOffBackup.WaitForExists(ctx, timeoutUI); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to find turn off & delete button\")\n\t\t}\n\n\t\tif err := turnOffBackup.Click(ctx); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to click turn off & delete button\")\n\t\t}\n\t}\n\n\tif oldBackupUI {\n\t\tif err := backupToggle.Click(ctx); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to click backup toggle in Old UI\")\n\t\t}\n\t} else {\n\t\tbackupToggleOn := arcDevice.Object(androidui.ClassName(\"android.widget.Button\"), androidui.TextMatches(\"(?i)Turn on\"), androidui.Enabled(true))\n\t\tif err := backupToggleOn.Click(ctx); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to click backup toggle New UI\")\n\t\t}\n\t}\n\n\tif oldBackupUI {\n\t\tbackupStatus, err = arcDevice.Object(androidui.ID(oldBackupID)).IsChecked(ctx)\n\t} else {\n\t\tbackupStatus, err = arcDevice.Object(androidui.ID(backupID)).IsChecked(ctx)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tif backupStatus == false {\n\t\treturn errors.New(\"unable to Turn Backup ON\")\n\t}\n\treturn nil\n}", "func UIToggleFromWIFISettings(ctx context.Context, s *testing.State) {\n\tcr := s.FixtValue().(*chrome.Chrome)\n\n\t// Shorten deadline to leave time for cleanup.\n\tcleanupCtx := ctx\n\tctx, cancel := ctxutil.Shorten(ctx, 5*time.Second)\n\tdefer cancel()\n\n\ttconn, err := cr.TestAPIConn(ctx)\n\tif err != nil {\n\t\ts.Fatal(\"Failed to create Test API connection: \", err)\n\t}\n\tui := uiauto.New(tconn)\n\twiFiButton := nodewith.Name(\"Wi-Fi\").Role(role.Button)\n\ttoggleWiFi := nodewith.Name(\"Wi-Fi enable\").Role(role.ToggleButton)\n\n\tnetworkFinder := nodewith.Name(\"Network\").Role(role.Link).Ancestor(ossettings.WindowFinder)\n\tif _, err := ossettings.LaunchAtPageURL(ctx, tconn, cr, \"Network\", ui.Exists(networkFinder)); err != nil {\n\t\ts.Fatal(\"Failed to launch Settings page: \", err)\n\t}\n\n\tif err := ui.LeftClick(networkFinder)(ctx); err != nil {\n\t\ts.Fatal(\"Failed to left click network tab: \", err)\n\t}\n\n\tmanager, err := shill.NewManager(ctx)\n\tif err != nil {\n\t\ts.Fatal(\"Failed to create shill Manager object: \", err)\n\t}\n\n\twiFiPrevState, err := manager.IsEnabled(ctx, shill.TechnologyWifi)\n\tif err != nil {\n\t\ts.Fatal(\"Failed to get WiFi state: \", err)\n\t}\n\n\tcheckWiFiEnabled := func(ctx context.Context, enable bool) error {\n\t\treturn testing.Poll(ctx, func(ctx context.Context) error {\n\t\t\twiFiEnabled, err := manager.IsEnabled(ctx, shill.TechnologyWifi)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"failed to check if WiFi is enabled\")\n\t\t\t}\n\t\t\tif enable && !wiFiEnabled {\n\t\t\t\treturn errors.New(\"WiFi not available after toggle on\")\n\t\t\t}\n\t\t\tif !enable && wiFiEnabled {\n\t\t\t\treturn errors.New(\"WiFi available after toggle off\")\n\t\t\t}\n\t\t\treturn nil\n\t\t}, &testing.PollOptions{Timeout: 5 * time.Second, Interval: 250 * time.Millisecond})\n\t}\n\n\tdefer func(ctx context.Context) {\n\t\ts.Log(\"Cleanup\")\n\t\twiFiCurState, err := manager.IsEnabled(ctx, shill.TechnologyWifi)\n\t\tif err != nil {\n\t\t\ts.Fatal(\"Failed to get WiFi state: \", err)\n\t\t}\n\t\tif wiFiPrevState != wiFiCurState {\n\t\t\tif err := ui.LeftClick(toggleWiFi)(ctx); err != nil {\n\t\t\t\ts.Fatal(\"Failed to left click toggleWiFi: \", err)\n\t\t\t}\n\t\t\tif err := checkWiFiEnabled(ctx, wiFiPrevState); err != nil {\n\t\t\t\ts.Fatal(\"Failed to check WiFi previous state: \", err)\n\t\t\t}\n\t\t}\n\t}(cleanupCtx)\n\n\tconst numIterations = 5\n\tfor i := 0; i < numIterations; i++ {\n\t\ts.Logf(\"Iteration %d of %d\", i+1, numIterations)\n\t\t// Toggle on WiFi button.\n\t\tif err := ui.Exists(wiFiButton)(ctx); err != nil {\n\t\t\tif err := ui.LeftClick(toggleWiFi)(ctx); err != nil {\n\t\t\t\ts.Fatal(\"Failed to left click toggleWiFi: \", err)\n\t\t\t}\n\t\t}\n\t\tif err := checkWiFiEnabled(ctx, true); err != nil {\n\t\t\ts.Fatal(\"Failed to check WiFi enable: \", err)\n\t\t}\n\t\t// Toggle off WiFi button.\n\t\tif err := ui.LeftClick(toggleWiFi)(ctx); err != nil {\n\t\t\ts.Fatal(\"Failed to left click toggleWiFi: \", err)\n\t\t}\n\t\tif err := checkWiFiEnabled(ctx, false); err != nil {\n\t\t\ts.Fatal(\"Failed to check WiFi disable: \", err)\n\t\t}\n\t}\n}", "func (m *AospDeviceOwnerDeviceConfiguration) SetBluetoothBlocked(value *bool)() {\n err := m.GetBackingStore().Set(\"bluetoothBlocked\", value)\n if err != nil {\n panic(err)\n }\n}", "func testSettings(ctx context.Context, cr *chrome.Chrome, tconn *chrome.TestConn) error {\n\tui := uiauto.New(tconn)\n\ttoggleAdaptiveCharging := nodewith.Name(\"Adaptive charging\").Role(role.ToggleButton)\n\tsettings, err := ossettings.LaunchAtPageURL(ctx, tconn, cr, \"power\", ui.WaitUntilExists(toggleAdaptiveCharging))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer settings.Close(ctx)\n\n\tif err := ui.LeftClick(toggleAdaptiveCharging)(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"failed to toggle Adaptive Charging off\")\n\t}\n\n\tif err := pollUntilBatterySustainingState(ctx, false); err != nil {\n\t\treturn err\n\t}\n\n\tif err := ui.LeftClick(toggleAdaptiveCharging)(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"failed to toggle Adaptive Charging on\")\n\t}\n\n\tif err := pollUntilBatterySustainingState(ctx, true); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (tf *TestFixture) ToggleConnection(ctx context.Context) error {\n\tif _, err := tf.RemoteCellularClient.Disable(ctx, &empty.Empty{}); err != nil {\n\t\treturn errors.Wrap(err, \"failed to disable cellular service\")\n\t}\n\tif _, err := tf.RemoteCellularClient.Enable(ctx, &empty.Empty{}); err != nil {\n\t\treturn errors.Wrap(err, \"failed to enable cellular service\")\n\t}\n\tif _, err := tf.RemoteCellularClient.Connect(ctx, &empty.Empty{}); err != nil {\n\t\treturn errors.Wrap(err, \"failed to connect to cellular service\")\n\t}\n\treturn nil\n}", "func (m *AospDeviceOwnerDeviceConfiguration) SetBluetoothBlockConfiguration(value *bool)() {\n err := m.GetBackingStore().Set(\"bluetoothBlockConfiguration\", value)\n if err != nil {\n panic(err)\n }\n}", "func checkBluetooth() {\n\t// init part: get the list of paired bluetooth devices\n\tresult, err := exec.Command(\"bluetoothctl\", \"devices\").Output()\n\tif err != nil {\n\t\tlogger.Error(err.Error())\n\t} else {\n\t\tarr := strings.Split(string(result), \"\\n\")\n\t\tlogger.Info(\"BT Devices paired:\")\n\t\tfor _, s := range arr {\n\t\t\tparts := strings.Split(s, \" \")\n\t\t\tif len(parts) > 1 {\n\t\t\t\tinfo, err2 := exec.Command(\"bluetoothctl\", \"info\", parts[1]).Output()\n\t\t\t\tif err2 == nil {\n\t\t\t\t\tif strings.Contains(string(info), \"Audio Sink\") {\n\t\t\t\t\t\tbtDevices = append(btDevices, parts[1])\n\t\t\t\t\t\tlogger.Info(parts[1])\n\t\t\t\t\t\tif strings.Contains(string(info), \"Connected: yes\") {\n\t\t\t\t\t\t\tlogger.Info(\"BT connected to \" + parts[1])\n\t\t\t\t\t\t\tbluetoothConnected = true\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\treadyForMplayer = true\n}", "func PollBluetoothBootPref(ctx context.Context, btClient network.BluetoothServiceClient, expectedStatus BtStatus, credKey string) error {\n\treturn testing.Poll(ctx, func(ctx context.Context) error {\n\t\tif response, err := btClient.GetBluetoothBootPref(ctx, &network.GetBluetoothBootPrefRequest{Credentials: credKey}); err != nil {\n\t\t\treturn errors.Wrap(err, \"could not get Bluetooth status\")\n\t\t} else if response.Persistent != bool(expectedStatus) {\n\t\t\treturn testing.PollBreak(errors.Wrapf(err, \"Bluetooth boot pref is %s, expected to be %s\", statusString(response.Persistent), statusString(bool(expectedStatus))))\n\t\t}\n\t\treturn nil\n\t}, &testing.PollOptions{\n\t\tTimeout: pollTimeout,\n\t\tInterval: pollInterval,\n\t})\n}", "func PollBluetoothPoweredStatus(ctx context.Context, btClient network.BluetoothServiceClient, expectedStatus BtStatus) error {\n\treturn testing.Poll(ctx, func(ctx context.Context) error {\n\t\tif response, err := btClient.GetBluetoothPoweredFast(ctx, &empty.Empty{}); err != nil {\n\t\t\treturn errors.Wrap(err, \"could not get Bluetooth status\")\n\t\t} else if response.Powered != bool(expectedStatus) {\n\t\t\treturn errors.Errorf(\"Bluetooth powered status is %s, expected to %s after boot\", statusString(response.Powered), statusString(bool(expectedStatus)))\n\t\t}\n\t\treturn nil\n\t}, &testing.PollOptions{\n\t\tTimeout: pollTimeout,\n\t\tInterval: pollInterval,\n\t})\n}", "func NavigateToBluetoothDetailedView(ctx context.Context, tconn *chrome.TestConn) error {\n\tif err := Expand(ctx, tconn); err != nil {\n\t\treturn err\n\t}\n\n\tui := uiauto.New(tconn)\n\n\tif err := uiauto.Combine(\"Click the Bluetooth feature pod label\",\n\t\tui.LeftClick(bluetoothFeaturePodLabelButton),\n\t\tui.WaitUntilExists(bluetoothDetailedView),\n\t)(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *AndroidWorkProfileGeneralDeviceConfiguration) SetWorkProfileBluetoothEnableContactSharing(value *bool)() {\n m.workProfileBluetoothEnableContactSharing = value\n}", "func TestConnectToBTPeers(ctx context.Context, s *testing.State) {\n\tfv := s.FixtValue().(*bluetooth.FixtValue)\n\n\tif _, err := fv.BTPeers[0].GetMacAddress(ctx); err != nil {\n\t\ts.Fatal(\"Failed to call chamleleond method 'GetMacAddress' on btpeer1: \", err)\n\t}\n\tif err := fv.BTPeers[1].BluetoothAudioDevice().Reboot(ctx); err != nil {\n\t\ts.Fatal(\"Failed to call chamleleond method 'Reboot' on btpeer2.BluetoothAudioDevice: \", err)\n\t}\n}", "func Enable(ctx context.Context, tconn *chrome.TestConn, cr *chrome.Chrome) error {\n\tsettings, err := ossettings.LaunchAtPageURL(ctx, tconn, cr, crossdevicesettings.ConnectedDevicesSettingsURL, func(context.Context) error { return nil })\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to launch OS settings at the multidevice feature page\")\n\t}\n\tsettingsConn, err := settings.ChromeConn(ctx, cr)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to start Chrome session to OS settings\")\n\t}\n\tdefer settingsConn.Close()\n\n\t// Turn on Phone Hub in the \"Connected devices\" subpage. The easiest way to get there is to reopen OS Settings on that specific page.\n\t_, err = ossettings.LaunchAtPageURL(ctx, tconn, cr, crossdevicesettings.ConnectedDevicesSettingsURL, func(context.Context) error { return nil })\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to re-launch OS Settings to the multidevice feature page\")\n\t}\n\n\t// Toggle Phone Hub on with JS.\n\tif err := settingsConn.WaitForExpr(ctx, phoneHubToggleJS); err != nil {\n\t\treturn errors.Wrap(err, \"failed to find the Phone Hub toggle\")\n\t}\n\tvar enabled bool\n\tif err := settingsConn.Eval(ctx, phoneHubToggleJS+featureCheckedJS, &enabled); err != nil {\n\t\treturn errors.Wrap(err, \"failed to get Phone Hub toggle status\")\n\t}\n\tif !enabled {\n\t\tif err := settingsConn.Eval(ctx, phoneHubToggleJS+`.click()`, nil); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to enable Phone Hub\")\n\t\t}\n\t}\n\t// Check that the toggle was correctly enabled.\n\tif err := settingsConn.WaitForExpr(ctx, phoneHubToggleJS+featureCheckedJS+`===true`); err != nil {\n\t\treturn errors.Wrap(err, \"failed to toggle Phone Hub on using JS\")\n\t}\n\t// Phone Hub is still not immediately ready to use after toggling it on from OS Settings,\n\t// since it takes a short amount of time for it to connect to the phone and display anything.\n\t// Wait for it to become usable by checking for the existence of a settings pod.\n\tui := uiauto.New(tconn).WithTimeout(30 * time.Second)\n\tif err := Show(ctx, tconn); err != nil {\n\t\treturn errors.Wrap(err, \"failed to show Phone Hub\")\n\t}\n\tif err := ui.WaitUntilExists(phoneHubSettingPod.First())(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"failed to find a Phone Hub setting pod\")\n\t}\n\n\treturn nil\n}", "func UnconfigureDependantSwitch(ctx context.Context, fabricGate *sync.WaitGroup, sw operation.ConfigSwitch,\n\tforce bool, errs chan actions.OperationError, persist bool) {\n\tdefer fabricGate.Done()\n\tctx = context.WithValue(ctx, appcontext.DeviceName, sw.Host)\n\tlog := appcontext.Logger(ctx)\n\tadapter := ad.GetAdapter(sw.Model)\n\tnetconfClient := &client.NetconfClient{Host: sw.Host, User: sw.UserName, Password: sw.Password}\n\tif err := netconfClient.Login(); err != nil {\n\t\terrs <- actions.OperationError{Operation: \"Configure Interface Login\", Error: err, Host: sw.Host}\n\t\treturn\n\t}\n\tdefer netconfClient.Close()\n\n\tif err := deleteRouterBGPNeighbors(log, adapter, netconfClient, &sw); err != nil {\n\t\terrs <- actions.OperationError{Operation: \"Delete Router BGP Neighbors Failed\", Error: err, Host: sw.Host}\n\t}\n\n\tif err := deleteInterfaces(log, adapter, netconfClient, &sw); err != nil {\n\t\terrs <- actions.OperationError{Operation: \"Configure Switch Interfaces\", Error: err, Host: sw.Host}\n\t}\n\tif persist {\n\t\tif _, err := adapter.PersistConfig(netconfClient); err != nil {\n\t\t\tmsg := fmt.Sprintf(\"Persist Config Failed %s:Error %s\", sw.Host, err)\n\t\t\tlog.Errorln(msg)\n\t\t\terrs <- actions.OperationError{Operation: \"Configure Switch Properties\", Error: errors.New(msg), Host: sw.Host}\n\t\t}\n\t}\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a flow from a single node This is useful for scenaries when usage of a single node is desired, manually feeding and processing packets on the node's ports.
func NewSingleFlowNode(nodeName string, nodeType FlowNodeType, inputPorts, outputPorts []uint16, options map[string]string, cb SingleFlowProcessCallback, data interface{}) *SingleFlowNode { cname := C.CString(nodeName) defer C.free(unsafe.Pointer(cname)) var coptions *C.struct_sol_flow_node_options strvOptions := newstrvOptions(options) success := true if strvOptions != nil { defer strvOptions.destroy() namedOptions := C.struct_sol_flow_node_named_options{} r := C.sol_flow_node_named_options_init_from_strv(&namedOptions, nodeType.ctype, strvOptions.cstrvOptions) if r == 0 { defer C.sol_flow_node_named_options_fini(&namedOptions) C.sol_flow_node_options_new(nodeType.ctype, &namedOptions, &coptions) defer C.sol_flow_node_options_del(nodeType.ctype, coptions) } else { success = false } } if !success { /* Assume this is a Go custom type */ coptions = mapOptionsToFlowOptions(options) } /* Create C array parameters for input and output ports */ step := unsafe.Sizeof((C.uint16_t)(0)) cinputPorts := C.malloc(C.size_t(uintptr(len(inputPorts)+1) * step)) coutputPorts := C.malloc(C.size_t(uintptr(len(outputPorts)+1) * step)) defer C.free(cinputPorts) defer C.free(coutputPorts) pindexIn, pindexOut := uintptr(cinputPorts), uintptr(coutputPorts) for _, inputPort := range inputPorts { *(*C.uint16_t)(unsafe.Pointer(pindexIn)) = C.uint16_t(inputPort) pindexIn += step } for _, outputPort := range outputPorts { *(*C.uint16_t)(unsafe.Pointer(pindexOut)) = C.uint16_t(outputPort) pindexOut += step } *(*C.uint16_t)(unsafe.Pointer(pindexIn)) = C.UINT16_MAX *(*C.uint16_t)(unsafe.Pointer(pindexOut)) = C.UINT16_MAX p := mapPointer(&singleFlowPacked{cb, data}) cnode := C.sol_flow_single_new(cname, nodeType.ctype, coptions, (*C.uint16_t)(cinputPorts), (*C.uint16_t)(coutputPorts), (*[0]byte)(C.goSingleFlowProcessCallback), unsafe.Pointer(p)) if cnode == nil { return nil } return &SingleFlowNode{&FlowNode{cnode}} }
[ "func NewFlowClient(addr string, port int) *FlowClient {\n\tFlowClient := &FlowClient{Addr: addr, Port: port}\n\tFlowClient.connect()\n\treturn FlowClient\n}", "func New(name string) *Flow {\n\treturn &Flow{\n\t\tName: name,\n\t\tDoneCh: make(chan *Task),\n\t\tActiveTasks: TaskList{},\n\t\tRootTasks: TaskList{},\n\t\tErrornousTasks: TaskList{},\n\t}\n}", "func NewFlow() *Flow {\n\treturn &Flow{\n\t\tMetric: &FlowMetric{},\n\t}\n}", "func NewFlow(ctx *pulumi.Context,\n\tname string, args *FlowArgs, opts ...pulumi.ResourceOption) (*Flow, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Definition == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Definition'\")\n\t}\n\tif args.Description == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Description'\")\n\t}\n\tif args.Type == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Type'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Flow\n\terr := ctx.RegisterResource(\"alicloud:fnf/flow:Flow\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewSFlow(raddr net.IP) (*SFlow, error) {\n\n\tconn, err := mirror.NewRawConn(raddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &SFlow{\n\t\tconn: conn,\n\t\tch: make(chan Packet, 10000),\n\t\tvflow: raddr,\n\t\tMaxRouter: 10,\n\t\tRateLimit: 25 * 10e3,\n\t}, nil\n}", "func NewFlowFromGoPacket(p gopacket.Packet, parentUUID string, uuids *UUIDs, opts *Opts) *Flow {\n\tf := NewFlow()\n\n\tvar length int64\n\tif p.Metadata() != nil {\n\t\tlength = int64(p.Metadata().CaptureLength)\n\t}\n\n\tpacket := &Packet{\n\t\tGoPacket: p,\n\t\tLayers: p.Layers(),\n\t\tData: p.Data(),\n\t\tLength: length,\n\t}\n\n\tkey, l2Key, l3Key := packet.Keys(parentUUID, uuids, opts)\n\n\tf.initFromPacket(key, l2Key, l3Key, packet, parentUUID, uuids, opts)\n\n\treturn f\n}", "func NewFlow(proto uint8, status StatusFlag, srcAddr, destAddr net.IP,\n\tsrcPort, destPort uint16, timeout, mark uint32) Flow {\n\n\tvar f Flow\n\n\tf.Status.Value = status\n\n\tf.Timeout = timeout\n\tf.Mark = mark\n\n\tf.TupleOrig.IP.SourceAddress = srcAddr\n\tf.TupleOrig.IP.DestinationAddress = destAddr\n\tf.TupleOrig.Proto.SourcePort = srcPort\n\tf.TupleOrig.Proto.DestinationPort = destPort\n\tf.TupleOrig.Proto.Protocol = proto\n\n\t// Set up TupleReply with source and destination inverted\n\tf.TupleReply.IP.SourceAddress = destAddr\n\tf.TupleReply.IP.DestinationAddress = srcAddr\n\tf.TupleReply.Proto.SourcePort = destPort\n\tf.TupleReply.Proto.DestinationPort = srcPort\n\tf.TupleReply.Proto.Protocol = proto\n\n\treturn f\n}", "func (f *tcpStreamFactory) New(netFlow, tcpFlow gopacket.Flow, tcp *layers.TCP, ac reassembly.AssemblerContext) reassembly.Stream {\n\t// This is the first packet seen for the tcp session, should be in direction of client to server.\n\t// In our case, egress flow\n\tk := key{netFlow, tcpFlow}\n\tif f.streams[k] != nil {\n\t\tlog.Errorf(\"[%v] found existing stream\", k)\n\t\treturn f.streams[k]\n\t}\n\n\t// We deal with session initiated from our side.\n\tisEgress := true\n\tif f.localEnpoint != netFlow.Src() {\n\t\tisEgress = false\n\t}\n\tif !isEgress {\n\t\tlog.V(2).Infof(\"[%v] found as first packet of TCP session in ingress direction\", k)\n\t\t// TODO: update gopacket/reassembly so it is possible to ignore certain flows.\n\t\t// return nil\n\t}\n\n\t// Create a new stream.\n\tci := ac.GetCaptureInfo()\n\ts := &tcpStream{key: k, ciEgress: &ci, factory: f}\n\tf.streams[k] = s\n\n\tlog.V(5).Infof(\"[%v] created TCP session\", k)\n\treturn s\n}", "func MakeNode(id int, port, ipAddress string, wg *sync.WaitGroup) (*Node, error) {\n\tfmt.Println(\"Creating Node:\", id)\n\tfmt.Println(\"------------------------------------------\")\n\t// create a tcp listener\n\t// using given ip address and port\n\tl, err := net.Listen(\"tcp\", fmt.Sprintf(\"%s:%s\", ipAddress, port))\n\t// return error if any\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// initialize and return new node\n\t// nil for no error\n\tn := &Node{\n\t\tID: id,\n\t\tPort: port,\n\t\tIPAddress: ipAddress,\n\t\tlistener: l,\n\t}\n\twg.Add(1)\n\tgo n.listenOnPort(wg)\n\tfmt.Printf(\"Node %d created successfully and started listening on port %s\\n\", id, port)\n\tfmt.Println(\"Node Info:\", n)\n\tfmt.Println(\"------------------------------------------\")\n\treturn n, nil\n}", "func (_Staking *StakingSession) NewNode(_nodeAddr common.Address, _tokenAmount *big.Int, _dropburnAmount *big.Int, _rewardCut *big.Int, _desc string) (*types.Transaction, error) {\n\treturn _Staking.Contract.NewNode(&_Staking.TransactOpts, _nodeAddr, _tokenAmount, _dropburnAmount, _rewardCut, _desc)\n}", "func (w *Workflow) MakeTaskNode(name string, t Task) *TaskNode {\n\ttn := &TaskNode{\n\t\tid: MakeID(name),\n\t\tname: name,\n\t\tC: make(chan *Params, 1), // a buffer of one - as we always send the end even if no one is listening\n\t}\n\ttn.SetTask(t)\n\ttn.SetWorkFlow(w)\n\tw.registerNode(tn)\n\treturn tn\n}", "func NewFlow(ctx *pulumi.Context,\n\tname string, args *FlowArgs, opts ...pulumi.ResourceOption) (*Flow, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.DestinationFlowConfigs == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'DestinationFlowConfigs'\")\n\t}\n\tif args.SourceFlowConfig == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'SourceFlowConfig'\")\n\t}\n\tif args.Tasks == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Tasks'\")\n\t}\n\tif args.TriggerConfig == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'TriggerConfig'\")\n\t}\n\tvar resource Flow\n\terr := ctx.RegisterResource(\"aws:appflow/flow:Flow\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (_Staking *StakingTransactor) NewNode(opts *bind.TransactOpts, _nodeAddr common.Address, _tokenAmount *big.Int, _dropburnAmount *big.Int, _rewardCut *big.Int, _desc string) (*types.Transaction, error) {\n\treturn _Staking.contract.Transact(opts, \"newNode\", _nodeAddr, _tokenAmount, _dropburnAmount, _rewardCut, _desc)\n}", "func (b *SecuritySchemeBuilder) Flow(v string) *SecuritySchemeBuilder {\n\tb.lock.Lock()\n\tdefer b.lock.Unlock()\n\tif b.target == nil {\n\t\treturn b\n\t}\n\tb.target.flow = v\n\treturn b\n}", "func (*AnnotatorForClinicalDataAcdV1) NewFlow(elements []FlowEntry, async *bool) (model *Flow, err error) {\n\tmodel = &Flow{\n\t\tElements: elements,\n\t\tAsync: async,\n\t}\n\terr = core.ValidateStruct(model, \"required parameters\")\n\treturn\n}", "func (n *Network) createNode(send int) *Node {\n\tnode := Node{value: 0, influenceRecieved: 0, inputRecieved: 0, id: len(n.nodeList), receive: make([]*Connection, 0, 0), send: make([]Connection, 0, send)}\n\n\tif len(n.nodeList) >= cap(n.nodeList) {\n\t\tn.nodeList = append(n.nodeList, node)\n\t} else {\n\t\tn.nodeList = n.nodeList[0 : len(n.nodeList)+1]\n\t\tn.nodeList[len(n.nodeList)-1] = node\n\t}\n\n\treturn &n.nodeList[len(n.nodeList)-1]\n}", "func FromNetworkNode(n NetworkNode) *protocol.Node {\n\treturn &protocol.Node{\n\t\tID: n.ID,\n\t\tIP: n.IP.String(),\n\t\tPort: int32(n.Port),\n\t}\n}", "func setupNode(t *testing.T, net mocknet.Mocknet) (*Node, chan struct{}) {\n\tp, err := net.GenPeer()\n\trequire.NoError(t, err)\n\tn := &Node{Service: service.New(\"node\"), Host: p}\n\tn.PakeProtocol = &PakeProtocol{}\n\tn.TransferProtocol = NewTransferProtocol(n)\n\tdone := make(chan struct{})\n\tn.RegisterTransferHandler(&TestTransferHandler{handler: tmpWriter(t), done: func() { close(done) }})\n\tn.PushProtocol = NewPushProtocol(n)\n\treturn n, done\n}", "func Read(line string) (*Node, error) {\n\tnode := Provider()\n\tfields := strings.Split(line, \",\")\n\tif len(fields) != 5 {\n\t\treturn nil, common.NewError(\"invalid_num_fields\", fmt.Sprintf(\"invalid number of fields [%v]\", line))\n\t}\n\tswitch fields[0] {\n\tcase \"m\":\n\t\tnode.Type = NodeTypeMiner\n\tcase \"s\":\n\t\tnode.Type = NodeTypeSharder\n\tcase \"b\":\n\t\tnode.Type = NodeTypeBlobber\n\tdefault:\n\t\treturn nil, common.NewError(\"unknown_node_type\", fmt.Sprintf(\"Unkown node type %v\", fields[0]))\n\t}\n\tnode.Host = fields[1]\n\tif node.Host == \"\" {\n\t\tif node.Port != config.Configuration.Port {\n\t\t\tnode.Host = config.Configuration.Host\n\t\t} else {\n\t\t\tpanic(fmt.Sprintf(\"invalid node setup for %v\\n\", node.GetKey()))\n\t\t}\n\t}\n\n\tport, err := strconv.ParseInt(fields[2], 10, 32)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnode.Port = int(port)\n\tnode.SetID(fields[3])\n\tnode.PublicKey = fields[4]\n\tnode.Client.SetPublicKey(node.PublicKey)\n\thash := encryption.Hash(node.PublicKeyBytes)\n\tif node.ID != hash {\n\t\treturn nil, common.NewError(\"invalid_client_id\", fmt.Sprintf(\"public key: %v, client_id: %v, hash: %v\\n\", node.PublicKey, node.ID, hash))\n\t}\n\tnode.ComputeProperties()\n\tSelf.SetNodeIfPublicKeyIsEqual(node)\n\treturn node, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
HandleGetIP is a gin HTTP handler that gather's the source IP from an incoming HTTP request and returns it in the response body.
func HandleGetIP(ctx *gin.Context) { ip, port, err := net.SplitHostPort(ctx.Request.RemoteAddr) if err != nil { glog.Error(err.Error()) ctx.JSON(500, gin.H{"result": "internal server error"}) return } glog.Info("Incoming request /getip:" + ip + ":" + port) // Only return the IP, even though we have their source ephemeral port. ctx.JSON(200, gin.H{"ip": ip}) }
[ "func GetIP(r *http.Request) (string, string) {\n\tfwd := r.Header.Get(\"X-Forwarded-For\")\n\taddrStr := \"\"\n\n\tif fwd != \"\" {\n\t\taddrStr = fwd\n\t} else {\n\t\taddrStr = r.RemoteAddr\n\t}\n\taddr := strings.Split(addrStr, \":\")\n\n\treturn addr[0], addr[1]\n}", "func HandleIPRequest(router *mux.Router, rootPath string) {\n\trouter.\n\t\tMethods(http.MethodGet).\n\t\tPath(rootPath).\n\t\tHeadersRegexp(\"Accept\", \".*((application/((xhtml+)?xml|json|javascript))|(text/x?html)).*\").\n\t\tHandlerFunc(provideIP).\n\t\tName(\"ip\")\n}", "func GetIP(r *http.Request) string {\n\tIPAddress := r.Header.Get(\"X-Real-Ip\")\n\tif IPAddress == \"\" {\n\t\tIPAddress = r.Header.Get(\"X-Forwarded-For\")\n\t}\n\tif IPAddress == \"\" {\n\t\treturn r.RemoteAddr[0:strings.LastIndex(r.RemoteAddr, \":\")]\n\t}\n\treturn IPAddress\n}", "func GetIP(r *http.Request, options ...*KeyOptions) net.IP {\n\tif len(options) >= 1 && options[0].TrustForwardHeader {\n\t\tip := r.Header.Get(\"X-Forwarded-For\")\n\t\tif ip != \"\" {\n\t\t\tparts := strings.SplitN(ip, \",\", 2)\n\t\t\tpart := strings.TrimSpace(parts[0])\n\t\t\treturn net.ParseIP(part)\n\t\t}\n\n\t\tip = strings.TrimSpace(r.Header.Get(\"X-Real-IP\"))\n\t\tif ip != \"\" {\n\t\t\treturn net.ParseIP(ip)\n\t\t}\n\t}\n\n\tremoteAddr := strings.TrimSpace(r.RemoteAddr)\n\thost, _, err := net.SplitHostPort(remoteAddr)\n\tif err != nil {\n\t\treturn net.ParseIP(remoteAddr)\n\t}\n\n\treturn net.ParseIP(host)\n}", "func GetIP(site, UserAgent string) string {\n\treturn getAPIResponse(site, UserAgent).ResponseIP\n}", "func GetIPAddress(r *http.Request) (string, error) {\r\n\tip, _, err := netHttp.SplitHostPort(r.RemoteAddr)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\treturn ip, nil\r\n}", "func GetIP(r *http.Request) string {\n\tsplit := strings.Split(r.RemoteAddr, \":\")\n\tip := strings.Join(split[:len(split)-1], \":\")\n\t// This is bad, and I feel bad\n\tip = strings.Replace(ip, \"[\", \"\", 1)\n\tip = strings.Replace(ip, \"]\", \"\", 1)\n\treturn ip\n}", "func GetIPAddress(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tplainAddress := vars[\"domainName\"]\n\tif reply, ok := servers[plainAddress]; ok {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tif enc, err := json.Marshal(reply); err == nil {\n\t\t\tw.Write([]byte(enc))\n\t\t} else {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t} else {\n\t\treply := r.RemoteAddr\n\t\tif enc, err := json.Marshal(reply); err == nil {\n\t\t\tw.Write([]byte(enc))\n\t\t} else {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t}\n}", "func (registry *Registry) GetIP(_, reply *string) error {\n\t*reply = registryService.GetIP()\n\treturn nil\n}", "func GetIp() string {\n\n\tout, err := exc.ExecuteWithBash(\"ip route get 1.1.1.1 | grep -oP 'src \\\\K\\\\S+'\")\n\n\tip := strings.TrimSpace(out)\n\tif log.Check(log.WarnLevel, \"Getting RH IP \"+ip, err) {\n\t\treturn \"\"\n\t}\n\n\treturn ip\n}", "func GetUserIP(req *http.Request) string {\n\treturn req.Header.Get(\"X-Forwarded-For\")\n}", "func GetIPIntel(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\tb, err := json.Marshal(GetIP(vars[\"ip\"]))\n\tif err != nil {\n\t\tw.Write([]byte(\"error\"))\n\t\treturn\n\t}\n\tw.Write(b)\n}", "func (i *IPGetter) Get(ctx context.Context) (string, error) {\n\tr, err := http.Get(canihaz)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Couldn't retrieve external IP address: %w\", err)\n\t}\n\n\tip, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not read IP address from response: %w\", err)\n\t}\n\n\treturn strings.TrimSpace(fmt.Sprintf(\"%s\", ip)), nil\n}", "func getIP(url string) string {\n\tres, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\tdefer res.Body.Close()\n\tb, _ := io.ReadAll(res.Body)\n\treturn string(b)\n}", "func getIP(r *http.Request) string {\n\tvar addr string\n\n\tif fwd := r.Header.Get(xForwardedFor); fwd != \"\" {\n\t\t// Only grab the first (client) address. Note that '192.168.0.1,\n\t\t// 10.1.1.1' is a valid key for X-Forwarded-For where addresses after\n\t\t// the first may represent forwarding proxies earlier in the chain.\n\t\ts := strings.Index(fwd, \", \")\n\t\tif s == -1 {\n\t\t\ts = len(fwd)\n\t\t}\n\t\taddr = fwd[:s]\n\t} else if fwd := r.Header.Get(xRealIP); fwd != \"\" {\n\t\t// X-Real-IP should only contain one IP address (the client making the\n\t\t// request).\n\t\taddr = fwd\n\t} else if fwd := r.Header.Get(forwarded); fwd != \"\" {\n\t\t// match should contain at least two elements if the protocol was\n\t\t// specified in the Forwarded header. The first element will always be\n\t\t// the 'for=' capture, which we ignore. In the case of multiple IP\n\t\t// addresses (for=8.8.8.8, 8.8.4.4,172.16.1.20 is valid) we only\n\t\t// extract the first, which should be the client IP.\n\t\tif match := forRegex.FindStringSubmatch(fwd); len(match) > 1 {\n\t\t\t// IPv6 addresses in Forwarded headers are quoted-strings. We strip\n\t\t\t// these quotes.\n\t\t\taddr = strings.Trim(match[1], `\"`)\n\t\t}\n\t}\n\n\tif addr == \"\" {\n\t\treturn r.RemoteAddr\n\t}\n\treturn addr\n}", "func getIP(r *http.Request, trustForwardHeader bool) net.IP {\n\tif trustForwardHeader {\n\t\tip := r.Header.Get(\"X-Forwarded-For\")\n\t\tif ip != \"\" {\n\t\t\tparts := strings.SplitN(ip, \",\", 2)\n\t\t\tpart := strings.TrimSpace(parts[0])\n\t\t\treturn net.ParseIP(part)\n\t\t}\n\t\tip = strings.TrimSpace(r.Header.Get(\"X-Real-IP\"))\n\t\tif ip != \"\" {\n\t\t\treturn net.ParseIP(ip)\n\t\t}\n\t}\n\n\tremoteAddr := strings.TrimSpace(r.RemoteAddr)\n\thost, _, err := net.SplitHostPort(remoteAddr)\n\tif err != nil {\n\t\treturn net.ParseIP(remoteAddr)\n\t}\n\n\treturn net.ParseIP(host)\n}", "func ipResponder(w http.ResponseWriter, r *http.Request) {\n\n\t// try to get IP from http headers\n\tip, err := getIPFromRequest(r)\n\tif err != nil {\n\t\tlog.Printf(\"[ERROR] %s\\n\", err.Error())\n\t\thttp.Error(w, \"Unable to determine remote address from request\", 400)\n\t\treturn\n\t}\n\n\tlog.Println(\"[INFO]\", ip.String(), r.UserAgent())\n\n\tw.WriteHeader(200)\n\tfmt.Fprintf(w, \"%s\\n\", ip.String())\n}", "func Ip(rw http.ResponseWriter, req *http.Request) {\n\n\t// Write to the web page.\n\tfmt.Fprintln(rw, \"Hello \"+req.Header.Get(\"X-Forwarded-For\"))\n\n\t// Write to the log.\n\tfmt.Println(\"Served client: \"+req.Header.Get(\"X-Forwarded-For\"))\n\n}", "func GetIPAdress(r *http.Request) (string, error) {\n\t//Get IP from the X-REAL-IP header\n\tip := r.Header.Get(\"X-REAL-IP\")\n\tnetIP := net.ParseIP(ip)\n\tif netIP != nil {\n\t\treturn ip, nil\n\t}\n\n\t//Get IP from X-FORWARDED-FOR header\n\tips := r.Header.Get(\"X-FORWARDED-FOR\")\n\tsplitIps := strings.Split(ips, \",\")\n\tfor _, ip := range splitIps {\n\t\tnetIP := net.ParseIP(ip)\n\t\tif netIP != nil {\n\t\t\treturn ip, nil\n\t\t}\n\t}\n\n\t//Get IP from RemoteAddr\n\tip, _, err := net.SplitHostPort(r.RemoteAddr)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tnetIP = net.ParseIP(ip)\n\tif netIP != nil {\n\t\treturn ip, nil\n\t}\n\treturn \"\", errors.New(\"No valid ip found\")\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CheckSlotSpan checks if the slot is within the span of slots, with MAXIMUM_GOSSIP_CLOCK_DISPARITY margin in time.
func CheckSlotSpan(slotAfter func(delta time.Duration) common.Slot, slot common.Slot, span common.Slot) error { if slot+span < slot { return fmt.Errorf("slot overflow: %d", slot) } // check minimum, with account for clock disparity if minSlot := slotAfter(-MAXIMUM_GOSSIP_CLOCK_DISPARITY); slot+span < minSlot { return fmt.Errorf("slot %d is too old, minimum slot is %d", slot, minSlot) } // check maximum, with account for clock disparity if maxSlot := slotAfter(MAXIMUM_GOSSIP_CLOCK_DISPARITY); slot > maxSlot { return fmt.Errorf("slot %d is too new, maximum slot is %d", slot, maxSlot) } return nil }
[ "func ValidSlot(n uint) (result bool) {\n\treturn 1 <= n && n <= TotalSlots\n}", "func (config *generator) validateSlots() {\n\n\t// default return value if validation fails\n\temptySlots := make([][2]int64, 0)\n\tif len(config.Slots) == 0 {\n\t\treturn\n\t}\n\n\treturnEmptySlots := false\n\n\t// check slot with 0 values\n\t// remove them from config.Slots\n\temptySlotCount := 0\n\tfor index, slot := range config.Slots {\n\t\tif slot[0] == 0 || slot[1] == 0 {\n\t\t\tutil.Logf(\"WARNING:Slot[%v][%v] is having 0 duration\\n\", index, slot)\n\t\t\temptySlotCount++\n\t\t\tcontinue\n\t\t}\n\n\t\t// check slot boundaries\n\t\tif slot[1] < config.requested.slotMinDuration || slot[1] > config.requested.slotMaxDuration {\n\t\t\tutil.Logf(\"ERROR: Slot%v Duration %v sec is out of either requested.slotMinDuration (%v) or requested.slotMaxDuration (%v)\\n\", index, slot[1], config.requested.slotMinDuration, config.requested.slotMaxDuration)\n\t\t\treturnEmptySlots = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// remove empty slot\n\tif emptySlotCount > 0 {\n\t\toptimizedSlots := make([][2]int64, len(config.Slots)-emptySlotCount)\n\t\tfor index, slot := range config.Slots {\n\t\t\tif slot[0] == 0 || slot[1] == 0 {\n\t\t\t} else {\n\t\t\t\toptimizedSlots[index][0] = slot[0]\n\t\t\t\toptimizedSlots[index][1] = slot[1]\n\t\t\t}\n\t\t}\n\t\tconfig.Slots = optimizedSlots\n\t\tutil.Logf(\"Removed %v empty slots\\n\", emptySlotCount)\n\t}\n\n\tif int64(len(config.Slots)) < config.requested.minAds || int64(len(config.Slots)) > config.requested.maxAds {\n\t\tutil.Logf(\"ERROR: slotSize %v is either less than Min Ads (%v) or greater than Max Ads (%v)\\n\", len(config.Slots), config.requested.minAds, config.requested.maxAds)\n\t\treturnEmptySlots = true\n\t}\n\n\t// ensure if min pod duration = max pod duration\n\t// config.TotalSlotTime = pod duration\n\tif config.requested.podMinDuration == config.requested.podMaxDuration && *config.totalSlotTime != config.requested.podMaxDuration {\n\t\tutil.Logf(\"ERROR: Total Slot Duration %v sec is not matching with Total Pod Duration %v sec\\n\", *config.totalSlotTime, config.requested.podMaxDuration)\n\t\treturnEmptySlots = true\n\t}\n\n\t// ensure slot duration lies between requested min pod duration and requested max pod duration\n\t// Testcase #15\n\tif *config.totalSlotTime < config.requested.podMinDuration || *config.totalSlotTime > config.requested.podMaxDuration {\n\t\tutil.Logf(\"ERROR: Total Slot Duration %v sec is either less than Requested Pod Min Duration (%v sec) or greater than Requested Pod Max Duration (%v sec)\\n\", *config.totalSlotTime, config.requested.podMinDuration, config.requested.podMaxDuration)\n\t\treturnEmptySlots = true\n\t}\n\n\tif returnEmptySlots {\n\t\tconfig.Slots = emptySlots\n\t\tconfig.freeTime = config.requested.podMaxDuration\n\t}\n}", "func TestAllocMax(t *testing.T) {\n\ts := newClutchSlotTester(t, &clutch{})\n\tdefer s.release()\n\n\tconst maxSlotItems = itemsLen*hunksLen - itemsLen/2 // insider knowledge\n\n\t// fill up slot 1\n\tfor i := 0; i < maxSlotItems; i++ {\n\t\t// don't use s.add() to avoid bookkeeping overhead\n\t\ttag := s.clutch.TagItem(s.slot, struct{}{})\n\t\tindex := tag & (markBase - 1)\n\t\tslot := index / slotBase\n\t\tif !assert.Equal(s.t, s.slot, slot) {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// this should go the shared slot\n\ttag := s.clutch.TagItem(s.slot, s.seq)\n\tif !assert.NotEqual(s.t, uint64(0), tag) {\n\t\treturn\n\t}\n\n\t// validate slot is 0\n\tindex := tag & (markBase - 1)\n\tslot := index / slotBase\n\tif !assert.Equal(s.t, uint64(0), slot) {\n\t\treturn\n\t}\n}", "func CheckSlots(t *testing.T, obj Interface, slots []string) {\n\tt.Helper()\n\to := obj.SP()\n\to.L.Lock()\n\tdefer o.L.Unlock()\n\tchecked := make(map[string]bool, len(slots))\n\tfor _, name := range slots {\n\t\tchecked[name] = true\n\t\tt.Run(\"Have_\"+name, func(t *testing.T) {\n\t\t\tslot, ok := o.Slots[name]\n\t\t\tif !ok {\n\t\t\t\tt.Fatal(\"no slot\", name)\n\t\t\t}\n\t\t\tif slot == nil {\n\t\t\t\tt.Fatal(\"slot\", name, \"is nil\")\n\t\t\t}\n\t\t})\n\t}\n\tfor name := range o.Slots {\n\t\tt.Run(\"Want_\"+name, func(t *testing.T) {\n\t\t\tif !checked[name] {\n\t\t\t\tt.Fatal(\"unexpected slot\", name)\n\t\t\t}\n\t\t})\n\t}\n}", "func (me TxsdTspanTypeLengthAdjust) IsSpacing() bool { return me.String() == \"spacing\" }", "func (a *BookAppointment) TimeSlotValidation() *apierrors.RestErr{\r\n\r\n\t//Loop to check the booking timeslot in available timeslot array\r\n\tfor _, value := range AvailableTimeSlot {\r\n\t\tif a.TimeSlot == value {\r\n\t\t\treturn nil\r\n\t\t}\r\n\t}\r\n\r\n\treturn apierrors.NewBadRequestError(\r\n\t\tfmt.Sprintf(\"Selected Slot is not available for the time %s,Please choose between 9.30 am to 11.30 am /2pm to 4pm /6pm to 8pm\",a.TimeSlot))\r\n\r\n}", "func (config generator) shouldAdjustSlotWithZeroDuration() bool {\n\tif config.requested.minAds == config.requested.maxAds {\n\t\treturn true\n\t}\n\treturn false\n}", "func checkOverlaps(a, ap Span) bool {\n\tif len(a.EndKey) == 0 {\n\t\treturn bytes.Compare(ap.EndKey, a.StartKey) > 0\n\t}\n\treturn bytes.Compare(a.StartKey, ap.EndKey) < 0 && bytes.Compare(ap.StartKey, a.EndKey) < 0\n}", "func (s *Slot) HasEnoughMsg(phase, round uint32) bool {\n\treturn s.RecvBCMsgsT[phase][round-1] >= config.Conf.NMinusF\n}", "func computeTimeForEachAdSlot(cfg generator, totalAds int64) int64 {\n\t// Compute time for each ad\n\tif totalAds <= 0 {\n\t\tutil.Logf(\"totalAds = 0, Hence timeForEachSlot = 0\")\n\t\treturn 0\n\t}\n\ttimeForEachSlot := cfg.requested.podMaxDuration / totalAds\n\n\tutil.Logf(\"Computed timeForEachSlot = %v (podMaxDuration/totalAds) (%v/%v)\\n\", timeForEachSlot, cfg.requested.podMaxDuration, totalAds)\n\n\tif timeForEachSlot < cfg.internal.slotMinDuration {\n\t\ttimeForEachSlot = cfg.internal.slotMinDuration\n\t\tutil.Logf(\"Computed timeForEachSlot < requested slotMinDuration (%v). Hence, setting timeForEachSlot = slotMinDuration = %v\\n\", cfg.internal.slotMinDuration, timeForEachSlot)\n\t}\n\n\tif timeForEachSlot > cfg.internal.slotMaxDuration {\n\t\ttimeForEachSlot = cfg.internal.slotMaxDuration\n\t\tutil.Logf(\"Computed timeForEachSlot > requested slotMaxDuration (%v). Hence, setting timeForEachSlot = slotMaxDuration = %v\\n\", cfg.internal.slotMaxDuration, timeForEachSlot)\n\t}\n\n\t// Case - Exact slot duration is given. No scope for finding multiples\n\t// of given number. Prefer to return computed timeForEachSlot\n\t// In such case timeForEachSlot no necessarily to be multiples of given number\n\tif cfg.requested.slotMinDuration == cfg.requested.slotMaxDuration {\n\t\tutil.Logf(\"requested.slotMinDuration = requested.slotMaxDuration = %v. Hence, not computing multiples of %v value.\", cfg.requested.slotMaxDuration, multipleOf)\n\t\treturn timeForEachSlot\n\t}\n\n\t// Case II - timeForEachSlot*totalAds > podmaxduration\n\t// In such case prefer to return cfg.podMaxDuration / totalAds\n\t// In such case timeForEachSlot no necessarily to be multiples of given number\n\tif (timeForEachSlot * totalAds) > cfg.requested.podMaxDuration {\n\t\tutil.Logf(\"timeForEachSlot*totalAds (%v) > cfg.requested.podMaxDuration (%v) \", timeForEachSlot*totalAds, cfg.requested.podMaxDuration)\n\t\tutil.Logf(\"Hence, not computing multiples of %v value.\", multipleOf)\n\t\t// need that division again\n\t\treturn cfg.requested.podMaxDuration / totalAds\n\t}\n\n\t// ensure timeForEachSlot is multipleof given number\n\tif cfg.internal.slotDurationComputed && !isMultipleOf(timeForEachSlot, multipleOf) {\n\t\t// get close to value of multiple\n\t\t// here we muse get either cfg.SlotMinDuration or cfg.SlotMaxDuration\n\t\t// these values are already pre-computed in multiples of given number\n\t\ttimeForEachSlot = getClosestFactor(timeForEachSlot, multipleOf)\n\t\tutil.Logf(\"Computed closet factor %v, in multiples of %v for timeForEachSlot\\n\", timeForEachSlot, multipleOf)\n\t}\n\tutil.Logf(\"Computed Final timeForEachSlot = %v [%v <= %v <= %v]\\n\", timeForEachSlot, cfg.requested.slotMinDuration, timeForEachSlot, cfg.requested.slotMaxDuration)\n\treturn timeForEachSlot\n}", "func inTimeSpan(start, end, check time.Time) bool {\n\treturn check.After(start) && check.Before(end)\n}", "func InTimeSpan(start, end, check time.Time) bool {\n\treturn check.After(start) && check.Before(end)\n}", "func validSlots(slots []ClimbingSlot) []ClimbingSlot {\n\tvalid := make([]ClimbingSlot, 0)\n\n\tfor _, slot := range slots {\n\tif slot.Availability != \"Full\" {\n\tvalid = append(valid, slot)\n\t}\n\t}\n\n\treturn valid\n\t}", "func ValidateSlotTimeResponseBody(body *SlotTimeResponseBody) (err error) {\n\tif body.ServiceID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"service_id\", \"body\"))\n\t}\n\tif body.StartSec == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"start_sec\", \"body\"))\n\t}\n\tif body.ConfirmationMode != nil {\n\t\tif !(*body.ConfirmationMode == \"CONFIRMATION_MODE_UNSPECIFIED\" || *body.ConfirmationMode == \"CONFIRMATION_MODE_SYNCHRONOUS\" || *body.ConfirmationMode == \"CONFIRMATION_MODE_ASYNCHRONOUS\") {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(\"body.confirmation_mode\", *body.ConfirmationMode, []interface{}{\"CONFIRMATION_MODE_UNSPECIFIED\", \"CONFIRMATION_MODE_SYNCHRONOUS\", \"CONFIRMATION_MODE_ASYNCHRONOUS\"}))\n\t\t}\n\t}\n\treturn\n}", "func (config generator) addTime(timeForEachSlot int64, fillZeroSlotsOnPriority bool) (int64, bool) {\n\ttime := int64(0)\n\n\t// iterate over each ad\n\tslotCountFullWithCapacity := 0\n\tfor ad := int64(0); ad < int64(len(config.Slots)); ad++ {\n\n\t\tslot := &config.Slots[ad]\n\t\t// check\n\t\t// 1. time(slot(0)) <= config.SlotMaxDuration\n\t\t// 2. if adding new time to slot0 not exeeding config.SlotMaxDuration\n\t\t// 3. if sum(slot time) + timeForEachSlot <= config.RequestedPodMaxDuration\n\t\tcanAdjustTime := (slot[1]+timeForEachSlot) <= config.requested.slotMaxDuration && (slot[1]+timeForEachSlot) >= config.requested.slotMinDuration\n\t\ttotalSlotTimeWithNewTimeLessThanRequestedPodMaxDuration := *config.totalSlotTime+timeForEachSlot <= config.requested.podMaxDuration\n\n\t\t// if fillZeroSlotsOnPriority= true ensure current slot value = 0\n\t\tallowCurrentSlot := !fillZeroSlotsOnPriority || (fillZeroSlotsOnPriority && slot[1] == 0)\n\t\tif slot[1] <= config.internal.slotMaxDuration && canAdjustTime && totalSlotTimeWithNewTimeLessThanRequestedPodMaxDuration && allowCurrentSlot {\n\t\t\tslot[0] += timeForEachSlot\n\n\t\t\t// if we are adjusting the free time which will match up with config.RequestedPodMaxDuration\n\t\t\t// then set config.SlotMinDuration as min value for this slot\n\t\t\t// TestCase #16\n\t\t\t//if timeForEachSlot == maxPodDurationMatchUpTime {\n\t\t\tif timeForEachSlot < multipleOf {\n\t\t\t\t// override existing value of slot[0] here\n\t\t\t\tslot[0] = config.requested.slotMinDuration\n\t\t\t}\n\n\t\t\t// check if this slot duration was zero\n\t\t\tif slot[1] == 0 {\n\t\t\t\t// decrememt config.slotsWithZeroTime as we added some time for this slot\n\t\t\t\t*config.slotsWithZeroTime--\n\t\t\t}\n\n\t\t\tslot[1] += timeForEachSlot\n\t\t\t*config.totalSlotTime += timeForEachSlot\n\t\t\ttime += timeForEachSlot\n\t\t\tutil.Logf(\"Slot %v = Added %v sec (New Time = %v)\\n\", ad, timeForEachSlot, slot[1])\n\t\t}\n\t\t// check slot capabity\n\t\t// !canAdjustTime - TestCase18\n\t\t// UOE-5268 - Check with Requested Slot Max Duration\n\t\tif slot[1] == config.requested.slotMaxDuration || !canAdjustTime {\n\t\t\t// slot is full\n\t\t\tslotCountFullWithCapacity++\n\t\t}\n\t}\n\tutil.Logf(\"adjustedTime = %v\\n \", time)\n\treturn time, slotCountFullWithCapacity == len(config.Slots)\n}", "func IsSpan(name string) bool {\n\treturn strings.Contains(name, \".span-\")\n}", "func (me TxsdTspanTypeLengthAdjust) IsSpacingAndGlyphs() bool {\n\treturn me.String() == \"spacingAndGlyphs\"\n}", "func (s *Slot) IsValidNow() bool {\n\tif s.nextIndex == Now().nextIndex {\n\t\treturn true\n\t}\n\treturn false\n}", "func (r *Replica) CheckCurrentSlotNum() bool {\n\tfor _, v := range r.decisions {\n\t\tif v.SlotIdx == r.slotNum {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LoadLoginPage Render login page
func LoadLoginPage(w http.ResponseWriter, r *http.Request) { cookie, _ := cookies.Read(r) if cookie["token"] != "" { http.Redirect(w, r, "/feed", 302) return } utils.RunTemplate(w, "login.html", nil) }
[ "func showLoginPage(c *gin.Context) {\n\trender(c, gin.H{\n\t\t\"title\": \"Login\",\n\t\t\"ErrorMessage\": \"\",\n\t}, \"login.html\")\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\n\tpageVars := PageVars{}\n\taddPageVars(r, &pageVars)\n\trender(w, \"login\", pageVars)\n}", "func LoadViewLogin(w http.ResponseWriter, r *http.Request) {\n\tutils.RunTemplate(w, \"login.html\", nil)\n}", "func Login(ctx echo.Context) error {\n\n\tf := forms.New(utils.GetLang(ctx))\n\tutils.SetData(ctx, \"form\", f)\n\n\t// set page tittle to login\n\tutils.SetData(ctx, settings.PageTitle, \"login\")\n\n\treturn ctx.Render(http.StatusOK, tmpl.LoginTpl, utils.GetData(ctx))\n}", "func login(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"GET\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tif _, err := data.CheckSession(r); err == nil {\n\t\tgenerateHTML(w, nil, []string{\"login.layout\", \"private.navbar\", \"login\"})\n\t} else {\n\t\tgenerateHTML(w, nil, []string{\"login.layout\", \"public.navbar\", \"login\"})\n\t}\n}", "func (m *Repository) GetLogin(w http.ResponseWriter, r *http.Request) {\n\tif m.App.Session.Exists(r.Context(), \"user_id\") {\n\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\trender.Template(w, r, \"login.page.tmpl\", &models.TemplateData{\n\t\tForm: forms.New(nil),\n\t})\n}", "func (h *webHandler) serveLoginPage(c *gin.Context) {\n\t// Check token\n\terr := h.checkToken(c.Request)\n\tif err == nil {\n\t\tredirectPage(c, \"/\")\n\t\treturn\n\t}\n\n\terr = serveFile(c, \"login.html\")\n\tutils.CheckError(err)\n}", "func (controller *Auth) ShowLoginPage() {\n\tif controller.AccountConnected {\n\t\tcontroller.Redirect(\"/\", 302)\n\t} else {\n\t\tcontroller.showLoginForm()\n\t}\n}", "func (s TppHTTPServer) Login(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\tdata := LoginPageData{PageTitle: \"AXA Pay Bank Login\", BankID: s.BankID, PIN: s.PIN}\n\t//fmt.Fprint(w, \"TPP server reference PISP Login\\n\")\n\ttmpl := template.Must(template.ParseFiles(\"api/login.html\"))\n\tr.ParseForm()\n\tlog.Println(\"Form:\", r.Form)\n\ttmpl.Execute(w, data)\n\n}", "func login(w http.ResponseWriter, r *http.Request) {\n\tcxt := loginContext{}\n\n\tif r.PostFormValue(\"username\") != \"\" {\n\t\tuser := r.PostFormValue(\"username\")\n\t\tpass := r.PostFormValue(\"password\")\n\t\tfmt.Printf(\"[INFO] Login request: username=%s, password=%s\\n\", user, pass)\n\t\tif validateLogin(user, pass) {\n\t\t\tlogmein(user, pass)\n\t\t\tshow(w, r)\n\t\t} else {\n\t\t\tfmt.Printf(\"[INFO] login rejected: username=%s, password=%s\\n\",\n\t\t\t\tuser, pass)\n\t\t}\n\t}\n\n\tfmt.Println(\"[INFO] Rendering template: login.html\")\n\ttemplates.ExecuteTemplate(w, \"login.html\", &cxt)\n}", "func (c Control) ServeLogin(w http.ResponseWriter, r *http.Request) {\n\ttemplate := map[string]interface{}{\"error\": false}\n\tif r.Method == http.MethodPost {\n\t\t// Get their submitted hash and the real hash.\n\t\tpassword := r.PostFormValue(\"password\")\n\t\thash := HashPassword(password)\n\t\tc.Config.RLock()\n\t\trealHash := c.Config.AdminHash\n\t\tc.Config.RUnlock()\n\t\t// Check if they got the password correct.\n\t\tif hash == realHash {\n\t\t\ts, _ := Store.Get(r, \"sessid\")\n\t\t\ts.Values[\"authenticated\"] = true\n\t\t\ts.Save(r, w)\n\t\t\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n\t\t\treturn\n\t\t}\n\t\ttemplate[\"error\"] = true\n\t}\n\n\t// Serve login page with no template.\n\tdata, err := Asset(\"templates/login.mustache\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n\tcontent := mustache.Render(string(data), template)\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\tw.Write([]byte(content))\n}", "func LoadPage(c *fiber.Ctx, login string, roles []int) error {\n\tquerypack.INFO.Roles = roles\n\tquerypack.INFO.Login = login\n\tquerypack.INFO.LoggedIn = true\n\tc.Method(\"GET\")\n\tc.Path(querypack.INFO.URL)\n\tquerypack.AddCookie(c)\n\treturn c.Next()\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tconditionsMap := map[string]interface{}{}\n\tsession, err := loggedUserSession.Get(r, \"authenticated-user-session\")\n\tif err != nil {\n\t\tlog.Println(\"Não há dados na sessão login\", err)\n\t}\n\n\tlog.Println(\"Session name : \", session.Name())\n\tlog.Println(\"Username Login : \", session.Values[\"username\"])\n\tconditionsMap[\"Username\"] = session.Values[\"username\"]\n\n\tif session.Values[\"tipoAcesso\"] == \"adm\" {\n\t\tconditionsMap[\"tipoAcesso\"] = session.Values[\"tipoAcesso\"]\n\t}\n\n\tif conditionsMap[\"Username\"] != \"\" && conditionsMap[\"Username\"] != nil {\n\t\ttmpl.ExecuteTemplate(w, \"login.html\", conditionsMap)\n\t} else {\n\t\ttmpl.ExecuteTemplate(w, \"login.html\", nil)\n\t}\n}", "func userPage(w http.ResponseWriter, r *http.Request){\n\tisLogged, name := CheckLoginStatus(w,r)\n\n\tif isLogged {\n\t\terr := templ.ExecuteTemplate(w, \"userHome\", name)\n\t\tif err != nil {\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t} else {\n\t\thttp.Redirect(w,r,\"/unauthorized\",http.StatusSeeOther)\n\t}\n}", "func (c *LoginController) ShowLogin(ctx *app.ShowLoginLoginContext) error {\n\t// LoginController_ShowLogin: start_implement\n\tloginError := map[string]interface{}{}\n\tc.SessionStore.GetAs(\"loginError\", &loginError, ctx.Request)\n\n\ttemplateContent, err := ioutil.ReadFile(\"public/login/login-form.html\")\n\tif err != nil {\n\t\treturn ctx.InternalServerError(err)\n\t}\n\n\tt, err := template.New(\"login-form\").Parse(string(templateContent))\n\tif err != nil {\n\t\treturn ctx.InternalServerError(err)\n\t}\n\n\tresponseCode := 200\n\n\tif loginErrorCode, ok := loginError[\"code\"]; ok {\n\t\tresponseCode = loginErrorCode.(int)\n\t}\n\n\trw := ctx.ResponseWriter\n\n\trw.Header().Set(\"Content-Type\", \"text/html\")\n\terr = t.Execute(rw, loginError)\n\trw.WriteHeader(responseCode)\n\tif err != nil {\n\t\tprintln(err.Error())\n\t}\n\t// LoginController_ShowLogin: end_implement\n\treturn nil\n}", "func (s *HttpServer) loginForm(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\ts.RenderTemplate(ctx, w, \"login\", nil)\n}", "func (a *noAuth) Login(w http.ResponseWriter, r *http.Request) {}", "func (a NoAuth) LoginPage() bool {\n\treturn false\n}", "func (h *Handler) LoginHandler(w http.ResponseWriter, r *http.Request) {\n\n\tchallenge, err := readURLChallangeParams(r, \"login\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif r.Method == \"POST\" {\n\t\tif r.Form == nil {\n\t\t\tif err := r.ParseForm(); 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}\n\t\tuserName := r.Form.Get(\"username\")\n\t\tpassword := r.Form.Get(\"password\")\n\t\tloginChallenge := r.Form.Get(\"challenge\")\n\t\tpass, err := h.LoginService.CheckPasswords(userName, password)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\n\t\tif pass {\n\n\t\t\tacceptLoginBody := h.ConfigService.FetchAcceptLoginConfig(userName)\n\t\t\trawJson, err := json.Marshal(acceptLoginBody)\n\n\t\t\tredirectURL, err := h.LoginService.SendAcceptBody(\"login\", loginChallenge, rawJson)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\thttp.Redirect(w, r, redirectURL, http.StatusFound)\n\t\t}\n\n\t\tw.WriteHeader(http.StatusForbidden)\n\t\ttemplLogin := template.Must(template.ParseFiles(\"templates/login.html\"))\n\t\tloginData := h.ConfigService.FetchLoginConfig(challenge, true)\n\t\ttemplLogin.Execute(w, loginData)\n\t} else {\n\t\tchallengeBody, err := h.LoginService.ReadChallenge(challenge, \"login\")\n\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tlog.Print(err)\n\t\t}\n\n\t\tif !challengeBody.Skip {\n\t\t\ttemplLogin := template.Must(template.ParseFiles(\"templates/login.html\"))\n\t\t\tloginData := h.ConfigService.FetchLoginConfig(challenge, false)\n\t\t\ttemplLogin.Execute(w, loginData)\n\t\t} else {\n\n\t\t\tacceptLoginBody := h.ConfigService.FetchAcceptLoginConfig(challengeBody.Subject)\n\t\t\trawJson, err := json.Marshal(acceptLoginBody)\n\n\t\t\tredirectURL, err := h.LoginService.SendAcceptBody(\"login\", challenge, rawJson)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\thttp.Redirect(w, r, redirectURL, http.StatusFound)\n\n\t\t}\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LoadRegisterPage Render register page
func LoadRegisterPage(w http.ResponseWriter, r *http.Request) { utils.RunTemplate(w, "register.html", nil) }
[ "func RegisterPageHandler(w http.ResponseWriter,r *http.Request) {\n\tvar body,_ = servers.LoadFile(\"static/register.html\")\n\tfmt.Fprintf(w, body)\n}", "func (c *UserController) ShowRegister() {\n\t//sum := sha256.Sum256([]byte(\"helloworda\"))\n\n\tc.TplName = \"register.html\"\n}", "func ShowResgistrationPage(c *gin.Context) {\n\trender(c, gin.H{\n\t\t\"title\": \"Register\",\n\t}, \"register.html\")\n}", "func (s *Server) registerHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"in register handle\")\n\ts.renderTemplate(w, \"register\", nil)\n}", "func AdminRegister(w http.ResponseWriter, data interface{}) {\n\trender(tpAdminRegister, w, data)\n}", "func RegisterHandler(c *gin.Context) {\n\tc.HTML(http.StatusOK, \"register.html\", nil)\n}", "func (u *UserView) ShowRegistrationPage(c *gin.Context) {\n\trender(c,\n\t\tgin.H{\"title\": \"Register\"},\n\t\t\"register.html\")\n}", "func (c *Controller) CtrRegisterGet(w http.ResponseWriter, r *http.Request, opt router.URLOptions, sm session.ISessionManager, s store.IStore) {\n\tc.RenderTemplate(w, r, \"register\", sm, make(map[string]interface{}), c.moduleID)\n}", "func (h *Handlers) Register(w http.ResponseWriter, r *http.Request) {\n\tif r.Method == \"GET\" {\n\t\th.rendr.HTML(w, http.StatusOK, h.cfg.RegisterTmpl, nil)\n\t\treturn\n\t}\n\tif r.Method == \"POST\" {\n\t\tr.ParseForm()\n\t\tuser := new(User)\n\t\tdata := render.NewTemplateData()\n\t\tif err := formam.Decode(r.Form, user); err != nil {\n\t\t\th.rendr.HTML(w, http.StatusInternalServerError, h.cfg.ServerErrTmpl, nil)\n\t\t\treturn\n\t\t}\n\t\tif v := user.Validate(); v != nil {\n\t\t\tdata.Add(\"errors\", v)\n\t\t\th.rendr.HTML(w, http.StatusOK, h.cfg.RegisterTmpl, data)\n\t\t\treturn\n\t\t}\n\t\tif h.ustore.Exist(user) {\n\t\t\tdata.Add(\"error\", \"user already exist\")\n\t\t\th.rendr.HTML(w, http.StatusOK, h.cfg.RegisterTmpl, data)\n\t\t\treturn\n\t\t}\n\t\tif err := h.ustore.CreateUser(user); err != nil {\n\t\t\th.rendr.HTML(w, http.StatusInternalServerError, h.cfg.ServerErrTmpl, nil)\n\t\t\treturn\n\t\t}\n\n\t\tss, err := h.sess.New(r, h.cfg.SessName)\n\t\tif err != nil {\n\t\t\t// TODO (gernest): log this error\n\t\t}\n\t\tss.Values[\"user\"] = user.Email\n\t\tflash := NewFlash()\n\t\tflash.Success(\"Successfully created your account\")\n\t\tflash.Add(ss)\n\t\tss.Save(r, w)\n\t\thttp.Redirect(w, r, h.cfg.RegRedir, http.StatusFound)\n\t\treturn\n\t}\n}", "func GetRegister(w http.ResponseWriter, req *http.Request, app *App) {\n\trender(w, \"admin/register\", nil, app)\n}", "func (c *Controller) GetRegister() mvc.Result {\n\tif c.isLoggedIn() {\n\t\treturn c.logout()\n\t}\n\n\t// You could just use it as a variable to win some time in serve-time,\n\t// this is an exersise for you :)\n\treturn mvc.View{\n\t\tName: pathRegister.Path + \".html\",\n\t\tData: page{\"User Registration\"},\n\t}\n}", "func LoadViewCreateUser(w http.ResponseWriter, r *http.Request) {\n\tutils.RunTemplate(w, \"register.html\", nil)\n}", "func RegisterPage(page *types.Page, nav *navigation.Navigation) {\n\n\tif build.ModuleConsole {\n\t\tconsole.RegisterPage(page, nav)\n\t}\n\n\tif build.ModuleLogViewer {\n\t\tlogviewer.RegisterPage(page, nav)\n\t}\n\n\tif build.ModuleBackup {\n\t\tbackup.RegisterPage(page, nav)\n\t}\n\n\tif build.ModuleOpenESPM {\n\t\topenespm.RegisterPage(page, nav)\n\t}\n\n\tif build.ModuleFileshare {\n\t\tfileshare.RegisterPage(page, nav)\n\t}\n\n\tif build.ModuleHomepage {\n\t\thomepage.RegisterPage(page, nav)\n\t}\n\n\tif build.ModuleMeshFS {\n\t\tmeshfilesync.RegisterPage(page, nav)\n\t}\n\n\tif build.ModuleMesh || build.ModuleMessenger || build.ModuleMeshFS {\n\t\tmesh.RegisterPage(page, nav)\n\t}\n\n\tif build.ModuleMediaDownloader {\n\t\tmediadownloader.RegisterPage(page, nav)\n\t}\n\n\tif build.ModuleIPTracker {\n\t\tiptracker.RegisterPage(page, nav)\n\t}\n\n\tif build.ModuleGasPrice {\n\t\tgasprice.RegisterPage(page, nav)\n\t}\n\n\tif build.ModulePictureX {\n\t\tpicturex.RegisterPage(page, nav)\n\t}\n\n\tif build.ModuleS7Backup {\n\t\ts7backup.RegisterPage(page, nav)\n\t}\n\n\tif build.ModuleInstaBackup {\n\t\tinstabackup.RegisterPage(page, nav)\n\t}\n\n\tif build.ModuleMonMotion {\n\t\tmonmotion.RegisterPage(page, nav)\n\t}\n\n\tif build.ModuleGPSNav {\n\t\tgpsnav.RegisterPage(page, nav)\n\t}\n}", "func (u *User) GetRegister(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\t// If the user already has a session (is logged in), redirect\n\t// them back to the home page.\n\t// if ok := u.session.HasSession(r); ok {\n\t// http.Redirect(w, r, \"/\", http.StatusFound)\n\t// return\n\t// }\n\tu.template.Render(w, \"register\", nil)\n}", "func (r *Router) register() {\n\tpages := []Page{\n\t\tr.projectListPage,\n\t\tr.projectBuildListPage,\n\t\tr.buildJobListPage,\n\t\tr.jobLogPage,\n\t}\n\n\t// Register all the pages on the ui.\n\tfor _, page := range pages {\n\t\tpage.Register(r.pages)\n\t}\n}", "func RegistrationPage(w http.ResponseWriter, r *http.Request) {\n var flag bool\n var details helpers.User\n var targettmpl string\n w.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n userDetails := getSession(r)\n \n if (len(userDetails.FirstName) <= 0 && userDetails.Role == \"Admin\" ) {\n w.Write([]byte(\"<script>alert('Unauthorized Access!!,please login');window.location = '/login'</script>\"))\n }\n\n if (userDetails.Role == \"Admin\" || userDetails.Role == \"admin\"){ \n targettmpl = \"templates/registrationPage.html\" \n }else{\n targettmpl = \"templates/registrationUser.html\" \n }\n\n t := template.Must(template.ParseFiles(targettmpl))\n\n if r.Method != http.MethodPost {\n t.Execute(w, nil)\n return\n }\n \n\n details = helpers.User{\n UserId: r.FormValue(\"userid\"),\n FirstName: r.FormValue(\"fname\"),\n LastName: r.FormValue(\"lname\"),\n Email: r.FormValue(\"email\"),\n Password: r.FormValue(\"pwd\"),\n Role: r.FormValue(\"role\"),\n ManagerID : \"unassigned\",\n }\n \n if details.Role ==\"\" {\n details.Role = \"User\" \n }\n \n msg := dbquery.CheckDuplicateEmail(details.Email)\n\n details.Password, _ = HashPassword(details.Password)\n\n if msg == \"\"{\n fmt.Println(\" **** Inserting a record ****\")\n flag = dbquery.RegisterUser(details)\n } \n\n t.Execute(w, Allinfo{EmailId: details.Email, IssueMsg: msg, SuccessFlag: flag} )\n}", "func SignupPage(c *gin.Context) {\n\tc.HTML(http.StatusOK, \"Signup.html\", gin.H{\n\t\t\"registerURL\": \"http://127.0.0.1:8080/user/register\",\n\t})\n}", "func (s *BaseasmZ80Listener) EnterRegister_(ctx *Register_Context) {}", "func (c *ProfileController) GetRegister() mvc.Result {\n\tif c.isProfileLoggedIn() {\n\t\tc.logout()\n\t}\n\n\treturn mvc.View{\n\t\tName: \"profile/register.html\",\n\t\tData: iris.Map{\"Title\": \"Profile Registration\"},\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LoadHomePage Render home page
func LoadHomePage(w http.ResponseWriter, r *http.Request) { url := fmt.Sprintf("%s/publications", config.APIURL) response, err := requests.RequestsWithAuthentication(r, http.MethodGet, url, nil) if err != nil { responses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: err.Error()}) return } defer response.Body.Close() if response.StatusCode >= 400 { responses.TreatStatusCode(w, response) return } var publications []models.Publication if err := json.NewDecoder(response.Body).Decode(&publications); err != nil { responses.JSON(w, http.StatusUnprocessableEntity, responses.ErrorAPI{Err: err.Error()}) return } cookie, _ := cookies.Read(r) userID, _ := strconv.ParseUint(cookie["id"], 10, 64) utils.RunTemplate(w, "home.html", struct { Publications []models.Publication UserID uint64 }{ Publications: publications, UserID: userID, }) }
[ "func (hc Home) Home(w http.ResponseWriter, r *http.Request) {\n\tdata := viewModels.NewHome()\n\thc.TemplateManager.Render(\"home\", w, data)\n}", "func Home(w http.ResponseWriter, req *http.Request) {\n\tgetContextAndRender(\"home\", w, req)\n}", "func showHomePage(c *gin.Context) {\n\tc.JSON(200, gin.H{\n\t\t\"Server\": \"Cool you are ready to start website in goLang\",\n\t})\n}", "func HomePage(w http.ResponseWriter, r *http.Request) {\n\tif r.URL.Path != \"/\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\tfmt.Fprint(w, constants.HOMEPAGE)\n}", "func GetHomepage(c *gin.Context) {\n\tRender(c, gin.H{\"title\": \"login\"}, \"homepage.html\")\n}", "func LoadHome(w http.ResponseWriter, req *http.Request) {\n\tw.Write([]byte(\"Try /hello/:name\"))\n}", "func PageHome() *Renderer {\n\treturn &Renderer{\n\t\tfilenames: []string{\n\t\t\t\"templates/layout.html\",\n\t\t\t\"templates/logo.html\",\n\t\t\t\"templates/pages/home.html\",\n\t\t},\n\t\tcontext: nil,\n\t}\n}", "func (server *Server) ShowHome(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Show Home\")\n\tdata := IndexPageData{\n\t\tTitle: \"Hunt\",\n\t\tSubTitle: \"Welcome to the new Hunt App (made with Go!)\",\n\t}\n\ttempl.ExecuteTemplate(w, \"main\", data)\n}", "func (hController HomeController) GetHomePage(w http.ResponseWriter, _ *http.Request) {\n\n\tfmt.Fprintf(w, \"Welcome to the HomePage!\")\n}", "func displayHome(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"displayHome: url %s\", r.URL.Path)\n\n\t// Tell health check probes that we are alive\n\tif !httphandling.AcceptHTML(r) {\n\t\tfmt.Fprintln(w, \"OK\")\n\t\treturn\n\t}\n\n\ttitle := b.webConfig.GetVarWithDefault(\"Title\", defTitle)\n\tcontent := htmlContent{\n\t\tTitle: title,\n\t}\n\tif config.PasswordProtected() {\n\t\tctx := context.Background()\n\t\tif b.authenticator == nil {\n\t\t\tvar err error\n\t\t\tb.authenticator, err = initAuth(ctx)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(\"displayHome authenticator could not be initialized\")\n\t\t\t\thttp.Error(w, \"Server error\", http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tsessionInfo := identity.InvalidSession()\n\t\tcookie, err := r.Cookie(\"session\")\n\t\tif err == nil {\n\t\t\tsessionInfo = b.authenticator.CheckSession(ctx, cookie.Value)\n\t\t} else {\n\t\t\tlog.Printf(\"displayHome error getting cookie: %v\", err)\n\t\t\tb.pageDisplayer.DisplayPage(w, \"login_form.html\", content)\n\t\t\treturn\n\t\t}\n\t\tif !sessionInfo.Valid {\n\t\t\tb.pageDisplayer.DisplayPage(w, \"login_form.html\", content)\n\t\t\treturn\n\t\t} else {\n\t\t\tlog.Printf(\"displayHome: using index_auth_template.html for url %s\", r.URL.Path)\n\t\t\tb.pageDisplayer.DisplayPage(w, \"index_auth_template.html\", content)\n\t\t\treturn\n\t\t}\n\t}\n\tlog.Printf(\"displayHome: template index.html for url %s\", r.URL.Path)\n\tb.pageDisplayer.DisplayPage(w, \"index.html\", content)\n}", "func HomeGET(w http.ResponseWriter, r *http.Request) handler.HTML {\n\t// Create an HTML response.\n\tresp := app.HTMLResponse(w, r)\n\t// Prepare home page data.\n\tpageData := &HomePageData{Time: time.Now().String()}\n\t// Generate page HTML.\n\tpageHTML := homeView.MustExecuteToString(resp.Lang(), pageData)\n\t// Create main page data, which is a core template shared by all your website pages.\n\td := app.MainPageData(resp.LocalizedDictionary().Home, pageHTML)\n\t// Complete the response.\n\treturn resp.MustComplete(d)\n}", "func HomePage(w http.ResponseWriter, req *http.Request) {\n\tswitch req.Method {\n\tcase \"GET\":\n\t\t// Serve the resource.\n\t\tfmt.Fprintf(w, \"Hello, %q\", html.EscapeString(req.URL.Path))\n\tdefault:\n\t\tfmt.Fprintf(w, \"Error: Invalid request\")\n\t}\n\n}", "func homePage(w http.ResponseWriter, r *http.Request) {\n\tif r.URL.Path != \"/\" {\n\t\thttp.Error(w, \"404 not found\", http.StatusNotFound)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, \"This is the Homepage\")\n\n}", "func HomePage(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Welcome to my ShortyResty :)\")\n}", "func HomeHandler(w http.ResponseWriter, r *http.Request) {\n\tcommon.ExecuteTemplate(w, r, \"index.html\")\n}", "func (h home) handleHome(w http.ResponseWriter, r *http.Request) {\n\tvm := viewmodel.NewBase()\n\th.homeTemplate.Execute(w, vm)\n}", "func (m *Repository) ServeHome(w http.ResponseWriter, r *http.Request) {\n\trender.RenderTemplate(w, \"home\")\n}", "func ServeHomepage(w http.ResponseWriter, _ *http.Request) {\n\thomepage.Data.Mu.Lock()\n\n\terr := webTemplate.ExecuteTemplate(w, \"home\", homepage.Data)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\thomepage.Data.Mu.Unlock()\n}", "func HomeHandler(p *DynamicHandlerFuncParams, w http.ResponseWriter, r *http.Request) {\n\terr := p.Template.Execute(w, HomePageParams{PageParams{\"home\", p.Config.Title}, p.Carousel})\n\tif err != nil {\n\t\tlog.Printf(\"error while serving template home: %s\", err)\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LoadEditPage Load edit page
func LoadEditPage(w http.ResponseWriter, r *http.Request) { parameters := mux.Vars(r) publicationID, err := strconv.ParseUint(parameters["publicationId"], 10, 64) if err != nil { responses.JSON(w, http.StatusBadRequest, responses.ErrorAPI{Err: err.Error()}) return } url := fmt.Sprintf("%s/publications/%d", config.APIURL, publicationID) response, err := requests.RequestsWithAuthentication(r, http.MethodGet, url, nil) if err != nil { responses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: err.Error()}) return } defer response.Body.Close() if response.StatusCode >= 400 { responses.TreatStatusCode(w, response) return } var publication models.Publication if err = json.NewDecoder(response.Body).Decode(&publication); err != nil { responses.JSON(w, http.StatusUnprocessableEntity, responses.ErrorAPI{Err: err.Error()}) return } utils.RunTemplate(w, "edit-publication.html", publication) }
[ "func editHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle := r.URL.Path[len(\"/edit/\"):]\n\tp,_ := find_page(title)\n\tif p == nil{\n\t\tp = &Page{Title:title, Body:\"\"}\n\t\tpage_lst.Pages = append(page_lst.Pages, p)\n\t}\n\trenderTemplate(w, \"edit\", p)\n}", "func handlerEdit(w http.ResponseWriter, r *http.Request, title string) {\r\n\tpage, err := loadPage(title)\r\n\tif err != nil {\r\n\t\tpage = &Page{Title: title}\r\n\t}\r\n\t//to use a html file we have to use the template.ParseFile\r\n\tfetchHTML(w, \"edit\", page)\r\n}", "func editHandler(w http.ResponseWriter, r *http.Request) {\n\n\tvar page_lst Pages\n\treceive(&page_lst)\n\ttitle := r.URL.Path[len(\"/edit/\"):]\n\tp,_ := find_page(title,page_lst)\n\tif p == nil{\n\t\tp = &Page{Title:title, Body:\"\"}\n\t\tpage_lst.Pages = append(page_lst.Pages, p)\n\t\tsend(&page_lst)\n\t}\n\tpath,_ := os.Getwd()\n\tt,_ := template.ParseFiles(path+\"/edit.html\")\n\tt.Execute(w,p)\n}", "func editHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle, err := getTitle(w, r)\n\tif err != nil {\n\t\treturn\n\t}\n\tp, err := loadPage(title)\n\tif err != nil {\n\t\tp = &Page{Title: title}\n\t}\n\trenderTemplate(w, \"edit\", p) // Passes: ResponseWriter, templatename, template page fill\n\t//t.Execute(w, p) Executes template, writes HTML to http.ResponseWriter (w)\n}", "func (h *Handler) EditPage(c echo.Context) error {\n\tm := echo.Map{}\n\tif err := c.Bind(&m); err != nil {\n\t\treturn err\n\t}\n\tnr, nt, route := m[\"newRoute\"].(string), m[\"newTitle\"].(string), m[\"route\"].(string)\n\n\tuserDataMap := utils.GetUserDataFromContext(&c)\n\temail := (*userDataMap)[\"email\"].(string)\n\n\tpage, err := h.pageStore.EditPage(email, route, nr, nt)\n\tif err != nil {\n\t\tutils.Logger.Error(err)\n\t\treturn c.JSON(http.StatusInternalServerError, createRes(false, nil, nil, http.StatusText(http.StatusInternalServerError)))\n\t}\n\treturn c.JSON(http.StatusOK, createRes(true, page, nil, \"\"))\n}", "func EditPage(c *fiber.Ctx) error {\n\t// Firstly checks if given table exists\n\tname := c.Params(\"name\")\n\tT := databasepack.FindTable(name)\n\tif T < 0 {\n\t\treturn c.Send([]byte(\"No table with such name!\"))\n\t}\n\t// Next checks if the user can actually perform this action\n\tif !databasepack.Allowed(querypack.INFO.Roles, \"editor_\"+name) {\n\t\treturn c.Send([]byte(\"Permission declined!\"))\n\t}\n\t// Lastly posts given post\n\tdatabasepack.CreatePosts(c.Body(), name, T)\n\treturn c.Send([]byte(\"Successfully edited!\"))\n}", "func EditPage(ctx *sweetygo.Context) error {\n\tctx.Set(\"title\", \"Edit\")\n\tctx.Set(\"editor\", true)\n\ttitle := ctx.Param(\"title\")\n\ttitle = strings.Replace(title, \"-\", \" \", -1)\n\tpost, err := model.GetPostByTitle(title)\n\tif err != nil {\n\t\treturn err\n\t}\n\tctx.Set(\"post\", post)\n\treturn ctx.Render(200, \"posts/edit\")\n}", "func PagesEditGet(c *gin.Context) {\n\tid := c.Param(\"id\")\n\n\tpage := models.Page{}\n\tmodels.DB.First(&page, id)\n\n\tif page.ID == 0 {\n\t\tc.HTML(404, \"errors/404\", nil)\n\t\treturn\n\t}\n\n\tsession := sessions.Default(c)\n\tflashes := session.Flashes()\n\tsession.Save()\n\n\tH := DefaultH(c)\n\tH[\"Title\"] = page.Title\n\tH[\"Page\"] = &page\n\tH[\"Flash\"] = flashes\n\tc.HTML(200, \"admin/pages/edit\", H)\n}", "func (controller *UserController) GetEditPage(ctx *fasthttp.RequestCtx) {\n\tcontroller.getProfile(ctx, true)\n}", "func Edit(w http.ResponseWriter, r *http.Request) {\n\n\t//Obtendo o id do produto\n\tidDoProduto := r.URL.Query().Get(\"id\")\n\n\t//Obtendo os dados do produto\n\tproduto := models.EditarProduto(idDoProduto)\n\n\t//Executndo aplicacao web\n\ttemplateDaAplicacaoWeb.ExecuteTemplate(w, \"Edit\", &produto)\n}", "func LoadUserPasswordEditPage(w http.ResponseWriter, r *http.Request) {\n\tutils.RunTemplate(w, \"update-password.html\", nil)\n}", "func LoadUserEditPage(w http.ResponseWriter, r *http.Request) {\n\tcookie, _ := cookies.Read(r)\n\tuserID, _ := strconv.ParseUint(cookie[\"id\"], 10, 64)\n\n\tchannel := make(chan models.User)\n\n\tgo models.GetUserData(channel, userID, r)\n\n\tuser := <-channel\n\tif user.ID == 0 {\n\t\tresponses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: \"Erro ao buscar o usuário\"})\n\t\treturn\n\t}\n\n\tutils.RunTemplate(w, \"edit-profile.html\", user)\n}", "func Edit(w http.ResponseWriter, r *http.Request) {\n\tid := r.URL.Query().Get(\"id\")\n\tproduto := repository.FindProduto(id)\n\ttemplates.ExecuteTemplate(w, \"Edit\", produto)\n}", "func AdminEdit(w http.ResponseWriter, data interface{}) {\n\trender(tpAdminEdit, w, data)\n}", "func (a *API) edit(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tid := ps.ByName(\"id\")\n\n\tj, err := a.jobstore.Get(id)\n\tif err != nil {\n\t\tsendErrorMessage(w)\n\t}\n\n\trenderPage(w, \"jobForm.html\", j)\n}", "func NewEditPage(p *BoardPage, listIdx, taskIdx int) *tview.Form {\n\ttask, err := p.data.GetTask(listIdx, taskIdx)\n\tif err != nil {\n\t\tapp.Stop()\n\t\tlog.Fatal(err)\n\t}\n\tform := tview.NewForm().\n\t\tAddInputField(\"Task\", task[0], 20, nil, nil).\n\t\tAddInputField(\"Task Description\", task[1], 20, nil, nil)\n\tform = form.AddButton(\"Save\", func() {\n\t\ttaskName := form.GetFormItemByLabel(\"Task\").(*tview.InputField).GetText()\n\t\ttaskName = strings.TrimSpace(taskName)\n\t\tif len(taskName) <= 0 {\n\t\t\temptyTitleNameModal := EmptyTitleNameModal()\n\t\t\tpages.AddAndSwitchToPage(\"emptyTitle\", emptyTitleNameModal, true)\n\t\t\treturn\n\t\t}\n\t\ttaskDesc := form.GetFormItemByLabel(\"Task Description\").(*tview.InputField).GetText()\n\t\ttaskDesc = strings.TrimSpace(taskDesc)\n\t\tactiveListIdx := p.activeListIdx\n\t\terr := p.data.EditTask(activeListIdx, p.activeTaskIdxs[activeListIdx], taskName, taskDesc)\n\t\tif err != nil {\n\t\t\tapp.Stop()\n\t\t\tpanic(err)\n\t\t}\n\t\tp.data.Save(p.fileName)\n\t\tp.redraw(activeListIdx)\n\t\tpages.SwitchToPage(\"board\")\n\t\tapp.SetFocus(p.lists[p.activeListIdx])\n\t}).\n\t\tAddButton(\"Cancel\", func() {\n\t\t\tpages.RemovePage(\"edit\")\n\t\t\tpages.SwitchToPage(\"board\")\n\t\t\tapp.SetFocus(p.lists[p.activeListIdx])\n\t\t})\n\tform.SetBorder(true).SetTitle(\"Edit Task\").SetTitleAlign(tview.AlignCenter)\n\treturn form\n}", "func InitEditPageHandler(db yoradb.PostRepository, templatesPath string) *EditPageHandler {\n\n\tpathes := make([]string, 3)\n\tpathes[0] = filepath.Join(templatesPath, \"layout.gohtml\")\n\tpathes[1] = filepath.Join(templatesPath, \"edit.gohtml\")\n\tpathes[2] = filepath.Join(templatesPath, \"empty_og.gohtml\")\n\n\ttempl, err := yotemplate.InitTemplate(pathes...)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tlog.Println(\"Edit page template is initialized.\")\n\n\treturn &EditPageHandler{template: templ, db: db}\n}", "func (ac *ArticleController) Edit(w http.ResponseWriter, r *http.Request) {\n\t// u := userContext(r.Context())\n\t// debug: dummy user\n\tctx := r.Context()\n\tu := models.UserContext(ctx)\n\tif u.IsAdmin {\n\t\tp := httptreemux.ContextParams(ctx)\n\n\t\tidParam, _ := strconv.Atoi(p[\"id\"])\n\t\tif idParam <= 0 { // conversion failed or bad input\n\t\t\tsendJSON(\"Input not valid\", http.StatusBadRequest, w)\n\t\t\treturn\n\t\t}\n\n\t\tid := uint(idParam)\n\t\ttitle := r.FormValue(\"title\")\n\t\ttext := r.FormValue(\"text\")\n\n\t\ta := models.ArticleUpdate(id, title, text)\n\t\tif a.ID == 0 { // Something went wrong\n\t\t\tsendJSON(\"Error: impossible to edit article\", http.StatusInternalServerError, w)\n\t\t\treturn\n\t\t}\n\n\t\turl := r.URL.EscapedPath()\n\t\tcache.RemoveURL(url)\n\n\t\tw.Header().Set(\"Content-Location\", url)\n\t\tsendJSON(a, http.StatusOK, w)\n\t} else {\n\t\tsendJSON(\"You are not admin\", http.StatusForbidden, w)\n\t}\n}", "func (h *MovieHandler) edit(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/edit.html\", movie)\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LoadUsersPage Load users page
func LoadUsersPage(w http.ResponseWriter, r *http.Request) { nameOrNick := strings.ToLower(r.URL.Query().Get("user")) url := fmt.Sprintf("%s/users?usuario=%s", config.APIURL, nameOrNick) response, err := requests.RequestsWithAuthentication(r, http.MethodGet, url, nil) if err != nil { responses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: err.Error()}) return } defer response.Body.Close() if response.StatusCode >= 400 { responses.TreatStatusCode(w, response) return } var users []models.User if err := json.NewDecoder(response.Body).Decode(&users); err != nil { responses.JSON(w, http.StatusUnprocessableEntity, responses.ErrorAPI{Err: err.Error()}) return } utils.RunTemplate(w, "users.html", users) }
[ "func LoadUserPage(w http.ResponseWriter, r *http.Request) {\n\tparameters := mux.Vars(r)\n\tuserID, err := strconv.ParseUint(parameters[\"userId\"], 10, 64)\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusBadRequest, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\n\tcookie, _ := cookies.Read(r)\n\tuserIDLogged, _ := strconv.ParseUint(cookie[\"id\"], 10, 64)\n\n\tuser, err := models.SearchCompleteUser(userID, r)\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\n\tif userID == userIDLogged {\n\t\thttp.Redirect(w, r, \"/profile\", 302)\n\t\treturn\n\t}\n\n\tutils.RunTemplate(w, \"user.html\", struct {\n\t\tUser models.User\n\t\tUserLoggedID uint64\n\t}{\n\t\tUser: user,\n\t\tUserLoggedID: userIDLogged,\n\t})\n}", "func LoadUserEditPage(w http.ResponseWriter, r *http.Request) {\n\tcookie, _ := cookies.Read(r)\n\tuserID, _ := strconv.ParseUint(cookie[\"id\"], 10, 64)\n\n\tchannel := make(chan models.User)\n\n\tgo models.GetUserData(channel, userID, r)\n\n\tuser := <-channel\n\tif user.ID == 0 {\n\t\tresponses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: \"Erro ao buscar o usuário\"})\n\t\treturn\n\t}\n\n\tutils.RunTemplate(w, \"edit-profile.html\", user)\n}", "func GetUsersPage(resp http.ResponseWriter, req *http.Request) {\n\tpage := request.MapPage(mux.Vars(req))\n\tstart := page.GetPage() * page.GetSize()\n\tend := start + page.GetSize()\n\n\tif end > len(users) {\n\t\tend = len(users)\n\t}\n\n\tvar content []interface{}\n\tif page.GetSize() > 0 && start < len(users) {\n\t\tcontent = append(content, users[start:end])\n\t}\n\n\tresult := response.BuildPage(&content, page, int64(len(users)))\n\n\tresponse.WriteJSON(http.StatusOK, result, resp)\n}", "func (s *peerRESTServer) LoadUsersHandler(w http.ResponseWriter, r *http.Request) {\n\tif !s.IsValid(w, r) {\n\t\ts.writeErrorResponse(w, errors.New(\"Invalid request\"))\n\t\treturn\n\t}\n\n\terr := globalIAMSys.Load()\n\tif err != nil {\n\t\ts.writeErrorResponse(w, err)\n\t\treturn\n\t}\n\n\tw.(http.Flusher).Flush()\n}", "func (h *handler) Users(w http.ResponseWriter, r *http.Request) {\n\tapiReq, err := http.NewRequest(\"GET\", h.serverAddress+\"/users\", nil)\n\tif err != nil {\n\t\tserverError(w, err)\n\t\treturn\n\t}\n\n\tclient := &http.Client{}\n\tres, err := client.Do(apiReq)\n\tif err != nil {\n\t\tserverError(w, err)\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\n\tvar uis []socialnet.UserItem\n\terr = json.NewDecoder(res.Body).Decode(&uis)\n\tif err != nil {\n\t\tserverError(w, err)\n\t\treturn\n\t}\n\n\terr = h.template.ExecuteTemplate(w, \"users.html\", uis)\n\tif err != nil {\n\t\tserverError(w, fmt.Errorf(\"failed to execute template users.html: %s\", err))\n\t\treturn\n\t}\n}", "func loadUsersInfo() {\r\n\r\n\t//call user data from db via REST API\r\n\tarr := getAllUsersFromDB()\r\n\r\n\tfor _, el := range arr {\r\n\t\tmapUsers[el.Username] = el\r\n\t\tcommon.Debug(\"user added\", mapUsers[el.Username])\r\n\t}\r\n}", "func userPage(w http.ResponseWriter, r *http.Request){\n\tisLogged, name := CheckLoginStatus(w,r)\n\n\tif isLogged {\n\t\terr := templ.ExecuteTemplate(w, \"userHome\", name)\n\t\tif err != nil {\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t} else {\n\t\thttp.Redirect(w,r,\"/unauthorized\",http.StatusSeeOther)\n\t}\n}", "func ShowUsers(baseURL string) int {\n\tif utils.LoginCheck() {\n\t\t// HTTP\n\t\tt := utils.GetToken()\n\t\tclient := &http.Client{}\n\t\treq, _ := http.NewRequest(\"GET\", baseURL+\"/v1/users?token=\"+t, nil)\n\n\t\tresp, err := client.Do(req)\n\t\tif err != nil {\n\t\t\tutils.PrintError(err.Error())\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\tutils.PrintError(err.Error())\n\t\t}\n\n\t\tr := &UserList{}\n\t\terr = json.Unmarshal([]byte(string(body)), &r)\n\t\tif err != nil {\n\t\t\tutils.PrintError(err.Error())\n\t\t}\n\n\t\tif resp.StatusCode == 200 {\n\t\t\tfor i := 0; i < len(r.Data); i++ {\n\t\t\t\tprintUser(r.Data[i])\n\t\t\t}\n\t\t\treturn 0\n\t\t}\n\n\t\tif resp.StatusCode == 401 {\n\t\t\tfmt.Println(r.Message)\n\t\t\treturn 1\n\t\t}\n\n\t\treturn 1\n\t} else {\n\t\tfmt.Println(\"Please Login First\")\n\t\treturn 1\n\t}\n}", "func LoadUserPasswordEditPage(w http.ResponseWriter, r *http.Request) {\n\tutils.RunTemplate(w, \"update-password.html\", nil)\n}", "func showUserPage(w http.ResponseWriter, user modele.Invite) {\n\t// Getting the user's voucher if exist\n\t// Connect to database first\n\tdb, err := tools.Connect()\n\tif err != nil {\n\t\terror502(w, err) // Show error to user and log it\n\t\treturn\n\t}\n\tdefer tools.Disconnect(db)\n\n\t// Getting all the vouchers\n\tvar vouchers map[int64]modele.Voucher\n\tvouchers = make(map[int64]modele.Voucher)\n\terr = tools.GetVouchers(db, vouchers)\n\n\t// Select the user's voucher\n\tuser.Voucher = vouchers[user.Id].Code\n\n\tt, err := template.ParseFiles(\"html/userpage.hbs\") // Load template\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tt.Execute(w, user) // Build and send page to user\n}", "func LoadDemoUsers(s storage.Store) {\n\ts.AddItem(NewUser(s.NextID(), \"[email protected]\", \"Fake Mike\", \"NaN\"))\n\ts.AddItem(NewUser(s.NextID(), \"[email protected]\", \"Test Mike\", \"123-456-7890\"))\n\ts.AddItem(NewUser(s.NextID(), \"[email protected]\", \"Test User\", \"555-555-5555\"))\n}", "func LoadPage(c *fiber.Ctx, login string, roles []int) error {\n\tquerypack.INFO.Roles = roles\n\tquerypack.INFO.Login = login\n\tquerypack.INFO.LoggedIn = true\n\tc.Method(\"GET\")\n\tc.Path(querypack.INFO.URL)\n\tquerypack.AddCookie(c)\n\treturn c.Next()\n}", "func ViewUsers(w http.ResponseWriter, r *http.Request) error {\n if r.Method == \"GET\" {\n myUid, err0 := GetMyUserId(r)\n if err0 != nil {\n return err0\n }\n ctx1, _ := context.WithTimeout(context.Background(), constant.ContextTimeoutDuration)\n response, err := BackendClientIns.FindAllUsers(ctx1, &FindAllUsersRequest{})\n if err != nil {\n return err\n }\n allUsers := response.Users\n newUserList := make([]user, 0)\n for _, value := range allUsers {\n if value.UserId == myUid { // Exclude myself\n continue\n }\n ctx, _ := context.WithTimeout(context.Background(), constant.ContextTimeoutDuration)\n responseFromWhetherFollowing, _ := BackendClientIns.UserCheckWhetherFollowing(ctx,\n &UserCheckWhetherFollowingRequest{\n SourceUserId: myUid,\n TargetUserId: value.UserId,\n })\n newUserList = append(newUserList, user{Name: value.UserName,\n Followed: responseFromWhetherFollowing.Ok,\n Id: strconv.Itoa(int(value.UserId))})\n }\n view := viewUserView{\n UserList: newUserList,\n }\n log.Println(view.UserList)\n t, _ := template.ParseFiles(constant.RelativePathForTemplate + \"users.html\")\n w.Header().Set(\"Content-Type\", \"text/html\")\n t.Execute(w, view)\n }\n return nil\n}", "func UsersGET(w http.ResponseWriter, r *http.Request) {\n\tqParams := r.URL.Query()\n\n\tvar (\n\t\tpageStr = qParams.Get(\"page\")\n\t\tperPageStr = qParams.Get(\"per_page\")\n\t\tsort = qParams.Get(\"sort\")\n\t\torder = qParams.Get(\"order\")\n\t)\n\n\tpage, err := strconv.ParseUint(pageStr, 10, 64)\n\tif err != nil {\n\t\tpage = 1\n\t}\n\n\tperPage, err := strconv.ParseUint(perPageStr, 10, 64)\n\tif err != nil {\n\t\tperPage = uint64(constants.UsersQueryMaxPageSize)\n\t}\n\n\tpc := helper.PaginationConfig{\n\t\tPage: page,\n\t\tPerPageCount: perPage,\n\t}\n\n\tsc := helper.SortingConfig{\n\t\tSortBy: sort,\n\t\tOrder: order,\n\t}\n\n\tuserRows, err := user.Search(nil, &pc, &sc)\n\tif err != nil {\n\t\tlog.Error(\"Error %s\", err)\n\t\terrorCtrl.Error500(w, r)\n\t\treturn\n\t}\n\n\tusers := make([]*types.User, len(userRows))\n\n\tfor i, ur := range userRows {\n\t\tusers[i] = &types.User{\n\t\t\tUsername: ur.Username,\n\t\t\tID: ur.ID,\n\t\t\tName: ur.Name,\n\t\t\tEmail: misc.TerOpt(ur.IsPublicEmail, ur.Email, \"\").(string),\n\t\t\tJoinedAt: ur.JoinedAt,\n\t\t\tAvatarURL: ur.Avatar,\n\t\t\tBlog: ur.URL,\n\t\t\tOrganization: ur.Organization,\n\t\t\tLocation: ur.Location,\n\t\t\tPackagesCount: ur.PackagesCount,\n\t\t\tSocial: types.UserSocialAccounts{\n\t\t\t\tGithub: ur.Github,\n\t\t\t\tTwitter: ur.Twitter,\n\t\t\t\tStackOverflow: ur.StackOverflow,\n\t\t\t\tLinkedIn: ur.LinkedIn,\n\t\t\t},\n\t\t}\n\t}\n\n\thelper.WriteResponseValueOK(w, r, users)\n}", "func LoadUserLoggedProfile(w http.ResponseWriter, r *http.Request) {\n\tcookie, _ := cookies.Read(r)\n\tuserID, _ := strconv.ParseUint(cookie[\"id\"], 10, 64)\n\n\tuser, err := models.SearchCompleteUser(userID, r)\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\n\tutils.RunTemplate(w, \"profile.html\", user)\n\n}", "func UsersShow(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tid := params[\"id\"]\n\tuserID, _ := strconv.Atoi(id)\n\n\tuser, err := models.UserFindByID(userID)\n\tif err != nil {\n\t\trespondWithError(w, http.StatusNotFound, err.Error())\n\n\t\treturn\n\t}\n\n\tresponse := Response{\n\t\t\"user\": user,\n\t}\n\trespondWithJSON(w, http.StatusOK, response)\n}", "func loadPage(pn string, r *http.Request) (*Page, error) {\n\tdata := &Page{\n\t\tPageName: pn,\n\t}\n\n\t/* Get user name for filling in template too */\n\tsesh, _ := store.Get(r, \"loginSession\")\n\tuname, ok := sesh.Values[\"username\"].(string)\n\tif !ok {\n\t\treturn nil, &ClientSafeError{Msg: \"invalid username\"}\n\t}\n\tdata.Username = uname\n\t/* get user's role */\n\trole, err := getRoleNum(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tswitch role {\n\tcase FACILITATOR:\n\t\tdata.Role = \"Facilitator\"\n\t\tdata.Messages, err = getNotifications(data.Username)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tcase TEACHER:\n\t\tdata.Role = \"Teacher\"\n\tcase ADMIN:\n\t\tdata.Role = \"Admin\"\n\tdefault:\n\t\treturn nil, &ClientSafeError{Msg: \"insufficient access rights\"}\n\t}\n\n\treturn data, nil\n}", "func ShowUsers(c *gin.Context) {\n\tvar Users []User\n\tdb.Find(&Users)\n\tc.Header(\"access-control-allow-origin\", \"*\")\n\tc.JSON(200, Users)\n\treturn\n}", "func UsersGet(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tlog.Println(\"starting retrieval\")\n\tstart := 0\n\tlimit := 10\n\n\tnext := start + limit\n\n\tw.Header().Set(\"Pragma\", \"no-cache\")\n\tw.Header().Set(\"Link\", \"<http://localhost:8080/api/users?start=\"+string(next)+\"; rel=\\\"next\\\"\")\n\n\trows, _ := database.Query(\"SELECT * FROM users LIMIT 10\")\n\n\tusers := Users{}\n\n\tfor rows.Next() {\n\t\tuser := User{}\n\t\trows.Scan(&user.ID, &user.Username, &user.First, &user.Last, &user.Email)\n\t\tusers.Users = append(users.Users, user)\n\t}\n\n\toutput, err := json.Marshal(users)\n\tif err != nil {\n\t\tfmt.Fprintln(w, \"Something went wrong while processing your request: \", err)\n\t}\n\n\tfmt.Fprintln(w, string(output))\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LoadUserPage Load user profile
func LoadUserPage(w http.ResponseWriter, r *http.Request) { parameters := mux.Vars(r) userID, err := strconv.ParseUint(parameters["userId"], 10, 64) if err != nil { responses.JSON(w, http.StatusBadRequest, responses.ErrorAPI{Err: err.Error()}) return } cookie, _ := cookies.Read(r) userIDLogged, _ := strconv.ParseUint(cookie["id"], 10, 64) user, err := models.SearchCompleteUser(userID, r) if err != nil { responses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: err.Error()}) return } if userID == userIDLogged { http.Redirect(w, r, "/profile", 302) return } utils.RunTemplate(w, "user.html", struct { User models.User UserLoggedID uint64 }{ User: user, UserLoggedID: userIDLogged, }) }
[ "func LoadUserEditPage(w http.ResponseWriter, r *http.Request) {\n\tcookie, _ := cookies.Read(r)\n\tuserID, _ := strconv.ParseUint(cookie[\"id\"], 10, 64)\n\n\tchannel := make(chan models.User)\n\n\tgo models.GetUserData(channel, userID, r)\n\n\tuser := <-channel\n\tif user.ID == 0 {\n\t\tresponses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: \"Erro ao buscar o usuário\"})\n\t\treturn\n\t}\n\n\tutils.RunTemplate(w, \"edit-profile.html\", user)\n}", "func LoadUserLoggedProfile(w http.ResponseWriter, r *http.Request) {\n\tcookie, _ := cookies.Read(r)\n\tuserID, _ := strconv.ParseUint(cookie[\"id\"], 10, 64)\n\n\tuser, err := models.SearchCompleteUser(userID, r)\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\n\tutils.RunTemplate(w, \"profile.html\", user)\n\n}", "func LoadUsersPage(w http.ResponseWriter, r *http.Request) {\n\tnameOrNick := strings.ToLower(r.URL.Query().Get(\"user\"))\n\n\turl := fmt.Sprintf(\"%s/users?usuario=%s\", config.APIURL, nameOrNick)\n\n\tresponse, err := requests.RequestsWithAuthentication(r, http.MethodGet, url, nil)\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\tdefer response.Body.Close()\n\n\tif response.StatusCode >= 400 {\n\t\tresponses.TreatStatusCode(w, response)\n\t\treturn\n\t}\n\n\tvar users []models.User\n\tif err := json.NewDecoder(response.Body).Decode(&users); err != nil {\n\t\tresponses.JSON(w, http.StatusUnprocessableEntity, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\n\tutils.RunTemplate(w, \"users.html\", users)\n}", "func profile(w http.ResponseWriter, req *http.Request) {\n\tsess, _ := session(w, req)\n\tuser, err := sess.User()\n\tif err != nil {\n\t\tlogger.SetPrefix(\"ERROR \")\n\t\tlogger.Println(err, \"Cannot fetch user\")\n\t}\n\tdata := struct {\n\t\tdata.User\n\t}{user}\n\tgenerateHTML(w, data, \"layout\", \"private.navbar\", \"profile\")\n}", "func (userController *UserController) GetProfilePage(w http.ResponseWriter, r *http.Request) {\n\t// Context for data in view template\n\ttype Context struct {\n\t\tUsers []Pengguna\n\t\tValidationMessage string\n\t}\n\tvar userList []Pengguna\n\n\t// Load profile view\n\tprofilePage := userController.Templates.Lookup(\"profile.html\")\n\n\t// Get all users from database\n\tusers := userController.UserRepository.GetUsers()\n\n\t// Assign user role\n\tfor _, user := range users {\n\t\tuser.Grup = userController.GroupRepository.GetGroupByUserID(user.ID)\n\t\tuserList = append(userList, user)\n\t}\n\n\tcontext := Context{\n\t\tUsers: userList,\n\t\tValidationMessage: userController.SessionHelper.GetValidationMessage(r)}\n\n\tprofilePage.Execute(w, context)\n}", "func LoadUserPasswordEditPage(w http.ResponseWriter, r *http.Request) {\n\tutils.RunTemplate(w, \"update-password.html\", nil)\n}", "func (t *OpetCode) loadUser(APIstub shim.ChaincodeStubInterface, userKey string) (User, error) {\n user_json, _ := APIstub.GetState(userKey)\n var user User\n\n if user_json == nil {\n return user, errors.New(\"There is no user exist\")\n } \n _ = json.Unmarshal([]byte(user_json), &user) \n return user, nil\n}", "func (a *Ctl) Profile(res http.ResponseWriter, req *http.Request) {\n\ttype pageData struct {\n\t\tUser User\n\t}\n\td := pageData{\n\t\tUser: a.getUser(res, req),\n\t}\n\tif !a.alreadyLoggedIn(req) {\n\t\ta.Logging.Warning.Println(\"Unauthorised access to Profile from \", req.UserAgent())\n\t\thttp.Redirect(res, req, \"/\", http.StatusSeeOther)\n\t\treturn\n\t}\n\ta.Template.ExecuteTemplate(res, \"profile.html\", d)\n}", "func (authUserL) LoadUserCommonUserprofile(e boil.Executor, singular bool, maybeAuthUser interface{}) error {\n\tvar slice []*AuthUser\n\tvar object *AuthUser\n\n\tcount := 1\n\tif singular {\n\t\tobject = maybeAuthUser.(*AuthUser)\n\t} else {\n\t\tslice = *maybeAuthUser.(*AuthUserSlice)\n\t\tcount = len(slice)\n\t}\n\n\targs := make([]interface{}, count)\n\tif singular {\n\t\tif object.R == nil {\n\t\t\tobject.R = &authUserR{}\n\t\t}\n\t\targs[0] = object.ID\n\t} else {\n\t\tfor i, obj := range slice {\n\t\t\tif obj.R == nil {\n\t\t\t\tobj.R = &authUserR{}\n\t\t\t}\n\t\t\targs[i] = obj.ID\n\t\t}\n\t}\n\n\tquery := fmt.Sprintf(\n\t\t\"select * from `common_userprofile` where `user_id` in (%s)\",\n\t\tstrmangle.Placeholders(dialect.IndexPlaceholders, count, 1, 1),\n\t)\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintf(boil.DebugWriter, \"%s\\n%v\\n\", query, args)\n\t}\n\n\tresults, err := e.Query(query, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to eager load CommonUserprofile\")\n\t}\n\tdefer results.Close()\n\n\tvar resultSlice []*CommonUserprofile\n\tif err = queries.Bind(results, &resultSlice); err != nil {\n\t\treturn errors.Wrap(err, \"failed to bind eager loaded slice CommonUserprofile\")\n\t}\n\n\tif len(resultSlice) == 0 {\n\t\treturn nil\n\t}\n\n\tif singular {\n\t\tobject.R.UserCommonUserprofile = resultSlice[0]\n\t\treturn nil\n\t}\n\n\tfor _, local := range slice {\n\t\tfor _, foreign := range resultSlice {\n\t\t\tif local.ID == foreign.UserID {\n\t\t\t\tlocal.R.UserCommonUserprofile = foreign\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func ProfilePage(w http.ResponseWriter, r *http.Request) {\n\tusername, auth := IsAuthorized(r)\n\n\tif !auth || username == \"\" {\n\t\thttp.Redirect(w, r, \"/login\", http.StatusSeeOther)\n\t\treturn\n\t}\n\tif r.URL.Path == \"/profile\" {\n\t\tif r.Method == \"GET\" {\n\t\t\tresponse := GetResponse(r)\n\t\t\tresponse.Posts = db.GetPostsByUserID(response.User.UserID)\n\t\t\tt := template.Must(template.New(\"profile\").ParseFiles(\"static/profile.html\", \"static/header.html\", \"static/footer.html\"))\n\t\t\tt.Execute(w, response)\n\t\t} else {\n\t\t\tBadRequest(w, r, r.Method+\" is not allowed\")\n\t\t}\n\t} else {\n\t\tPageNotFound(w, r)\n\t}\n}", "func Profile(response http.ResponseWriter, request *http.Request) {\n\tswitch request.Method {\n\tcase \"GET\":\n\t\tuserName := blogpost.GetUserName(request)\n\t\tuser, err := model.GetUser(userName)\n\n\t\tif err != nil {\n\t\t\tfmt.Fprint(response, `<p>You are not Logged in, Click <a href=\"/login\">Here</a> to Log in </p>`)\n\t\t\treturn\n\t\t}\n\n\t\ttype detail struct {\n\t\t\tProfile model.User\n\t\t}\n\n\t\tdetails := detail{\n\t\t\tProfile: user,\n\t\t}\n\n\t\tif user.LoginState {\n\t\t\ttmp, err := template.ParseFiles(\n\t\t\t\t\"admin/template/template.gohtml\",\n\t\t\t\t\"admin/template/sidebar.gohtml\",\n\t\t\t\t\"admin/template/header.gohtml\",\n\t\t\t\t\"admin/template/footer.gohtml\",\n\t\t\t\t\"admin/profile.gohtml\",\n\t\t\t)\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\thttp.Error(response, \"internal server error\", http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ttmp.ExecuteTemplate(response, \"layout\", details)\n\t\t\treturn\n\n\t\t} else {\n\n\t\t\thttp.Redirect(response, request, \"/login\", http.StatusSeeOther)\n\t\t\treturn\n\t\t}\n\n\tcase \"POST\":\n\t\t//get current user from session the nfind in db.\n\t\tuserName := blogpost.GetUserName(request)\n\t\tuser, err := model.GetUser(userName)\n\n\t\tif err != nil {\n\t\t\t//handle err\n\t\t\tfmt.Fprint(response, `<p>You are not Logged in, Click <a href=\"/login\">Here</a> to Log in </p>`)\n\t\t\treturn\n\t\t}\n\n\t\t//check if current user is loggedin.\n\t\tif user.LoginState {\n\t\t\trequest.ParseMultipartForm(100000)\n\n\t\t\tuserName := request.FormValue(\"userName\")\n\t\t\tfirstname := request.FormValue(\"firstName\")\n\t\t\tlastName := request.FormValue(\"lastName\")\n\t\t\tPassWord := request.FormValue(\"password\")\n\t\t\tEmail := request.FormValue(\"email\")\n\t\t\tID, _ := primitive.ObjectIDFromHex(request.FormValue(\"ID\"))\n\t\t\taddress := request.FormValue(\"address\")\n\t\t\tCity := request.FormValue(\"city\")\n\t\t\tState := request.FormValue(\"state\")\n\t\t\tZip := request.FormValue(\"zip\")\n\t\t\tpics, header, err := request.FormFile(\"pics\")\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintln(response, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t//save profile image to upload folder.\n\t\t\t//refer \"github.com/ukane-philemon/RudigoNews/utils/saveimage\"\n\t\t\tsaveimage.SaveImage(pics, header)\n\n\t\t\t//Hash new password.\n\t\t\tPassWord = model.PasswordHash(PassWord)\n\n\t\t\tnewUser := model.User{\n\t\t\t\tID: ID,\n\t\t\t\tUserName: userName,\n\t\t\t\tEmail: Email,\n\t\t\t\tFirst: firstname,\n\t\t\t\tLast: lastName,\n\t\t\t\tPassword: PassWord,\n\t\t\t\tAddress: address,\n\t\t\t\tAvatar: header.Filename,\n\t\t\t\tCity: City,\n\t\t\t\tState: State,\n\t\t\t\tZip: Zip,\n\t\t\t}\n\n\t\t\tif model.UpdateUser(newUser, ID) == nil {\n\t\t\t\thttp.Redirect(response, request, \"/admin/profile\", http.StatusSeeOther)\n\t\t\t\tfmt.Print(\"user updated\")\n\n\t\t\t} else {\n\t\t\t\tmodel.CreateUser(newUser)\n\t\t\t}\n\n\t\t} else {\n\t\t\thttp.Redirect(response, request, \"/login\", http.StatusFound)\n\t\t}\n\tdefault:\n\t\thttp.Redirect(response, request, \"/login\", http.StatusForbidden)\n\t}\n\n}", "func userPage(w http.ResponseWriter, r *http.Request){\n\tisLogged, name := CheckLoginStatus(w,r)\n\n\tif isLogged {\n\t\terr := templ.ExecuteTemplate(w, \"userHome\", name)\n\t\tif err != nil {\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t} else {\n\t\thttp.Redirect(w,r,\"/unauthorized\",http.StatusSeeOther)\n\t}\n}", "func USERS_GET_ProfileView(res http.ResponseWriter, req *http.Request, params httprouter.Params) {\n\tctx := appengine.NewContext(req)\n\tu, _ := GetUserFromSession(req)\n\tid, convErr := strconv.ParseInt(params.ByName(\"ID\"), 10, 64)\n\tif ErrorPage(ctx, res, nil, \"Invalid ID\", convErr, http.StatusBadRequest) {\n\t\treturn\n\t}\n\tci, getErr := GetUserFromID(ctx, id)\n\tif ErrorPage(ctx, res, u, \"Not a valid user ID\", getErr, http.StatusNotFound) {\n\t\treturn\n\t}\n\tlog.Infof(ctx, \"error ID: \", id)\n\tnotes, err := GetAllNotes(ctx, id)\n\tlog.Infof(ctx, \"error: \", len(notes))\n\tif ErrorPage(ctx, res, nil, \"Internal Server Error\", err, http.StatusSeeOther) {\n\t\treturn\n\t}\n\tscreen := struct {\n\t\tHeaderData\n\t\tData *User\n\t\tAllNotes []NoteOutput\n\t}{\n\t\t*MakeHeader(res, req, true, true),\n\t\tci,\n\t\tnotes,\n\t}\n\tServeTemplateWithParams(res, \"user-profile\", screen)\n}", "func (braceletPhotoL) LoadUser(e boil.Executor, singular bool, maybeBraceletPhoto interface{}) error {\n\tvar slice []*BraceletPhoto\n\tvar object *BraceletPhoto\n\n\tcount := 1\n\tif singular {\n\t\tobject = maybeBraceletPhoto.(*BraceletPhoto)\n\t} else {\n\t\tslice = *maybeBraceletPhoto.(*BraceletPhotoSlice)\n\t\tcount = len(slice)\n\t}\n\n\targs := make([]interface{}, count)\n\tif singular {\n\t\tif object.R == nil {\n\t\t\tobject.R = &braceletPhotoR{}\n\t\t}\n\t\targs[0] = object.UserID\n\t} else {\n\t\tfor i, obj := range slice {\n\t\t\tif obj.R == nil {\n\t\t\t\tobj.R = &braceletPhotoR{}\n\t\t\t}\n\t\t\targs[i] = obj.UserID\n\t\t}\n\t}\n\n\tquery := fmt.Sprintf(\n\t\t\"select * from `auth_user` where `id` in (%s)\",\n\t\tstrmangle.Placeholders(dialect.IndexPlaceholders, count, 1, 1),\n\t)\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintf(boil.DebugWriter, \"%s\\n%v\\n\", query, args)\n\t}\n\n\tresults, err := e.Query(query, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to eager load AuthUser\")\n\t}\n\tdefer results.Close()\n\n\tvar resultSlice []*AuthUser\n\tif err = queries.Bind(results, &resultSlice); err != nil {\n\t\treturn errors.Wrap(err, \"failed to bind eager loaded slice AuthUser\")\n\t}\n\n\tif len(resultSlice) == 0 {\n\t\treturn nil\n\t}\n\n\tif singular {\n\t\tobject.R.User = resultSlice[0]\n\t\treturn nil\n\t}\n\n\tfor _, local := range slice {\n\t\tfor _, foreign := range resultSlice {\n\t\t\tif local.UserID == foreign.ID {\n\t\t\t\tlocal.R.User = foreign\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *Context) LoadUser(key string) error {\n\tif c.User != nil {\n\t\treturn nil\n\t}\n\n\tvar user interface{}\n\tvar err error\n\n\tif index := strings.IndexByte(key, ';'); index > 0 {\n\t\tuser, err = c.OAuth2Storer.GetOAuth(key[:index], key[index+1:])\n\t} else {\n\t\tuser, err = c.Storer.Get(key)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.User = Unbind(user)\n\treturn nil\n}", "func Profile() echo.HandlerFunc {\n\treturn func(context echo.Context) error {\n\t\tuser, err := FindByID(context.Param(\"userID\"))\n\t\tif err != nil || user == nil {\n\t\t\treturn context.JSON(http.StatusInternalServerError, errors.New(\"Cannot load user with ID %s\"))\n\t\t}\n\n\t\tsession := context.Get(\"session\").(*session.Session)\n\n\t\tif session != nil && (session.IsAdmin || session.UserID == user.ID) {\n\t\t\tuser.Hash = \"\" // don't leak user Hash, for security\n\t\t\treturn context.JSON(http.StatusOK, user)\n\t\t}\n\n\t\treturn context.JSON(http.StatusOK, formatUser(user))\n\t}\n}", "func (a *Adapter) LoadUserData(uuid string) (*core.ProfileUserData, error) {\n\turl := fmt.Sprintf(\"%s/%s\", a.host, uuid)\n\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tlog.Printf(\"error creating load user data request - %s\", err)\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"ROKWIRE-API-KEY\", a.apiKey)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Printf(\"error loading user data - %s\", err)\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\tlog.Printf(\"error with response code - %d\", resp.StatusCode)\n\t\treturn nil, errors.New(\"error with response code != 200\")\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Printf(\"error reading the body data for the loading user data request - %s\", err)\n\t\treturn nil, err\n\t}\n\n\tvar result core.ProfileUserData\n\terr = json.Unmarshal(body, &result)\n\tif err != nil {\n\t\tlog.Printf(\"error converting data for the loading user data request - %s\", err)\n\t\treturn nil, err\n\t}\n\n\treturn &result, nil\n}", "func loadPage(pn string, r *http.Request) (*Page, error) {\n\tdata := &Page{\n\t\tPageName: pn,\n\t}\n\n\t/* Get user name for filling in template too */\n\tsesh, _ := store.Get(r, \"loginSession\")\n\tuname, ok := sesh.Values[\"username\"].(string)\n\tif !ok {\n\t\treturn nil, &ClientSafeError{Msg: \"invalid username\"}\n\t}\n\tdata.Username = uname\n\t/* get user's role */\n\trole, err := getRoleNum(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tswitch role {\n\tcase FACILITATOR:\n\t\tdata.Role = \"Facilitator\"\n\t\tdata.Messages, err = getNotifications(data.Username)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tcase TEACHER:\n\t\tdata.Role = \"Teacher\"\n\tcase ADMIN:\n\t\tdata.Role = \"Admin\"\n\tdefault:\n\t\treturn nil, &ClientSafeError{Msg: \"insufficient access rights\"}\n\t}\n\n\treturn data, nil\n}", "func ProfileHandler(c buffalo.Context) error {\n\tuser := models.User{}\n\tdb := c.Value(\"tx\").(*pop.Connection)\n\tdb.Find(&user, c.Param(\"uid\"))\n\treturn c.Render(200, r.JSON(user))\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LoadUserLoggedProfile Load the user profile
func LoadUserLoggedProfile(w http.ResponseWriter, r *http.Request) { cookie, _ := cookies.Read(r) userID, _ := strconv.ParseUint(cookie["id"], 10, 64) user, err := models.SearchCompleteUser(userID, r) if err != nil { responses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: err.Error()}) return } utils.RunTemplate(w, "profile.html", user) }
[ "func (authUserL) LoadUserCommonUserprofile(e boil.Executor, singular bool, maybeAuthUser interface{}) error {\n\tvar slice []*AuthUser\n\tvar object *AuthUser\n\n\tcount := 1\n\tif singular {\n\t\tobject = maybeAuthUser.(*AuthUser)\n\t} else {\n\t\tslice = *maybeAuthUser.(*AuthUserSlice)\n\t\tcount = len(slice)\n\t}\n\n\targs := make([]interface{}, count)\n\tif singular {\n\t\tif object.R == nil {\n\t\t\tobject.R = &authUserR{}\n\t\t}\n\t\targs[0] = object.ID\n\t} else {\n\t\tfor i, obj := range slice {\n\t\t\tif obj.R == nil {\n\t\t\t\tobj.R = &authUserR{}\n\t\t\t}\n\t\t\targs[i] = obj.ID\n\t\t}\n\t}\n\n\tquery := fmt.Sprintf(\n\t\t\"select * from `common_userprofile` where `user_id` in (%s)\",\n\t\tstrmangle.Placeholders(dialect.IndexPlaceholders, count, 1, 1),\n\t)\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintf(boil.DebugWriter, \"%s\\n%v\\n\", query, args)\n\t}\n\n\tresults, err := e.Query(query, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to eager load CommonUserprofile\")\n\t}\n\tdefer results.Close()\n\n\tvar resultSlice []*CommonUserprofile\n\tif err = queries.Bind(results, &resultSlice); err != nil {\n\t\treturn errors.Wrap(err, \"failed to bind eager loaded slice CommonUserprofile\")\n\t}\n\n\tif len(resultSlice) == 0 {\n\t\treturn nil\n\t}\n\n\tif singular {\n\t\tobject.R.UserCommonUserprofile = resultSlice[0]\n\t\treturn nil\n\t}\n\n\tfor _, local := range slice {\n\t\tfor _, foreign := range resultSlice {\n\t\t\tif local.ID == foreign.UserID {\n\t\t\t\tlocal.R.UserCommonUserprofile = foreign\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (context *authenticationContext) LoadUser(login, salt, hash string) error {\n\tif _, found := context.registeredUsers[login]; found {\n\t\treturn errors.New(\"user already exists\")\n\t}\n\tcontext.registeredUsers[login] = PasswordInformation{salt, hash}\n\treturn nil\n}", "func (m *MockDatabase) LoadUserSessionID(SessionID string) (general.User, error) {\n\targs := m.Called(SessionID)\n\treturn args.Get(0).(general.User), args.Error(1)\n}", "func LoadUserPage(w http.ResponseWriter, r *http.Request) {\n\tparameters := mux.Vars(r)\n\tuserID, err := strconv.ParseUint(parameters[\"userId\"], 10, 64)\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusBadRequest, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\n\tcookie, _ := cookies.Read(r)\n\tuserIDLogged, _ := strconv.ParseUint(cookie[\"id\"], 10, 64)\n\n\tuser, err := models.SearchCompleteUser(userID, r)\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\n\tif userID == userIDLogged {\n\t\thttp.Redirect(w, r, \"/profile\", 302)\n\t\treturn\n\t}\n\n\tutils.RunTemplate(w, \"user.html\", struct {\n\t\tUser models.User\n\t\tUserLoggedID uint64\n\t}{\n\t\tUser: user,\n\t\tUserLoggedID: userIDLogged,\n\t})\n}", "func (c *Context) LoadUser(key string) error {\n\tif c.User != nil {\n\t\treturn nil\n\t}\n\n\tvar user interface{}\n\tvar err error\n\n\tif index := strings.IndexByte(key, ';'); index > 0 {\n\t\tuser, err = c.OAuth2Storer.GetOAuth(key[:index], key[index+1:])\n\t} else {\n\t\tuser, err = c.Storer.Get(key)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.User = Unbind(user)\n\treturn nil\n}", "func (s *VaultUserStore) Load(id msp.IdentityIdentifier) (*msp.UserData, error) {\n\tsecret, err := s.client.Logical().Read(\"fabric/kv/users/\" + strings.ToLower(id.ID) + \"@\" + strings.ToLower(id.MSPID))\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif secret == nil {\n\t\treturn nil, msp.ErrUserNotFound\n\t}\n\n\tvalue, ok := secret.Data[\"value\"]\n\n\tif !ok {\n\t\treturn nil, msp.ErrUserNotFound\n\t}\n\n\tcertString, ok := value.(string)\n\n\tif !ok {\n\t\treturn nil, msp.ErrUserNotFound\n\t}\n\n\tcertBytes := []byte(certString)\n\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to hex decode cert bytes\")\n\t}\n\n\tuserData := msp.UserData{\n\t\tID: id.ID,\n\t\tMSPID: id.MSPID,\n\t\tEnrollmentCertificate: certBytes,\n\t}\n\n\treturn &userData, nil\n}", "func (t *OpetCode) loadUser(APIstub shim.ChaincodeStubInterface, userKey string) (User, error) {\n user_json, _ := APIstub.GetState(userKey)\n var user User\n\n if user_json == nil {\n return user, errors.New(\"There is no user exist\")\n } \n _ = json.Unmarshal([]byte(user_json), &user) \n return user, nil\n}", "func (y *YKAuth) LoadUser(name, public string) (*yubico.User, error) {\n\tlogger := y.With().Str(\"public\", public).Str(\"name\", name).\n\t\tStr(\"db\", \"ykauth\").Logger()\n\tlogger.Debug().Msgf(\"loading user\")\n\thash := sql.NullString{}\n\tstmt, err := y.Prepare(getUser)\n\tif err != nil {\n\t\tlogger.Error().Err(err).Msg(\"query preparation failed\")\n\t\treturn nil, ErrDB\n\t}\n\tdefer func() { _ = stmt.Close() }()\n\tif err = stmt.QueryRow(name, public).Scan(&hash); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\tlogger.Error().Msgf(\"unknown user\")\n\t\t\terr = ykauth.ErrNoUser\n\t\t} else {\n\t\t\tlogger.Error().Err(err).Msgf(\"query execution failed\")\n\t\t\terr = ErrDB\n\t\t}\n\t}\n\tuser := &yubico.User{Name: name, Hash: hash.String}\n\treturn user, err\n}", "func (c *Context) LoadSessionUser() error {\n\tif c.User != nil {\n\t\treturn nil\n\t}\n\n\tkey, ok := c.SessionStorer.Get(SessionKey)\n\tif !ok {\n\t\treturn ErrUserNotFound\n\t}\n\n\treturn c.LoadUser(key)\n}", "func (sys *IAMSys) LoadUser(objAPI ObjectLayer, accessKey string, isSTS bool) error {\n\tif objAPI == nil {\n\t\treturn errInvalidArgument\n\t}\n\n\tsys.Lock()\n\tdefer sys.Unlock()\n\n\tif globalEtcdClient == nil {\n\t\terr := loadUser(objAPI, accessKey, isSTS, sys.iamUsersMap)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = loadMappedPolicy(objAPI, accessKey, isSTS, sys.iamUserPolicyMap)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// When etcd is set, we use watch APIs so this code is not needed.\n\treturn nil\n}", "func loadProfile(sysOS *sys.OS, name string) error {\n\tif !sysOS.AppArmorAdmin {\n\t\treturn nil\n\t}\n\n\treturn runApparmor(sysOS, cmdLoad, name)\n}", "func profile(w http.ResponseWriter, req *http.Request) {\n\tsess, _ := session(w, req)\n\tuser, err := sess.User()\n\tif err != nil {\n\t\tlogger.SetPrefix(\"ERROR \")\n\t\tlogger.Println(err, \"Cannot fetch user\")\n\t}\n\tdata := struct {\n\t\tdata.User\n\t}{user}\n\tgenerateHTML(w, data, \"layout\", \"private.navbar\", \"profile\")\n}", "func LoadProfile() (*ini.File, error) {\n\thome, err := homedir.Dir()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsharedCredentialsPath, err := envOrDefault(envSharedCredentialsFile, func() (string, error) {\n\t\treturn filepath.Join(home, \".aws\", \"credentials\"), nil\n\t})\n\tconfigFilePath, err := envOrDefault(envAWSConfigFile, func() (string, error) {\n\t\treturn filepath.Join(home, \".aws\", \"config\"), nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ini.Load(sharedCredentialsPath, configFilePath)\n}", "func (u *User) Load() error {\n\treturn DB.LoadUser(u)\n}", "func (a *Adapter) LoadUserData(uuid string) (*core.ProfileUserData, error) {\n\turl := fmt.Sprintf(\"%s/%s\", a.host, uuid)\n\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tlog.Printf(\"error creating load user data request - %s\", err)\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"ROKWIRE-API-KEY\", a.apiKey)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Printf(\"error loading user data - %s\", err)\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\tlog.Printf(\"error with response code - %d\", resp.StatusCode)\n\t\treturn nil, errors.New(\"error with response code != 200\")\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Printf(\"error reading the body data for the loading user data request - %s\", err)\n\t\treturn nil, err\n\t}\n\n\tvar result core.ProfileUserData\n\terr = json.Unmarshal(body, &result)\n\tif err != nil {\n\t\tlog.Printf(\"error converting data for the loading user data request - %s\", err)\n\t\treturn nil, err\n\t}\n\n\treturn &result, nil\n}", "func Profile() echo.HandlerFunc {\n\treturn func(context echo.Context) error {\n\t\tuser, err := FindByID(context.Param(\"userID\"))\n\t\tif err != nil || user == nil {\n\t\t\treturn context.JSON(http.StatusInternalServerError, errors.New(\"Cannot load user with ID %s\"))\n\t\t}\n\n\t\tsession := context.Get(\"session\").(*session.Session)\n\n\t\tif session != nil && (session.IsAdmin || session.UserID == user.ID) {\n\t\t\tuser.Hash = \"\" // don't leak user Hash, for security\n\t\t\treturn context.JSON(http.StatusOK, user)\n\t\t}\n\n\t\treturn context.JSON(http.StatusOK, formatUser(user))\n\t}\n}", "func qemuImgProfileLoad(sysOS *sys.OS, imgPath string, dstPath string, allowedCmdPaths []string) error {\n\tprofile := filepath.Join(aaPath, \"profiles\", qemuImgProfileFilename(imgPath))\n\tcontent, err := ioutil.ReadFile(profile)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\n\tupdated, err := qemuImgProfile(imgPath, dstPath, allowedCmdPaths)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif string(content) != string(updated) {\n\t\terr = ioutil.WriteFile(profile, []byte(updated), 0600)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = loadProfile(sysOS, qemuImgProfileFilename(imgPath))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (braceletPhotoL) LoadUser(e boil.Executor, singular bool, maybeBraceletPhoto interface{}) error {\n\tvar slice []*BraceletPhoto\n\tvar object *BraceletPhoto\n\n\tcount := 1\n\tif singular {\n\t\tobject = maybeBraceletPhoto.(*BraceletPhoto)\n\t} else {\n\t\tslice = *maybeBraceletPhoto.(*BraceletPhotoSlice)\n\t\tcount = len(slice)\n\t}\n\n\targs := make([]interface{}, count)\n\tif singular {\n\t\tif object.R == nil {\n\t\t\tobject.R = &braceletPhotoR{}\n\t\t}\n\t\targs[0] = object.UserID\n\t} else {\n\t\tfor i, obj := range slice {\n\t\t\tif obj.R == nil {\n\t\t\t\tobj.R = &braceletPhotoR{}\n\t\t\t}\n\t\t\targs[i] = obj.UserID\n\t\t}\n\t}\n\n\tquery := fmt.Sprintf(\n\t\t\"select * from `auth_user` where `id` in (%s)\",\n\t\tstrmangle.Placeholders(dialect.IndexPlaceholders, count, 1, 1),\n\t)\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintf(boil.DebugWriter, \"%s\\n%v\\n\", query, args)\n\t}\n\n\tresults, err := e.Query(query, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to eager load AuthUser\")\n\t}\n\tdefer results.Close()\n\n\tvar resultSlice []*AuthUser\n\tif err = queries.Bind(results, &resultSlice); err != nil {\n\t\treturn errors.Wrap(err, \"failed to bind eager loaded slice AuthUser\")\n\t}\n\n\tif len(resultSlice) == 0 {\n\t\treturn nil\n\t}\n\n\tif singular {\n\t\tobject.R.User = resultSlice[0]\n\t\treturn nil\n\t}\n\n\tfor _, local := range slice {\n\t\tfor _, foreign := range resultSlice {\n\t\t\tif local.UserID == foreign.ID {\n\t\t\t\tlocal.R.User = foreign\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func LoadProfileFromFile(profile string, generator *generate.Generator) error {\n\treturn nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LoadUserEditPage Load page to edit user
func LoadUserEditPage(w http.ResponseWriter, r *http.Request) { cookie, _ := cookies.Read(r) userID, _ := strconv.ParseUint(cookie["id"], 10, 64) channel := make(chan models.User) go models.GetUserData(channel, userID, r) user := <-channel if user.ID == 0 { responses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: "Erro ao buscar o usuário"}) return } utils.RunTemplate(w, "edit-profile.html", user) }
[ "func LoadUserPasswordEditPage(w http.ResponseWriter, r *http.Request) {\n\tutils.RunTemplate(w, \"update-password.html\", nil)\n}", "func UserEdit(w http.ResponseWriter, r *http.Request, u *User) error {\n\treturn RenderTemplate(w, \"user_profile.html\", struct{ User *User }{u})\n}", "func (controller *UserController) GetEditPage(ctx *fasthttp.RequestCtx) {\n\tcontroller.getProfile(ctx, true)\n}", "func (s *Server) handleDashboardUserEdit() http.HandlerFunc {\n\tvar o sync.Once\n\tvar tpl *template.Template\n\n\t//steps on the page\n\tsteps := struct {\n\t\tStepDel string\n\t}{\n\t\tStepDel: \"stepDel\",\n\t}\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx, logger := GetLogger(s.getCtx(r))\n\t\to.Do(func() {\n\t\t\ttpl = s.loadWebTemplateDashboard(ctx, \"user-edit.html\")\n\t\t})\n\t\tctx, provider, data, _, ok := s.createTemplateDataDashboard(w, r.WithContext(ctx), tpl, true)\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\t//setup the breadcrumbs\n\t\tbreadcrumbs := []breadcrumb{\n\t\t\t{\"Users\", provider.GetURLUsers()},\n\t\t\t{\"Edit Team Member\", \"\"},\n\t\t}\n\t\tdata[TplParamBreadcrumbs] = breadcrumbs\n\t\tdata[TplParamActiveNav] = provider.GetURLUsers()\n\t\tdata[TplParamFormAction] = provider.GetURLUserEdit()\n\t\tdata[TplParamSteps] = steps\n\n\t\t//handle the input\n\t\tidStr := r.FormValue(URLParams.UserID)\n\t\tstep := r.FormValue(URLParams.Step)\n\n\t\t//prepare the data\n\t\tdata[TplParamUserID] = idStr\n\n\t\t//load the provider user\n\t\tid := uuid.FromStringOrNil(idStr)\n\t\tif id == uuid.Nil {\n\t\t\tlogger.Warnw(\"invalid uuid\", \"id\", idStr)\n\t\t\ts.SetCookieErr(w, Err)\n\t\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLUsers(), http.StatusSeeOther)\n\t\t\treturn\n\t\t}\n\t\tctx, providerUser, err := LoadProviderUserByProviderIDAndID(ctx, s.getDB(), provider.ID, &id)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"load provider user\", \"error\", err, \"id\", id)\n\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\t\tif providerUser == nil {\n\t\t\tlogger.Errorw(\"no provider user\", \"id\", id)\n\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\t\tdata[TplParamUser] = providerUser\n\n\t\t//prepare the confirmation modal\n\t\tdata[TplParamConfirmMsg] = GetMsgText(MsgUserDelConfirm)\n\t\tdata[TplParamConfirmSubmitName] = URLParams.Step\n\t\tdata[TplParamConfirmSubmitValue] = steps.StepDel\n\n\t\t//check the method\n\t\tif r.Method == http.MethodGet {\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\n\t\t//execute the correct operation\n\t\tvar msgKey MsgKey\n\t\tswitch step {\n\t\tcase steps.StepDel:\n\t\t\t//delete the provider user\n\t\t\tctx, err := DeleteUserProvider(ctx, s.getDB(), provider.ID, providerUser.ID)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorw(\"delete provider user\", \"error\", err, \"id\", providerUser.ID)\n\t\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tmsgKey = MsgUserDel\n\t\tdefault:\n\t\t\tlogger.Errorw(\"invalid step\", \"id\", providerUser.ID, \"step\", step)\n\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\n\t\t//success\n\t\ts.SetCookieMsg(w, msgKey, providerUser.Login)\n\t\thttp.Redirect(w, r.WithContext(ctx), provider.GetURLUsers(), http.StatusSeeOther)\n\t}\n}", "func EditUser(c *gin.Context) {\n\tAuthorizedUser(c)\n\tuser := CurrentUser(c)\n\n\tc.HTML(http.StatusOK, \"users/edit\", gin.H{\n\t\t\"title\": \"Update User\",\n\t\t\"action\": \"Update\",\n\t\t\"user\": &user,\n\t\t\"CurrentPath\": c.Request.URL.Path,\n\t})\n}", "func (userController *UserController) GetEditProfilePage(w http.ResponseWriter, r *http.Request) {\n\t// Context for data in view template\n\ttype Context struct {\n\t\tGroups []rolemodule.Grup\n\t\tUser Pengguna\n\t\tUserGroupID int64\n\t\tValidationMessage string\n\t\tCsrfToken string\n\t}\n\n\tvars := mux.Vars(r)\n\n\t// Load edit profile view\n\teditProfileTemplate := userController.Templates.Lookup(\"edit_profile.html\")\n\n\t// Load user id from input type hidden in edit profile\n\tuserID, err := strconv.ParseInt(template.HTMLEscapeString(vars[\"userId\"]), 10, 64)\n\tif err != nil {\n\t\tfmt.Println(\"error when parse user group id\")\n\t}\n\n\t// Get all groups from database\n\tgroups := userController.GroupRepository.GetGroups()\n\n\t// Get user group id by given user id\n\tuserGroupID := userController.GroupRepository.GetUserGroupIDByUserID(userID)\n\n\t// Get user by given user id\n\tuser := userController.UserRepository.GetUserByID(userID)\n\n\t// Save csrf token to session for comparison when form submission\n\tsess := userController.SessionHelper.GetSession(r)\n\tcsrfToken := csrfbanana.Token(w, r, sess)\n\tuserController.SessionHelper.SetCSRFToken(r, w, csrfToken)\n\n\tcontext := Context{\n\t\tGroups: groups,\n\t\tUser: user,\n\t\tUserGroupID: userGroupID,\n\t\tValidationMessage: userController.SessionHelper.GetValidationMessage(r),\n\t\tCsrfToken: csrfToken}\n\n\teditProfileTemplate.Execute(w, context)\n}", "func (h *Handler) EditUser(c *fiber.Ctx) error {\n\tservice := services.NewUserService()\n\tid, err := strconv.ParseInt(c.Params(\"id\"), 10, 32)\n\n\tif err != nil {\n\t\treturn c.Status(400).JSON(fiber.Map{\"status\": \"error\", \"message\": err.Error()})\n\t}\n\n\tvar usr user.User\n\tif err := c.BodyParser(&usr); err != nil {\n\t\treturn c.Status(422).JSON(fiber.Map{\"status\": \"error\", \"message\": \"Invalid fields\"})\n\t}\n\n\terr = service.UpdateUser(&usr, int(id))\n\n\tif err != nil {\n\t\treturn c.Status(500).JSON(fiber.Map{\"status\": \"error\", \"message\": err.Error()})\n\t}\n\n\treturn c.JSON(fiber.Map{\"status\": \"success\", \"message\": \"UpdatedUser\", \"data\": usr})\n}", "func EditPage(c *fiber.Ctx) error {\n\t// Firstly checks if given table exists\n\tname := c.Params(\"name\")\n\tT := databasepack.FindTable(name)\n\tif T < 0 {\n\t\treturn c.Send([]byte(\"No table with such name!\"))\n\t}\n\t// Next checks if the user can actually perform this action\n\tif !databasepack.Allowed(querypack.INFO.Roles, \"editor_\"+name) {\n\t\treturn c.Send([]byte(\"Permission declined!\"))\n\t}\n\t// Lastly posts given post\n\tdatabasepack.CreatePosts(c.Body(), name, T)\n\treturn c.Send([]byte(\"Successfully edited!\"))\n}", "func EditUser(w http.ResponseWriter, r *http.Request) {\n\n\tif !UserAuthorized(r) {\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tuserId, _ := strconv.Atoi(mux.Vars(r)[\"userId\"])\n\n\tvar user models.User\n\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&user); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := env.db.UpdateUser(userId, &user); err != nil {\n\t\tpanic(err)\n\t}\n\n\tupdatedUser, err := env.db.FindUserById(userId)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tw.Header().Set(\"Content-Type\", JSON)\n\tw.WriteHeader(http.StatusOK)\n\tif err := json.NewEncoder(w).Encode(updatedUser); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (h *Handler) EditPage(c echo.Context) error {\n\tm := echo.Map{}\n\tif err := c.Bind(&m); err != nil {\n\t\treturn err\n\t}\n\tnr, nt, route := m[\"newRoute\"].(string), m[\"newTitle\"].(string), m[\"route\"].(string)\n\n\tuserDataMap := utils.GetUserDataFromContext(&c)\n\temail := (*userDataMap)[\"email\"].(string)\n\n\tpage, err := h.pageStore.EditPage(email, route, nr, nt)\n\tif err != nil {\n\t\tutils.Logger.Error(err)\n\t\treturn c.JSON(http.StatusInternalServerError, createRes(false, nil, nil, http.StatusText(http.StatusInternalServerError)))\n\t}\n\treturn c.JSON(http.StatusOK, createRes(true, page, nil, \"\"))\n}", "func LoadEditPage(w http.ResponseWriter, r *http.Request) {\n\tparameters := mux.Vars(r)\n\tpublicationID, err := strconv.ParseUint(parameters[\"publicationId\"], 10, 64)\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusBadRequest, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\n\turl := fmt.Sprintf(\"%s/publications/%d\", config.APIURL, publicationID)\n\tresponse, err := requests.RequestsWithAuthentication(r, http.MethodGet, url, nil)\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\tdefer response.Body.Close()\n\n\tif response.StatusCode >= 400 {\n\t\tresponses.TreatStatusCode(w, response)\n\t\treturn\n\t}\n\n\tvar publication models.Publication\n\tif err = json.NewDecoder(response.Body).Decode(&publication); err != nil {\n\t\tresponses.JSON(w, http.StatusUnprocessableEntity, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\n\tutils.RunTemplate(w, \"edit-publication.html\", publication)\n}", "func handlerEdit(w http.ResponseWriter, r *http.Request, title string) {\r\n\tpage, err := loadPage(title)\r\n\tif err != nil {\r\n\t\tpage = &Page{Title: title}\r\n\t}\r\n\t//to use a html file we have to use the template.ParseFile\r\n\tfetchHTML(w, \"edit\", page)\r\n}", "func editHandler(w http.ResponseWriter, r *http.Request) {\n\ttitle := r.URL.Path[len(\"/edit/\"):]\n\tp,_ := find_page(title)\n\tif p == nil{\n\t\tp = &Page{Title:title, Body:\"\"}\n\t\tpage_lst.Pages = append(page_lst.Pages, p)\n\t}\n\trenderTemplate(w, \"edit\", p)\n}", "func (c Users) Edit(id uint) revel.Result {\n\tcurrentUser := connected(c.RenderArgs, c.Session)\n\t// if currentUser == nil || (currentUser.UserGroup < models.GroupAdmin && currentUser.ID != id) {\n\t// \treturn c.Render(currentUser)\n\t// }\n\n\tvar user models.User\n\tdbgorm.Db.First(&user, id)\n\treturn c.Render(user, currentUser)\n}", "func (config *AppConfig) EditUser(editUser UserAttributes, userID int) (user User, err error) {\n\teditUserBytes, err := json.Marshal(editUser)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// get json bytes from the panel.\n\tuserBytes, err := config.queryApplicationAPI(fmt.Sprintf(\"users/%d\", userID), \"patch\", editUserBytes)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Get user info from the panel\n\t// Unmarshal the bytes to a usable struct.\n\terr = json.Unmarshal(userBytes, &user)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (a *User) EditUser(id int64, data map[string]interface{}) error {\n\ttx := GetSessionTx(a.Session)\n\treturn tx.Model(&User{}).Where(\"id = ?\", id).Updates(data).Error\n}", "func LoadUserPage(w http.ResponseWriter, r *http.Request) {\n\tparameters := mux.Vars(r)\n\tuserID, err := strconv.ParseUint(parameters[\"userId\"], 10, 64)\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusBadRequest, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\n\tcookie, _ := cookies.Read(r)\n\tuserIDLogged, _ := strconv.ParseUint(cookie[\"id\"], 10, 64)\n\n\tuser, err := models.SearchCompleteUser(userID, r)\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\n\tif userID == userIDLogged {\n\t\thttp.Redirect(w, r, \"/profile\", 302)\n\t\treturn\n\t}\n\n\tutils.RunTemplate(w, \"user.html\", struct {\n\t\tUser models.User\n\t\tUserLoggedID uint64\n\t}{\n\t\tUser: user,\n\t\tUserLoggedID: userIDLogged,\n\t})\n}", "func (t *SimpleChaincode) Edit(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tvar err error\n\tif len(args) != 2 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 2. \")\n\t}\n\tUserID := args[0]\n\tNewUserInfo := args[1]\n\tOldUserInfo, err := stub.GetState(UserID)\n\n\t//test if the user has been existed\n\tif err != nil {\n\t\treturn nil, errors.New(\"The user never been exited\")\n\t}\n\n\tif OldUserInfo == nil {\n\t\treturn nil, errors.New(\"The user`s information is empty!\")\n\t}\n\n\t// edit the user\n\terr = stub.PutState(UserID, []byte(NewUserInfo))\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to edit the user\")\n\t}\n\n\treturn nil, nil\n}", "func editHandler(w http.ResponseWriter, r *http.Request) {\n\n\tvar page_lst Pages\n\treceive(&page_lst)\n\ttitle := r.URL.Path[len(\"/edit/\"):]\n\tp,_ := find_page(title,page_lst)\n\tif p == nil{\n\t\tp = &Page{Title:title, Body:\"\"}\n\t\tpage_lst.Pages = append(page_lst.Pages, p)\n\t\tsend(&page_lst)\n\t}\n\tpath,_ := os.Getwd()\n\tt,_ := template.ParseFiles(path+\"/edit.html\")\n\tt.Execute(w,p)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LoadUserPasswordEditPage Method to load page to update password
func LoadUserPasswordEditPage(w http.ResponseWriter, r *http.Request) { utils.RunTemplate(w, "update-password.html", nil) }
[ "func LoadUserEditPage(w http.ResponseWriter, r *http.Request) {\n\tcookie, _ := cookies.Read(r)\n\tuserID, _ := strconv.ParseUint(cookie[\"id\"], 10, 64)\n\n\tchannel := make(chan models.User)\n\n\tgo models.GetUserData(channel, userID, r)\n\n\tuser := <-channel\n\tif user.ID == 0 {\n\t\tresponses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: \"Erro ao buscar o usuário\"})\n\t\treturn\n\t}\n\n\tutils.RunTemplate(w, \"edit-profile.html\", user)\n}", "func (h *AuthHandler) RenderUpdatePassword(w http.ResponseWriter, r *http.Request) {\n\tview := NewView(r)\n\tview.Render(w, \"auth/password\")\n}", "func ChangePasswordDisplay(w http.ResponseWriter, r *http.Request) {\n\tauth := service.GetSessionMember(r)\n\ttemplateData := map[string]interface{}{\n\t\t\"title\": \"Change Password\",\n\t\t\"auth\": auth,\n\t}\n\n\ttmpl := template.Must(template.ParseFiles(\"template/admin_members/change_password.tmpl\", setting.UserTemplate))\n\tif err := tmpl.ExecuteTemplate(w, \"base\", templateData); err != nil {\n\t\tLogger.Error(err.Error())\n\t}\n}", "func (controller *UserController) GetEditPage(ctx *fasthttp.RequestCtx) {\n\tcontroller.getProfile(ctx, true)\n}", "func EditPassword(uuid, password string) (err error) {\n\t_, err = db.Exec(\"UPDATE users SET password=? WHERE uuid=?\", password, uuid)\n\treturn\n}", "func UpdatePassword(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\treq := new(putPasswordReq)\n\terrs := binding.Bind(r, req)\n\tif errs.Handle(w) {\n\t\treturn\n\t}\n\tlog.DebugJson(req)\n\tidentity := ps.Get(\"identity\")\n\tcode := cache.GetSet(identity+\":code\", \"\")\n\tif code == \"\" {\n\t\tbase.ForbidErr(w, ExpiredErr)\n\t\treturn\n\t}\n\tif code != req.VerifyCode {\n\t\tbase.ForbidErr(w, CodeMismatchErr)\n\t\treturn\n\t}\n\tuid := dbms.ReadUserIdWithIndex(identity, req.Type)\n\tif uid == 0 {\n\t\tbase.NotFoundErr(w, NotRegisteredErr)\n\t\treturn\n\t}\n\tus := &model.User{\n\t\tId: uid,\n\t\tPassword: base.EncryptedPassword(req.Password),\n\t}\n\tus.Save()\n\tmakeResp(w, r, putPasswordResp{})\n}", "func UserUpdatePassword(id int, n string) {\n\tvar i int\n\ti = GetIndexOfUser(id)\n\tuserList[i].uPassword = n\n}", "func ChangePass(w http.ResponseWriter, r *http.Request) {\n\tusername := r.PostFormValue(\"username\")\n\tpassword1 := r.PostFormValue(\"password1\")\n\tpassword2 := r.PostFormValue(\"password2\")\n\tif password1 != password2 {\n\t\tmessages.SetMessage(r, \"Οι 2 κωδικοί χρήστη δεν ταιριάζουν\")\n\t\thttp.Redirect(w, r, \"/retrieveuser?id=\"+username, http.StatusMovedPermanently)\n\t\treturn\n\t}\n\thash, _ := bcrypt.GenerateFromPassword([]byte(password1), bcrypt.DefaultCost)\n\tstmt := datastorage.GetDataRouter().GetStmt(\"update_password\")\n\t_, err := stmt.Exec(hash, username)\n\tif err != nil {\n\t\tmessages.SetMessage(r, \"Σφάλμα κατά την αλλαγή κωδικού χρήστη\")\n\t\thttp.Redirect(w, r, \"/retrieveuser?id=\"+username, http.StatusMovedPermanently)\n\t\treturn\n\t}\n\tmessages.SetMessage(r, \"Ο κωδικός τροποποιήθηκε επιτυχώς!\")\n\thttp.Redirect(w, r, \"/retrieveuser?id=\"+username, http.StatusMovedPermanently)\n}", "func changePasswordFormHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := context.Background()\n\tsessionInfo := b.sessionEnforcer.EnforceValidSession(ctx, w, r)\n\tif sessionInfo.Authenticated != 1 {\n\t\tlog.Printf(\"changePasswordHandler not authenticated: %d\", sessionInfo.Authenticated)\n\t\thttp.Error(w, \"Not authenticated\", http.StatusForbidden)\n\t\treturn\n\t} else {\n\t\ttitle := b.webConfig.GetVarWithDefault(\"Title\", defTitle)\n\t\tresult := ChangePasswordHTML{\n\t\t\tTitle: title,\n\t\t\tOldPasswordValid: false,\n\t\t\tChangeSuccessful: false,\n\t\t\tShowNewForm: true,\n\t\t}\n\t\tb.pageDisplayer.DisplayPage(w, \"change_password_form.html\", result)\n\t}\n}", "func changePasswordHandler(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"changePasswordHandler enter\")\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.Printf(\"changePasswordHandler authenticator could not be initialized: %v\", err)\n\t\t\thttp.Error(w, \"Server error\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\tsessionInfo := b.sessionEnforcer.EnforceValidSession(ctx, w, r)\n\tif sessionInfo.Authenticated != 1 {\n\t\tlog.Printf(\"changePasswordHandler not authenticated: %d\", sessionInfo.Authenticated)\n\t\thttp.Error(w, \"Not authenticated\", http.StatusForbidden)\n\t\treturn\n\t} else {\n\t\toldPassword := r.PostFormValue(\"OldPassword\")\n\t\tpassword := r.PostFormValue(\"Password\")\n\t\tresult := b.authenticator.ChangePassword(ctx, sessionInfo.User, oldPassword,\n\t\t\tpassword)\n\t\tif strings.Contains(r.Header.Get(\"Accept\"), \"application/json\") {\n\t\t\tsendJSON(w, result)\n\t\t} else {\n\t\t\ttitle := b.webConfig.GetVarWithDefault(\"Title\", defTitle)\n\t\t\tcontent := ChangePasswordHTML{\n\t\t\t\tTitle: title,\n\t\t\t\tOldPasswordValid: result.OldPasswordValid,\n\t\t\t\tChangeSuccessful: result.ChangeSuccessful,\n\t\t\t\tShowNewForm: result.ShowNewForm,\n\t\t\t}\n\t\t\tb.pageDisplayer.DisplayPage(w, \"change_password_form.html\", content)\n\t\t}\n\t}\n}", "func partialUpdatePassword(providedUser *models.User, payload inputs.ProfileInput) error {\n\n\tif payload.OldPassword == \"\" || payload.NewPassword == \"\" {\n\t\treturn nil\n\t}\n\n\tok, err := AuthorizationServices.ComparePasswords(payload.OldPassword, providedUser.Password)\n\tif !ok || err != nil {\n\t\treturn &utils.IncorrectPasswordError{}\n\t}\n\n\thashedPassword, _ := AuthorizationServices.GeneratePassword(payload.NewPassword)\n\n\tprovidedUser.Password = hashedPassword\n\n\treturn nil\n}", "func RandomPasswordPage(c *fiber.Ctx) error {\n\tlogin := c.Params(\"login\")\n\thash := c.Params(\"hash\")\n\t// Just change it, if everything goes okay that is\n\treturn c.Send([]byte(databasepack.RandomPasswordUser(login, hash)))\n}", "func (app *appDB) postChangePwd(w http.ResponseWriter, r *http.Request) {\r\n\t//redirect to main page if there's no session found\r\n\tif !session.Check(w, r) {\r\n\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\r\n\t\treturn\r\n\t}\r\n\r\n\tcp := chgPwdPage{}\r\n\toldPwd := r.FormValue(\"oldPassword\")\r\n\tnewPwd1 := r.FormValue(\"newPassword1\")\r\n\tnewPwd2 := r.FormValue(\"newPassword2\")\r\n\r\n\terr := validateChgPwd(oldPwd, newPwd1, newPwd2)\r\n\tif err != nil {\r\n\t\tcp.Error = err\r\n\t\tlogger.Error.Println(err)\r\n\t\tapp.render(w, chgPwdTemplate, cp)\r\n\t\treturn\r\n\t}\r\n\r\n\tuserID, _ := session.Get(r)\r\n\r\n\t//encrypt new password\r\n\tbPwd, _ := bcrypt.GenerateFromPassword([]byte(newPwd1), bcrypt.MinCost)\r\n\r\n\tdb := data.InitAppDB(app.client, app.mDB, app.env)\r\n\terr = db.UpdateUserPwd(userID, bPwd)\r\n\tif err != nil {\r\n\t\tapp.render(w, chgPwdTemplate, errors.New(\"Unable to process. Please re-login.\"))\r\n\t\treturn\r\n\t}\r\n\r\n\tlogger.Info.Println(\"password updated: \" + userID)\r\n\tapp.postMessage(w, \"Password updated\")\r\n\treturn\r\n}", "func ShowPassword(ctx context.Context, s *testing.State) {\n\tconst PIN = \"123456789012\"\n\tenablePIN := s.Param().(testParams).EnablePIN\n\tautosubmit := s.Param().(testParams).Autosubmit\n\tvar creds chrome.Creds\n\n\t// Log in and log out to create a user pod on the login screen.\n\tfunc() {\n\t\tcr, err := chrome.New(ctx)\n\t\tif err != nil {\n\t\t\ts.Fatal(\"Chrome login failed: \", err)\n\t\t}\n\t\tdefer cr.Close(ctx)\n\t\tcreds = cr.Creds()\n\n\t\ttconn, err := cr.TestAPIConn(ctx)\n\t\tif err != nil {\n\t\t\ts.Fatal(\"Getting test API connection failed: \", err)\n\t\t}\n\t\tdefer faillog.DumpUITreeOnError(ctx, s.OutDir(), s.HasError, tconn)\n\n\t\tif enablePIN {\n\t\t\t// Set up PIN through a connection to the Settings page.\n\t\t\tsettings, err := ossettings.Launch(ctx, tconn)\n\t\t\tif err != nil {\n\t\t\t\ts.Fatal(\"Failed to launch Settings app: \", err)\n\t\t\t}\n\t\t\ts.Log(\"Performing PIN set up\")\n\t\t\tif err := settings.EnablePINUnlock(cr, creds.Pass, PIN, autosubmit)(ctx); err != nil {\n\t\t\t\ts.Fatal(\"Failed to enable PIN unlock: \", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\t// chrome.NoLogin() and chrome.KeepState() are needed to show the login screen with a user pod (instead of the OOBE login screen).\n\tcr, err := chrome.New(ctx,\n\t\tchrome.ExtraArgs(\"--skip-force-online-signin-for-testing\"),\n\t\tchrome.NoLogin(),\n\t\tchrome.KeepState(),\n\t\tchrome.LoadSigninProfileExtension(s.RequiredVar(\"ui.signinProfileTestExtensionManifestKey\")),\n\t)\n\tif err != nil {\n\t\ts.Fatal(\"Failed to start Chrome: \", err)\n\t}\n\tdefer cr.Close(ctx)\n\n\ttconn, err := cr.SigninProfileTestAPIConn(ctx)\n\tif err != nil {\n\t\ts.Fatal(\"Creating login test API connection failed: \", err)\n\t}\n\tdefer faillog.DumpUITreeOnError(ctx, s.OutDir(), s.HasError, tconn)\n\n\t// Wait for the login screen to be ready for PIN / Password entry.\n\tif st, err := lockscreen.WaitState(ctx, tconn, func(st lockscreen.State) bool { return st.ReadyForPassword }, 30*time.Second); err != nil {\n\t\ts.Fatalf(\"Failed waiting for the login screen to be ready for PIN / Password entry: %v, last state: %+v\", err, st)\n\t}\n\n\t// Clicking the \"Switch to password\" button to view the Password field when PIN autosubmit is enabled\n\tif autosubmit {\n\t\tif err := lockscreen.SwitchToPassword(ctx, tconn); err != nil {\n\t\t\ts.Fatal(\"Failed to click the Switch to password button: \", err)\n\t\t}\n\t}\n\n\t// Test the working of \"Show password\" and \"Hide password\" button on login screen.\n\tif enablePIN && !autosubmit {\n\t\tif err := showAndHidePassword(ctx, tconn, creds.User, PIN, true); err != nil {\n\t\t\ts.Fatal(\"Failed to Show/Hide PIN on login screen: \", err)\n\t\t}\n\t} else {\n\t\tif err := showAndHidePassword(ctx, tconn, creds.User, creds.Pass, false); err != nil {\n\t\t\ts.Fatal(\"Failed to Show/Hide Password on login screen: \", err)\n\t\t}\n\t}\n}", "func EditUserNoPassword(ID int, Email, Fname, Lname string, Privileges int) (err error) {\n\t_, err = db.Exec(\"UPDATE users SET email=?, fname=?, lname=?, privilege=? WHERE uuid=?\", Email, Fname, Lname, Privileges, ID)\n\treturn\n}", "func redirectToChangePassword(c *contextmodel.ReqContext) {\n\tc.Redirect(\"/profile/password\", 302)\n}", "func (userController *UserController) GetEditProfilePage(w http.ResponseWriter, r *http.Request) {\n\t// Context for data in view template\n\ttype Context struct {\n\t\tGroups []rolemodule.Grup\n\t\tUser Pengguna\n\t\tUserGroupID int64\n\t\tValidationMessage string\n\t\tCsrfToken string\n\t}\n\n\tvars := mux.Vars(r)\n\n\t// Load edit profile view\n\teditProfileTemplate := userController.Templates.Lookup(\"edit_profile.html\")\n\n\t// Load user id from input type hidden in edit profile\n\tuserID, err := strconv.ParseInt(template.HTMLEscapeString(vars[\"userId\"]), 10, 64)\n\tif err != nil {\n\t\tfmt.Println(\"error when parse user group id\")\n\t}\n\n\t// Get all groups from database\n\tgroups := userController.GroupRepository.GetGroups()\n\n\t// Get user group id by given user id\n\tuserGroupID := userController.GroupRepository.GetUserGroupIDByUserID(userID)\n\n\t// Get user by given user id\n\tuser := userController.UserRepository.GetUserByID(userID)\n\n\t// Save csrf token to session for comparison when form submission\n\tsess := userController.SessionHelper.GetSession(r)\n\tcsrfToken := csrfbanana.Token(w, r, sess)\n\tuserController.SessionHelper.SetCSRFToken(r, w, csrfToken)\n\n\tcontext := Context{\n\t\tGroups: groups,\n\t\tUser: user,\n\t\tUserGroupID: userGroupID,\n\t\tValidationMessage: userController.SessionHelper.GetValidationMessage(r),\n\t\tCsrfToken: csrfToken}\n\n\teditProfileTemplate.Execute(w, context)\n}", "func (app *appDB) getChangePwd(w http.ResponseWriter, r *http.Request) {\r\n\t//redirect to main page if there's no session found\r\n\tif !session.Check(w, r) {\r\n\t\thttp.Redirect(w, r, \"/\", http.StatusSeeOther)\r\n\t\treturn\r\n\t}\r\n\tapp.render(w, chgPwdTemplate, nil)\r\n\treturn\r\n}", "func errorPasswordHandler(w http.ResponseWriter, r *http.Request) {\n\tp := Profile{}\n\trenderTemplate(w, \"loginError\", &p)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ PlaceholdersApiServiceTests Read slide placeholder info. Test for PlaceholdersApi.GetSlidesPlaceholder method
func TestGetSlidesPlaceholder(t *testing.T) { request := createGetSlidesPlaceholderRequest() e := initializeTest("GetSlidesPlaceholder", "", "") if e != nil { t.Errorf("Error: %v.", e) return } c := getTestApiClient() r, _, e := c.PlaceholdersApi.GetSlidesPlaceholder(request) if e != nil { t.Errorf("Error: %v.", e) return } if r.Code != 200 && r.Code != 201 { t.Errorf("Wrong response code: %d.", r.Code) return } }
[ "func TestGetSlidesPlaceholders(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n e := initializeTest(\"GetSlidesPlaceholders\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.PlaceholdersApi.GetSlidesPlaceholders(request)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestGetSlidesPlaceholderInvalidslideIndex(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.slideIndex = invalidizeTestParamValue(request.slideIndex, \"slideIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholder\", \"slideIndex\", request.slideIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"slideIndex\", r.Code, e)\n}", "func TestGetSlidesPlaceholderInvalidplaceholderIndex(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.placeholderIndex = invalidizeTestParamValue(request.placeholderIndex, \"placeholderIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholder\", \"placeholderIndex\", request.placeholderIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"placeholderIndex\", r.Code, e)\n}", "func TestGetSlidesPlaceholdersInvalidslideIndex(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.slideIndex = invalidizeTestParamValue(request.slideIndex, \"slideIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholders\", \"slideIndex\", request.slideIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"slideIndex\", r.Code, e)\n}", "func TestGetSlidesPlaceholderInvalidstorage(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.storage = invalidizeTestParamValue(request.storage, \"storage\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholder\", \"storage\", request.storage)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"storage\", r.Code, e)\n}", "func TestGetSlidesPlaceholdersInvalidstorage(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.storage = invalidizeTestParamValue(request.storage, \"storage\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholders\", \"storage\", request.storage)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"storage\", r.Code, e)\n}", "func GetPlaceHolders(conf *viper.Viper) Placeholders {\n\tlist := parseMap(conf.AllSettings())\n\n\tproperties := CreateProperties(list)\n\n\treturn Placeholders{properties}\n}", "func ImageGetPlaceholder(key data.UUID) (*Image, error) {\n\treturn imageGet(key, false, true)\n}", "func TestGetSlidesPlaceholderInvalidpassword(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholder\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"password\", r.Code, e)\n}", "func TestGetSlidesApiInfo(t *testing.T) {\n e := initializeTest(\"GetSlidesApiInfo\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.DocumentApi.GetSlidesApiInfo()\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func (a *ClinicalMetadataServiceApiService) GetSlide(ctx _context.Context, slideId string) (Ga4ghSlide, *_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 Ga4ghSlide\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/slides/{slide_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"slide_id\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", slideId)), -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\"}\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 Ga4ghSlide\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 TestGetSlidesPlaceholdersInvalidpassword(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholders\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"password\", r.Code, e)\n}", "func TestNotesSlideGetFromStorage(t *testing.T) {\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := c.SlidesApi.GetNotesSlide(fileName, 1, \"password\", folderName, \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(result.GetText()) == 0 {\n\t\tt.Errorf(\"Note text is empty.\")\n\t\treturn\n\t}\n}", "func GetPlaceHolder(count int) string {\n\tif count > 0 {\n\t\tstr := strings.Repeat(\"?, \", count)\n\t\treturn str[:len(str)-2]\n\t}\n\n\treturn \"\"\n}", "func TestNotesSlideExistsFromStorage(t *testing.T) {\n\tfolderName := \"TempSlidesSDK\"\n\tfileName := \"test.pptx\"\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := c.SlidesApi.NotesSlideExists(fileName, 1, \"password\", folderName, \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif !result.GetExists() {\n\t\tt.Errorf(\"Note does not exist.\")\n\t\treturn\n\t}\n}", "func TestSlideCommentsGet(t *testing.T) {\n\tvar slideIndex int32 = 1\n\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresponse, _, e := c.SlidesApi.GetSlideComments(fileName, slideIndex, password, folderName, \"\")\n\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tif len(response.GetList()) != 2 {\n\t\tt.Errorf(\"Expected %v, but was %v\", 2, len(response.GetList()))\n\t\treturn\n\t}\n\n\tif len(response.GetList()[0].GetChildComments()) != 1 {\n\t\tt.Errorf(\"Expected %v, but was %v\", 1, len(response.GetList()[0].GetChildComments()))\n\t\treturn\n\t}\n}", "func TestGetSlidesDocument(t *testing.T) {\n request := createGetSlidesDocumentRequest()\n e := initializeTest(\"GetSlidesDocument\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.DocumentApi.GetSlidesDocument(request)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func (b Bot) InlinePlaceholder() (string, bool) {\n\treturn b.raw.GetBotInlinePlaceholder()\n}", "func TestNotesSlideGetFromRequest(t *testing.T) {\n\tsource, e := ioutil.ReadFile(localTestFile)\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := slidescloud.GetTestApiClient().SlidesApi.GetNotesSlideOnline(source, 1, \"password\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(result.GetText()) == 0 {\n\t\tt.Errorf(\"Note text is empty.\")\n\t\treturn\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ PlaceholdersApiServiceTests Read slide placeholder info. Test for PlaceholdersApi.GetSlidesPlaceholder method with invalid slideIndex
func TestGetSlidesPlaceholderInvalidslideIndex(t *testing.T) { request := createGetSlidesPlaceholderRequest() request.slideIndex = invalidizeTestParamValue(request.slideIndex, "slideIndex", "int32").(int32) e := initializeTest("GetSlidesPlaceholder", "slideIndex", request.slideIndex) if e != nil { t.Errorf("Error: %v.", e) return } r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request) assertError(t, "GetSlidesPlaceholder", "slideIndex", r.Code, e) }
[ "func TestGetSlidesPlaceholderInvalidplaceholderIndex(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.placeholderIndex = invalidizeTestParamValue(request.placeholderIndex, \"placeholderIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholder\", \"placeholderIndex\", request.placeholderIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"placeholderIndex\", r.Code, e)\n}", "func TestGetSlidesPlaceholdersInvalidslideIndex(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.slideIndex = invalidizeTestParamValue(request.slideIndex, \"slideIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholders\", \"slideIndex\", request.slideIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"slideIndex\", r.Code, e)\n}", "func TestGetSlidesPlaceholder(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n e := initializeTest(\"GetSlidesPlaceholder\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.PlaceholdersApi.GetSlidesPlaceholder(request)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestGetSlidesPlaceholders(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n e := initializeTest(\"GetSlidesPlaceholders\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.PlaceholdersApi.GetSlidesPlaceholders(request)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestGetSlidesPlaceholderInvalidstorage(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.storage = invalidizeTestParamValue(request.storage, \"storage\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholder\", \"storage\", request.storage)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"storage\", r.Code, e)\n}", "func TestGetSlidesPlaceholdersInvalidstorage(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.storage = invalidizeTestParamValue(request.storage, \"storage\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholders\", \"storage\", request.storage)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"storage\", r.Code, e)\n}", "func TestGetSlidesPlaceholderInvalidpassword(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholder\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"password\", r.Code, e)\n}", "func ImageGetPlaceholder(key data.UUID) (*Image, error) {\n\treturn imageGet(key, false, true)\n}", "func GetPlaceHolders(conf *viper.Viper) Placeholders {\n\tlist := parseMap(conf.AllSettings())\n\n\tproperties := CreateProperties(list)\n\n\treturn Placeholders{properties}\n}", "func TestGetSlidesPlaceholdersInvalidpassword(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholders\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"password\", r.Code, e)\n}", "func GetPlaceHolder(count int) string {\n\tif count > 0 {\n\t\tstr := strings.Repeat(\"?, \", count)\n\t\treturn str[:len(str)-2]\n\t}\n\n\treturn \"\"\n}", "func TestGetSlidesApiInfo(t *testing.T) {\n e := initializeTest(\"GetSlidesApiInfo\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.DocumentApi.GetSlidesApiInfo()\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func (a *ClinicalMetadataServiceApiService) GetSlide(ctx _context.Context, slideId string) (Ga4ghSlide, *_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 Ga4ghSlide\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/slides/{slide_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"slide_id\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", slideId)), -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\"}\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 Ga4ghSlide\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 TestNotesSlideGetFromStorage(t *testing.T) {\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := c.SlidesApi.GetNotesSlide(fileName, 1, \"password\", folderName, \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(result.GetText()) == 0 {\n\t\tt.Errorf(\"Note text is empty.\")\n\t\treturn\n\t}\n}", "func TestSlideCommentsGet(t *testing.T) {\n\tvar slideIndex int32 = 1\n\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresponse, _, e := c.SlidesApi.GetSlideComments(fileName, slideIndex, password, folderName, \"\")\n\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tif len(response.GetList()) != 2 {\n\t\tt.Errorf(\"Expected %v, but was %v\", 2, len(response.GetList()))\n\t\treturn\n\t}\n\n\tif len(response.GetList()[0].GetChildComments()) != 1 {\n\t\tt.Errorf(\"Expected %v, but was %v\", 1, len(response.GetList()[0].GetChildComments()))\n\t\treturn\n\t}\n}", "func TestNotesSlideExistsFromStorage(t *testing.T) {\n\tfolderName := \"TempSlidesSDK\"\n\tfileName := \"test.pptx\"\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := c.SlidesApi.NotesSlideExists(fileName, 1, \"password\", folderName, \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif !result.GetExists() {\n\t\tt.Errorf(\"Note does not exist.\")\n\t\treturn\n\t}\n}", "func TestGetSlidesDocument(t *testing.T) {\n request := createGetSlidesDocumentRequest()\n e := initializeTest(\"GetSlidesDocument\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.DocumentApi.GetSlidesDocument(request)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func GetSlide(url string) (*Slide, error) {\n\tslug, err := parseSlideURL(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdoc, err := goquery.NewDocument(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdetails := doc.Find(\"#talk-details\")\n\n\tsidebar := doc.Find(\".sidebar\")\n\ta := sidebar.Find(\"h2 a\")\n\tuser := NewUser(a.AttrOr(\"href\", \"\")[1:], a.Text())\n\n\tcat := sidebar.Find(\".category a\")\n\tcategory := NewCategory(cat.Text(), strings.Split(cat.AttrOr(\"href\", \"\"), \"/\")[2])\n\n\tstars, err := strconv.Atoi(strings.Split(sidebar.Find(\".stargazers\").Text(), \" \")[0])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpublished, err := time.Parse(\"January 2, 2006\", details.Find(\"header mark\").First().Text())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Slide{\n\t\tSlug: slug,\n\t\tTitle: details.Find(\"h1\").Text(),\n\t\tDescription: strings.TrimSpace(details.Find(\".description\").Text()),\n\t\tPublished: published,\n\t\tDownloadURL: doc.Find(\"#share_pdf\").AttrOr(\"href\", \"\"),\n\t\tUser: user,\n\t\tCategory: category,\n\t\tStars: stars,\n\t\tURL: user.URL + \"/\" + slug,\n\t}, nil\n}", "func (r *repo) DescribeSlide(ctx context.Context, slideID uint64) (*model.Slide, error) {\n\tquery := squirrel.Select(\n\t\t\"id\",\n\t\t\"presentation_id\",\n\t\t\"number\",\n\t\t\"type\",\n\t).\n\t\tFrom(tableName).\n\t\tWhere(squirrel.Eq{\"id\": slideID}).\n\t\tRunWith(r.db).\n\t\tPlaceholderFormat(squirrel.Dollar)\n\n\trows, err := query.QueryContext(ctx)\n\tif err != nil {\n\t\tif errors.Is(err, sql.ErrNoRows) {\n\t\t\treturn nil, ErrSlideNotFound\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\tif err = rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar slides []model.Slide\n\tfor rows.Next() {\n\t\tvar slide model.Slide\n\t\tif err = rows.Scan(\n\t\t\t&slide.ID,\n\t\t\t&slide.PresentationID,\n\t\t\t&slide.Number,\n\t\t\t&slide.Type); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tslides = append(slides, slide)\n\t}\n\n\tif len(slides) == 0 {\n\t\treturn nil, ErrUnknown\n\t}\n\n\treturn &slides[0], nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ PlaceholdersApiServiceTests Read slide placeholder info. Test for PlaceholdersApi.GetSlidesPlaceholder method with invalid placeholderIndex
func TestGetSlidesPlaceholderInvalidplaceholderIndex(t *testing.T) { request := createGetSlidesPlaceholderRequest() request.placeholderIndex = invalidizeTestParamValue(request.placeholderIndex, "placeholderIndex", "int32").(int32) e := initializeTest("GetSlidesPlaceholder", "placeholderIndex", request.placeholderIndex) if e != nil { t.Errorf("Error: %v.", e) return } r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request) assertError(t, "GetSlidesPlaceholder", "placeholderIndex", r.Code, e) }
[ "func TestGetSlidesPlaceholder(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n e := initializeTest(\"GetSlidesPlaceholder\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.PlaceholdersApi.GetSlidesPlaceholder(request)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestGetSlidesPlaceholderInvalidslideIndex(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.slideIndex = invalidizeTestParamValue(request.slideIndex, \"slideIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholder\", \"slideIndex\", request.slideIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"slideIndex\", r.Code, e)\n}", "func TestGetSlidesPlaceholdersInvalidslideIndex(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.slideIndex = invalidizeTestParamValue(request.slideIndex, \"slideIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholders\", \"slideIndex\", request.slideIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"slideIndex\", r.Code, e)\n}", "func TestGetSlidesPlaceholders(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n e := initializeTest(\"GetSlidesPlaceholders\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.PlaceholdersApi.GetSlidesPlaceholders(request)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestGetSlidesPlaceholderInvalidstorage(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.storage = invalidizeTestParamValue(request.storage, \"storage\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholder\", \"storage\", request.storage)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"storage\", r.Code, e)\n}", "func TestGetSlidesPlaceholdersInvalidstorage(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.storage = invalidizeTestParamValue(request.storage, \"storage\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholders\", \"storage\", request.storage)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"storage\", r.Code, e)\n}", "func GetPlaceHolders(conf *viper.Viper) Placeholders {\n\tlist := parseMap(conf.AllSettings())\n\n\tproperties := CreateProperties(list)\n\n\treturn Placeholders{properties}\n}", "func ImageGetPlaceholder(key data.UUID) (*Image, error) {\n\treturn imageGet(key, false, true)\n}", "func TestGetSlidesPlaceholderInvalidpassword(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholder\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"password\", r.Code, e)\n}", "func TestGetSlidesPlaceholdersInvalidpassword(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholders\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"password\", r.Code, e)\n}", "func GetPlaceHolder(count int) string {\n\tif count > 0 {\n\t\tstr := strings.Repeat(\"?, \", count)\n\t\treturn str[:len(str)-2]\n\t}\n\n\treturn \"\"\n}", "func TestGetSlidesApiInfo(t *testing.T) {\n e := initializeTest(\"GetSlidesApiInfo\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.DocumentApi.GetSlidesApiInfo()\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestNotesSlideGetFromStorage(t *testing.T) {\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := c.SlidesApi.GetNotesSlide(fileName, 1, \"password\", folderName, \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(result.GetText()) == 0 {\n\t\tt.Errorf(\"Note text is empty.\")\n\t\treturn\n\t}\n}", "func (a *ClinicalMetadataServiceApiService) GetSlide(ctx _context.Context, slideId string) (Ga4ghSlide, *_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 Ga4ghSlide\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/slides/{slide_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"slide_id\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", slideId)), -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\"}\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 Ga4ghSlide\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 (ref *UIElement) PlaceholderValue() string {\n\tret, _ := ref.StringAttr(PlaceholderValueAttribute)\n\treturn ret\n}", "func TestSlideCommentsGet(t *testing.T) {\n\tvar slideIndex int32 = 1\n\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresponse, _, e := c.SlidesApi.GetSlideComments(fileName, slideIndex, password, folderName, \"\")\n\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tif len(response.GetList()) != 2 {\n\t\tt.Errorf(\"Expected %v, but was %v\", 2, len(response.GetList()))\n\t\treturn\n\t}\n\n\tif len(response.GetList()[0].GetChildComments()) != 1 {\n\t\tt.Errorf(\"Expected %v, but was %v\", 1, len(response.GetList()[0].GetChildComments()))\n\t\treturn\n\t}\n}", "func TestNotesSlideExistsFromStorage(t *testing.T) {\n\tfolderName := \"TempSlidesSDK\"\n\tfileName := \"test.pptx\"\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := c.SlidesApi.NotesSlideExists(fileName, 1, \"password\", folderName, \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif !result.GetExists() {\n\t\tt.Errorf(\"Note does not exist.\")\n\t\treturn\n\t}\n}", "func (b Bot) InlinePlaceholder() (string, bool) {\n\treturn b.raw.GetBotInlinePlaceholder()\n}", "func IsPlaceholder(key string) bool {\n\treturn len(key) > 4 && key[0:2] == \"((\" && key[len(key)-2:] == \"))\"\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ PlaceholdersApiServiceTests Read slide placeholder info. Test for PlaceholdersApi.GetSlidesPlaceholder method with invalid password
func TestGetSlidesPlaceholderInvalidpassword(t *testing.T) { request := createGetSlidesPlaceholderRequest() request.password = invalidizeTestParamValue(request.password, "password", "string").(string) e := initializeTest("GetSlidesPlaceholder", "password", request.password) if e != nil { t.Errorf("Error: %v.", e) return } r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request) assertError(t, "GetSlidesPlaceholder", "password", r.Code, e) }
[ "func TestGetSlidesPlaceholder(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n e := initializeTest(\"GetSlidesPlaceholder\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.PlaceholdersApi.GetSlidesPlaceholder(request)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestGetSlidesPlaceholdersInvalidpassword(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholders\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"password\", r.Code, e)\n}", "func TestGetSlidesPlaceholders(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n e := initializeTest(\"GetSlidesPlaceholders\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.PlaceholdersApi.GetSlidesPlaceholders(request)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestGetSlidesPlaceholderInvalidslideIndex(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.slideIndex = invalidizeTestParamValue(request.slideIndex, \"slideIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholder\", \"slideIndex\", request.slideIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"slideIndex\", r.Code, e)\n}", "func TestGetSlidesPlaceholderInvalidplaceholderIndex(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.placeholderIndex = invalidizeTestParamValue(request.placeholderIndex, \"placeholderIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholder\", \"placeholderIndex\", request.placeholderIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"placeholderIndex\", r.Code, e)\n}", "func TestGetSlidesPlaceholderInvalidstorage(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.storage = invalidizeTestParamValue(request.storage, \"storage\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholder\", \"storage\", request.storage)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"storage\", r.Code, e)\n}", "func TestGetSlidesPlaceholdersInvalidstorage(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.storage = invalidizeTestParamValue(request.storage, \"storage\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholders\", \"storage\", request.storage)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"storage\", r.Code, e)\n}", "func TestGetSlidesPlaceholdersInvalidslideIndex(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.slideIndex = invalidizeTestParamValue(request.slideIndex, \"slideIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholders\", \"slideIndex\", request.slideIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"slideIndex\", r.Code, e)\n}", "func TestGetSlidesDocumentWithFormatInvalidpassword(t *testing.T) {\n request := createGetSlidesDocumentWithFormatRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"GetSlidesDocumentWithFormat\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n _, r, e := getTestApiClient().DocumentApi.GetSlidesDocumentWithFormat(request)\n assertError(t, \"GetSlidesDocumentWithFormat\", \"password\", int32(r.StatusCode), e)\n}", "func ImageGetPlaceholder(key data.UUID) (*Image, error) {\n\treturn imageGet(key, false, true)\n}", "func GetPlaceHolders(conf *viper.Viper) Placeholders {\n\tlist := parseMap(conf.AllSettings())\n\n\tproperties := CreateProperties(list)\n\n\treturn Placeholders{properties}\n}", "func TestPutSlidesDocumentFromHtmlInvalidpassword(t *testing.T) {\n request := createPutSlidesDocumentFromHtmlRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"PutSlidesDocumentFromHtml\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().DocumentApi.PutSlidesDocumentFromHtml(request)\n assertError(t, \"PutSlidesDocumentFromHtml\", \"password\", r.Code, e)\n}", "func TestNotesSlideGetFromStorage(t *testing.T) {\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := c.SlidesApi.GetNotesSlide(fileName, 1, \"password\", folderName, \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(result.GetText()) == 0 {\n\t\tt.Errorf(\"Note text is empty.\")\n\t\treturn\n\t}\n}", "func TestGetSlidesApiInfo(t *testing.T) {\n e := initializeTest(\"GetSlidesApiInfo\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.DocumentApi.GetSlidesApiInfo()\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestPostSlidesDocumentInvalidpassword(t *testing.T) {\n request := createPostSlidesDocumentRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"PostSlidesDocument\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().DocumentApi.PostSlidesDocument(request)\n assertError(t, \"PostSlidesDocument\", \"password\", r.Code, e)\n}", "func TestPutNewPresentationInvalidpassword(t *testing.T) {\n request := createPutNewPresentationRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"PutNewPresentation\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().DocumentApi.PutNewPresentation(request)\n assertError(t, \"PutNewPresentation\", \"password\", r.Code, e)\n}", "func TestPostSlidesSaveAsInvalidpassword(t *testing.T) {\n request := createPostSlidesSaveAsRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"PostSlidesSaveAs\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n _, r, e := getTestApiClient().DocumentApi.PostSlidesSaveAs(request)\n assertError(t, \"PostSlidesSaveAs\", \"password\", int32(r.StatusCode), e)\n}", "func privateDataPlaceholder() string {\n\treturn \"[PRIVATE DATA HIDDEN]\"\n}", "func TestNotesSlideGetFromRequest(t *testing.T) {\n\tsource, e := ioutil.ReadFile(localTestFile)\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := slidescloud.GetTestApiClient().SlidesApi.GetNotesSlideOnline(source, 1, \"password\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(result.GetText()) == 0 {\n\t\tt.Errorf(\"Note text is empty.\")\n\t\treturn\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ PlaceholdersApiServiceTests Read slide placeholder info. Test for PlaceholdersApi.GetSlidesPlaceholder method with invalid storage
func TestGetSlidesPlaceholderInvalidstorage(t *testing.T) { request := createGetSlidesPlaceholderRequest() request.storage = invalidizeTestParamValue(request.storage, "storage", "string").(string) e := initializeTest("GetSlidesPlaceholder", "storage", request.storage) if e != nil { t.Errorf("Error: %v.", e) return } r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request) assertError(t, "GetSlidesPlaceholder", "storage", r.Code, e) }
[ "func TestGetSlidesPlaceholder(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n e := initializeTest(\"GetSlidesPlaceholder\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.PlaceholdersApi.GetSlidesPlaceholder(request)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestGetSlidesPlaceholdersInvalidstorage(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.storage = invalidizeTestParamValue(request.storage, \"storage\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholders\", \"storage\", request.storage)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"storage\", r.Code, e)\n}", "func TestGetSlidesPlaceholders(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n e := initializeTest(\"GetSlidesPlaceholders\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.PlaceholdersApi.GetSlidesPlaceholders(request)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestGetSlidesPlaceholderInvalidslideIndex(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.slideIndex = invalidizeTestParamValue(request.slideIndex, \"slideIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholder\", \"slideIndex\", request.slideIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"slideIndex\", r.Code, e)\n}", "func TestGetSlidesPlaceholderInvalidplaceholderIndex(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.placeholderIndex = invalidizeTestParamValue(request.placeholderIndex, \"placeholderIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholder\", \"placeholderIndex\", request.placeholderIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"placeholderIndex\", r.Code, e)\n}", "func TestGetSlidesPlaceholdersInvalidslideIndex(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.slideIndex = invalidizeTestParamValue(request.slideIndex, \"slideIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholders\", \"slideIndex\", request.slideIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"slideIndex\", r.Code, e)\n}", "func ImageGetPlaceholder(key data.UUID) (*Image, error) {\n\treturn imageGet(key, false, true)\n}", "func TestNotesSlideGetFromStorage(t *testing.T) {\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := c.SlidesApi.GetNotesSlide(fileName, 1, \"password\", folderName, \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(result.GetText()) == 0 {\n\t\tt.Errorf(\"Note text is empty.\")\n\t\treturn\n\t}\n}", "func GetPlaceHolders(conf *viper.Viper) Placeholders {\n\tlist := parseMap(conf.AllSettings())\n\n\tproperties := CreateProperties(list)\n\n\treturn Placeholders{properties}\n}", "func TestGetSlidesPlaceholderInvalidpassword(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholder\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"password\", r.Code, e)\n}", "func TestNotesSlideExistsFromStorage(t *testing.T) {\n\tfolderName := \"TempSlidesSDK\"\n\tfileName := \"test.pptx\"\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := c.SlidesApi.NotesSlideExists(fileName, 1, \"password\", folderName, \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif !result.GetExists() {\n\t\tt.Errorf(\"Note does not exist.\")\n\t\treturn\n\t}\n}", "func TestGetSlidesPlaceholdersInvalidpassword(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholders\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"password\", r.Code, e)\n}", "func GetPlaceHolder(count int) string {\n\tif count > 0 {\n\t\tstr := strings.Repeat(\"?, \", count)\n\t\treturn str[:len(str)-2]\n\t}\n\n\treturn \"\"\n}", "func (a *ClinicalMetadataServiceApiService) GetSlide(ctx _context.Context, slideId string) (Ga4ghSlide, *_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 Ga4ghSlide\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/slides/{slide_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"slide_id\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", slideId)), -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\"}\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 Ga4ghSlide\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 TestGetSlidesApiInfo(t *testing.T) {\n e := initializeTest(\"GetSlidesApiInfo\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.DocumentApi.GetSlidesApiInfo()\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestNotesSlideDownloadFromStorage(t *testing.T) {\n\tfolderName := \"TempSlidesSDK\"\n\tfileName := \"test.pptx\"\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\t_, _, e = c.SlidesApi.DownloadNotesSlide(fileName, 1, \"png\", nil, nil, \"password\", folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n}", "func TestPostSlidesSplitInvalidstorage(t *testing.T) {\n request := createPostSlidesSplitRequest()\n request.storage = invalidizeTestParamValue(request.storage, \"storage\", \"string\").(string)\n e := initializeTest(\"PostSlidesSplit\", \"storage\", request.storage)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().DocumentApi.PostSlidesSplit(request)\n assertError(t, \"PostSlidesSplit\", \"storage\", r.Code, e)\n}", "func NeedPlaceholder(t string) bool {\n\tswitch t {\n\tcase SecretVariable, KeyVariable, SSHKeyVariable, PGPKeyVariable:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (d *ceph) getPlaceholderVolume() Volume {\n\treturn NewVolume(d, d.name, VolumeType(\"incus\"), ContentTypeFS, d.config[\"ceph.osd.pool_name\"], nil, nil)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ PlaceholdersApiServiceTests Read slide placeholders info. Test for PlaceholdersApi.GetSlidesPlaceholders method
func TestGetSlidesPlaceholders(t *testing.T) { request := createGetSlidesPlaceholdersRequest() e := initializeTest("GetSlidesPlaceholders", "", "") if e != nil { t.Errorf("Error: %v.", e) return } c := getTestApiClient() r, _, e := c.PlaceholdersApi.GetSlidesPlaceholders(request) if e != nil { t.Errorf("Error: %v.", e) return } if r.Code != 200 && r.Code != 201 { t.Errorf("Wrong response code: %d.", r.Code) return } }
[ "func TestGetSlidesPlaceholder(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n e := initializeTest(\"GetSlidesPlaceholder\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.PlaceholdersApi.GetSlidesPlaceholder(request)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestGetSlidesPlaceholderInvalidslideIndex(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.slideIndex = invalidizeTestParamValue(request.slideIndex, \"slideIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholder\", \"slideIndex\", request.slideIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"slideIndex\", r.Code, e)\n}", "func TestGetSlidesPlaceholdersInvalidslideIndex(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.slideIndex = invalidizeTestParamValue(request.slideIndex, \"slideIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholders\", \"slideIndex\", request.slideIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"slideIndex\", r.Code, e)\n}", "func TestGetSlidesPlaceholderInvalidplaceholderIndex(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.placeholderIndex = invalidizeTestParamValue(request.placeholderIndex, \"placeholderIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholder\", \"placeholderIndex\", request.placeholderIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"placeholderIndex\", r.Code, e)\n}", "func GetPlaceHolders(conf *viper.Viper) Placeholders {\n\tlist := parseMap(conf.AllSettings())\n\n\tproperties := CreateProperties(list)\n\n\treturn Placeholders{properties}\n}", "func TestGetSlidesPlaceholdersInvalidstorage(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.storage = invalidizeTestParamValue(request.storage, \"storage\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholders\", \"storage\", request.storage)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"storage\", r.Code, e)\n}", "func TestGetSlidesPlaceholderInvalidstorage(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.storage = invalidizeTestParamValue(request.storage, \"storage\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholder\", \"storage\", request.storage)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"storage\", r.Code, e)\n}", "func TestGetSlidesPlaceholderInvalidpassword(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholder\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"password\", r.Code, e)\n}", "func TestGetSlidesPlaceholdersInvalidpassword(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholders\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"password\", r.Code, e)\n}", "func ImageGetPlaceholder(key data.UUID) (*Image, error) {\n\treturn imageGet(key, false, true)\n}", "func TestGetSlidesApiInfo(t *testing.T) {\n e := initializeTest(\"GetSlidesApiInfo\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.DocumentApi.GetSlidesApiInfo()\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestNotesSlideGetFromStorage(t *testing.T) {\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := c.SlidesApi.GetNotesSlide(fileName, 1, \"password\", folderName, \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(result.GetText()) == 0 {\n\t\tt.Errorf(\"Note text is empty.\")\n\t\treturn\n\t}\n}", "func (a *ClinicalMetadataServiceApiService) GetSlide(ctx _context.Context, slideId string) (Ga4ghSlide, *_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 Ga4ghSlide\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/slides/{slide_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"slide_id\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", slideId)), -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\"}\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 Ga4ghSlide\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 TestNotesSlideExistsFromStorage(t *testing.T) {\n\tfolderName := \"TempSlidesSDK\"\n\tfileName := \"test.pptx\"\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := c.SlidesApi.NotesSlideExists(fileName, 1, \"password\", folderName, \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif !result.GetExists() {\n\t\tt.Errorf(\"Note does not exist.\")\n\t\treturn\n\t}\n}", "func TestSlideCommentsGet(t *testing.T) {\n\tvar slideIndex int32 = 1\n\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresponse, _, e := c.SlidesApi.GetSlideComments(fileName, slideIndex, password, folderName, \"\")\n\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tif len(response.GetList()) != 2 {\n\t\tt.Errorf(\"Expected %v, but was %v\", 2, len(response.GetList()))\n\t\treturn\n\t}\n\n\tif len(response.GetList()[0].GetChildComments()) != 1 {\n\t\tt.Errorf(\"Expected %v, but was %v\", 1, len(response.GetList()[0].GetChildComments()))\n\t\treturn\n\t}\n}", "func GetPlaceHolder(count int) string {\n\tif count > 0 {\n\t\tstr := strings.Repeat(\"?, \", count)\n\t\treturn str[:len(str)-2]\n\t}\n\n\treturn \"\"\n}", "func TestNotesSlideGetFromRequest(t *testing.T) {\n\tsource, e := ioutil.ReadFile(localTestFile)\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := slidescloud.GetTestApiClient().SlidesApi.GetNotesSlideOnline(source, 1, \"password\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(result.GetText()) == 0 {\n\t\tt.Errorf(\"Note text is empty.\")\n\t\treturn\n\t}\n}", "func TestNotesSlideParagraphs(t *testing.T) {\n\tvar slideIndex int32 = 1\n\tvar shapeIndex int32 = 2\n\tvar paragraphCount int32 = 1\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tparagraphs, _, e := c.SlidesApi.GetSpecialSlideParagraphs(fileName, slideIndex, \"notesSlide\", shapeIndex, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(paragraphs.GetParagraphLinks()) != int(paragraphCount) {\n\t\tt.Errorf(\"Wrong paragraph count. Expected %v but was %v.\", paragraphCount, len(paragraphs.GetParagraphLinks()))\n\t\treturn\n\t}\n\n\tportion := slidescloud.NewPortion()\n\tportion.Text = \"New Paragraph\"\n\tdto := slidescloud.NewParagraph()\n\tdto.Alignment = \"Right\"\n\tdto.PortionList = []slidescloud.IPortion{portion}\n\tparagraph, _, e := c.SlidesApi.CreateSpecialSlideParagraph(fileName, slideIndex, \"notesSlide\", shapeIndex, dto, nil, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif paragraph.GetAlignment() != dto.GetAlignment() {\n\t\tt.Errorf(\"Wrong paragraph alignment. Expected %v but was %v.\", dto.GetAlignment(), paragraph.GetAlignment())\n\t\treturn\n\t}\n\tparagraphs, _, e = c.SlidesApi.GetSpecialSlideParagraphs(fileName, slideIndex, \"notesSlide\", shapeIndex, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(paragraphs.GetParagraphLinks()) != int(paragraphCount)+1 {\n\t\tt.Errorf(\"Wrong paragraph count. Expected %v but was %v.\", paragraphCount, len(paragraphs.GetParagraphLinks())+1)\n\t\treturn\n\t}\n\n\tdto = slidescloud.NewParagraph()\n\tdto.Alignment = \"Center\"\n\tparagraph, _, e = c.SlidesApi.UpdateSpecialSlideParagraph(fileName, slideIndex, \"notesSlide\", shapeIndex, paragraphCount+1, dto, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif paragraph.GetAlignment() != dto.GetAlignment() {\n\t\tt.Errorf(\"Wrong paragraph alignment. Expected %v but was %v.\", dto.GetAlignment(), paragraph.GetAlignment())\n\t\treturn\n\t}\n\tparagraphs, _, e = c.SlidesApi.GetSpecialSlideParagraphs(fileName, slideIndex, \"notesSlide\", shapeIndex, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(paragraphs.GetParagraphLinks()) != int(paragraphCount)+1 {\n\t\tt.Errorf(\"Wrong paragraph count. Expected %v but was %v.\", paragraphCount, len(paragraphs.GetParagraphLinks())+1)\n\t\treturn\n\t}\n\n\t_, _, e = c.SlidesApi.DeleteSpecialSlideParagraph(fileName, slideIndex, \"notesSlide\", shapeIndex, paragraphCount+1, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tparagraphs, _, e = c.SlidesApi.GetSpecialSlideParagraphs(fileName, slideIndex, \"notesSlide\", shapeIndex, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(paragraphs.GetParagraphLinks()) != int(paragraphCount) {\n\t\tt.Errorf(\"Wrong paragraph count. Expected %v but was %v.\", paragraphCount, len(paragraphs.GetParagraphLinks()))\n\t\treturn\n\t}\n}", "func TestGetSlidesDocument(t *testing.T) {\n request := createGetSlidesDocumentRequest()\n e := initializeTest(\"GetSlidesDocument\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.DocumentApi.GetSlidesDocument(request)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ PlaceholdersApiServiceTests Read slide placeholders info. Test for PlaceholdersApi.GetSlidesPlaceholders method with invalid slideIndex
func TestGetSlidesPlaceholdersInvalidslideIndex(t *testing.T) { request := createGetSlidesPlaceholdersRequest() request.slideIndex = invalidizeTestParamValue(request.slideIndex, "slideIndex", "int32").(int32) e := initializeTest("GetSlidesPlaceholders", "slideIndex", request.slideIndex) if e != nil { t.Errorf("Error: %v.", e) return } r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request) assertError(t, "GetSlidesPlaceholders", "slideIndex", r.Code, e) }
[ "func TestGetSlidesPlaceholderInvalidslideIndex(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.slideIndex = invalidizeTestParamValue(request.slideIndex, \"slideIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholder\", \"slideIndex\", request.slideIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"slideIndex\", r.Code, e)\n}", "func TestGetSlidesPlaceholderInvalidplaceholderIndex(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.placeholderIndex = invalidizeTestParamValue(request.placeholderIndex, \"placeholderIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholder\", \"placeholderIndex\", request.placeholderIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"placeholderIndex\", r.Code, e)\n}", "func TestGetSlidesPlaceholder(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n e := initializeTest(\"GetSlidesPlaceholder\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.PlaceholdersApi.GetSlidesPlaceholder(request)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestGetSlidesPlaceholders(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n e := initializeTest(\"GetSlidesPlaceholders\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.PlaceholdersApi.GetSlidesPlaceholders(request)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestGetSlidesPlaceholdersInvalidstorage(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.storage = invalidizeTestParamValue(request.storage, \"storage\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholders\", \"storage\", request.storage)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"storage\", r.Code, e)\n}", "func TestGetSlidesPlaceholderInvalidstorage(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.storage = invalidizeTestParamValue(request.storage, \"storage\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholder\", \"storage\", request.storage)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"storage\", r.Code, e)\n}", "func GetPlaceHolders(conf *viper.Viper) Placeholders {\n\tlist := parseMap(conf.AllSettings())\n\n\tproperties := CreateProperties(list)\n\n\treturn Placeholders{properties}\n}", "func TestGetSlidesPlaceholderInvalidpassword(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholder\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"password\", r.Code, e)\n}", "func TestGetSlidesPlaceholdersInvalidpassword(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholders\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"password\", r.Code, e)\n}", "func TestGetSlidesApiInfo(t *testing.T) {\n e := initializeTest(\"GetSlidesApiInfo\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.DocumentApi.GetSlidesApiInfo()\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func GetPlaceHolder(count int) string {\n\tif count > 0 {\n\t\tstr := strings.Repeat(\"?, \", count)\n\t\treturn str[:len(str)-2]\n\t}\n\n\treturn \"\"\n}", "func ImageGetPlaceholder(key data.UUID) (*Image, error) {\n\treturn imageGet(key, false, true)\n}", "func TestNotesSlideGetFromStorage(t *testing.T) {\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := c.SlidesApi.GetNotesSlide(fileName, 1, \"password\", folderName, \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(result.GetText()) == 0 {\n\t\tt.Errorf(\"Note text is empty.\")\n\t\treturn\n\t}\n}", "func (a *ClinicalMetadataServiceApiService) GetSlide(ctx _context.Context, slideId string) (Ga4ghSlide, *_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 Ga4ghSlide\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/slides/{slide_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"slide_id\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", slideId)), -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\"}\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 Ga4ghSlide\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 TestSlideCommentsGet(t *testing.T) {\n\tvar slideIndex int32 = 1\n\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresponse, _, e := c.SlidesApi.GetSlideComments(fileName, slideIndex, password, folderName, \"\")\n\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tif len(response.GetList()) != 2 {\n\t\tt.Errorf(\"Expected %v, but was %v\", 2, len(response.GetList()))\n\t\treturn\n\t}\n\n\tif len(response.GetList()[0].GetChildComments()) != 1 {\n\t\tt.Errorf(\"Expected %v, but was %v\", 1, len(response.GetList()[0].GetChildComments()))\n\t\treturn\n\t}\n}", "func TestNotesSlideExistsFromStorage(t *testing.T) {\n\tfolderName := \"TempSlidesSDK\"\n\tfileName := \"test.pptx\"\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := c.SlidesApi.NotesSlideExists(fileName, 1, \"password\", folderName, \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif !result.GetExists() {\n\t\tt.Errorf(\"Note does not exist.\")\n\t\treturn\n\t}\n}", "func TestNotesSlideParagraphs(t *testing.T) {\n\tvar slideIndex int32 = 1\n\tvar shapeIndex int32 = 2\n\tvar paragraphCount int32 = 1\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tparagraphs, _, e := c.SlidesApi.GetSpecialSlideParagraphs(fileName, slideIndex, \"notesSlide\", shapeIndex, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(paragraphs.GetParagraphLinks()) != int(paragraphCount) {\n\t\tt.Errorf(\"Wrong paragraph count. Expected %v but was %v.\", paragraphCount, len(paragraphs.GetParagraphLinks()))\n\t\treturn\n\t}\n\n\tportion := slidescloud.NewPortion()\n\tportion.Text = \"New Paragraph\"\n\tdto := slidescloud.NewParagraph()\n\tdto.Alignment = \"Right\"\n\tdto.PortionList = []slidescloud.IPortion{portion}\n\tparagraph, _, e := c.SlidesApi.CreateSpecialSlideParagraph(fileName, slideIndex, \"notesSlide\", shapeIndex, dto, nil, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif paragraph.GetAlignment() != dto.GetAlignment() {\n\t\tt.Errorf(\"Wrong paragraph alignment. Expected %v but was %v.\", dto.GetAlignment(), paragraph.GetAlignment())\n\t\treturn\n\t}\n\tparagraphs, _, e = c.SlidesApi.GetSpecialSlideParagraphs(fileName, slideIndex, \"notesSlide\", shapeIndex, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(paragraphs.GetParagraphLinks()) != int(paragraphCount)+1 {\n\t\tt.Errorf(\"Wrong paragraph count. Expected %v but was %v.\", paragraphCount, len(paragraphs.GetParagraphLinks())+1)\n\t\treturn\n\t}\n\n\tdto = slidescloud.NewParagraph()\n\tdto.Alignment = \"Center\"\n\tparagraph, _, e = c.SlidesApi.UpdateSpecialSlideParagraph(fileName, slideIndex, \"notesSlide\", shapeIndex, paragraphCount+1, dto, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif paragraph.GetAlignment() != dto.GetAlignment() {\n\t\tt.Errorf(\"Wrong paragraph alignment. Expected %v but was %v.\", dto.GetAlignment(), paragraph.GetAlignment())\n\t\treturn\n\t}\n\tparagraphs, _, e = c.SlidesApi.GetSpecialSlideParagraphs(fileName, slideIndex, \"notesSlide\", shapeIndex, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(paragraphs.GetParagraphLinks()) != int(paragraphCount)+1 {\n\t\tt.Errorf(\"Wrong paragraph count. Expected %v but was %v.\", paragraphCount, len(paragraphs.GetParagraphLinks())+1)\n\t\treturn\n\t}\n\n\t_, _, e = c.SlidesApi.DeleteSpecialSlideParagraph(fileName, slideIndex, \"notesSlide\", shapeIndex, paragraphCount+1, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tparagraphs, _, e = c.SlidesApi.GetSpecialSlideParagraphs(fileName, slideIndex, \"notesSlide\", shapeIndex, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(paragraphs.GetParagraphLinks()) != int(paragraphCount) {\n\t\tt.Errorf(\"Wrong paragraph count. Expected %v but was %v.\", paragraphCount, len(paragraphs.GetParagraphLinks()))\n\t\treturn\n\t}\n}", "func TestNotesSlidePortions(t *testing.T) {\n\tvar slideIndex int32 = 1\n\tvar shapeIndex int32 = 2\n\tvar paragraphIndex int32 = 1\n\tvar portionCount int32 = 1\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tportions, _, e := c.SlidesApi.GetSpecialSlidePortions(fileName, slideIndex, \"notesSlide\", shapeIndex, paragraphIndex, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(portions.GetItems()) != int(portionCount) {\n\t\tt.Errorf(\"Wrong portion count. Expected %v but was %v.\", portionCount, len(portions.GetItems()))\n\t\treturn\n\t}\n\n\tdto := slidescloud.NewPortion()\n\tdto.Text = \"New portion\"\n\tdto.FontBold = \"True\"\n\tportion, _, e := c.SlidesApi.CreateSpecialSlidePortion(fileName, slideIndex, \"notesSlide\", shapeIndex, paragraphIndex, dto, nil, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif portion.GetFontBold() != dto.GetFontBold() {\n\t\tt.Errorf(\"Wrong portion font bold. Expected %v but was %v.\", dto.GetFontBold(), portion.GetFontBold())\n\t\treturn\n\t}\n\tif portion.GetText() != dto.GetText() {\n\t\tt.Errorf(\"Wrong portion text. Expected %v but was %v.\", dto.GetText(), portion.GetText())\n\t\treturn\n\t}\n\tportions, _, e = c.SlidesApi.GetSpecialSlidePortions(fileName, slideIndex, \"notesSlide\", shapeIndex, paragraphIndex, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(portions.GetItems()) != int(portionCount)+1 {\n\t\tt.Errorf(\"Wrong portion count. Expected %v but was %v.\", portionCount, len(portions.GetItems())+1)\n\t\treturn\n\t}\n\n\tdto2 := slidescloud.NewPortion()\n\tdto2.Text = \"Updated portion\"\n\tdto2.FontHeight = 22\n\tportion, _, e = c.SlidesApi.UpdateSpecialSlidePortion(fileName, slideIndex, \"notesSlide\", shapeIndex, paragraphIndex, portionCount+1, dto2, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif portion.GetFontBold() != dto.GetFontBold() {\n\t\tt.Errorf(\"Wrong portion font bold. Expected %v but was %v.\", dto.GetFontBold(), portion.GetFontBold())\n\t\treturn\n\t}\n\tif portion.GetFontHeight() != dto2.GetFontHeight() {\n\t\tt.Errorf(\"Wrong portion font height. Expected %v but was %v.\", dto2.GetFontHeight(), portion.GetFontHeight())\n\t\treturn\n\t}\n\tif portion.GetText() != dto2.GetText() {\n\t\tt.Errorf(\"Wrong portion text. Expected %v but was %v.\", dto2.GetText(), portion.GetText())\n\t\treturn\n\t}\n\tportions, _, e = c.SlidesApi.GetSpecialSlidePortions(fileName, slideIndex, \"notesSlide\", shapeIndex, paragraphIndex, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(portions.GetItems()) != int(portionCount)+1 {\n\t\tt.Errorf(\"Wrong portion count. Expected %v but was %v.\", portionCount, len(portions.GetItems())+1)\n\t\treturn\n\t}\n\n\t_, _, e = c.SlidesApi.DeleteSpecialSlidePortion(fileName, slideIndex, \"notesSlide\", shapeIndex, paragraphIndex, portionCount+1, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tportions, _, e = c.SlidesApi.GetSpecialSlidePortions(fileName, slideIndex, \"notesSlide\", shapeIndex, paragraphIndex, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(portions.GetItems()) != int(portionCount) {\n\t\tt.Errorf(\"Wrong portion count. Expected %v but was %v.\", portionCount, len(portions.GetItems()))\n\t\treturn\n\t}\n}", "func TestLayoutSlideParagraphs(t *testing.T) {\n\tvar slideIndex int32 = 1\n\tvar shapeIndex int32 = 2\n\tvar paragraphCount int32 = 1\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tparagraphs, _, e := c.SlidesApi.GetSpecialSlideParagraphs(fileName, slideIndex, \"layoutSlide\", shapeIndex, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(paragraphs.GetParagraphLinks()) != int(paragraphCount) {\n\t\tt.Errorf(\"Wrong paragraph count. Expected %v but was %v.\", paragraphCount, len(paragraphs.GetParagraphLinks()))\n\t\treturn\n\t}\n\n\tportion := slidescloud.NewPortion()\n\tportion.Text = \"New Paragraph\"\n\tdto := slidescloud.NewParagraph()\n\tdto.Alignment = \"Right\"\n\tdto.PortionList = []slidescloud.IPortion{portion}\n\tparagraph, _, e := c.SlidesApi.CreateSpecialSlideParagraph(fileName, slideIndex, \"layoutSlide\", shapeIndex, dto, nil, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif paragraph.GetAlignment() != dto.GetAlignment() {\n\t\tt.Errorf(\"Wrong paragraph alignment. Expected %v but was %v.\", dto.GetAlignment(), paragraph.GetAlignment())\n\t\treturn\n\t}\n\tparagraphs, _, e = c.SlidesApi.GetSpecialSlideParagraphs(fileName, slideIndex, \"layoutSlide\", shapeIndex, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(paragraphs.GetParagraphLinks()) != int(paragraphCount)+1 {\n\t\tt.Errorf(\"Wrong paragraph count. Expected %v but was %v.\", paragraphCount, len(paragraphs.GetParagraphLinks())+1)\n\t\treturn\n\t}\n\n\tdto = slidescloud.NewParagraph()\n\tdto.Alignment = \"Center\"\n\tparagraph, _, e = c.SlidesApi.UpdateSpecialSlideParagraph(fileName, slideIndex, \"layoutSlide\", shapeIndex, paragraphCount+1, dto, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif paragraph.GetAlignment() != dto.GetAlignment() {\n\t\tt.Errorf(\"Wrong paragraph alignment. Expected %v but was %v.\", dto.GetAlignment(), paragraph.GetAlignment())\n\t\treturn\n\t}\n\tparagraphs, _, e = c.SlidesApi.GetSpecialSlideParagraphs(fileName, slideIndex, \"layoutSlide\", shapeIndex, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(paragraphs.GetParagraphLinks()) != int(paragraphCount)+1 {\n\t\tt.Errorf(\"Wrong paragraph count. Expected %v but was %v.\", paragraphCount, len(paragraphs.GetParagraphLinks())+1)\n\t\treturn\n\t}\n\n\t_, _, e = c.SlidesApi.DeleteSpecialSlideParagraph(fileName, slideIndex, \"layoutSlide\", shapeIndex, paragraphCount+1, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tparagraphs, _, e = c.SlidesApi.GetSpecialSlideParagraphs(fileName, slideIndex, \"layoutSlide\", shapeIndex, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(paragraphs.GetParagraphLinks()) != int(paragraphCount) {\n\t\tt.Errorf(\"Wrong paragraph count. Expected %v but was %v.\", paragraphCount, len(paragraphs.GetParagraphLinks()))\n\t\treturn\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ PlaceholdersApiServiceTests Read slide placeholders info. Test for PlaceholdersApi.GetSlidesPlaceholders method with invalid password
func TestGetSlidesPlaceholdersInvalidpassword(t *testing.T) { request := createGetSlidesPlaceholdersRequest() request.password = invalidizeTestParamValue(request.password, "password", "string").(string) e := initializeTest("GetSlidesPlaceholders", "password", request.password) if e != nil { t.Errorf("Error: %v.", e) return } r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request) assertError(t, "GetSlidesPlaceholders", "password", r.Code, e) }
[ "func TestGetSlidesPlaceholder(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n e := initializeTest(\"GetSlidesPlaceholder\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.PlaceholdersApi.GetSlidesPlaceholder(request)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestGetSlidesPlaceholderInvalidpassword(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholder\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"password\", r.Code, e)\n}", "func TestGetSlidesPlaceholders(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n e := initializeTest(\"GetSlidesPlaceholders\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.PlaceholdersApi.GetSlidesPlaceholders(request)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestGetSlidesPlaceholderInvalidslideIndex(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.slideIndex = invalidizeTestParamValue(request.slideIndex, \"slideIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholder\", \"slideIndex\", request.slideIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"slideIndex\", r.Code, e)\n}", "func TestGetSlidesPlaceholderInvalidplaceholderIndex(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.placeholderIndex = invalidizeTestParamValue(request.placeholderIndex, \"placeholderIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholder\", \"placeholderIndex\", request.placeholderIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"placeholderIndex\", r.Code, e)\n}", "func TestGetSlidesPlaceholdersInvalidslideIndex(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.slideIndex = invalidizeTestParamValue(request.slideIndex, \"slideIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholders\", \"slideIndex\", request.slideIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"slideIndex\", r.Code, e)\n}", "func TestGetSlidesPlaceholdersInvalidstorage(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.storage = invalidizeTestParamValue(request.storage, \"storage\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholders\", \"storage\", request.storage)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"storage\", r.Code, e)\n}", "func TestGetSlidesPlaceholderInvalidstorage(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.storage = invalidizeTestParamValue(request.storage, \"storage\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholder\", \"storage\", request.storage)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"storage\", r.Code, e)\n}", "func TestGetSlidesDocumentWithFormatInvalidpassword(t *testing.T) {\n request := createGetSlidesDocumentWithFormatRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"GetSlidesDocumentWithFormat\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n _, r, e := getTestApiClient().DocumentApi.GetSlidesDocumentWithFormat(request)\n assertError(t, \"GetSlidesDocumentWithFormat\", \"password\", int32(r.StatusCode), e)\n}", "func GetPlaceHolders(conf *viper.Viper) Placeholders {\n\tlist := parseMap(conf.AllSettings())\n\n\tproperties := CreateProperties(list)\n\n\treturn Placeholders{properties}\n}", "func TestPutSlidesDocumentFromHtmlInvalidpassword(t *testing.T) {\n request := createPutSlidesDocumentFromHtmlRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"PutSlidesDocumentFromHtml\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().DocumentApi.PutSlidesDocumentFromHtml(request)\n assertError(t, \"PutSlidesDocumentFromHtml\", \"password\", r.Code, e)\n}", "func TestNotesSlideGetFromStorage(t *testing.T) {\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := c.SlidesApi.GetNotesSlide(fileName, 1, \"password\", folderName, \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(result.GetText()) == 0 {\n\t\tt.Errorf(\"Note text is empty.\")\n\t\treturn\n\t}\n}", "func TestPostSlidesDocumentInvalidpassword(t *testing.T) {\n request := createPostSlidesDocumentRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"PostSlidesDocument\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().DocumentApi.PostSlidesDocument(request)\n assertError(t, \"PostSlidesDocument\", \"password\", r.Code, e)\n}", "func TestPostSlidesSaveAsInvalidpassword(t *testing.T) {\n request := createPostSlidesSaveAsRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"PostSlidesSaveAs\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n _, r, e := getTestApiClient().DocumentApi.PostSlidesSaveAs(request)\n assertError(t, \"PostSlidesSaveAs\", \"password\", int32(r.StatusCode), e)\n}", "func TestGetSlidesApiInfo(t *testing.T) {\n e := initializeTest(\"GetSlidesApiInfo\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.DocumentApi.GetSlidesApiInfo()\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestPutNewPresentationInvalidpassword(t *testing.T) {\n request := createPutNewPresentationRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"PutNewPresentation\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().DocumentApi.PutNewPresentation(request)\n assertError(t, \"PutNewPresentation\", \"password\", r.Code, e)\n}", "func ImageGetPlaceholder(key data.UUID) (*Image, error) {\n\treturn imageGet(key, false, true)\n}", "func TestNotesSlideGetFromRequest(t *testing.T) {\n\tsource, e := ioutil.ReadFile(localTestFile)\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := slidescloud.GetTestApiClient().SlidesApi.GetNotesSlideOnline(source, 1, \"password\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(result.GetText()) == 0 {\n\t\tt.Errorf(\"Note text is empty.\")\n\t\treturn\n\t}\n}", "func privateDataPlaceholder() string {\n\treturn \"[PRIVATE DATA HIDDEN]\"\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ PlaceholdersApiServiceTests Read slide placeholders info. Test for PlaceholdersApi.GetSlidesPlaceholders method with invalid storage
func TestGetSlidesPlaceholdersInvalidstorage(t *testing.T) { request := createGetSlidesPlaceholdersRequest() request.storage = invalidizeTestParamValue(request.storage, "storage", "string").(string) e := initializeTest("GetSlidesPlaceholders", "storage", request.storage) if e != nil { t.Errorf("Error: %v.", e) return } r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request) assertError(t, "GetSlidesPlaceholders", "storage", r.Code, e) }
[ "func TestGetSlidesPlaceholder(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n e := initializeTest(\"GetSlidesPlaceholder\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.PlaceholdersApi.GetSlidesPlaceholder(request)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestGetSlidesPlaceholders(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n e := initializeTest(\"GetSlidesPlaceholders\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.PlaceholdersApi.GetSlidesPlaceholders(request)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestGetSlidesPlaceholderInvalidstorage(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.storage = invalidizeTestParamValue(request.storage, \"storage\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholder\", \"storage\", request.storage)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"storage\", r.Code, e)\n}", "func TestGetSlidesPlaceholderInvalidslideIndex(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.slideIndex = invalidizeTestParamValue(request.slideIndex, \"slideIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholder\", \"slideIndex\", request.slideIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"slideIndex\", r.Code, e)\n}", "func TestGetSlidesPlaceholdersInvalidslideIndex(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.slideIndex = invalidizeTestParamValue(request.slideIndex, \"slideIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholders\", \"slideIndex\", request.slideIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"slideIndex\", r.Code, e)\n}", "func TestGetSlidesPlaceholderInvalidplaceholderIndex(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.placeholderIndex = invalidizeTestParamValue(request.placeholderIndex, \"placeholderIndex\", \"int32\").(int32)\n e := initializeTest(\"GetSlidesPlaceholder\", \"placeholderIndex\", request.placeholderIndex)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"placeholderIndex\", r.Code, e)\n}", "func GetPlaceHolders(conf *viper.Viper) Placeholders {\n\tlist := parseMap(conf.AllSettings())\n\n\tproperties := CreateProperties(list)\n\n\treturn Placeholders{properties}\n}", "func TestNotesSlideGetFromStorage(t *testing.T) {\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := c.SlidesApi.GetNotesSlide(fileName, 1, \"password\", folderName, \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(result.GetText()) == 0 {\n\t\tt.Errorf(\"Note text is empty.\")\n\t\treturn\n\t}\n}", "func TestGetSlidesPlaceholderInvalidpassword(t *testing.T) {\n request := createGetSlidesPlaceholderRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholder\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholder(request)\n assertError(t, \"GetSlidesPlaceholder\", \"password\", r.Code, e)\n}", "func TestGetSlidesPlaceholdersInvalidpassword(t *testing.T) {\n request := createGetSlidesPlaceholdersRequest()\n request.password = invalidizeTestParamValue(request.password, \"password\", \"string\").(string)\n e := initializeTest(\"GetSlidesPlaceholders\", \"password\", request.password)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().PlaceholdersApi.GetSlidesPlaceholders(request)\n assertError(t, \"GetSlidesPlaceholders\", \"password\", r.Code, e)\n}", "func TestNotesSlideExistsFromStorage(t *testing.T) {\n\tfolderName := \"TempSlidesSDK\"\n\tfileName := \"test.pptx\"\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := c.SlidesApi.NotesSlideExists(fileName, 1, \"password\", folderName, \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif !result.GetExists() {\n\t\tt.Errorf(\"Note does not exist.\")\n\t\treturn\n\t}\n}", "func ImageGetPlaceholder(key data.UUID) (*Image, error) {\n\treturn imageGet(key, false, true)\n}", "func GetPlaceHolder(count int) string {\n\tif count > 0 {\n\t\tstr := strings.Repeat(\"?, \", count)\n\t\treturn str[:len(str)-2]\n\t}\n\n\treturn \"\"\n}", "func TestPostSlidesSplitInvalidstorage(t *testing.T) {\n request := createPostSlidesSplitRequest()\n request.storage = invalidizeTestParamValue(request.storage, \"storage\", \"string\").(string)\n e := initializeTest(\"PostSlidesSplit\", \"storage\", request.storage)\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n r, _, e := getTestApiClient().DocumentApi.PostSlidesSplit(request)\n assertError(t, \"PostSlidesSplit\", \"storage\", r.Code, e)\n}", "func TestGetSlidesApiInfo(t *testing.T) {\n e := initializeTest(\"GetSlidesApiInfo\", \"\", \"\")\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n c := getTestApiClient()\n r, _, e := c.DocumentApi.GetSlidesApiInfo()\n if e != nil {\n t.Errorf(\"Error: %v.\", e)\n return\n }\n if r.Code != 200 && r.Code != 201 {\n t.Errorf(\"Wrong response code: %d.\", r.Code)\n return\n }\n}", "func TestNotesSlideDownloadFromStorage(t *testing.T) {\n\tfolderName := \"TempSlidesSDK\"\n\tfileName := \"test.pptx\"\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\t_, _, e = c.SlidesApi.DownloadNotesSlide(fileName, 1, \"png\", nil, nil, \"password\", folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n}", "func (a *ClinicalMetadataServiceApiService) GetSlide(ctx _context.Context, slideId string) (Ga4ghSlide, *_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 Ga4ghSlide\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/slides/{slide_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"slide_id\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", slideId)), -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\"}\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 Ga4ghSlide\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 TestNotesSlideGetFromRequest(t *testing.T) {\n\tsource, e := ioutil.ReadFile(localTestFile)\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tresult, _, e := slidescloud.GetTestApiClient().SlidesApi.GetNotesSlideOnline(source, 1, \"password\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(result.GetText()) == 0 {\n\t\tt.Errorf(\"Note text is empty.\")\n\t\treturn\n\t}\n}", "func TestNotesSlideParagraphs(t *testing.T) {\n\tvar slideIndex int32 = 1\n\tvar shapeIndex int32 = 2\n\tvar paragraphCount int32 = 1\n\tc := slidescloud.GetTestApiClient()\n\t_, e := c.SlidesApi.CopyFile(\"TempTests/\"+fileName, folderName+\"/\"+fileName, \"\", \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\n\tparagraphs, _, e := c.SlidesApi.GetSpecialSlideParagraphs(fileName, slideIndex, \"notesSlide\", shapeIndex, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(paragraphs.GetParagraphLinks()) != int(paragraphCount) {\n\t\tt.Errorf(\"Wrong paragraph count. Expected %v but was %v.\", paragraphCount, len(paragraphs.GetParagraphLinks()))\n\t\treturn\n\t}\n\n\tportion := slidescloud.NewPortion()\n\tportion.Text = \"New Paragraph\"\n\tdto := slidescloud.NewParagraph()\n\tdto.Alignment = \"Right\"\n\tdto.PortionList = []slidescloud.IPortion{portion}\n\tparagraph, _, e := c.SlidesApi.CreateSpecialSlideParagraph(fileName, slideIndex, \"notesSlide\", shapeIndex, dto, nil, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif paragraph.GetAlignment() != dto.GetAlignment() {\n\t\tt.Errorf(\"Wrong paragraph alignment. Expected %v but was %v.\", dto.GetAlignment(), paragraph.GetAlignment())\n\t\treturn\n\t}\n\tparagraphs, _, e = c.SlidesApi.GetSpecialSlideParagraphs(fileName, slideIndex, \"notesSlide\", shapeIndex, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(paragraphs.GetParagraphLinks()) != int(paragraphCount)+1 {\n\t\tt.Errorf(\"Wrong paragraph count. Expected %v but was %v.\", paragraphCount, len(paragraphs.GetParagraphLinks())+1)\n\t\treturn\n\t}\n\n\tdto = slidescloud.NewParagraph()\n\tdto.Alignment = \"Center\"\n\tparagraph, _, e = c.SlidesApi.UpdateSpecialSlideParagraph(fileName, slideIndex, \"notesSlide\", shapeIndex, paragraphCount+1, dto, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif paragraph.GetAlignment() != dto.GetAlignment() {\n\t\tt.Errorf(\"Wrong paragraph alignment. Expected %v but was %v.\", dto.GetAlignment(), paragraph.GetAlignment())\n\t\treturn\n\t}\n\tparagraphs, _, e = c.SlidesApi.GetSpecialSlideParagraphs(fileName, slideIndex, \"notesSlide\", shapeIndex, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(paragraphs.GetParagraphLinks()) != int(paragraphCount)+1 {\n\t\tt.Errorf(\"Wrong paragraph count. Expected %v but was %v.\", paragraphCount, len(paragraphs.GetParagraphLinks())+1)\n\t\treturn\n\t}\n\n\t_, _, e = c.SlidesApi.DeleteSpecialSlideParagraph(fileName, slideIndex, \"notesSlide\", shapeIndex, paragraphCount+1, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tparagraphs, _, e = c.SlidesApi.GetSpecialSlideParagraphs(fileName, slideIndex, \"notesSlide\", shapeIndex, password, folderName, \"\", \"\")\n\tif e != nil {\n\t\tt.Errorf(\"Error: %v.\", e)\n\t\treturn\n\t}\n\tif len(paragraphs.GetParagraphLinks()) != int(paragraphCount) {\n\t\tt.Errorf(\"Wrong paragraph count. Expected %v but was %v.\", paragraphCount, len(paragraphs.GetParagraphLinks()))\n\t\treturn\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LoadHTTPS returns the HTTP routes and middleware
func LoadHTTPS() http.Handler { return middleware(routes()) }
[ "func LoadHTTPS() http.Handler {\n Flogger.Println(\"HTTPS routes LoadHTTPS\")\n\treturn middleware(routes())\n}", "func LoadHTTP() http.Handler {\r\n\treturn middleware(routes())\r\n\r\n\t// Uncomment this and comment out the line above to always redirect to HTTPS\r\n\t//return http.HandlerFunc(redirectToHTTPS)\r\n}", "func (r *Router) HTTPS() *Router {\n\tif r.root != nil {\n\t\treturn r.root.HTTPS()\n\t}\n\tr.mu.Lock()\n\tif r.httpsrouter == nil {\n\t\tr.httpsrouter = &Router{\n\t\t\trouter: newRouter(),\n\t\t\tapp: r.app,\n\t\t\troot: r,\n\t\t}\n\t}\n\tr.mu.Unlock()\n\n\treturn r.httpsrouter\n}", "func Load() http.Handler {\n Flogger.Println(\"HTTP routes Load\")\n\treturn middleware(routes())\n}", "func routerHTTPS(conf *runtime.Configuration) {\n\tconf.Routers[\"https-custom-tls\"] = &runtime.RouterInfo{\n\t\tRouter: &dynamic.Router{\n\t\t\tEntryPoints: []string{\"web\"},\n\t\t\tService: \"http\",\n\t\t\tRule: \"Host(`foo.bar`)\",\n\t\t\tTLS: &dynamic.RouterTLSConfig{\n\t\t\t\tOptions: \"tls12\",\n\t\t\t},\n\t\t},\n\t}\n}", "func HTTPS(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tproto := r.Header.Get(\"x-forwarded-proto\")\n\t\tif proto == \"http\" {\n\t\t\thttp.Redirect(w, r, \"https://\"+r.Host+r.URL.Path, http.StatusPermanentRedirect)\n\t\t\treturn\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func NewHTTPS(host string, port int) Static {\n\treturn Static{\n\t\tprotocol: ProtocolHTTPS,\n\t\thost: host,\n\t\tport: port,\n\t}\n}", "func start_HTTPS(handler http.Handler, server Server) {\n\tfmt.Println(time.Now().Format(\"2006-01-02 03:04:05 PM\"), \"Running HTTPS \"+get_https_address(server))\n\n\t// Start the HTTPS listener\n\tlog.Fatal(http.ListenAndServeTLS(get_https_address(server), server.CertFile, server.KeyFile, handler))\n}", "func routerHTTPSPathPrefix(conf *runtime.Configuration) {\n\tconf.Routers[\"https\"] = &runtime.RouterInfo{\n\t\tRouter: &dynamic.Router{\n\t\t\tEntryPoints: []string{\"web\"},\n\t\t\tService: \"http\",\n\t\t\tRule: \"PathPrefix(`/`)\",\n\t\t\tTLS: &dynamic.RouterTLSConfig{\n\t\t\t\tOptions: \"tls10\",\n\t\t\t},\n\t\t},\n\t}\n}", "func (s *Server) ServeHTTPS(domain string) error {\n\treturn autotls.Run(s.router, domain)\n}", "func startHTTPS(handlers http.Handler, s Server) {\n\tfmt.Println(time.Now().Format(\"2006-01-02 03:04:05 PM\"), \"Running HTTPS \"+httpsAddress(s))\n\n\t// Start the HTTPS listener\n\tlog.Fatal(http.ListenAndServeTLS(httpsAddress(s), s.CertFile, s.KeyFile, handlers))\n}", "func IsHTTPS(r *rest.Request) bool {\n\treturn r.URL.Scheme == \"https\" || r.TLS != nil\n}", "func redirectToHTTPS(w http.ResponseWriter, req *http.Request) {\n Flogger.Println(\"HTTP redirect\")\n\thttp.Redirect(w, req, \"https://\"+req.Host, http.StatusMovedPermanently)\n}", "func main() {\n\tr := &http.ServeMux{}\n\tr.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(\"A web page on HTTPS\"))\n\t})\n\n\thttp.ListenAndServeTLS(\":8080\", \"../cert/server.crt\", \"../cert/server.key\", r)\n}", "func ToHTTPS(w http.ResponseWriter, req *http.Request) {\n\tif req.Method == http.MethodGet {\n\t\ttarget := \"https://\" + req.Host + req.URL.Path\n\t\tif len(req.URL.RawQuery) > 0 {\n\t\t\ttarget += \"?\" + req.URL.RawQuery\n\t\t}\n\t\thttp.Redirect(w, req, target, http.StatusTemporaryRedirect)\n\t} else {\n\t\thttp.NotFound(w, req)\n\t}\n}", "func Routes(api *operations.ReturnEverythingAPI) {\n\tapi.GetEverythingHandler = operations.GetEverythingHandlerFunc(getEverything)\n\n\tapi.ApplicationGetAppHandler = application.GetAppHandlerFunc(getApp)\n\tapi.ApplicationGetAppFieldHandler = application.GetAppFieldHandlerFunc(getAppField)\n\tapi.ApplicationGetAppEnvsHandler = application.GetAppEnvsHandlerFunc(getAppEnvs)\n\tapi.ApplicationGetAppEnvHandler = application.GetAppEnvHandlerFunc(getAppEnv)\n\n\tapi.HostGetHostHandler = host.GetHostHandlerFunc(getHost)\n\tapi.HostGetHostFieldHandler = host.GetHostFieldHandlerFunc(getHostField)\n\n\tapi.RequestGetRequestInfoHandler = request.GetRequestInfoHandlerFunc(getRequestInfo)\n\tapi.RequestGetRequestFieldHandler = request.GetRequestFieldHandlerFunc(getRequestField)\n\tapi.RequestGetRequestHeadersHandler = request.GetRequestHeadersHandlerFunc(getRequestHeaders)\n\tapi.RequestGetRequestHeaderHandler = request.GetRequestHeaderHandlerFunc(getRequestHeader)\n\tapi.RequestGetRequestFormHandler = request.GetRequestFormHandlerFunc(getRequestForm)\n\tapi.RequestGetRequestPostFormHandler = request.GetRequestPostFormHandlerFunc(getRequestPostForm)\n\n\tapi.AwsGetAWSHandler = aws.GetAWSHandlerFunc(getAWS)\n\tapi.AwsGetAmazonEC2Handler = aws.GetAmazonEC2HandlerFunc(getAmazonEC2)\n\tapi.AwsGetAmazonEC2FieldHandler = aws.GetAmazonEC2FieldHandlerFunc(getAmazonEC2Field)\n\tapi.AwsGetAmazonECSHandler = aws.GetAmazonECSHandlerFunc(getAmazonECS)\n\tapi.AwsGetAmazonECSFieldHandler = aws.GetAmazonECSFieldHandlerFunc(getAmazonECSField)\n\n\tapi.GoogleGetGoogleCloudHandler = google.GetGoogleCloudHandlerFunc(getGoogleCloud)\n\tapi.GoogleGetGoogleComputeEngineHandler = google.GetGoogleComputeEngineHandlerFunc(getGoogleComputeEngine)\n\tapi.GoogleGetGoogleComputeEngineFieldHandler = google.GetGoogleComputeEngineFieldHandlerFunc(getGoogleComputeEngineField)\n\tapi.GoogleGetGoogleKubernetesEngineHandler = google.GetGoogleKubernetesEngineHandlerFunc(getGoogleKubernetesEngine)\n\tapi.GoogleGetGoogleKubernetesEngineFieldHandler = google.GetGoogleKubernetesEngineFieldHandlerFunc(getGoogleKubernetesEngineField)\n}", "func init() {\n\tRegister(\"http\", StartHTTP)\n\tRegister(\"https\", StartHTTPS)\n}", "func (c *Cluster) initClusterAndHTTPS(ctx context.Context) error {\n\t// Set up dynamiclistener TLS listener and request handler\n\tlistener, handler, err := c.newListener(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get the base request handler\n\thandler, err = c.getHandler(handler)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Config the cluster database and allow it to add additional request handlers\n\thandler, err = c.initClusterDB(ctx, handler)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.config.EnablePProf {\n\t\tmux := mux.NewRouter()\n\t\tmux.HandleFunc(\"/debug/pprof/cmdline\", pprof.Cmdline)\n\t\tmux.HandleFunc(\"/debug/pprof/profile\", pprof.Profile)\n\t\tmux.HandleFunc(\"/debug/pprof/symbol\", pprof.Symbol)\n\t\tmux.HandleFunc(\"/debug/pprof/trace\", pprof.Trace)\n\t\tmux.PathPrefix(\"/debug/pprof/\").HandlerFunc(pprof.Index)\n\t\tmux.NotFoundHandler = handler\n\t\thandler = mux\n\t}\n\n\t// Create a HTTP server with the registered request handlers, using logrus for logging\n\tserver := http.Server{\n\t\tHandler: handler,\n\t}\n\n\tif logrus.IsLevelEnabled(logrus.DebugLevel) {\n\t\tserver.ErrorLog = log.New(logrus.StandardLogger().Writer(), \"Cluster-Http-Server \", log.LstdFlags)\n\t} else {\n\t\tserver.ErrorLog = log.New(io.Discard, \"Cluster-Http-Server\", 0)\n\t}\n\n\t// Start the supervisor http server on the tls listener\n\tgo func() {\n\t\terr := server.Serve(listener)\n\t\tif err != nil && !errors.Is(err, http.ErrServerClosed) {\n\t\t\tlogrus.Fatalf(\"server stopped: %v\", err)\n\t\t}\n\t}()\n\n\t// Shutdown the http server when the context is closed\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tserver.Shutdown(context.Background())\n\t}()\n\n\treturn nil\n}", "func IsProxiedHTTPS(r *rest.Request) bool {\n\treturn r.Header.Get(\"X-Forwarded-Proto\") == \"https\" || r.Header.Get(\"$WSSC\") == \"https\"\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LoadHTTP returns the HTTPS routes and middleware
func LoadHTTP() http.Handler { return middleware(routes()) // Uncomment this and comment out the line above to always redirect to HTTPS //return http.HandlerFunc(redirectToHTTPS) }
[ "func LoadHTTPS() http.Handler {\n Flogger.Println(\"HTTPS routes LoadHTTPS\")\n\treturn middleware(routes())\n}", "func LoadHTTPS() http.Handler {\r\n\treturn middleware(routes())\r\n}", "func Load() http.Handler {\n Flogger.Println(\"HTTP routes Load\")\n\treturn middleware(routes())\n}", "func (r *Router) HTTPS() *Router {\n\tif r.root != nil {\n\t\treturn r.root.HTTPS()\n\t}\n\tr.mu.Lock()\n\tif r.httpsrouter == nil {\n\t\tr.httpsrouter = &Router{\n\t\t\trouter: newRouter(),\n\t\t\tapp: r.app,\n\t\t\troot: r,\n\t\t}\n\t}\n\tr.mu.Unlock()\n\n\treturn r.httpsrouter\n}", "func routerHTTPS(conf *runtime.Configuration) {\n\tconf.Routers[\"https-custom-tls\"] = &runtime.RouterInfo{\n\t\tRouter: &dynamic.Router{\n\t\t\tEntryPoints: []string{\"web\"},\n\t\t\tService: \"http\",\n\t\t\tRule: \"Host(`foo.bar`)\",\n\t\t\tTLS: &dynamic.RouterTLSConfig{\n\t\t\t\tOptions: \"tls12\",\n\t\t\t},\n\t\t},\n\t}\n}", "func NewHTTP(opts HTTPOptions, mux FuncHandler) *HTTP {\n\taddr := opts.Addr.String()\n\terrorLogger := log.New(loggerFromExternalLogger{Print: opts.Loggers.ServerEvent}, \"\", 0)\n\n\tif !opts.Disable.LivenessProbe {\n\t\terrorLogger.Print(\"liveness probe is ENABLED\")\n\t\tmux.HandleFunc(opts.LivenessProbe.Path, handlers.GetHTTPReadinessProbe(opts.ReadinessProbe.Handlers))\n\t}\n\n\tif !opts.Disable.ReadinessProbe {\n\t\terrorLogger.Print(\"readiness probe is ENABLED\")\n\t\tmux.HandleFunc(opts.ReadinessProbe.Path, handlers.GetHTTPLivenessProbe(opts.ReadinessProbe.Handlers))\n\t}\n\n\tif !opts.Disable.Metrics {\n\t\terrorLogger.Print(\"metrics is ENABLED\")\n\t\tmux.HandleFunc(opts.Metrics.Path, handlers.GetHTTPMetrics())\n\t}\n\n\tif !opts.Disable.Version {\n\t\terrorLogger.Print(\"version is ENABLED\")\n\t\tmux.HandleFunc(opts.Version.Path, handlers.GetHTTPVersion(opts.Version.Value))\n\t}\n\n\thandler := http.Handler(mux)\n\n\tmiddlewares := middleware.Middlewares{}\n\tif opts.Middlewares != nil && len(opts.Middlewares) > 0 {\n\t\tmiddlewares = append(middlewares, opts.Middlewares...)\n\t}\n\tif !opts.Disable.CORS {\n\t\terrorLogger.Print(\"cross-origin resource sharing is ENABLED\")\n\t\tmiddlewares = append(middlewares, middleware.NewCORS(opts.CORS))\n\t}\n\tif !opts.Disable.RequestLogger {\n\t\terrorLogger.Print(\"request logging is ENABLED\")\n\t\tmiddlewares = append(middlewares, middleware.NewRequestLogger(middleware.RequestLoggerConfiguration{Log: opts.Loggers.Request}))\n\t}\n\tif !opts.Disable.RequestIdentifier {\n\t\terrorLogger.Print(\"request identification is ENABLED\")\n\t\tmiddlewares = append(middlewares, middleware.NewRequestIdentifier(middleware.RequestIdentifierConfiguration{}))\n\t}\n\tfor i := 0; i < len(middlewares); i++ {\n\t\tapply := middlewares[i]\n\t\thandler = apply(handler)\n\t}\n\ts := HTTP{\n\t\tOptions: &opts,\n\t\tServer: &http.Server{\n\t\t\tAddr: addr,\n\t\t\tHandler: handler,\n\t\t\tErrorLog: errorLogger,\n\t\t\tIdleTimeout: opts.Timeouts.Idle,\n\t\t\tMaxHeaderBytes: opts.Limit.HeaderBytes,\n\t\t\tReadTimeout: opts.Timeouts.Read,\n\t\t\tReadHeaderTimeout: opts.Timeouts.ReadHeader,\n\t\t\tWriteTimeout: opts.Timeouts.Write,\n\t\t},\n\t}\n\treturn &s\n}", "func HTTPS(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tproto := r.Header.Get(\"x-forwarded-proto\")\n\t\tif proto == \"http\" {\n\t\t\thttp.Redirect(w, r, \"https://\"+r.Host+r.URL.Path, http.StatusPermanentRedirect)\n\t\t\treturn\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func HTTPServeTLS(host string, tlsCert, tlsKey string, gerdu cache.UnImplementedCache) {\n\trouter := newRouter(gerdu)\n\tlog.Printf(\"Gerdu started listening HTTPS TLS at %s\\n\", host)\n\tlog.Fatal(http.ListenAndServeTLS(host, tlsCert, tlsKey, router))\n}", "func (a *Agent) listenHTTP() ([]*HTTPServer, error) {\n\tvar ln []net.Listener\n\tvar servers []*HTTPServer\n\tstart := func(proto string, addrs []net.Addr) error {\n\t\tlisteners, err := a.startListeners(addrs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, l := range listeners {\n\t\t\tvar tlscfg *tls.Config\n\t\t\t_, isTCP := l.(*tcpKeepAliveListener)\n\t\t\tif isTCP && proto == \"https\" {\n\t\t\t\ttlscfg = a.tlsConfigurator.IncomingHTTPSConfig()\n\t\t\t\tl = tls.NewListener(l, tlscfg)\n\t\t\t}\n\t\t\tsrv := &HTTPServer{\n\t\t\t\tServer: &http.Server{\n\t\t\t\t\tAddr: l.Addr().String(),\n\t\t\t\t\tTLSConfig: tlscfg,\n\t\t\t\t},\n\t\t\t\tln: l,\n\t\t\t\tagent: a,\n\t\t\t\tblacklist: NewBlacklist(a.config.HTTPBlockEndpoints),\n\t\t\t\tproto: proto,\n\t\t\t}\n\t\t\tsrv.Server.Handler = srv.handler(a.config.EnableDebug)\n\n\t\t\t// This will enable upgrading connections to HTTP/2 as\n\t\t\t// part of TLS negotiation.\n\t\t\tif proto == \"https\" {\n\t\t\t\terr = http2.ConfigureServer(srv.Server, nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tln = append(ln, l)\n\t\t\tservers = append(servers, srv)\n\t\t}\n\t\treturn nil\n\t}\n\n\tif err := start(\"http\", a.config.HTTPAddrs); err != nil {\n\t\tfor _, l := range ln {\n\t\t\tl.Close()\n\t\t}\n\t\treturn nil, err\n\t}\n\tif err := start(\"https\", a.config.HTTPSAddrs); err != nil {\n\t\tfor _, l := range ln {\n\t\t\tl.Close()\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn servers, nil\n}", "func MakeHttpRoute(\n\tr *chi.Mux,\n\topts []kitHttp.ServerOption,\n) http.Handler {\n\t// I normally use group to separate the different url path\n\t// or to separate the endpoints which needs middleware or not\n\tr.Group(func(r chi.Router) {\n\t\tr.Post(\"/guest_list/{name}\", addGuest(opts))\n\t\tr.Get(\"/guest_list\", listGuest(opts))\n\t})\n\n\tr.Group(func(r chi.Router) {\n\t\tr.Get(\"/guests\", listArrivedGuest(opts))\n\t\tr.Put(\"/guests/{name}\", guestArrived(opts))\n\t\tr.Delete(\"/guests/{name}\", guestLeaves(opts))\n\t})\n\n\tr.Group(func(r chi.Router) {\n\t\tr.Get(\"/seats_empty\", countEmptySeats(opts))\n\t})\n\n\treturn r\n}", "func (h *HTTP) GetLoader(_ modules.Job) lua.LGFunction {\n\treturn func() lua.LGFunction {\n\t\treturn func(luaState *lua.LState) int {\n\t\t\tvar exports = map[string]lua.LGFunction{\n\t\t\t\t\"request\": h.request,\n\t\t\t\t\"post\": h.send(http.MethodPost),\n\t\t\t\t\"get\": h.send(http.MethodGet),\n\t\t\t\t\"put\": h.send(http.MethodPut),\n\t\t\t\t\"delete\": h.send(http.MethodDelete),\n\t\t\t}\n\n\t\t\tmod := luaState.SetFuncs(luaState.NewTable(), exports)\n\n\t\t\tmod.RawSetString(\"methodGet\", lua.LString(http.MethodGet))\n\t\t\tmod.RawSetString(\"methodHead\", lua.LString(http.MethodHead))\n\t\t\tmod.RawSetString(\"methodPost\", lua.LString(http.MethodPost))\n\t\t\tmod.RawSetString(\"methodPut\", lua.LString(http.MethodPut))\n\t\t\tmod.RawSetString(\"methodPatch\", lua.LString(http.MethodPatch))\n\t\t\tmod.RawSetString(\"methodDelete\", lua.LString(http.MethodDelete))\n\t\t\tmod.RawSetString(\"methodConnect\", lua.LString(http.MethodConnect))\n\t\t\tmod.RawSetString(\"methodOptions\", lua.LString(http.MethodOptions))\n\t\t\tmod.RawSetString(\"methodTrace\", lua.LString(http.MethodTrace))\n\n\t\t\tluaState.Push(mod)\n\t\t\treturn 1\n\t\t}\n\t}()\n}", "func httpsOrHTTP(importPath string) (urlStr string, body io.ReadCloser, err error) {\n\tfetch := func(scheme string) (urlStr string, res *http.Response, err error) {\n\t\tu, err := url.Parse(scheme + \"://\" + importPath)\n\t\tif err != nil {\n\t\t\treturn \"\", nil, err\n\t\t}\n\t\tu.RawQuery = \"go-get=1\"\n\t\turlStr = u.String()\n\t\tlog.Debug(\"Fetching %s\", urlStr)\n\t\tres, err = grobot.GetHTTP(urlStr)\n\t\treturn\n\t}\n\tcloseBody := func(res *http.Response) {\n\t\tif res != nil {\n\t\t\tres.Body.Close()\n\t\t}\n\t}\n\turlStr, res, err := fetch(\"https\")\n\tif err != nil || res.StatusCode != 200 {\n\t\tif err != nil {\n\t\t\tlog.Debug(\"https fetch failed.\")\n\t\t} else {\n\t\t\tlog.Debug(\"Ignoring https fetch with status code %d\", res.StatusCode)\n\t\t}\n\t\tcloseBody(res)\n\t\turlStr, res, err = fetch(\"http\")\n\t}\n\tif err != nil {\n\t\tcloseBody(res)\n\t\treturn \"\", nil, err\n\t}\n\t// Note: accepting a non-200 OK here, so people can serve a\n\t// meta import in their http 404 page.\n\tlog.Debug(\"Parsing meta tags from %s (status code %d)\", urlStr, res.StatusCode)\n\treturn urlStr, res.Body, nil\n}", "func (r *Router) HTTP() *Router {\n\tif r.root != nil {\n\t\treturn r.root.HTTP()\n\t}\n\tr.mu.Lock()\n\tif r.httprouter == nil {\n\t\tr.httprouter = &Router{\n\t\t\trouter: newRouter(),\n\t\t\tapp: r.app,\n\t\t\troot: r,\n\t\t}\n\t}\n\tr.mu.Unlock()\n\n\treturn r.httprouter\n}", "func (multy *Multy) initHttpRoutes(conf *Configuration) error {\n\trouter := gin.Default()\n\tmulty.route = router\n\t//\n\tgin.SetMode(gin.DebugMode)\n\n\trestClient, err := client.SetRestHandlers(\n\t\tmulty.userStore,\n\t\trouter,\n\t\tconf.DonationAddresses,\n\t\tmulty.BTC,\n\t\tmulty.ETH,\n\t\tconf.MultyVerison,\n\t\tconf.Secretkey,\n\t\tconf.DeviceVersions,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmulty.restClient = restClient\n\n\t// socketIO server initialization. server -> mobile client\n\tsocketIORoute := router.Group(\"/socketio\")\n\tsocketIOPool, err := client.SetSocketIOHandlers(multy.restClient, multy.BTC, multy.ETH, socketIORoute, conf.SocketioAddr, conf.NSQAddress, multy.userStore)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmulty.clientPool = socketIOPool\n\n\tfirebaseClient, err := client.InitFirebaseConn(&conf.Firebase, multy.route, conf.NSQAddress)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmulty.firebaseClient = firebaseClient\n\n\treturn nil\n}", "func start_HTTPS(handler http.Handler, server Server) {\n\tfmt.Println(time.Now().Format(\"2006-01-02 03:04:05 PM\"), \"Running HTTPS \"+get_https_address(server))\n\n\t// Start the HTTPS listener\n\tlog.Fatal(http.ListenAndServeTLS(get_https_address(server), server.CertFile, server.KeyFile, handler))\n}", "func InitHTTP(cfg HTTPConfig) error {\n\tif cfg.Schema == \"https\" {\n\t\tbeego.BConfig.Listen.EnableHTTPS = true\n\t\tbeego.BConfig.Listen.EnableHTTP = false\n\t\tif cfg.Port != 0 {\n\t\t\tbeego.BConfig.Listen.HTTPSPort = cfg.Port\n\t\t}\n\n\t\tbeego.BConfig.Listen.HTTPSKeyFile = cfg.KeyFile\n\t\tbeego.BConfig.Listen.HTTPSCertFile = cfg.CertFile\n\t} else if cfg.Schema == \"http\" {\n\t\tif cfg.Port != 0 {\n\t\t\tbeego.BConfig.Listen.HTTPPort = cfg.Port\n\t\t}\n\t} else {\n\t\treturn fmt.Errorf(\"invalid schema '%s', only 'http' and 'https' are supported \", cfg.Schema)\n\t}\n\n\treturn nil\n}", "func routerHTTP(conf *runtime.Configuration) {\n\tconf.Routers[\"http\"] = &runtime.RouterInfo{\n\t\tRouter: &dynamic.Router{\n\t\t\tEntryPoints: []string{\"web\"},\n\t\t\tService: \"http\",\n\t\t\tRule: \"Host(`foo.bar`)\",\n\t\t},\n\t}\n}", "func LoadHTTPRoutes() {\n\tr := setupRouter()\n\terr := r.Run()\n\tpanic(err)\n}", "func HSTSMiddleware(h http.HandlerFunc) http.HandlerFunc {\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\t// Allow only https connections for the next 2 years, requesting to be preloaded\n\t\tw.Header().Set(\"Strict-Transport-Security\", \"max-age=63072000; includeSubDomains; preload\")\n\n\t\t// Call the handler\n\t\th(w, r)\n\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Less returns true if o < oo; Lender < Owner
func (o OwnershipLevel) Less(oo OwnershipLevel) bool { if o == OwnershipLevels.Lender && oo == OwnershipLevels.Owner { return true } return false }
[ "func (o openList) Less(i, j int) bool {\n\ta, b := o[i], o[j]\n\tif a.f == b.f {\n\t\treturn a.g > b.g\n\t}\n\treturn a.f < b.f\n}", "func less(c1, c2 cost) bool {\n\tswitch {\n\tcase c1.opCode != c2.opCode:\n\t\treturn c1.opCode < c2.opCode\n\tcase c1.isUnique == c2.isUnique:\n\t\treturn c1.vindexCost <= c2.vindexCost\n\tdefault:\n\t\treturn c1.isUnique\n\t}\n}", "func (slice Lenders) Less(i, j int) bool {\n\n\tif slice[i].Rate != slice[j].Rate {\n\t\t// Base the sorting on the lowest rate.\n\t\treturn slice[i].Rate < slice[j].Rate\n\t} else {\n\t\t// In the instance of the same rate, sort by who has more\n\t\t// funds available to reduce number of lenders\n\t\treturn slice[i].Available > slice[j].Available\n\t}\n\n}", "func (r *RID) OperatorLess(rid *RID) bool {\n\treturn bool(C.godot_rid_operator_less(r.rid, rid.rid))\n}", "func less(v, w float64) bool {\n\treturn v < w\n}", "func (c Compare) IsLess(lhs, rhs interface{}) bool { return c(lhs, rhs) }", "func (t Targets) IsLess(o Targets) bool {\n\tif len(t) < len(o) {\n\t\treturn true\n\t}\n\tif len(t) > len(o) {\n\t\treturn false\n\t}\n\n\tsort.Sort(t)\n\tsort.Sort(o)\n\n\tfor i, e := range t {\n\t\tif e != o[i] {\n\t\t\treturn e < o[i]\n\t\t}\n\t}\n\treturn false\n}", "func lessByDelta(i, j BenchCmp, calcDelta func(BenchCmp) Delta) bool {\n\tiDelta, jDelta := calcDelta(i).mag(), calcDelta(j).mag()\n\tif iDelta != jDelta {\n\t\treturn iDelta < jDelta\n\t}\n\treturn i.Name() < j.Name()\n}", "func less(a, b *ExpireResult) bool {\n\tif a.Repository < b.Repository {\n\t\treturn true\n\t}\n\tif a.Repository > b.Repository {\n\t\treturn false\n\t}\n\tif a.Branch < b.Branch {\n\t\treturn true\n\t}\n\tif a.Branch > b.Branch {\n\t\treturn false\n\t}\n\tif a.InternalReference < b.InternalReference {\n\t\treturn true\n\t}\n\tif a.InternalReference > b.InternalReference {\n\t\treturn false\n\t}\n\treturn a.PhysicalAddress < b.PhysicalAddress\n}", "func (contact *Contact) Less(otherContact *Contact) bool {\n\treturn contact.distance.Less(otherContact.distance)\n}", "func (l DriverInfoList) Less(i, j int) bool { return l[i].Order < l[j].Order }", "func (b Buildings) Less(i, j int) bool {\n\treturn b[i].Left < b[j].Left\n}", "func OwnerLT(v string) predicate.Task {\n\treturn predicate.Task(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldOwner), v))\n\t})\n}", "func (a Objects) Less(i, j int) bool {\n\treturn a[i].Seq < a[j].Seq\n}", "func (g Gain) Less(gain Gain) bool {\n\tswitch {\n\tcase g.Station < gain.Station:\n\t\treturn true\n\tcase g.Station > gain.Station:\n\t\treturn false\n\tcase g.Location < gain.Location:\n\t\treturn true\n\tcase g.Location > gain.Location:\n\t\treturn false\n\tcase g.Sublocation < gain.Sublocation:\n\t\treturn true\n\tcase g.Sublocation > gain.Sublocation:\n\t\treturn false\n\tcase g.Subsource < gain.Subsource:\n\t\treturn true\n\tcase g.Subsource > gain.Subsource:\n\t\treturn false\n\tcase g.Span.Start.Before(gain.Span.Start):\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (i *info) less(b *info) bool {\n\tswitch t := i.Val.(type) {\n\tcase int64:\n\t\treturn t < b.Val.(int64)\n\tcase float64:\n\t\treturn t < b.Val.(float64)\n\tcase string:\n\t\treturn t < b.Val.(string)\n\tdefault:\n\t\tif ord, ok := i.Val.(util.Ordered); ok {\n\t\t\treturn ord.Less(b.Val.(util.Ordered))\n\t\t}\n\t\tlog.Fatalf(\"unhandled info value type: %s\", t)\n\t}\n\treturn false\n}", "func (g *GroupInfo) LT(o *GroupInfo) bool {\n\tif g.Type == o.Type {\n\t\treturn strings.ToUpper(g.Name) < strings.ToUpper(o.Name)\n\t}\n\treturn o.Type == \"default\"\n}", "func (d DirInfos) Less(i, j int) bool {\n\treturn d[i].Full < d[j].Full\n}", "func (o Offset) Less(other Offset) bool {\n\tif o == other {\n\t\treturn true\n\t}\n\n\tif o.H != other.H {\n\t\treturn o.H < other.H\n\t}\n\n\treturn o.M < other.M\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
BuildResourceHierarchy returns an instance of ResourceHierarchy from a string
func BuildResourceHierarchy(rh string) ResourceHierarchy { return ResourceHierarchy(rh) }
[ "func createCRDObject(s string) (*extensionsobj.CustomResourceDefinition, error) {\n\tsr := strings.NewReader(s)\n\td := yaml.NewYAMLOrJSONDecoder(sr, len(s))\n\tcrdVar := &extensionsobj.CustomResourceDefinition{}\n\tif err := d.Decode(crdVar); err != nil {\n\t\treturn nil, err\n\t}\n\treturn crdVar, nil\n\n}", "func ResourceTypeFromString(typeString string) (ResourceType, error) {\n\tswitch strings.ToUpper(typeString) {\n\tcase \"ANY\":\n\t\treturn ResourceAny, nil\n\tcase \"TOPIC\":\n\t\treturn ResourceTopic, nil\n\tcase \"GROUP\":\n\t\treturn ResourceGroup, nil\n\tcase \"BROKER\":\n\t\treturn ResourceBroker, nil\n\tdefault:\n\t\treturn ResourceUnknown, NewError(ErrInvalidArg, \"Unknown resource type\", false)\n\t}\n}", "func NewResource(k8s *k8s.Client, res string) (Resource, error) {\n\tvar err error\n\tr := resource{\n\t\tk8s: k8s,\n\t\tNamespace: defaultNamespace,\n\t\tType: TypePod,\n\t}\n\tchunks := strings.Split(res, \"/\")\n\tnbc := len(chunks)\n\tif nbc == 1 {\n\t\t// Z: the pod \"Z\" in namespace \"default\"\n\t\tr.Name = chunks[0]\n\t} else if nbc == 2 {\n\t\t// Y/Z: all the pods of the resource \"Z\" of type \"Y\" in namespace \"default\"\n\t\tr.Type, err = strTypeToConst(chunks[0])\n\t\tr.Name = chunks[1]\n\t} else if nbc == 3 {\n\t\t// X/Y/Z: all the pods of the resource \"Z\" of type \"Y\" in namespace \"X\"\n\t\tr.Namespace = chunks[0]\n\t\tr.Type, err = strTypeToConst(chunks[1])\n\t\tr.Name = chunks[2]\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn types[r.Type](r), nil\n\t// var ret Resource\n\t// switch r.Type {\n\t// case TypePod:\n\t// \tret = &Pod{r}\n\t// case TypeDeploy:\n\t// \tret = &Deployment{r}\n\t// case TypeStatefulSet:\n\t// \tret = &StatefulSet{r}\n\t// }\n\t// return ret, nil\n}", "func ParseResources(s string) (Resources, error) {\n\tvar parts []string\n\tinRange := false\n\tvar sb strings.Builder\n\tfor _, c := range s {\n\t\tif inRange {\n\t\t\tif c == ']' {\n\t\t\t\tinRange = false\n\t\t\t}\n\t\t} else {\n\t\t\tif c == '[' {\n\t\t\t\tinRange = true\n\t\t\t} else if c == ',' {\n\t\t\t\tparts = append(parts, sb.String())\n\t\t\t\tsb.Reset()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tsb.WriteRune(c)\n\t}\n\tparts = append(parts, sb.String())\n\tif len(parts) != 3 {\n\t\treturn Resources{}, fmt.Errorf(\"invalid resources: %q\", s)\n\t}\n\tvcpu, err := parseResource(\"vcpu\", parts[0])\n\tif err != nil {\n\t\treturn Resources{}, err\n\t}\n\tmemory, err := parseResource(\"memory\", parts[1])\n\tif err != nil {\n\t\treturn Resources{}, err\n\t}\n\tdisk, err := parseResource(\"disk\", parts[2])\n\tif err != nil {\n\t\treturn Resources{}, err\n\t}\n\treturn Resources{Vcpu: vcpu, Memory: memory, Disk: disk}, nil\n}", "func NewResourceFromString(res string, registry validator.Registry) (*Resource, error) {\n\tvar d map[string]interface{}\n\tif err := json.Unmarshal([]byte(res), &d); err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewResource(d, registry)\n}", "func CreateResourceProviderFromPath(directory string) (*ResourceProvider, error) {\n\tresources := ResourceProvider{\n\t\tServerVersion: \"unknown\",\n\t\tNodes: []corev1.Node{},\n\t\tDeployments: []appsv1.Deployment{},\n\t\tNamespaces: []corev1.Namespace{},\n\t\tPods: []corev1.Pod{},\n\t}\n\n\taddYaml := func(contents string) error {\n\t\tcontentBytes := []byte(contents)\n\t\tdecoder := k8sYaml.NewYAMLOrJSONDecoder(bytes.NewReader(contentBytes), 1000)\n\t\tresource := k8sResource{}\n\t\terr := decoder.Decode(&resource)\n\t\tif err != nil {\n\t\t\t// TODO: should we panic if the YAML is bad?\n\t\t\tlogrus.Errorf(\"Invalid YAML: %s\", string(contents))\n\t\t\treturn nil\n\t\t}\n\t\tdecoder = k8sYaml.NewYAMLOrJSONDecoder(bytes.NewReader(contentBytes), 1000)\n\t\tif resource.Kind == \"Deployment\" {\n\t\t\tdep := appsv1.Deployment{}\n\t\t\terr = decoder.Decode(&dep)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Errorf(\"Error parsing deployment %v\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tresources.Deployments = append(resources.Deployments, dep)\n\t\t} else if resource.Kind == \"Namespace\" {\n\t\t\tns := corev1.Namespace{}\n\t\t\terr = decoder.Decode(&ns)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Errorf(\"Error parsing namespace %v\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tresources.Namespaces = append(resources.Namespaces, ns)\n\t\t} else if resource.Kind == \"Pod\" {\n\t\t\tpod := corev1.Pod{}\n\t\t\terr = decoder.Decode(&pod)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Errorf(\"Error parsing pod %v\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tresources.Pods = append(resources.Pods, pod)\n\t\t}\n\t\treturn nil\n\t}\n\n\tvisitFile := func(path string, f os.FileInfo, err error) error {\n\t\tif !strings.HasSuffix(path, \".yml\") && !strings.HasSuffix(path, \".yaml\") {\n\t\t\treturn nil\n\t\t}\n\t\tcontents, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Error reading file %v\", path)\n\t\t\treturn err\n\t\t}\n\t\tspecs := regexp.MustCompile(\"\\n-+\\n\").Split(string(contents), -1)\n\t\tfor _, spec := range specs {\n\t\t\tif strings.TrimSpace(spec) == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terr = addYaml(spec)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Errorf(\"Error parsing YAML %v\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\terr := filepath.Walk(directory, visitFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resources, nil\n}", "func BuildResource(namespace, resourceType, resourceID string) (resource string, err error) {\n\tif namespace == \"\" || resourceType == \"\" {\n\t\terr = fmt.Errorf(\"required parameter are not set (node id, namespace or resource type)\")\n\t\treturn\n\t}\n\tresource = fmt.Sprintf(\"%s%s%s\", namespace, constants.ResourceSep, resourceType)\n\tif resourceID != \"\" {\n\t\tresource += fmt.Sprintf(\"%s%s\", constants.ResourceSep, resourceID)\n\t}\n\treturn\n}", "func makeResource(mod string, res string) tokens.Type {\n\tfn := string(unicode.ToLower(rune(res[0]))) + res[1:]\n\treturn makeType(mod+\"/\"+fn, res)\n}", "func getResourceFromArguments(args map[string]interface{}) (unversioned.Resource, error) {\n\tkind := args[\"<KIND>\"].(string)\n\tname := argutils.ArgStringOrBlank(args, \"<NAME>\")\n\tnode := argutils.ArgStringOrBlank(args, \"--node\")\n\tworkload := argutils.ArgStringOrBlank(args, \"--workload\")\n\torchestrator := argutils.ArgStringOrBlank(args, \"--orchestrator\")\n\tresScope := argutils.ArgStringOrBlank(args, \"--scope\")\n\tswitch strings.ToLower(kind) {\n\tcase \"node\", \"nodes\", \"no\", \"nos\":\n\t\tp := api.NewNode()\n\t\tp.Metadata.Name = name\n\t\treturn *p, nil\n\tcase \"hostendpoint\", \"hostendpoints\", \"hep\", \"heps\":\n\t\th := api.NewHostEndpoint()\n\t\th.Metadata.Name = name\n\t\th.Metadata.Node = node\n\t\treturn *h, nil\n\tcase \"workloadendpoint\", \"workloadendpoints\", \"wep\", \"weps\":\n\t\th := api.NewWorkloadEndpoint()\n\t\th.Metadata.Name = name\n\t\th.Metadata.Orchestrator = orchestrator\n\t\th.Metadata.Workload = workload\n\t\th.Metadata.Node = node\n\t\treturn *h, nil\n\tcase \"profile\", \"profiles\", \"pro\", \"pros\":\n\t\tp := api.NewProfile()\n\t\tp.Metadata.Name = name\n\t\treturn *p, nil\n\tcase \"policy\", \"policies\", \"pol\", \"pols\":\n\t\tp := api.NewPolicy()\n\t\tp.Metadata.Name = name\n\t\treturn *p, nil\n\tcase \"ippool\", \"ippools\", \"ipp\", \"ipps\", \"pool\", \"pools\":\n\t\tp := api.NewIPPool()\n\t\tif name != \"\" {\n\t\t\t_, cidr, err := net.ParseCIDR(name)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tp.Metadata.CIDR = *cidr\n\t\t}\n\t\treturn *p, nil\n\tcase \"bgppeer\", \"bgppeers\", \"bgpp\", \"bgpps\", \"bp\", \"bps\":\n\t\tp := api.NewBGPPeer()\n\t\tif name != \"\" {\n\t\t\terr := p.Metadata.PeerIP.UnmarshalText([]byte(name))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\tp.Metadata.Node = node\n\t\tswitch resScope {\n\t\tcase \"node\":\n\t\t\tp.Metadata.Scope = scope.Node\n\t\tcase \"global\":\n\t\t\tp.Metadata.Scope = scope.Global\n\t\tcase \"\":\n\t\t\tp.Metadata.Scope = scope.Undefined\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"Unrecognized scope '%s', must be one of: global, node\", resScope)\n\t\t}\n\t\treturn *p, nil\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Resource type '%s' is not supported\", kind)\n\t}\n}", "func BuildPermission(str string) (Permission, error) {\n\tif valid, err := ValidatePermission(str); !valid {\n\t\treturn Permission{}, err\n\t}\n\tparts := strings.Split(str, \"::\")\n\tservice := parts[0]\n\tol := OwnershipLevel(parts[1])\n\taction := BuildAction(parts[2])\n\trh := ResourceHierarchy(strings.Join(parts[3:], \"::\"))\n\treturn Permission{\n\t\tService: service,\n\t\tOwnershipLevel: ol,\n\t\tAction: action,\n\t\tResourceHierarchy: rh,\n\t}, nil\n}", "func BuildResource(nodeID, namespace, resourceType, resourceID string) (resource string, err error) {\n\tif namespace == \"\" || resourceType == \"\" || nodeID == \"\" {\n\t\terr = fmt.Errorf(\"required parameter are not set (node id, namespace or resource type)\")\n\t\treturn\n\t}\n\n\tresource = fmt.Sprintf(\"%s%s%s%s%s%s%s\", controller.ResourceNode, constants.ResourceSep, nodeID, constants.ResourceSep, namespace, constants.ResourceSep, resourceType)\n\tif resourceID != \"\" {\n\t\tresource += fmt.Sprintf(\"%s%s\", constants.ResourceSep, resourceID)\n\t}\n\treturn\n}", "func ParseResourceTag(tag string) ResourceTags {\n\tresult := ResourceTags{}\n\tfor _, elem := range strings.Split(tag, \",\") {\n\t\tkv := strings.Split(elem, \"=\")\n\t\tif len(kv) != 2 {\n\t\t\tklog.Fatalf(\"// +resource: tags must be key value pairs. Expected \"+\n\t\t\t\t\"keys [path=<subresourcepath>] \"+\n\t\t\t\t\"Got string: [%s]\", tag)\n\t\t}\n\t\tvalue := kv[1]\n\t\tswitch kv[0] {\n\t\tcase \"rest\":\n\t\t\tresult.REST = value\n\t\tcase \"path\":\n\t\t\tresult.Resource = value\n\t\tcase \"strategy\":\n\t\t\tresult.Strategy = value\n\t\tcase \"shortname\":\n\t\t\tresult.ShortName = value\n\t\t}\n\t}\n\treturn result\n}", "func (builder *RuleBuilder) BuildRuleFromResource(resource pkg.Resource) error {\n\tdata, err := resource.Load()\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tsdata := string(data)\n\n\tis := antlr.NewInputStream(sdata)\n\tlexer := parser.NewgroolLexer(is)\n\tstream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)\n\n\tlistener := antlr2.NewGroolParserListener(builder.KnowledgeBase)\n\n\tpsr := parser.NewgroolParser(stream)\n\tpsr.BuildParseTrees = true\n\tantlr.ParseTreeWalkerDefault.Walk(listener, psr.Root())\n\n\tif len(listener.ParseErrors) > 0 {\n\t\tlog.Errorf(\"Loading rule resource : %s failed. Got %d errors. 1st error : %v\", resource.String(), len(listener.ParseErrors), listener.ParseErrors[0])\n\t\treturn errors.Errorf(\"error were found before builder bailing out. %d errors. 1st error : %v\", len(listener.ParseErrors), listener.ParseErrors[0])\n\t}\n\tlog.Debugf(\"Loading rule resource : %s success\", resource.String())\n\treturn nil\n}", "func parseHier(spec string) (keyGenFunc, error) {\n\tif depth, err := strconv.Atoi(spec); err == nil {\n\t\tkeys := []string{\"{account}\", \"{region}\", \"{service}\", \"{api}\", \"{id}\"}\n\t\tif depth <= 0 {\n\t\t\tspec = strings.Join(keys, \"/\")\n\t\t} else if depth >= len(keys)-1 {\n\t\t\tspec = strings.Join(keys, \",\")\n\t\t} else {\n\t\t\ti := len(keys) - depth\n\t\t\tkeys[0] = strings.Join(keys[:i], \"/\")\n\t\t\tspec = strings.Join(append(keys[:1], keys[i:]...), \",\")\n\t\t}\n\t} else if !strings.Contains(spec, \"{id}\") {\n\t\treturn nil, errors.New(`hierarchy spec must contain \"{id}\"`)\n\t}\n\treturn func(m *scan.Map, api string, c *scan.Call) []string {\n\t\tkeys := strings.NewReplacer(\n\t\t\t\"{account}\", m.Account,\n\t\t\t\"{region}\", m.Region,\n\t\t\t\"{service}\", m.Service,\n\t\t\t\"{api}\", api,\n\t\t\t\"{id}\", c.ID,\n\t\t).Replace(spec)\n\t\treturn strings.Split(keys, \",\")\n\t}, nil\n}", "func ParseResourceIdsFromFullName(p string) map[string]string {\n\tp = strings.TrimPrefix(strings.TrimSuffix(p, \"/\"), \"/\")\n\tresults := map[string]string{\n\t\t\"Namespace\": \"\",\n\t\t\"ExperimentId\": \"\",\n\t\t\"PipelineId\": \"\",\n\t\t\"PipelineVersionId\": \"\",\n\t\t\"RunId\": \"\",\n\t\t\"RecurringRunId\": \"\",\n\t\t\"ArtifactId\": \"\",\n\t\t\"ExecutionId\": \"\",\n\t}\n\tnames := strings.Split(p, \"/\")\n\ti := 0\n\tfor i < len(names) {\n\t\tif i+1 < len(names) {\n\t\t\tswitch strings.ToLower(names[i]) {\n\t\t\tcase \"namespaces\", \"namespace\":\n\t\t\t\tresults[\"Namespace\"] = names[i+1]\n\t\t\tcase \"pipelines\", \"pipeline\":\n\t\t\t\tresults[\"PipelineId\"] = names[i+1]\n\t\t\tcase \"versions\", \"version\", \"pipelineversions\", \"pipelineversion\", \"pipeline_versions\", \"pipeline_version\":\n\t\t\t\tresults[\"PipelineVersionId\"] = names[i+1]\n\t\t\tcase \"experiments\", \"experiment\":\n\t\t\t\tresults[\"ExperimentId\"] = names[i+1]\n\t\t\tcase \"runs\", \"run\":\n\t\t\t\tresults[\"RunId\"] = names[i+1]\n\t\t\tcase \"jobs\", \"job\", \"recurringruns\", \"recurringrun\", \"recurring_runs\", \"recurring_run\":\n\t\t\t\tresults[\"RecurringRunId\"] = names[i+1]\n\t\t\tcase \"artifacts\", \"artifact\":\n\t\t\t\tresults[\"ArtifactId\"] = names[i+1]\n\t\t\tcase \"executions\", \"execution\":\n\t\t\t\tresults[\"ExecutionId\"] = names[i+1]\n\t\t\t}\n\t\t}\n\t\ti = i + 2\n\t}\n\treturn results\n}", "func SubresourceName(subresource interface{}, subresourceType SubresourceType) string {\n\tswitch res := subresource.(type) {\n\tcase *regv1.Notary:\n\t\tswitch subresourceType {\n\t\t// Notary DB\n\t\tcase SubTypeNotaryDBPod, SubTypeNotaryDBPVC, SubTypeNotaryDBService:\n\t\t\treturn regv1.K8sPrefix + regv1.K8sNotaryPrefix + NotaryDBPrefix + res.Name\n\n\t\t// Notary Server\n\t\tcase SubTypeNotaryServerIngress, SubTypeNotaryServerPod, SubTypeNotaryServerSecret, SubTypeNotaryServerService:\n\t\t\treturn regv1.K8sPrefix + regv1.K8sNotaryPrefix + NotaryServerPrefix + res.Name\n\n\t\t// Notary signer\n\t\tcase SubTypeNotarySignerPod, SubTypeNotarySignerSecret, SubTypeNotarySignerService:\n\t\t\treturn regv1.K8sPrefix + regv1.K8sNotaryPrefix + NotarySignerPrefix + res.Name\n\t\t}\n\n\tcase *regv1.Registry:\n\t\tswitch subresourceType {\n\t\tcase SubTypeRegistryNotary:\n\t\t\treturn res.Name\n\n\t\tcase SubTypeRegistryService, SubTypeRegistryPVC, SubTypeRegistryDeployment, SubTypeRegistryOpaqueSecret, SubTypeRegistryConfigmap, SubTypeRegistryIngress:\n\t\t\treturn regv1.K8sPrefix + res.Name\n\n\t\tcase SubTypeRegistryTLSSecret:\n\t\t\treturn regv1.K8sPrefix + regv1.TLSPrefix + res.Name\n\n\t\tcase SubTypeRegistryDCJSecret:\n\t\t\treturn regv1.K8sPrefix + regv1.K8sRegistryPrefix + res.Name\n\t\t}\n\n\tcase *regv1.ExternalRegistry:\n\t\tswitch subresourceType {\n\t\tcase SubTypeExternalRegistryLoginSecret:\n\t\t\treturn regv1.K8sPrefix + ExternalRegistryPrefix + LoginSecretPrefix + res.Name\n\t\tcase SubTypeExternalRegistryCronJob:\n\t\t\treturn regv1.K8sPrefix + ExternalRegistryPrefix + res.Name\n\t\tcase SubTypeExternalRegistryJob:\n\t\t\treturn regv1.K8sPrefix + ExternalRegistryPrefix + res.Name + \"-\" + utils.RandomString(10)\n\t\t}\n\n\tcase *regv1.ImageReplicate:\n\t\tswitch subresourceType {\n\t\tcase SubTypeImageReplicateJob:\n\t\t\treturn regv1.K8sPrefix + ImageReplicatePrefix + res.Name\n\t\tcase SubTypeImageReplicateSyncJob:\n\t\t\treturn regv1.K8sPrefix + ImageReplicatePrefix + SynchronizePrefix + res.Name\n\t\tcase SubTypeImageReplicateImageSignRequest:\n\t\t\tif res.Status.ImageSignRequestName != \"\" {\n\t\t\t\treturn res.Status.ImageSignRequestName\n\t\t\t}\n\t\t\treturn regv1.K8sPrefix + ImageReplicatePrefix + res.Name + \"-\" + utils.RandomString(10)\n\t\t}\n\t}\n\n\treturn \"\"\n}", "func (rh *ResourceHelper) NewResourceFromBytes(bytes []byte) (*Resource, error) {\n\n\t// K8s deserialiser does all the hard work for us here - figures out\n\t// format, API group, kind, version\n\tobj, _, err := scheme.Codecs.UniversalDeserializer().Decode(bytes, nil, nil)\n\n\tif err != nil {\n\t\treturn &Resource{}, fmt.Errorf(\"parse resource from bytes: %s\", err.Error())\n\t}\n\n\treturn rh.NewResource(obj)\n}", "func FromString(segstr string) Segment {\n\tfields := strings.Fields(segstr)\n\tlength := len(fields) - 1\n\tiastrs := make([]string, length)\n\tidstrs := make([]string, length)\n\tfor i := 0; i < length; i++ {\n\t\tif i%2 == 0 {\n\t\t\tiastrs[i] = fields[i]\n\t\t\tids := strings.Split(fields[i+1], \">\")\n\t\t\tidstrs[i], idstrs[i+1] = ids[0], ids[1]\n\t\t} else {\n\t\t\tiastrs[i] = fields[i+1]\n\t\t}\n\t}\n\tinterfaces := make([]snet.PathInterface, length)\n\tvar sb strings.Builder\n\tfor i := 0; i < length; i++ {\n\t\tia, err := addr.IAFromString(iastrs[i])\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tid, err := strconv.Atoi(idstrs[i])\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tinterfaces[i] = snet.PathInterface{ID: common.IFIDType(id), IA: ia}\n\t\tsb.WriteString(fmt.Sprintf(\" %s#%d \", ia, common.IFIDType(id)))\n\t}\n\treturn Literal{Interfaces: interfaces, fingerprint: sb.String()}\n}", "func (c *Client) FromString(targetPath, content string) (resource.Resource, error) {\n\treturn c.rs.ResourceCache.GetOrCreate(path.Join(resources.CACHE_OTHER, targetPath), func() (resource.Resource, error) {\n\t\treturn c.rs.New(\n\t\t\tresources.ResourceSourceDescriptor{\n\t\t\t\tFs: c.rs.FileCaches.AssetsCache().Fs,\n\t\t\t\tLazyPublish: true,\n\t\t\t\tOpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) {\n\t\t\t\t\treturn hugio.NewReadSeekerNoOpCloserFromString(content), nil\n\t\t\t\t},\n\t\t\t\tRelTargetFilename: filepath.Clean(targetPath),\n\t\t\t})\n\t})\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PermissionMatches returns a slice of all possible ways to check if a service account has any level of permission over this ResourceHierarchy Example: rh = "x::y::z".PermissionMatches() = ["", "x::", "x::y::", "x::y::z"]
func (rh ResourceHierarchy) PermissionMatches() []string { whole := string(rh) if whole == "*" { return []string{whole} } parts := strings.Split(whole, "::") ret := []string{"*"} for i := 1; i < len(parts); i++ { if parts[i] == "*" { break } match := strings.Join(parts[:i], "::") ret = append(ret, match+"::*") } return append(ret, whole) }
[ "func (p *Permissions) Match(scope PermissionScope, path string, user *User) bool {\n\ts, ok := p.current[scope]\n\tif !ok {\n\t\t// potential to return an error here\n\t\treturn false\n\t}\n\n\tpath = strings.ToLower(path)\n\n\tfor _, r := range s {\n\n\t\tif r.g.Match(path) {\n\t\t\treturn r.acl.Match(user)\n\t\t}\n\t}\n\n\treturn false\n}", "func (a Auth0) Allowed(token string, perm introspector.Permission, expectedScopes ...string) (*introspector.Introspection, bool, error) {\n\ti, err := a.Introspect(token)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\t// Check scopes and permissions\n\tscopes := strings.Split(i.Scope, \" \")\n\tpermScope := perm.Action + \":\" + perm.Resource\n\tfound := false\n\tfor _, scope := range expectedScopes {\n\t\tif !in(scopes, scope) {\n\t\t\treturn i, false, errors.New(\"missing scope \" + scope)\n\t\t}\n\n\t\tif scope == permScope {\n\t\t\tfound = true\n\t\t}\n\t}\n\n\tif !found {\n\t\treturn i, false, errors.New(\"cannot \" + perm.Action + \" \" + perm.Resource)\n\t}\n\n\treturn i, true, nil\n}", "func Matches(resourceQuota *api.ResourceQuota, item runtime.Object, matchFunc MatchingResourceNamesFunc, scopeFunc MatchesScopeFunc) (bool, error) {\n\tif resourceQuota == nil {\n\t\treturn false, fmt.Errorf(\"expected non-nil quota\")\n\t}\n\t// verify the quota matches on at least one resource\n\tmatchResource := len(matchFunc(quota.ResourceNames(resourceQuota.Status.Hard))) > 0\n\t// by default, no scopes matches all\n\tmatchScope := true\n\tfor _, scope := range resourceQuota.Spec.Scopes {\n\t\tinnerMatch, err := scopeFunc(scope, item)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tmatchScope = matchScope && innerMatch\n\t}\n\treturn matchResource && matchScope, nil\n}", "func (m *Group) GetPermissionGrants()([]ResourceSpecificPermissionGrantable) {\n return m.permissionGrants\n}", "func (r *Role) CanAccess(resource Resource, mask AccessMask) bool {\n\tfor res, level := range r.resources {\n\t\tif res.String() == resource.String() {\n\t\t\treturn uint8(mask)&bits.RotateLeft8(1, level.Int()) != 0\n\t\t}\n\t}\n\treturn false\n}", "func (o GrpcRouteRouteRuleResponseOutput) Matches() GrpcRouteRouteMatchResponseArrayOutput {\n\treturn o.ApplyT(func(v GrpcRouteRouteRuleResponse) []GrpcRouteRouteMatchResponse { return v.Matches }).(GrpcRouteRouteMatchResponseArrayOutput)\n}", "func Can(method string, user string) bool {\n\tmethodPermission, ok := permissions[method]\n\tif !ok {\n\t\treturn false\n\t}\n\n\tuserPermission, ok := authzUsers[user]\n\tif !ok {\n\t\treturn false\n\t}\n\n\tfor _, up := range userPermission {\n\t\tfor _, mp := range methodPermission {\n\t\t\tif up == mp {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}", "func Test_CheckPermissions(t *testing.T) {\n\tname := \"User1\"\n\t//\n\t//\tul := um.NewUsersList()\n\t//\tuser1, _ := um.NewUser(name, nil)\n\t//\tul.AddUser(user1)\n\ta, _ := NewEntry(name)\n\n\t// verify that valid permission can be added\n\tok, permission := addPermissions(a, permissionsMap, true)\n\tif ok == false {\n\t\tt.Errorf(\"Test fail: Fail to add valid permission: '%v' to %v\", permission, a)\n\t}\n\t// verify that only permission that are in the list returns true\n\tfor p, val := range permissionsMap {\n\t\tok, _ := a.CheckPermission(p)\n\t\tif ok == false && val == true {\n\t\t\tt.Errorf(\"Test fail: Permission: '%v' from %v wasn't found\", p, a)\n\t\t} else if ok == true && val == false {\n\t\t\tt.Errorf(\"Test fail: Permission: '%v' that is not in %v, was found\", p, a)\n\t\t}\n\t}\n}", "func ValidatePermission(str string) (bool, error) {\n\t// Format: OwnershipLevel::Action::Service::{ResourceHierarchy}\n\tparts := strings.Split(str, \"::\")\n\tif len(parts) < 4 {\n\t\treturn false, fmt.Errorf(\n\t\t\t\"Incomplete permission. Expected format: \" +\n\t\t\t\t\"Service::OwnershipLevel::Action::{ResourceHierarchy}\",\n\t\t)\n\t}\n\tol := OwnershipLevel(parts[1])\n\tif ol != OwnershipLevels.Owner && ol != OwnershipLevels.Lender {\n\t\treturn false, fmt.Errorf(\"OwnershipLevel needs to be RO or RL\")\n\t}\n\tfor _, part := range parts {\n\t\tif part == \"\" {\n\t\t\treturn false, fmt.Errorf(\"No parts can be empty\")\n\t\t}\n\t}\n\treturn true, nil\n}", "func (r *RPC) Matchs(c context.Context, a *matmdl.ArgMatch, res *[]*matmdl.Match) (err error) {\n\t*res, err = r.s.Match(c, a.Sid)\n\treturn\n}", "func (set Set) Match(caps [][]string) []string {\n\tif set == nil {\n\t\treturn nil\n\t}\nanyof:\n\tfor _, andList := range caps {\n\t\tfor _, cap := range andList {\n\t\t\tif _, ok := set[cap]; !ok {\n\t\t\t\tcontinue anyof\n\t\t\t}\n\t\t}\n\t\treturn andList\n\t}\n\t// match anything\n\treturn nil\n}", "func (permission CheckResponse) PermissionListQuery(filterOutput FilterIDsOutput) ([]string, []string) {\n\tvar allows []string\n\tvar denies []string\n\tif permission.Allow.All { //if permission has allow all\n\t\tif len(permission.Deny.Resources) > 0 {\n\t\t\tdenies = permission.Deny.Resources\n\t\t}\n\n\t} else if permission.Deny.All { //if permission has deny all\n\t\tif len(permission.Allow.Resources) > 0 {\n\t\t\tallows = permission.Allow.Resources\n\t\t}\n\t} else { //if permission has individual deny and allow\n\t\tif len(permission.Deny.Resources) > 0 {\n\t\t\tdenies = permission.Deny.Resources\n\t\t}\n\t\tif len(permission.Allow.Resources) > 0 {\n\t\t\tallows = permission.Allow.Resources\n\t\t}\n\t\tif len(permission.Deny.Resources) <= 0 && len(permission.Allow.Resources) <= 0 {\n\t\t\tallows = []string{\"-1\"}\n\t\t}\n\t}\n\treturn allows, denies\n}", "func PolicyRuleResourceMatches(rule *rbacv1.PolicyRule, requestedResource string) bool {\n\tfor _, ruleResource := range rule.Resources {\n\t\tif ruleResource == rbacv1.ResourceAll {\n\t\t\treturn true\n\t\t}\n\n\t\tif ruleResource == requestedResource {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (client *ClientImpl) HasPermissions(ctx context.Context, args HasPermissionsArgs) (*[]bool, error) {\n\trouteValues := make(map[string]string)\n\tif args.SecurityNamespaceId == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.SecurityNamespaceId\"}\n\t}\n\trouteValues[\"securityNamespaceId\"] = (*args.SecurityNamespaceId).String()\n\tif args.Permissions != nil {\n\t\trouteValues[\"permissions\"] = strconv.Itoa(*args.Permissions)\n\t}\n\n\tqueryParams := url.Values{}\n\tif args.Tokens != nil {\n\t\tqueryParams.Add(\"tokens\", *args.Tokens)\n\t}\n\tif args.AlwaysAllowAdministrators != nil {\n\t\tqueryParams.Add(\"alwaysAllowAdministrators\", strconv.FormatBool(*args.AlwaysAllowAdministrators))\n\t}\n\tif args.Delimiter != nil {\n\t\tqueryParams.Add(\"delimiter\", *args.Delimiter)\n\t}\n\tlocationId, _ := uuid.Parse(\"dd3b8bd6-c7fc-4cbd-929a-933d9c011c9d\")\n\tresp, err := client.Client.Send(ctx, http.MethodGet, locationId, \"7.1-preview.2\", routeValues, queryParams, nil, \"\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue []bool\n\terr = client.Client.UnmarshalCollectionBody(resp, &responseValue)\n\treturn &responseValue, err\n}", "func (p *serviceEvaluator) MatchingResources(input []api.ResourceName) []api.ResourceName {\n\treturn quota.Intersection(input, serviceResources)\n}", "func (p Principal) Match(principal string) bool {\n\tfor _, pattern := range p.AWS.ToSlice() {\n\t\tif wildcard.MatchSimple(pattern, principal) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (m *Permission) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tfor idx, item := range m.GetPaths() {\n\t\t_, _ = idx, item\n\n\t\tif v, ok := interface{}(item).(interface{ Validate() error }); ok {\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\treturn PermissionValidationError{\n\t\t\t\t\tField: fmt.Sprintf(\"Paths[%v]\", idx),\n\t\t\t\t\tReason: \"embedded message failed validation\",\n\t\t\t\t\tCause: err,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tfor idx, item := range m.GetConditions() {\n\t\t_, _ = idx, item\n\n\t\tif v, ok := interface{}(item).(interface{ Validate() error }); ok {\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\treturn PermissionValidationError{\n\t\t\t\t\tField: fmt.Sprintf(\"Conditions[%v]\", idx),\n\t\t\t\t\tReason: \"embedded message failed validation\",\n\t\t\t\t\tCause: err,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func PermissionsContains(permissions, permission int) bool {\n\treturn permissions&permission == permission\n}", "func (UserService) GetAllPermissions(uid string) []string {\n\tperms := []string{}\n\tvar path = map[string]bool{}\n\tfor _, perm := range perm.GetAllPermsByUser(uid) {\n\t\tprefix := strings.Split(perm[1], \":\")\n\t\tseg := strings.Split(prefix[0], \"/\")\n\t\tss := \"\"\n\t\tfor _, s := range seg[1:] {\n\t\t\tss += \"/\" + s\n\t\t\tif ok := path[ss]; !ok {\n\t\t\t\tpath[ss] = true\n\t\t\t\tperms = append(perms, ss)\n\t\t\t}\n\t\t}\n\t\tperms = append(perms, perm[1])\n\t}\n\treturn perms\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Contains checks whether rh.Hierarchy contains orh.Hierarchy
func (rh ResourceHierarchy) Contains(orh ResourceHierarchy) bool { rhh := buildResourceHierarchy(rh) orhh := buildResourceHierarchy(orh) if rhh.size > orhh.size { return false } for i := range orhh.hierarchy { if i >= len(rhh.hierarchy) { return false } if rhh.hierarchy[i] == "*" { return true } if orhh.hierarchy[i] != rhh.hierarchy[i] { return false } } return true }
[ "func (t *Tree) Has(b gfx.Boundable) bool {\n\tt.RLock()\n\t_, ok := t.nodeByObject[b]\n\tt.RUnlock()\n\treturn ok\n}", "func (s *Set) Contain(nt symbols.NT, left, right int) bool {\n // fmt.Printf(\"bsr.Contain(%s,%d,%d)\\n\",nt,left,right)\n for e := range s.slotEntries {\n // fmt.Printf(\" (%s,%d,%d)\\n\",e.Label.Head(),e.leftExtent,e.rightExtent)\n if e.Label.Head() == nt && e.leftExtent == left && e.rightExtent == right {\n // fmt.Println(\" true\")\n return true\n }\n }\n // fmt.Println(\" false\")\n return false\n}", "func Contains(ancestor, descendant Reader) bool {\n\tcurrent := descendant.Parent()\n\tfor current != nil {\n\t\tif current == ancestor {\n\t\t\treturn true\n\t\t}\n\t\tcurrent = current.Parent()\n\t}\n\n\treturn false\n}", "func (p *pathTree) has(rel string) bool {\n\tif p == nil {\n\t\treturn false\n\t}\n\n\tif !p.caseSensitive {\n\t\trel = strings.ToLower(rel)\n\t}\n\n\t// It matches some added entry exactly?\n\tif p.leafs.Has(rel) {\n\t\treturn true\n\t}\n\t// Was added as a parent of some entry?\n\tif p.nodes.Has(rel) {\n\t\treturn true\n\t}\n\n\t// Maybe it has some added entry as its parent?\n\tfound := false\n\tparentDirs(rel, func(par string) bool {\n\t\tfound = p.leafs.Has(par)\n\t\treturn !found\n\t})\n\treturn found\n}", "func (s Set) Include(x interface{}) bool {\n\t_, ok := s.Tree.Search(x)\n\treturn ok\n}", "func (self *TileSprite) Contains(child *DisplayObject) bool{\n return self.Object.Call(\"contains\", child).Bool()\n}", "func (t MeSHTree) Contains(term string) bool {\n\tif _, ok := t.Locations[strings.ToLower(term)]; ok {\n\t\treturn true\n\t}\n\treturn false\n}", "func (p *ancestorTree) Has(blkID ids.ID) bool {\n\t_, ok := p.childToParent[blkID]\n\treturn ok\n}", "func (self *Graphics) Contains(child *DisplayObject) bool{\n return self.Object.Call(\"contains\", child).Bool()\n}", "func (set *Set) Contains(items ...interface{}) bool {\n\tfor _, item := range items {\n\t\tif _, contains := set.tree.Get(item); !contains {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (hh HashesSet) Contains(hash Hash) bool {\n\t_, ok := hh[hash]\n\treturn ok\n}", "func (s *HashSet) Contain(data interface{}) (bool, error) {\n\terr := s.checkT(data)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\t_, ok := s.set[data]\n\tif ok {\n\t\treturn true, nil\n\t} else {\n\t\treturn false, nil\n\t}\n}", "func (o *Workloadv1Location) HasSubdivision() bool {\n\tif o != nil && o.Subdivision != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (ons *orderedNodeSet) contains(node *Node) bool {\n\t_, ok := ons.nodes[node]\n\treturn ok\n}", "func (s *vSite) Contains(p image.Point) bool {\n\tother := s.parent.SiteFor(p.X, p.Y)\n\treturn s.ID() == other.ID()\n}", "func (o *BoundaryConds) Has(node int) bool {\n\treturn o.n2i[node] >= 0\n}", "func (grp *GrpType) Has(recPtr interface{}) (count int) {\n\tif recPtr != nil {\n\t\tgrp.mutex.Lock()\n\t\tfor _, index := range grp.list {\n\t\t\tif index.bt.Has(btreeRecType{less: index.less, recPtr: recPtr}) {\n\t\t\t\tcount++\n\t\t\t}\n\t\t}\n\t\tgrp.mutex.Unlock()\n\t}\n\treturn\n}", "func nodeContains(container *html.Node, contained *html.Node) bool {\n\t// Check if the parent of the contained node is the container node, traversing\n\t// upward until the top is reached, or the container is found.\n\tfor contained = contained.Parent; contained != nil; contained = contained.Parent {\n\t\tif container == contained {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (this *MultiMap) Contains(value interface{}) bool {\n\tif this.tree.Find(value) != nil {\n\t\treturn true\n\t}\n\treturn false\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ValidatePermission validates a permission in string format
func ValidatePermission(str string) (bool, error) { // Format: OwnershipLevel::Action::Service::{ResourceHierarchy} parts := strings.Split(str, "::") if len(parts) < 4 { return false, fmt.Errorf( "Incomplete permission. Expected format: " + "Service::OwnershipLevel::Action::{ResourceHierarchy}", ) } ol := OwnershipLevel(parts[1]) if ol != OwnershipLevels.Owner && ol != OwnershipLevels.Lender { return false, fmt.Errorf("OwnershipLevel needs to be RO or RL") } for _, part := range parts { if part == "" { return false, fmt.Errorf("No parts can be empty") } } return true, nil }
[ "func ValidatePermissionName(name string) error {\n\tif parts := strings.Split(name, \".\"); len(parts) == 3 {\n\t\tgood := true\n\t\tfor _, p := range parts {\n\t\t\tif p == \"\" {\n\t\t\t\tgood = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif good {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn errors.Reason(\"bad permission %q - must have form <service>.<subject>.<verb>\", name).Err()\n}", "func (m *EffectivePermission) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateFilePermissions(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateShare(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSharePermissions(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSvm(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(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 *DomainPermission) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStatus(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 validatePermissions(permissions ...string) error {\n\tfor _, perm := range permissions {\n\t\tif strings.TrimSpace(perm) == \"\" {\n\t\t\treturn fmt.Errorf(\"module permission is empty\")\n\t\t}\n\t}\n\treturn nil\n}", "func Test_FSValidation_AddPermission_ToString(t *testing.T) {\n\tfilePath := \"asdasda\"\n\tresult := TryAddPermission(filePath, 0755)\n\tfmt.Println(result)\n\tassert.Equal(t, result, false)\n}", "func (m *Permission) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tfor idx, item := range m.GetPaths() {\n\t\t_, _ = idx, item\n\n\t\tif v, ok := interface{}(item).(interface{ Validate() error }); ok {\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\treturn PermissionValidationError{\n\t\t\t\t\tField: fmt.Sprintf(\"Paths[%v]\", idx),\n\t\t\t\t\tReason: \"embedded message failed validation\",\n\t\t\t\t\tCause: err,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tfor idx, item := range m.GetConditions() {\n\t\t_, _ = idx, item\n\n\t\tif v, ok := interface{}(item).(interface{ Validate() error }); ok {\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\treturn PermissionValidationError{\n\t\t\t\t\tField: fmt.Sprintf(\"Conditions[%v]\", idx),\n\t\t\t\t\tReason: \"embedded message failed validation\",\n\t\t\t\t\tCause: err,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func IsPermission(err error) bool", "func (m *AzureKeyVaultPermission) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with AzureResourcePermission\n\tif err := m.AzureResourcePermission.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 parsePermissions(s string) ([]bool, error) {\n\tret := make([]bool, len(s))\n\tfor i := range s {\n\t\tif s[i] == 't' {\n\t\t\tret[i] = true\n\t\t} else if s[i] == 'f' {\n\t\t\tret[i] = false\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"error: invalid permissions string in database: %q\",\n\t\t\t\ts,\n\t\t\t)\n\t\t}\n\t}\n\treturn ret, nil\n}", "func BuildPermission(str string) (Permission, error) {\n\tif valid, err := ValidatePermission(str); !valid {\n\t\treturn Permission{}, err\n\t}\n\tparts := strings.Split(str, \"::\")\n\tservice := parts[0]\n\tol := OwnershipLevel(parts[1])\n\taction := BuildAction(parts[2])\n\trh := ResourceHierarchy(strings.Join(parts[3:], \"::\"))\n\treturn Permission{\n\t\tService: service,\n\t\tOwnershipLevel: ol,\n\t\tAction: action,\n\t\tResourceHierarchy: rh,\n\t}, nil\n}", "func validatePermissions(permissions *Permissions) error {\n\tif len(permissions.Roles) <= 0 {\n\t\treturn errors.New(\"no role defined\")\n\t}\n\n\t// @step: build a map of the roles\n\tfor name, x := range permissions.Roles {\n\t\tif err := validateRole(x); err != nil {\n\t\t\treturn fmt.Errorf(\"roles.%s %s\", name, err)\n\t\t}\n\t}\n\n\t// @step: iterate the principle and make sure they have a valid role\n\tfor name, x := range permissions.Principals {\n\t\t// @check the principal is ok\n\t\tif err := validatePrincipal(x); err != nil {\n\t\t\treturn fmt.Errorf(\"principals.%s %s\", name, err)\n\t\t}\n\n\t\t// @check the roles the principal has exist\n\t\tfor i, r := range x.Roles {\n\t\t\tif _, found := permissions.Roles[r]; !found {\n\t\t\t\treturn fmt.Errorf(\"principals[%d].role %s does not exist\", i, r)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *PublicPermissions) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateDacl(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGroup(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOwner(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 *UserPermissions) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateDirect(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGroups(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 *PermissionResources) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateTargetAction(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTargetKind(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateUUID(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 parsePermissions(s string) (*ProcMapPermissions, error) {\n\tif len(s) < 4 {\n\t\treturn nil, fmt.Errorf(\"invalid permissions token\")\n\t}\n\n\tperms := ProcMapPermissions{}\n\tfor _, ch := range s {\n\t\tswitch ch {\n\t\tcase 'r':\n\t\t\tperms.Read = true\n\t\tcase 'w':\n\t\t\tperms.Write = true\n\t\tcase 'x':\n\t\t\tperms.Execute = true\n\t\tcase 'p':\n\t\t\tperms.Private = true\n\t\tcase 's':\n\t\t\tperms.Shared = true\n\t\t}\n\t}\n\n\treturn &perms, nil\n}", "func (m *PublicPermissionsLin) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateACL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBasic(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDefaultACL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGroup(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOwner(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 ValidateFormat(pwd string) error {\n\tl := len(pwd)\n\tif l < 5 || l > 40 {\n\t\treturn errInvalidFormat\n\t}\n\treturn nil\n}", "func (m *AuthorizationRule) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCreatedAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOrganizationID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOwnerID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateResourceNames(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateResources(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateUpdatedAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVerbs(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 *Permission_Condition) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tswitch m.ConditionSpec.(type) {\n\n\tcase *Permission_Condition_Header:\n\n\t\tif v, ok := interface{}(m.GetHeader()).(interface{ Validate() error }); ok {\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\treturn Permission_ConditionValidationError{\n\t\t\t\t\tField: \"Header\",\n\t\t\t\t\tReason: \"embedded message failed validation\",\n\t\t\t\t\tCause: err,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tcase *Permission_Condition_DestinationIps:\n\n\t\tif v, ok := interface{}(m.GetDestinationIps()).(interface{ Validate() error }); ok {\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\treturn Permission_ConditionValidationError{\n\t\t\t\t\tField: \"DestinationIps\",\n\t\t\t\t\tReason: \"embedded message failed validation\",\n\t\t\t\t\tCause: err,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tcase *Permission_Condition_DestinationPorts:\n\n\t\tif v, ok := interface{}(m.GetDestinationPorts()).(interface{ Validate() error }); ok {\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\treturn Permission_ConditionValidationError{\n\t\t\t\t\tField: \"DestinationPorts\",\n\t\t\t\t\tReason: \"embedded message failed validation\",\n\t\t\t\t\tCause: err,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
BuildPermission transforms a string into struct
func BuildPermission(str string) (Permission, error) { if valid, err := ValidatePermission(str); !valid { return Permission{}, err } parts := strings.Split(str, "::") service := parts[0] ol := OwnershipLevel(parts[1]) action := BuildAction(parts[2]) rh := ResourceHierarchy(strings.Join(parts[3:], "::")) return Permission{ Service: service, OwnershipLevel: ol, Action: action, ResourceHierarchy: rh, }, nil }
[ "func parsePermissions(s string) (*ProcMapPermissions, error) {\n\tif len(s) < 4 {\n\t\treturn nil, fmt.Errorf(\"invalid permissions token\")\n\t}\n\n\tperms := ProcMapPermissions{}\n\tfor _, ch := range s {\n\t\tswitch ch {\n\t\tcase 'r':\n\t\t\tperms.Read = true\n\t\tcase 'w':\n\t\t\tperms.Write = true\n\t\tcase 'x':\n\t\t\tperms.Execute = true\n\t\tcase 'p':\n\t\t\tperms.Private = true\n\t\tcase 's':\n\t\t\tperms.Shared = true\n\t\t}\n\t}\n\n\treturn &perms, nil\n}", "func stringToAccessPerm(perm string) accessPerms {\n\tvar policy accessPerms\n\tswitch perm {\n\tcase \"none\":\n\t\tpolicy = accessNone\n\tcase \"readonly\":\n\t\tpolicy = accessDownload\n\tcase \"writeonly\":\n\t\tpolicy = accessUpload\n\tcase \"readwrite\":\n\t\tpolicy = accessPublic\n\tcase \"custom\":\n\t\tpolicy = accessCustom\n\t}\n\treturn policy\n}", "func ValidatePermission(str string) (bool, error) {\n\t// Format: OwnershipLevel::Action::Service::{ResourceHierarchy}\n\tparts := strings.Split(str, \"::\")\n\tif len(parts) < 4 {\n\t\treturn false, fmt.Errorf(\n\t\t\t\"Incomplete permission. Expected format: \" +\n\t\t\t\t\"Service::OwnershipLevel::Action::{ResourceHierarchy}\",\n\t\t)\n\t}\n\tol := OwnershipLevel(parts[1])\n\tif ol != OwnershipLevels.Owner && ol != OwnershipLevels.Lender {\n\t\treturn false, fmt.Errorf(\"OwnershipLevel needs to be RO or RL\")\n\t}\n\tfor _, part := range parts {\n\t\tif part == \"\" {\n\t\t\treturn false, fmt.Errorf(\"No parts can be empty\")\n\t\t}\n\t}\n\treturn true, nil\n}", "func PermStringToFlag(perm string) (pf PermFlag, err error) {\n\tswitch strings.ToLower(perm) {\n\tcase \"root\":\n\t\tpf = Root\n\tcase \"send\":\n\t\tpf = Send\n\tcase \"call\":\n\t\tpf = Call\n\tcase \"createcontract\", \"create_contract\":\n\t\tpf = CreateContract\n\tcase \"createaccount\", \"create_account\":\n\t\tpf = CreateAccount\n\tcase \"bond\":\n\t\tpf = Bond\n\tcase \"name\":\n\t\tpf = Name\n\tcase \"hasbase\", \"has_base\":\n\t\tpf = HasBase\n\tcase \"setbase\", \"set_base\":\n\t\tpf = SetBase\n\tcase \"unsetbase\", \"unset_base\":\n\t\tpf = UnsetBase\n\tcase \"setglobal\", \"set_global\":\n\t\tpf = SetGlobal\n\tcase \"hasrole\", \"has_role\":\n\t\tpf = HasRole\n\tcase \"addrole\", \"add_role\":\n\t\tpf = AddRole\n\tcase \"removerole\", \"rmrole\", \"rm_role\":\n\t\tpf = RmRole\n\tdefault:\n\t\terr = fmt.Errorf(\"Unknown permission %s\", perm)\n\t}\n\treturn\n}", "func Test_FSValidation_AddPermission_ToString(t *testing.T) {\n\tfilePath := \"asdasda\"\n\tresult := TryAddPermission(filePath, 0755)\n\tfmt.Println(result)\n\tassert.Equal(t, result, false)\n}", "func BuildCreatePermissionGroupIn() *model.CreatePermissionGroupIn {\n\treturn &model.CreatePermissionGroupIn{\n\t\tName: *RandomString(10),\n\t\tDescription: RandomString(20),\n\t\tPermissions: []model.Permission{\n\t\t\tmodel.PermissionUser,\n\t\t\tmodel.PermissionPermissionGroup,\n\t\t},\n\t}\n}", "func (perm *tokenPermission) UnmarshalJSON(b []byte) (err error) {\n\tperm.Permission = &dal.Permission{}\n\tpermissionReflection := reflect.TypeOf(perm.Permission)\n\n\tvar stringVal = string(b)\n\t//remove the surrounding brackets of the json string\n\tstringVal = strings.Trim(stringVal, \"{\")\n\tstringVal = strings.Trim(stringVal, \"}\")\n\n\t//take each json field with it's attached value and store it in a slice\n\tvar fields = strings.Split(stringVal, \",\")\n\n\tfor _, field := range fields {\n\n\t\tif len(field) > 0 {\n\t\t\t//separate the field from it's value\n\t\t\tvar fieldValuePair = strings.Split(field, \":\")\n\t\t\tif len(fieldValuePair) == 2 {\n\t\t\t\t//the field name has quotes around it - remove them\n\t\t\t\tfieldValuePair[0] = strings.Replace(fieldValuePair[0], \"\\\"\", \"\", 2)\n\n\t\t\t\t//iterate through each method\n\t\t\t\tfor methodIndex := 0; methodIndex < permissionReflection.NumMethod(); methodIndex++ {\n\t\t\t\t\tmethod := permissionReflection.Method(methodIndex)\n\t\t\t\t\tvar methodName = strings.ToLower(method.Name)\n\t\t\t\t\t//find the set method that corresponds to the json field\n\t\t\t\t\tif strings.Index(methodName, \"set\") == 0 && strings.Index(methodName, fieldValuePair[0]) > 0 {\n\t\t\t\t\t\tvar arguments []reflect.Value\n\t\t\t\t\t\t//pull the argument from the json pair\n\t\t\t\t\t\tif strings.ToLower(fieldValuePair[1]) == \"true\" {\n\t\t\t\t\t\t\targuments = []reflect.Value{reflect.ValueOf(perm.Permission), reflect.ValueOf(true)}\n\t\t\t\t\t\t} else if strings.ToLower(fieldValuePair[1]) == \"false\" {\n\t\t\t\t\t\t\targuments = []reflect.Value{reflect.ValueOf(perm.Permission), reflect.ValueOf(false)}\n\t\t\t\t\t\t} else { //int\n\t\t\t\t\t\t\tvar intVal int\n\t\t\t\t\t\t\tintVal, err = strconv.Atoi(fieldValuePair[1])\n\t\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\t\targuments = []reflect.Value{reflect.ValueOf(perm.Permission), reflect.ValueOf(int(intVal))}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\terr = errors.New(\"unable to unmarshal json string\")\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\n\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\t//execute the set method with the parsed argument\n\t\t\t\t\t\t\tmethod.Func.Call(arguments)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\terr = errors.New(\"unable to unmarshal json string\")\n\t\t\t}\n\t\t} else {\n\t\t\t// TODO should this ever hit/should this be an error?\n\t\t}\n\t}\n\n\treturn err\n}", "func parseBlobPermissions(s string) (BlobPermissions, error) {\n\tp := BlobPermissions{} // Clear the flags\n\tfor _, r := range s {\n\t\tswitch r {\n\t\tcase 'r':\n\t\t\tp.Read = true\n\t\tcase 'a':\n\t\t\tp.Add = true\n\t\tcase 'c':\n\t\t\tp.Create = true\n\t\tcase 'w':\n\t\t\tp.Write = true\n\t\tcase 'd':\n\t\t\tp.Delete = true\n\t\tcase 'x':\n\t\t\tp.DeletePreviousVersion = true\n\t\tcase 'y':\n\t\t\tp.PermanentDelete = true\n\t\tcase 'l':\n\t\t\tp.List = true\n\t\tcase 't':\n\t\t\tp.Tag = true\n\t\tcase 'm':\n\t\t\tp.Move = true\n\t\tcase 'e':\n\t\t\tp.Execute = true\n\t\tcase 'o':\n\t\t\tp.Ownership = true\n\t\tcase 'p':\n\t\t\tp.Permissions = true\n\t\tcase 'i':\n\t\t\tp.SetImmutabilityPolicy = true\n\t\tdefault:\n\t\t\treturn BlobPermissions{}, fmt.Errorf(\"invalid permission: '%v'\", r)\n\t\t}\n\t}\n\treturn p, nil\n}", "func parseContainerPermissions(s string) (ContainerPermissions, error) {\n\tp := ContainerPermissions{} // Clear the flags\n\tfor _, r := range s {\n\t\tswitch r {\n\t\tcase 'r':\n\t\t\tp.Read = true\n\t\tcase 'a':\n\t\t\tp.Add = true\n\t\tcase 'c':\n\t\t\tp.Create = true\n\t\tcase 'w':\n\t\t\tp.Write = true\n\t\tcase 'd':\n\t\t\tp.Delete = true\n\t\tcase 'x':\n\t\t\tp.DeletePreviousVersion = true\n\t\tcase 'l':\n\t\t\tp.List = true\n\t\tcase 't':\n\t\t\tp.Tag = true\n\t\tcase 'f':\n\t\t\tp.FilterByTags = true\n\t\tcase 'm':\n\t\t\tp.Move = true\n\t\tcase 'e':\n\t\t\tp.Execute = true\n\t\tcase 'o':\n\t\t\tp.ModifyOwnership = true\n\t\tcase 'p':\n\t\t\tp.ModifyPermissions = true\n\t\tcase 'i':\n\t\t\tp.SetImmutabilityPolicy = true\n\t\tdefault:\n\t\t\treturn ContainerPermissions{}, fmt.Errorf(\"invalid permission: '%v'\", r)\n\t\t}\n\t}\n\treturn p, nil\n}", "func CreatePermission(ctx context.Context, clientsEndpoint string, clientID string, permission KeycloakPermission, protectionAPIToken string) (string, error) {\n\tb, err := json.Marshal(permission)\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"permission\": permission,\n\t\t\t\"err\": err.Error(),\n\t\t}, \"unable to marshal keycloak permission struct\")\n\t\treturn \"\", errors.NewInternalError(errs.Wrap(err, \"unable to marshal keycloak permission struct\"))\n\t}\n\n\treq, err := http.NewRequest(\"POST\", clientsEndpoint+\"/\"+clientID+\"/authz/resource-server/policy\", strings.NewReader(string(b)))\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"err\": err.Error(),\n\t\t}, \"unable to create http request\")\n\t\treturn \"\", errors.NewInternalError(errs.Wrap(err, \"unable to create http request\"))\n\t}\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Header.Add(\"Authorization\", \"Bearer \"+protectionAPIToken)\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"client_id\": clientID,\n\t\t\t\"permission\": permission,\n\t\t\t\"err\": err.Error(),\n\t\t}, \"unable to create the Keycloak permission\")\n\t\treturn \"\", errors.NewInternalError(errs.Wrap(err, \"unable to create the Keycloak permission\"))\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != http.StatusCreated {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"client_id\": clientID,\n\t\t\t\"permission\": permission,\n\t\t\t\"response_status\": res.Status,\n\t\t\t\"response_body\": rest.ReadBody(res.Body),\n\t\t}, \"unable to update the Keycloak permission\")\n\t\treturn \"\", errors.NewInternalError(errs.New(\"unable to create the Keycloak permission. Response status: \" + res.Status + \". Responce body: \" + rest.ReadBody(res.Body)))\n\t}\n\tjsonString := rest.ReadBody(res.Body)\n\n\tvar r createPolicyRequestResultPayload\n\terr = json.Unmarshal([]byte(jsonString), &r)\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"client_id\": clientID,\n\t\t\t\"permission\": permission,\n\t\t\t\"json_string\": jsonString,\n\t\t}, \"unable to unmarshal json with the create keycloak permission request result\")\n\t\treturn \"\", errors.NewInternalError(errs.Wrapf(err, \"error when unmarshal json with the create keycloak permission request result %s \", jsonString))\n\t}\n\n\treturn r.ID, nil\n}", "func parseSharePermissions(s string) (SharePermissions, error) {\n\tp := SharePermissions{} // Clear the flags\n\tfor _, r := range s {\n\t\tswitch r {\n\t\tcase 'r':\n\t\t\tp.Read = true\n\t\tcase 'c':\n\t\t\tp.Create = true\n\t\tcase 'w':\n\t\t\tp.Write = true\n\t\tcase 'd':\n\t\t\tp.Delete = true\n\t\tcase 'l':\n\t\t\tp.List = true\n\t\tdefault:\n\t\t\treturn SharePermissions{}, fmt.Errorf(\"invalid permission: '%v'\", r)\n\t\t}\n\t}\n\treturn p, nil\n}", "func BuildPermissions(ps []string) ([]Permission, error) {\n\tpSl := make([]Permission, len(ps))\n\tvar err error\n\tfor i := range ps {\n\t\tpSl[i], err = BuildPermission(ps[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn pSl, nil\n}", "func parseFilePermissions(s string) (FilePermissions, error) {\n\tp := FilePermissions{} // Clear the flags\n\tfor _, r := range s {\n\t\tswitch r {\n\t\tcase 'r':\n\t\t\tp.Read = true\n\t\tcase 'c':\n\t\t\tp.Create = true\n\t\tcase 'w':\n\t\t\tp.Write = true\n\t\tcase 'd':\n\t\t\tp.Delete = true\n\t\tdefault:\n\t\t\treturn FilePermissions{}, fmt.Errorf(\"invalid permission: '%v'\", r)\n\t\t}\n\t}\n\treturn p, nil\n}", "func TransformPermission(permission db.Permission) ResponsePermission {\n\treturn ResponsePermission{\n\t\tKey: permission.Key,\n\t\tDescription: permission.Description,\n\t}\n}", "func NewPermission(a Action, r Resource) (*Permission, error) {\n\tp := &Permission{\n\t\tAction: a,\n\t\tResource: r,\n\t}\n\n\treturn p, p.Valid()\n}", "func PermFlagToString(pf PermFlag) (perm string) {\n\tswitch pf {\n\tcase Root:\n\t\tperm = \"root\"\n\tcase Send:\n\t\tperm = \"send\"\n\tcase Call:\n\t\tperm = \"call\"\n\tcase CreateContract:\n\t\tperm = \"create_contract\"\n\tcase CreateAccount:\n\t\tperm = \"create_account\"\n\tcase Bond:\n\t\tperm = \"bond\"\n\tcase Name:\n\t\tperm = \"name\"\n\tcase HasBase:\n\t\tperm = \"hasBase\"\n\tcase SetBase:\n\t\tperm = \"setBase\"\n\tcase UnsetBase:\n\t\tperm = \"unsetBase\"\n\tcase SetGlobal:\n\t\tperm = \"setGlobal\"\n\tcase HasRole:\n\t\tperm = \"hasRole\"\n\tcase AddRole:\n\t\tperm = \"addRole\"\n\tcase RmRole:\n\t\tperm = \"removeRole\"\n\tdefault:\n\t\tperm = \"#-UNKNOWN-#\"\n\t}\n\treturn\n}", "func NewPermission(ctx *pulumi.Context,\n\tname string, args *PermissionArgs, opts ...pulumi.ResourceOption) (*Permission, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.StackId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'StackId'\")\n\t}\n\tif args.UserArn == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'UserArn'\")\n\t}\n\tvar resource Permission\n\terr := ctx.RegisterResource(\"aws:opsworks/permission:Permission\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func bindPermission(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(PermissionABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func parsePerm(p string) (os.FileMode, error) {\n\t/* Make sure it's a number */\n\ti, err := strconv.ParseUint(p, 8, 32)\n\tif nil != err {\n\t\treturn 0, err\n\t}\n\t/* Too large no worky */\n\tif 0777 < i {\n\t\treturn 0, fmt.Errorf(\"invalid octal permissions\")\n\t}\n\t/* Mask off the lower nine bits */\n\treturn os.FileMode(i & 0x000001FF), nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
BuildPermissions calls BuildPermission for all strings
func BuildPermissions(ps []string) ([]Permission, error) { pSl := make([]Permission, len(ps)) var err error for i := range ps { pSl[i], err = BuildPermission(ps[i]) if err != nil { return nil, err } } return pSl, nil }
[ "func BuildPermission(str string) (Permission, error) {\n\tif valid, err := ValidatePermission(str); !valid {\n\t\treturn Permission{}, err\n\t}\n\tparts := strings.Split(str, \"::\")\n\tservice := parts[0]\n\tol := OwnershipLevel(parts[1])\n\taction := BuildAction(parts[2])\n\trh := ResourceHierarchy(strings.Join(parts[3:], \"::\"))\n\treturn Permission{\n\t\tService: service,\n\t\tOwnershipLevel: ol,\n\t\tAction: action,\n\t\tResourceHierarchy: rh,\n\t}, nil\n}", "func TestPermissionsLength(t *testing.T) {\n\tpermissionsString := \"\"\n\tfor _, permission := range ALL_PERMISSIONS {\n\t\tpermissionsString += \" \" + permission.Id\n\t}\n\n\tassert.True(t, len(permissionsString) < 4096)\n}", "func validatePermissions(permissions ...string) error {\n\tfor _, perm := range permissions {\n\t\tif strings.TrimSpace(perm) == \"\" {\n\t\t\treturn fmt.Errorf(\"module permission is empty\")\n\t\t}\n\t}\n\treturn nil\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 ResourceBuildFolderPermissions() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceBuildFolderPermissionsCreateOrUpdate,\n\t\tRead: resourceBuildFolderPermissionsRead,\n\t\tUpdate: resourceBuildFolderPermissionsCreateOrUpdate,\n\t\tDelete: resourceBuildFolderPermissionsDelete,\n\t\tSchema: securityhelper.CreatePermissionResourceSchema(map[string]*schema.Schema{\n\t\t\t\"project_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tValidateFunc: validation.IsUUID,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"path\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t}),\n\t}\n}", "func (App) Permissions() []evo.Permission { return []evo.Permission{} }", "func Test_FSValidation_AddPermission_ToString(t *testing.T) {\n\tfilePath := \"asdasda\"\n\tresult := TryAddPermission(filePath, 0755)\n\tfmt.Println(result)\n\tassert.Equal(t, result, false)\n}", "func Test_CheckPermissions(t *testing.T) {\n\tname := \"User1\"\n\t//\n\t//\tul := um.NewUsersList()\n\t//\tuser1, _ := um.NewUser(name, nil)\n\t//\tul.AddUser(user1)\n\ta, _ := NewEntry(name)\n\n\t// verify that valid permission can be added\n\tok, permission := addPermissions(a, permissionsMap, true)\n\tif ok == false {\n\t\tt.Errorf(\"Test fail: Fail to add valid permission: '%v' to %v\", permission, a)\n\t}\n\t// verify that only permission that are in the list returns true\n\tfor p, val := range permissionsMap {\n\t\tok, _ := a.CheckPermission(p)\n\t\tif ok == false && val == true {\n\t\t\tt.Errorf(\"Test fail: Permission: '%v' from %v wasn't found\", p, a)\n\t\t} else if ok == true && val == false {\n\t\t\tt.Errorf(\"Test fail: Permission: '%v' that is not in %v, was found\", p, a)\n\t\t}\n\t}\n}", "func (o IoTHubSharedAccessPolicyOutput) Permissions() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v IoTHubSharedAccessPolicy) *string { return v.Permissions }).(pulumi.StringPtrOutput)\n}", "func PipelinePermission(key string, name string, u *sdk.User) int {\n\tif u.Admin {\n\t\treturn PermissionReadWriteExecute\n\t}\n\n\treturn u.Permissions.PipelinesPerm[sdk.UserPermissionKey(key, name)]\n}", "func (o ObjectCopyGrantOutput) Permissions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ObjectCopyGrant) []string { return v.Permissions }).(pulumi.StringArrayOutput)\n}", "func ProjectPermission(projectKey string, u *sdk.User) int {\n\tif u.Admin || u == nil {\n\t\treturn PermissionReadWriteExecute\n\t}\n\n\treturn u.Permissions.ProjectsPerm[projectKey]\n}", "func ValidatePermissions(ctx context.Context, spec *argoappv1.ApplicationSpec, proj *argoappv1.AppProject, db db.ArgoDB) ([]argoappv1.ApplicationCondition, error) {\n\tconditions := make([]argoappv1.ApplicationCondition, 0)\n\n\tif spec.HasMultipleSources() {\n\t\tfor _, source := range spec.Sources {\n\t\t\tcondition := validateSourcePermissions(ctx, source, proj, spec.Project, spec.HasMultipleSources())\n\t\t\tif len(condition) > 0 {\n\t\t\t\tconditions = append(conditions, condition...)\n\t\t\t\treturn conditions, nil\n\t\t\t}\n\n\t\t\tif !proj.IsSourcePermitted(source) {\n\t\t\t\tconditions = append(conditions, argoappv1.ApplicationCondition{\n\t\t\t\t\tType: argoappv1.ApplicationConditionInvalidSpecError,\n\t\t\t\t\tMessage: fmt.Sprintf(\"application repo %s is not permitted in project '%s'\", source.RepoURL, spec.Project),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\tconditions = validateSourcePermissions(ctx, spec.GetSource(), proj, spec.Project, spec.HasMultipleSources())\n\t\tif len(conditions) > 0 {\n\t\t\treturn conditions, nil\n\t\t}\n\n\t\tif !proj.IsSourcePermitted(spec.GetSource()) {\n\t\t\tconditions = append(conditions, argoappv1.ApplicationCondition{\n\t\t\t\tType: argoappv1.ApplicationConditionInvalidSpecError,\n\t\t\t\tMessage: fmt.Sprintf(\"application repo %s is not permitted in project '%s'\", spec.GetSource().RepoURL, spec.Project),\n\t\t\t})\n\t\t}\n\t}\n\n\t// ValidateDestination will resolve the destination's server address from its name for us, if possible\n\tif err := ValidateDestination(ctx, &spec.Destination, db); err != nil {\n\t\tconditions = append(conditions, argoappv1.ApplicationCondition{\n\t\t\tType: argoappv1.ApplicationConditionInvalidSpecError,\n\t\t\tMessage: err.Error(),\n\t\t})\n\t\treturn conditions, nil\n\t}\n\n\tif spec.Destination.Server != \"\" {\n\t\tpermitted, err := proj.IsDestinationPermitted(spec.Destination, func(project string) ([]*argoappv1.Cluster, error) {\n\t\t\treturn db.GetProjectClusters(ctx, project)\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !permitted {\n\t\t\tconditions = append(conditions, argoappv1.ApplicationCondition{\n\t\t\t\tType: argoappv1.ApplicationConditionInvalidSpecError,\n\t\t\t\tMessage: fmt.Sprintf(\"application destination server '%s' and namespace '%s' do not match any of the allowed destinations in project '%s'\", spec.Destination.Server, spec.Destination.Namespace, spec.Project),\n\t\t\t})\n\t\t}\n\t\t// Ensure the k8s cluster the app is referencing, is configured in Argo CD\n\t\t_, err = db.GetCluster(ctx, spec.Destination.Server)\n\n\t\tif err != nil {\n\t\t\tif errStatus, ok := status.FromError(err); ok && errStatus.Code() == codes.NotFound {\n\t\t\t\tconditions = append(conditions, argoappv1.ApplicationCondition{\n\t\t\t\t\tType: argoappv1.ApplicationConditionInvalidSpecError,\n\t\t\t\t\tMessage: fmt.Sprintf(\"cluster '%s' has not been configured\", spec.Destination.Server),\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"error getting cluster: %w\", err)\n\t\t\t}\n\t\t}\n\t} else if spec.Destination.Server == \"\" {\n\t\tconditions = append(conditions, argoappv1.ApplicationCondition{Type: argoappv1.ApplicationConditionInvalidSpecError, Message: errDestinationMissing})\n\t}\n\treturn conditions, nil\n}", "func (vr *VoiceRecorder) grantPermissions(ctx context.Context) error {\n\tfor _, permission := range []string{\n\t\t\"android.permission.RECORD_AUDIO\",\n\t\t\"android.permission.READ_EXTERNAL_STORAGE\",\n\t} {\n\t\tif err := vr.app.ARC.Command(ctx, \"pm\", \"grant\", pkgName, permission).Run(testexec.DumpLogOnError); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to grant access permission\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func LFPermission_Values() []string {\n\treturn []string{\n\t\tLFPermissionDescribe,\n\t\tLFPermissionSelect,\n\t}\n}", "func parsePermissions(s string) ([]bool, error) {\n\tret := make([]bool, len(s))\n\tfor i := range s {\n\t\tif s[i] == 't' {\n\t\t\tret[i] = true\n\t\t} else if s[i] == 'f' {\n\t\t\tret[i] = false\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"error: invalid permissions string in database: %q\",\n\t\t\t\ts,\n\t\t\t)\n\t\t}\n\t}\n\treturn ret, 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 (m *Permission) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tfor idx, item := range m.GetPaths() {\n\t\t_, _ = idx, item\n\n\t\tif v, ok := interface{}(item).(interface{ Validate() error }); ok {\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\treturn PermissionValidationError{\n\t\t\t\t\tField: fmt.Sprintf(\"Paths[%v]\", idx),\n\t\t\t\t\tReason: \"embedded message failed validation\",\n\t\t\t\t\tCause: err,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tfor idx, item := range m.GetConditions() {\n\t\t_, _ = idx, item\n\n\t\tif v, ok := interface{}(item).(interface{ Validate() error }); ok {\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\treturn PermissionValidationError{\n\t\t\t\t\tField: fmt.Sprintf(\"Conditions[%v]\", idx),\n\t\t\t\t\tReason: \"embedded message failed validation\",\n\t\t\t\t\tCause: err,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func (o SecurityProfileOutput) Permissions() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *SecurityProfile) pulumi.StringArrayOutput { return v.Permissions }).(pulumi.StringArrayOutput)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
IsPresent checks if a permission is satisfied in a slice
func (p Permission) IsPresent(permissions []Permission) bool { for _, pp := range permissions { if (pp.Service != "*" && pp.Service != p.Service) || (pp.Action != "*" && pp.Action != p.Action) || pp.OwnershipLevel.Less(p.OwnershipLevel) { continue } if pp.ResourceHierarchy.Contains(p.ResourceHierarchy) { return true } } return false }
[ "func pvtHasAdminScreenAccess(s *sess.Session, el int, perm int) bool {\n\tvar p int\n\tvar ok bool\n\tfor i := 0; i < len(adminScreenFields); i++ {\n\t\tif adminScreenFields[i].Elem == el {\n\t\t\tif (el == authz.ELEMPERSON && adminScreenFields[i].AdminScreen) || (el != authz.ELEMPERSON) {\n\t\t\t\tswitch el {\n\t\t\t\tcase authz.ELEMPERSON:\n\t\t\t\t\tp, ok = s.PMap.Pp[adminScreenFields[i].FieldName] // here's the permission we have\n\t\t\t\tcase authz.ELEMCOMPANY:\n\t\t\t\t\tp, ok = s.PMap.Pco[adminScreenFields[i].FieldName] // here's the permission we have\n\t\t\t\tcase authz.ELEMCLASS:\n\t\t\t\t\tp, ok = s.PMap.Pcl[adminScreenFields[i].FieldName] // here's the permission we have\n\t\t\t\tcase authz.ELEMPBSVC:\n\t\t\t\t\tp, ok = s.PMap.Ppr[adminScreenFields[i].FieldName] // here's the permission we have\n\t\t\t\t}\n\t\t\t\tif ok { // if we have a permission for the field name\n\t\t\t\t\t// fmt.Printf(\"p = 0x%02x\\n\", p)\n\t\t\t\t\tpcheck := p & perm // AND it with the required permission\n\t\t\t\t\tif 0 != pcheck { // if the result is non-zero...\n\t\t\t\t\t\t// fmt.Printf(\"granted\\n\")\n\t\t\t\t\t\treturn true // ... we have the permission to view the screen\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// fmt.Printf(\"not granted\\n\")\n\treturn false\n}", "func (role *Role[T]) Permit(p Permission[T]) (ok bool) {\n\tvar zero Permission[T]\n\tif p == zero {\n\t\treturn false\n\t}\n\n\trole.RLock()\n\tfor _, rp := range role.permissions {\n\t\tif rp.Match(p) {\n\t\t\tok = true\n\t\t\tbreak\n\t\t}\n\t}\n\trole.RUnlock()\n\treturn\n}", "func HasPermission(c *JWTClaims, e string, p string) bool {\n\treturn strings.Contains(c.Permissions[e], p)\n}", "func IsPermission(err error) bool", "func (client *ClientImpl) HasPermissions(ctx context.Context, args HasPermissionsArgs) (*[]bool, error) {\n\trouteValues := make(map[string]string)\n\tif args.SecurityNamespaceId == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.SecurityNamespaceId\"}\n\t}\n\trouteValues[\"securityNamespaceId\"] = (*args.SecurityNamespaceId).String()\n\tif args.Permissions != nil {\n\t\trouteValues[\"permissions\"] = strconv.Itoa(*args.Permissions)\n\t}\n\n\tqueryParams := url.Values{}\n\tif args.Tokens != nil {\n\t\tqueryParams.Add(\"tokens\", *args.Tokens)\n\t}\n\tif args.AlwaysAllowAdministrators != nil {\n\t\tqueryParams.Add(\"alwaysAllowAdministrators\", strconv.FormatBool(*args.AlwaysAllowAdministrators))\n\t}\n\tif args.Delimiter != nil {\n\t\tqueryParams.Add(\"delimiter\", *args.Delimiter)\n\t}\n\tlocationId, _ := uuid.Parse(\"dd3b8bd6-c7fc-4cbd-929a-933d9c011c9d\")\n\tresp, err := client.Client.Send(ctx, http.MethodGet, locationId, \"7.1-preview.2\", routeValues, queryParams, nil, \"\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue []bool\n\terr = client.Client.UnmarshalCollectionBody(resp, &responseValue)\n\treturn &responseValue, err\n}", "func pvtHasAdminScreenAccess(s *db.Session, el int, perm int64) bool {\n\tvar p int64\n\tvar ok bool\n\tfor i := 0; i < len(adminScreenFields); i++ {\n\t\tif adminScreenFields[i].Elem == el {\n\t\t\tif (el == db.ELEMPERSON && adminScreenFields[i].AdminScreen) || (el != db.ELEMPERSON) {\n\t\t\t\tswitch el {\n\t\t\t\tcase db.ELEMPERSON:\n\t\t\t\t\tp, ok = s.PMap.Pp[adminScreenFields[i].FieldName] // here's the permission we have\n\t\t\t\tcase db.ELEMCOMPANY:\n\t\t\t\t\tp, ok = s.PMap.Pco[adminScreenFields[i].FieldName] // here's the permission we have\n\t\t\t\tcase db.ELEMCLASS:\n\t\t\t\t\tp, ok = s.PMap.Pcl[adminScreenFields[i].FieldName] // here's the permission we have\n\t\t\t\tcase db.ELEMPBSVC:\n\t\t\t\t\tp, ok = s.PMap.Ppr[adminScreenFields[i].FieldName] // here's the permission we have\n\t\t\t\t}\n\t\t\t\tif ok { // if we have a permission for the field name\n\t\t\t\t\t// fmt.Printf(\"p = 0x%02x\\n\", p)\n\t\t\t\t\tpcheck := p & perm // AND it with the required permission\n\t\t\t\t\tif 0 != pcheck { // if the result is non-zero...\n\t\t\t\t\t\t// fmt.Printf(\"granted\\n\")\n\t\t\t\t\t\treturn true // ... we have the permission to view the screen\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// fmt.Printf(\"not granted\\n\")\n\treturn false\n}", "func (pa PermissionsForAddress) HasPermission(permission string) bool {\n\tfor _, perm := range pa.permissions {\n\t\tif perm == permission {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (o *InlineResponse20027Person) HasPermissions() bool {\n\tif o != nil && o.Permissions != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func hasPermissions(path string, modules []string) bool {\n\t// If no modules allow access\n\tif len(modules) == 0 {\n\t\treturn true\n\t}\n\t// Iterate and check for each module in grant list\n\tfor _, userModule := range modules {\n\t\tif userModule == moduleutils.GetCurrentModule(path) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (k Key) HasPermission(flag uint32) bool {\n\tp := k.Permissions()\n\treturn (p & flag) == flag\n}", "func (_Storage *StorageCaller) PermissionExists(opts *bind.CallOpts, kind uint8, addr common.Address) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _Storage.contract.Call(opts, out, \"permissionExists\", kind, addr)\n\treturn *ret0, err\n}", "func (ctl Controller) HasPermission(ctx *gin.Context) bool {\n\n\tperms := ctl.this.GetPermissions(ctx)\n\tfor _, f := range perms {\n\t\tif !f(ctl.user) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func hasAccess(need, have []string, all bool, enableWildcard bool) bool {\n\tif len(need) == 0 {\n\t\treturn true\n\t}\n\n\tvar matched int\n\tfor _, x := range need {\n\t\tfound := containedIn(x, have, enableWildcard)\n\t\tswitch found {\n\t\tcase true:\n\t\t\tif !all {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tmatched++\n\t\tdefault:\n\t\t\tif all {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn matched > 0\n}", "func sliceHasMember(slice []string, member string) bool {\n\tfor _, m := range slice {\n\t\tif m == member {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (sp *SalePermission) Exists() bool { //sale_permission\n\treturn sp._exists\n}", "func pvtElemPermsAny(s *Session, elem int, perm int) bool {\n\t// lib.Ulog(\"elemPermsAny: elem=%d, perm = 0x%02x\\n\", elem, perm)\n\tfor i := 0; i < len(s.PMap.Urole.Perms); i++ {\n\t\t// lib.Ulog(\"s.PMap.Urole.Perms[%d].Elem = %d\\n\", i, s.PMap.Urole.Perms[i].Elem)\n\t\tif s.PMap.Urole.Perms[i].Elem == elem {\n\t\t\tres := s.PMap.Urole.Perms[i].Perm & perm\n\t\t\t// lib.Ulog(\"fieldname: %s s.PMap.Urole.Perms[%d].Perm = 0x%02x, s.PMap.Urole.Perms[%d].Perm & perm = 0x%02x\\n\", s.PMap.Urole.Perms[i].Field, i, s.PMap.Urole.Perms[i].Elem, i, res)\n\t\t\tif res != 0 { // if any of the permissions exist\n\t\t\t\t// lib.Ulog(\"return true\") // we're good to go for this check\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\t// lib.Ulog(\"return false\")\n\treturn false\n}", "func (_SimpleReadAccessController *SimpleReadAccessControllerCallerSession) HasAccess(_user common.Address, _calldata []byte) (bool, error) {\n\treturn _SimpleReadAccessController.Contract.HasAccess(&_SimpleReadAccessController.CallOpts, _user, _calldata)\n}", "func Has(ctx context.Context, permission int) bool {\n\taccessToken := ctx.Value(util.ContextKey(\"token\")).(string)\n\n\tconn, err := grpc.Dial(AuthRPCAddress, grpc.WithInsecure())\n\tif err != nil {\n\t\tlog.Printf(\"Failed to dial auth rpc service: %v\", err)\n\t\treturn false\n\t}\n\tdefer conn.Close()\n\n\tclient := proto.NewPermissionServiceClient(conn)\n\tctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)\n\tdefer cancel()\n\n\tdata := &proto.PermissionData{\n\t\tAccessToken: accessToken,\n\t\tPermission: int32(permission),\n\t}\n\n\tpErr, err := client.HasPermission(ctx, data)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to call client method: HasPermission: %v\", err)\n\t\treturn false\n\t}\n\n\treturn pErr.GetStatusCode() == 200\n}", "func (_LvRecordableStream *LvRecordableStreamCaller) HasRightsHolderPermission(opts *bind.CallOpts) (bool, error) {\n\tvar out []interface{}\n\terr := _LvRecordableStream.contract.Call(opts, &out, \"hasRightsHolderPermission\")\n\n\tif err != nil {\n\t\treturn *new(bool), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(bool)).(*bool)\n\n\treturn out0, err\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
HasServiceFullAccess checks if permission allows it's role to execute any action over any resourch hierarchy under it's service
func (p Permission) HasServiceFullAccess() bool { if !p.Action.All() { return false } return p.ResourceHierarchy.All() }
[ "func (p Permission) HasServiceFullOwnership() bool {\n\treturn p.HasServiceFullAccess() && p.OwnershipLevel == OwnershipLevels.Owner\n}", "func (_BaseAccessControlGroup *BaseAccessControlGroupCaller) HasAccessRight(opts *bind.CallOpts, candidate common.Address, mgr bool) (bool, error) {\n\tvar out []interface{}\n\terr := _BaseAccessControlGroup.contract.Call(opts, &out, \"hasAccessRight\", candidate, mgr)\n\n\tif err != nil {\n\t\treturn *new(bool), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(bool)).(*bool)\n\n\treturn out0, err\n\n}", "func (authSvc *AuthService) partyHasAccess(dbClient DBClient, party Party,\n\tactionMask []bool, resource Resource) (bool, error) {\n\t\n\t// Discover which field of the action mask is set.\n\tvar action int = -1\n\tfor i, entry := range actionMask {\n\t\tif entry {\n\t\t\tif action != -1 { return false, utilities.ConstructUserError(\"More than one field set in action mask\") }\n\t\t\taction = i\n\t\t}\n\t}\n\tif action == -1 { return false, nil } // no action mask fields were set.\n\t\n\tvar entries []string = party.getACLEntryIds()\n\tfor _, entryId := range entries { // for each of the party's ACL entries...\n\t\t\n\t\tvar entry ACLEntry\n\t\tvar err error\n\t\tentry, err = dbClient.getACLEntry(entryId)\n\t\tif err != nil { return false, err }\n\t\t\n\t\tif entry.getResourceId() == resource.getId() { // if the entry references the resource,\n\t\t\tvar mask []bool = entry.getPermissionMask()\n\t\t\tif mask[action] { return true, nil } // party has access to the resource\n\t\t}\n\t}\n\treturn false, nil\n}", "func (svc *Service) HasPrivilege(ctx context.Context, priv string) (bool, error) {\n\tif priv == \"\" {\n\t\treturn false, nil\n\t}\n\tprivs, err := svc.getPrivileges(ctx)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tfor i := range privs {\n\t\tif privs[i].Key == priv {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\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 hasAdminRights() (bool, error) {\n\tclientset, err := kubeutils.GetClientSet(true)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tsar := &authorizationv1.SelfSubjectAccessReview{\n\t\tSpec: authorizationv1.SelfSubjectAccessReviewSpec{\n\t\t\tResourceAttributes: &authorizationv1.ResourceAttributes{},\n\t\t},\n\t}\n\tresp, err := clientset.AuthorizationV1().SelfSubjectAccessReviews().Create(context.TODO(), sar, v1.CreateOptions{})\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn resp.Status.Allowed, nil\n}", "func (client *ClientImpl) HasPermissions(ctx context.Context, args HasPermissionsArgs) (*[]bool, error) {\n\trouteValues := make(map[string]string)\n\tif args.SecurityNamespaceId == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.SecurityNamespaceId\"}\n\t}\n\trouteValues[\"securityNamespaceId\"] = (*args.SecurityNamespaceId).String()\n\tif args.Permissions != nil {\n\t\trouteValues[\"permissions\"] = strconv.Itoa(*args.Permissions)\n\t}\n\n\tqueryParams := url.Values{}\n\tif args.Tokens != nil {\n\t\tqueryParams.Add(\"tokens\", *args.Tokens)\n\t}\n\tif args.AlwaysAllowAdministrators != nil {\n\t\tqueryParams.Add(\"alwaysAllowAdministrators\", strconv.FormatBool(*args.AlwaysAllowAdministrators))\n\t}\n\tif args.Delimiter != nil {\n\t\tqueryParams.Add(\"delimiter\", *args.Delimiter)\n\t}\n\tlocationId, _ := uuid.Parse(\"dd3b8bd6-c7fc-4cbd-929a-933d9c011c9d\")\n\tresp, err := client.Client.Send(ctx, http.MethodGet, locationId, \"7.1-preview.2\", routeValues, queryParams, nil, \"\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue []bool\n\terr = client.Client.UnmarshalCollectionBody(resp, &responseValue)\n\treturn &responseValue, err\n}", "func (s *Service) IsAccessAllowed(r *AccessRequest)(bool) {\n\t// TODO: Sort on importance of policy\n\tsort.SliceStable(s.Policies, func(i, j int) bool {return s.Policies[i].Id < s.Policies[j].Id})\n\n\tlog.Printf(\"Checking policy for user=%s, groups=%s, access=%s, location=%s\\n\",\n\t\tr.User, r.UserGroups, r.AccessType, r.Resource.Location)\n\n\tallowed := false\n\tresourceMatch := false\n\n\tfor _, p := range s.Policies {\n\t\t// match resource\n\t\tfor _, v := range p.Resources {\n\t\t\tfor _, bucketName := range v.Values {\n\t\t\t\tif v.IsRecursive {\n\t\t\t\t\tbucketName += \"*\"\n\t\t\t\t}\n\t\t\t\tif glob.Glob(bucketName, r.Resource.Location) {\n\t\t\t\t\tresourceMatch = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlog.Printf(\"Policy id=%d, name=%s, resource_match=%s\\n\", p.Id, p.Name, resourceMatch)\n\n\t\tif !resourceMatch {\n\t\t\tcontinue\n\t\t}\n\n\t\t// We have a resource match\n\n\t\tlog.Printf(\"Checking allow policy items=%d\\n\", len(p.PolicyItems))\n\t\tfor _, item := range p.PolicyItems {\n\t\t\t// user first\n\t\t\tallowed = hasAccess([]string{r.User}, item.Users, item.Accesses, r.AccessType, r.User == r.Resource.Owner)\n\n\t\t\t// groups\n\t\t\tif !allowed {\n\t\t\t\tallowed = hasAccess(r.UserGroups, item.Groups, item.Accesses, r.AccessType, false)\n\t\t\t}\n\n\t\t\t// conditions\n\t\t\tif allowed {\n\t\t\t\tlog.Printf(\"Checking allow policy conditions\\n\")\n\t\t\t\tfound := false\n\t\t\t\tfor _, condition := range item.Conditions {\n\t\t\t\t\tvar err error\n\t\t\t\t\terr, found = condition.isInCondition(r)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Printf(\"Error checking condition=%s err=%s\\n\", condition, err)\n\t\t\t\t\t}\n\t\t\t\t\tif found {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !found && len(item.Conditions) > 0 {\n\t\t\t\t\tlog.Printf(\"policyItem=%s conditions not met\\n\", item)\n\t\t\t\t\tallowed = false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// TODO: check exceptions\n\t\t}\n\n\t\tlog.Printf(\"Checking deny policy items=%d\\n\", len(p.DenyPolicyItems))\n\n\t\tfor _, item := range p.DenyPolicyItems {\n\t\t\t// allowed signals denial\n\t\t\tallowed = !hasAccess([]string{r.User}, item.Users, item.Accesses, r.AccessType, r.User == r.Resource.Owner)\n\n\t\t\t// groups\n\t\t\tif allowed {\n\t\t\t\tallowed = !hasAccess(r.UserGroups, item.Groups, item.Accesses, r.AccessType, false)\n\t\t\t}\n\n\t\t\t// conditions\n\t\t\tif !allowed {\n\t\t\t\tlog.Printf(\"Checking deny policy conditions\\n\")\n\t\t\t\tfound := false\n\t\t\t\tfor _, condition := range item.Conditions {\n\t\t\t\t\t_, found = condition.isInCondition(r)\n\t\t\t\t\tif found {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !found && len(item.Conditions) > 0 {\n\t\t\t\t\tallowed = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// TODO: check exceptions\n\t\t}\n\n\t\t// if we got here we had a resource match\n\t\tbreak\n\t}\n\n\treturn allowed\n}", "func hasTargetPermission(c Config, s iam.Statement) bool {\n\tif !s.IsAllow() {\n\t\treturn false\n\t}\n\n\tsvc := c.GetTargetActionServices()\n\tif svc.hasService() {\n\t\treturn svc.HasTargetInActions(s.Action)\n\t}\n\tif containsStringInList(s.Resource, c.GetTargetResources()) {\n\t\treturn true\n\t}\n\treturn containsStringInList(s.Action, c.GetTargetActions())\n}", "func (ctl Controller) HasPermission(ctx *gin.Context) bool {\n\n\tperms := ctl.this.GetPermissions(ctx)\n\tfor _, f := range perms {\n\t\tif !f(ctl.user) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func hasPermissions(path string, modules []string) bool {\n\t// If no modules allow access\n\tif len(modules) == 0 {\n\t\treturn true\n\t}\n\t// Iterate and check for each module in grant list\n\tfor _, userModule := range modules {\n\t\tif userModule == moduleutils.GetCurrentModule(path) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (r *Role) CanAccess(resource Resource, mask AccessMask) bool {\n\tfor res, level := range r.resources {\n\t\tif res.String() == resource.String() {\n\t\t\treturn uint8(mask)&bits.RotateLeft8(1, level.Int()) != 0\n\t\t}\n\t}\n\treturn false\n}", "func (c *Command) canAccess(r *http.Request, user *userState) accessResult {\n\tif c.AdminOnly && (c.UserOK || c.GuestOK || c.UntrustedOK) {\n\t\tlogger.Panicf(\"internal error: command cannot have AdminOnly together with any *OK flag\")\n\t}\n\n\tif user != nil && !c.AdminOnly {\n\t\t// Authenticated users do anything not requiring explicit admin.\n\t\treturn accessOK\n\t}\n\n\t// isUser means we have a UID for the request\n\tisUser := false\n\tpid, uid, socket, err := ucrednetGet(r.RemoteAddr)\n\tif err == nil {\n\t\tisUser = true\n\t} else if err != errNoID {\n\t\tlogger.Noticef(\"unexpected error when attempting to get UID: %s\", err)\n\t\treturn accessForbidden\n\t}\n\n\tisUntrusted := (socket == c.d.untrustedSocketPath)\n\n\t_ = pid\n\t_ = uid\n\n\tif isUntrusted {\n\t\tif c.UntrustedOK {\n\t\t\treturn accessOK\n\t\t}\n\t\treturn accessUnauthorized\n\t}\n\n\t// the !AdminOnly check is redundant, but belt-and-suspenders\n\tif r.Method == \"GET\" && !c.AdminOnly {\n\t\t// Guest and user access restricted to GET requests\n\t\tif c.GuestOK {\n\t\t\treturn accessOK\n\t\t}\n\n\t\tif isUser && c.UserOK {\n\t\t\treturn accessOK\n\t\t}\n\t}\n\n\t// Remaining admin checks rely on identifying peer uid\n\tif !isUser {\n\t\treturn accessUnauthorized\n\t}\n\n\tif uid == 0 || sys.UserID(uid) == sysGetuid() {\n\t\t// Superuser and process owner can do anything.\n\t\treturn accessOK\n\t}\n\n\tif c.AdminOnly {\n\t\treturn accessUnauthorized\n\t}\n\n\treturn accessUnauthorized\n}", "func (_BaseContentSpace *BaseContentSpaceCaller) HasAccess(opts *bind.CallOpts, arg0 common.Address) (bool, error) {\n\tvar out []interface{}\n\terr := _BaseContentSpace.contract.Call(opts, &out, \"hasAccess\", arg0)\n\n\tif err != nil {\n\t\treturn *new(bool), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(bool)).(*bool)\n\n\treturn out0, err\n\n}", "func (*AuthorizationStrategyAllowAll) CheckAccess(_ context.Context, _ RequestType, _ api.CloudServiceRequest) bool {\n\treturn true\n}", "func (o *ReportingTaskEntity) HasOperatePermissions() bool {\n\tif o != nil && o.OperatePermissions != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (jc *JetCoordinator) IsAuthorized(\n\tctx context.Context,\n\trole core.DynamicRole,\n\tobj *core.RecordID,\n\tpulse core.PulseNumber,\n\tnode core.RecordRef,\n) (bool, error) {\n\tnodes, err := jc.QueryRole(ctx, role, obj, pulse)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tfor _, n := range nodes {\n\t\tif n == node {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}", "func hasPermission(b *Brute, m *discordgo.MessageCreate, cmd *Command) bool {\n\tif cmd.Auth == nil || len(cmd.Auth) == 0 {\n\t\treturn true\n\t}\n\n\tfmt.Printf(\"Checking permissions for %s. Required Auth: %s\\n\", m.Author.Username, strings.Join(cmd.Auth, \",\"))\n\tg, err := GetGuild(b.Session, m.ChannelID)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to get guild: %v\\n\", err)\n\t\treturn false\n\t}\n\tmember, err := b.Session.GuildMember(g.ID, m.Author.ID)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to get guild member: %v\\n\", err)\n\t\treturn false\n\t}\n\n\tfor _, allowedRole := range cmd.Auth {\n\t\t// try to convert name to ID, but if that fails - use the provided string directly\n\t\tvar convertedRoleId = getRoleId(g, allowedRole)\n\t\tif convertedRoleId != \"\" {\n\t\t\tallowedRole = convertedRoleId\n\t\t}\n\t\tif hasRole(member, allowedRole) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (_SimpleReadAccessController *SimpleReadAccessControllerCallerSession) HasAccess(_user common.Address, _calldata []byte) (bool, error) {\n\treturn _SimpleReadAccessController.Contract.HasAccess(&_SimpleReadAccessController.CallOpts, _user, _calldata)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
HasServiceFullOwnership checks if permission allows it's role to execute any action over any resourch hierarchy under it's service and it's RO
func (p Permission) HasServiceFullOwnership() bool { return p.HasServiceFullAccess() && p.OwnershipLevel == OwnershipLevels.Owner }
[ "func (p Permission) HasServiceFullAccess() bool {\n\tif !p.Action.All() {\n\t\treturn false\n\t}\n\treturn p.ResourceHierarchy.All()\n}", "func (o *Object) CheckOwnership(creds *auth.Credentials) bool {\n\tif o.OwnerUID == creds.EffectiveKUID || o.CreatorUID == creds.EffectiveKUID {\n\t\treturn true\n\t}\n\n\t// Tasks with CAP_SYS_ADMIN may bypass ownership checks. Strangely, Linux\n\t// doesn't use CAP_IPC_OWNER for this despite CAP_IPC_OWNER being documented\n\t// for use to \"override IPC ownership checks\".\n\treturn creds.HasCapabilityIn(linux.CAP_SYS_ADMIN, o.UserNS)\n}", "func (p Permission) IsPresent(permissions []Permission) bool {\n\tfor _, pp := range permissions {\n\t\tif (pp.Service != \"*\" && pp.Service != p.Service) ||\n\t\t\t(pp.Action != \"*\" && pp.Action != p.Action) ||\n\t\t\tpp.OwnershipLevel.Less(p.OwnershipLevel) {\n\t\t\tcontinue\n\t\t}\n\t\tif pp.ResourceHierarchy.Contains(p.ResourceHierarchy) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (o *Object) CheckPermissions(creds *auth.Credentials, req vfs.AccessTypes) bool {\n\tperms := uint16(o.Mode.Permissions())\n\tif o.OwnerUID == creds.EffectiveKUID {\n\t\tperms >>= 6\n\t} else if creds.InGroup(o.OwnerGID) {\n\t\tperms >>= 3\n\t}\n\n\tif uint16(req)&perms == uint16(req) {\n\t\treturn true\n\t}\n\treturn creds.HasCapabilityIn(linux.CAP_IPC_OWNER, o.UserNS)\n}", "func (client *ClientImpl) HasPermissions(ctx context.Context, args HasPermissionsArgs) (*[]bool, error) {\n\trouteValues := make(map[string]string)\n\tif args.SecurityNamespaceId == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.SecurityNamespaceId\"}\n\t}\n\trouteValues[\"securityNamespaceId\"] = (*args.SecurityNamespaceId).String()\n\tif args.Permissions != nil {\n\t\trouteValues[\"permissions\"] = strconv.Itoa(*args.Permissions)\n\t}\n\n\tqueryParams := url.Values{}\n\tif args.Tokens != nil {\n\t\tqueryParams.Add(\"tokens\", *args.Tokens)\n\t}\n\tif args.AlwaysAllowAdministrators != nil {\n\t\tqueryParams.Add(\"alwaysAllowAdministrators\", strconv.FormatBool(*args.AlwaysAllowAdministrators))\n\t}\n\tif args.Delimiter != nil {\n\t\tqueryParams.Add(\"delimiter\", *args.Delimiter)\n\t}\n\tlocationId, _ := uuid.Parse(\"dd3b8bd6-c7fc-4cbd-929a-933d9c011c9d\")\n\tresp, err := client.Client.Send(ctx, http.MethodGet, locationId, \"7.1-preview.2\", routeValues, queryParams, nil, \"\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue []bool\n\terr = client.Client.UnmarshalCollectionBody(resp, &responseValue)\n\treturn &responseValue, err\n}", "func isProvisioned(ctx context.Context) (bool, error) {\n\treturn len(service.DefaultPermissions.FindRulesByRoleID(permissions.EveryoneRoleID)) > 0 &&\n\t\tlen(service.DefaultPermissions.FindRulesByRoleID(permissions.AdminsRoleID)) > 0, nil\n}", "func hasPermission(b *Brute, m *discordgo.MessageCreate, cmd *Command) bool {\n\tif cmd.Auth == nil || len(cmd.Auth) == 0 {\n\t\treturn true\n\t}\n\n\tfmt.Printf(\"Checking permissions for %s. Required Auth: %s\\n\", m.Author.Username, strings.Join(cmd.Auth, \",\"))\n\tg, err := GetGuild(b.Session, m.ChannelID)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to get guild: %v\\n\", err)\n\t\treturn false\n\t}\n\tmember, err := b.Session.GuildMember(g.ID, m.Author.ID)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to get guild member: %v\\n\", err)\n\t\treturn false\n\t}\n\n\tfor _, allowedRole := range cmd.Auth {\n\t\t// try to convert name to ID, but if that fails - use the provided string directly\n\t\tvar convertedRoleId = getRoleId(g, allowedRole)\n\t\tif convertedRoleId != \"\" {\n\t\t\tallowedRole = convertedRoleId\n\t\t}\n\t\tif hasRole(member, allowedRole) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func IsPermission(err error) bool", "func hasTargetPermission(c Config, s iam.Statement) bool {\n\tif !s.IsAllow() {\n\t\treturn false\n\t}\n\n\tsvc := c.GetTargetActionServices()\n\tif svc.hasService() {\n\t\treturn svc.HasTargetInActions(s.Action)\n\t}\n\tif containsStringInList(s.Resource, c.GetTargetResources()) {\n\t\treturn true\n\t}\n\treturn containsStringInList(s.Action, c.GetTargetActions())\n}", "func (_BaseAccessControlGroup *BaseAccessControlGroupCaller) HasAccessRight(opts *bind.CallOpts, candidate common.Address, mgr bool) (bool, error) {\n\tvar out []interface{}\n\terr := _BaseAccessControlGroup.contract.Call(opts, &out, \"hasAccessRight\", candidate, mgr)\n\n\tif err != nil {\n\t\treturn *new(bool), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(bool)).(*bool)\n\n\treturn out0, err\n\n}", "func (authSvc *AuthService) partyHasAccess(dbClient DBClient, party Party,\n\tactionMask []bool, resource Resource) (bool, error) {\n\t\n\t// Discover which field of the action mask is set.\n\tvar action int = -1\n\tfor i, entry := range actionMask {\n\t\tif entry {\n\t\t\tif action != -1 { return false, utilities.ConstructUserError(\"More than one field set in action mask\") }\n\t\t\taction = i\n\t\t}\n\t}\n\tif action == -1 { return false, nil } // no action mask fields were set.\n\t\n\tvar entries []string = party.getACLEntryIds()\n\tfor _, entryId := range entries { // for each of the party's ACL entries...\n\t\t\n\t\tvar entry ACLEntry\n\t\tvar err error\n\t\tentry, err = dbClient.getACLEntry(entryId)\n\t\tif err != nil { return false, err }\n\t\t\n\t\tif entry.getResourceId() == resource.getId() { // if the entry references the resource,\n\t\t\tvar mask []bool = entry.getPermissionMask()\n\t\t\tif mask[action] { return true, nil } // party has access to the resource\n\t\t}\n\t}\n\treturn false, nil\n}", "func (svc *Service) HasPrivilege(ctx context.Context, priv string) (bool, error) {\n\tif priv == \"\" {\n\t\treturn false, nil\n\t}\n\tprivs, err := svc.getPrivileges(ctx)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tfor i := range privs {\n\t\tif privs[i].Key == priv {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}", "func ResourceOwnedBy(owner runtime.Object) Func {\n\treturn func(obj runtime.Object) bool {\n\t\treturn metav1.IsControlledBy(obj.(metav1.Object), owner.(metav1.Object))\n\t}\n}", "func (sp *serviceOwnedEdgeLBObjectMetadata) IsOwnedBy(service *corev1.Service) bool {\n\treturn sp.ClusterName == cluster.Name && sp.Namespace == service.Namespace && sp.Name == service.Name\n}", "func (r *Role) CanAccess(resource Resource, mask AccessMask) bool {\n\tfor res, level := range r.resources {\n\t\tif res.String() == resource.String() {\n\t\t\treturn uint8(mask)&bits.RotateLeft8(1, level.Int()) != 0\n\t\t}\n\t}\n\treturn false\n}", "func (h *Handler) IsOwnedBy(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\taccountIDString, _ := vars[\"accountID\"]\n\tusername, _ := vars[\"username\"]\n\taccountID, err := strconv.Atoi(accountIDString)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprintf(w, \"Invalid account id passed as parameter\")\n\t\treturn\n\t}\n\tok, err := h.svc.IsOwnedBy(username, accountID)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintf(w, \"Unable to check ownership of account\")\n\t\tlogrus.Error(\"Unable to chech ownership of account in IsOwnedBy method\", err)\n\t\treturn\n\t}\n\tresult := Result{\n\t\tOK: ok,\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tbytes, _ := json.Marshal(result)\n\tfmt.Fprintf(w, string(bytes))\n}", "func (ctl Controller) HasPermission(ctx *gin.Context) bool {\n\n\tperms := ctl.this.GetPermissions(ctx)\n\tfor _, f := range perms {\n\t\tif !f(ctl.user) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func CheckPermissions(session *discordgo.Session, memberID string, channel discordgo.Channel, perms Permission) bool {\n\tif perms == 0 {\n\t\treturn true // If no permissions are required then just return true\n\t}\n\n\tfor _, overwrite := range channel.PermissionOverwrites {\n\t\tif overwrite.ID == memberID {\n\t\t\tif overwrite.Allow&int64(perms) != 0 {\n\t\t\t\treturn true // If the channel has an overwrite for the user then true\n\t\t\t} else if overwrite.Deny&int64(perms) != 0 {\n\t\t\t\treturn false // If there is an explicit deny then false\n\t\t\t}\n\t\t}\n\t}\n\n\tmember, err := session.State.Member(channel.GuildID, memberID)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn false\n\t}\n\tfor _, roleID := range member.Roles {\n\t\trole, err := session.State.Role(channel.GuildID, roleID)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\n\t\tfor _, overwrite := range channel.PermissionOverwrites {\n\t\t\tif overwrite.ID == roleID {\n\t\t\t\tif overwrite.Allow&int64(perms) != 0 {\n\t\t\t\t\treturn true // If the channel has an overwrite for the role then true\n\t\t\t\t} else if overwrite.Deny&int64(perms) != 0 {\n\t\t\t\t\treturn false // If there is an explicit deny then false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif role.Permissions&int64(PermissionAdministrator) != 0 {\n\t\t\treturn true // If they are an administrator then they automatically have all permissions\n\t\t}\n\n\t\tif role.Permissions&int64(perms) != 0 {\n\t\t\treturn true // The role has the required permissions\n\t\t}\n\t}\n\n\treturn false // Default to false\n}", "func (c KubernetesDefaultRouter) isOwnedByCanary(obj interface{}, name string) (bool, bool) {\n\tobject, ok := obj.(metav1.Object)\n\tif !ok {\n\t\treturn false, false\n\t}\n\n\townerRef := metav1.GetControllerOf(object)\n\tif ownerRef == nil {\n\t\treturn false, false\n\t}\n\n\tif ownerRef.Kind != flaggerv1.CanaryKind {\n\t\treturn false, false\n\t}\n\n\treturn true, ownerRef.Name == name\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
buildWillIAMPermission builds a permission in the format expected by WillIAM handlers
func buildWillIAMPermission(ro OwnershipLevel, action, rh string) string { return fmt.Sprintf( "%s::%s::%s::%s", constants.AppInfo.Name, string(ro), action, rh, ) }
[ "func BuildWillIAMPermissionLender(action, rh string) string {\n\treturn buildWillIAMPermission(OwnershipLevels.Lender, action, rh)\n}", "func BuildPermission(str string) (Permission, error) {\n\tif valid, err := ValidatePermission(str); !valid {\n\t\treturn Permission{}, err\n\t}\n\tparts := strings.Split(str, \"::\")\n\tservice := parts[0]\n\tol := OwnershipLevel(parts[1])\n\taction := BuildAction(parts[2])\n\trh := ResourceHierarchy(strings.Join(parts[3:], \"::\"))\n\treturn Permission{\n\t\tService: service,\n\t\tOwnershipLevel: ol,\n\t\tAction: action,\n\t\tResourceHierarchy: rh,\n\t}, nil\n}", "func PermissionItoA(permission int) string {\n\tif permission < PermissionDefault {\n\t\treturn PermissionBannedString\n\t} else if permission < PermissionVerified {\n\t\treturn PermissionDefaultString\n\t} else if permission < PermissionTeam {\n\t\treturn PermissionVerifiedString\n\t} else if permission < PermissionAdmin {\n\t\treturn PermissionTeamString\n\t}\n\treturn PermissionAdminString\n}", "func generateIAMPolicy(principalId string, effect string, resource string) events.APIGatewayCustomAuthorizerResponse {\n\tdefer track(time.Now(), \"generateIAMPolicy()\")\n\tauthResponse := events.APIGatewayCustomAuthorizerResponse{PrincipalID: principalId}\n\n\tif effect != \"\" && resource != \"\" {\n\t\tauthResponse.PolicyDocument = events.APIGatewayCustomAuthorizerPolicy{\n\t\t\tVersion: \"2012-10-17\",\n\t\t\tStatement: []events.IAMPolicyStatement{\n\t\t\t\t{\n\t\t\t\t\tAction: []string{\"execute-api:Invoke\"},\n\t\t\t\t\tEffect: effect,\n\t\t\t\t\tResource: []string{resource},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\tauthResponse.Context = map[string]interface{}{}\n\treturn authResponse\n}", "func convertPMPermissions(scopedPerms map[string][]meta.Permission) map[string][]Privilege {\n\tprivileges := make(map[string][]Privilege, len(scopedPerms))\n\tfor scope, perms := range scopedPerms {\n\t\tdbResource := auth.DatabaseResource(scope)\n\t\tfor _, perm := range perms {\n\t\t\tswitch perm {\n\t\t\tcase meta.KapacitorAPIPermission:\n\t\t\t\tprivileges[rootResource] = []Privilege{AllPrivileges}\n\t\t\t\t// Do not give config API access unless specifically granted\n\t\t\t\tif _, ok := privileges[configResource]; !ok {\n\t\t\t\t\tprivileges[configResource] = []Privilege{NoPrivileges}\n\t\t\t\t}\n\t\t\tcase meta.KapacitorConfigAPIPermission:\n\t\t\t\tprivileges[pingResource] = []Privilege{AllPrivileges}\n\t\t\t\tprivileges[configResource] = []Privilege{AllPrivileges}\n\t\t\tcase meta.WriteDataPermission:\n\t\t\t\tprivileges[dbResource] = append(privileges[dbResource], WritePrivilege)\n\t\t\t\tprivileges[writeResource] = []Privilege{WritePrivilege}\n\t\t\t\tprivileges[pingResource] = []Privilege{AllPrivileges}\n\t\t\tcase meta.ReadDataPermission:\n\t\t\t\tprivileges[pingResource] = []Privilege{AllPrivileges}\n\t\t\t\tprivileges[dbResource] = append(privileges[dbResource], ReadPrivilege)\n\t\t\tdefault:\n\t\t\t\t// Ignore, user can have permissions for InfluxDB related actions.\n\t\t\t}\n\t\t}\n\t}\n\treturn privileges\n}", "func BuildWillIAMPermissionOwner(action, rh string) string {\n\treturn buildWillIAMPermission(OwnershipLevels.Owner, action, rh)\n}", "func CreatePermission(ctx context.Context, clientsEndpoint string, clientID string, permission KeycloakPermission, protectionAPIToken string) (string, error) {\n\tb, err := json.Marshal(permission)\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"permission\": permission,\n\t\t\t\"err\": err.Error(),\n\t\t}, \"unable to marshal keycloak permission struct\")\n\t\treturn \"\", errors.NewInternalError(errs.Wrap(err, \"unable to marshal keycloak permission struct\"))\n\t}\n\n\treq, err := http.NewRequest(\"POST\", clientsEndpoint+\"/\"+clientID+\"/authz/resource-server/policy\", strings.NewReader(string(b)))\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"err\": err.Error(),\n\t\t}, \"unable to create http request\")\n\t\treturn \"\", errors.NewInternalError(errs.Wrap(err, \"unable to create http request\"))\n\t}\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Header.Add(\"Authorization\", \"Bearer \"+protectionAPIToken)\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"client_id\": clientID,\n\t\t\t\"permission\": permission,\n\t\t\t\"err\": err.Error(),\n\t\t}, \"unable to create the Keycloak permission\")\n\t\treturn \"\", errors.NewInternalError(errs.Wrap(err, \"unable to create the Keycloak permission\"))\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != http.StatusCreated {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"client_id\": clientID,\n\t\t\t\"permission\": permission,\n\t\t\t\"response_status\": res.Status,\n\t\t\t\"response_body\": rest.ReadBody(res.Body),\n\t\t}, \"unable to update the Keycloak permission\")\n\t\treturn \"\", errors.NewInternalError(errs.New(\"unable to create the Keycloak permission. Response status: \" + res.Status + \". Responce body: \" + rest.ReadBody(res.Body)))\n\t}\n\tjsonString := rest.ReadBody(res.Body)\n\n\tvar r createPolicyRequestResultPayload\n\terr = json.Unmarshal([]byte(jsonString), &r)\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"client_id\": clientID,\n\t\t\t\"permission\": permission,\n\t\t\t\"json_string\": jsonString,\n\t\t}, \"unable to unmarshal json with the create keycloak permission request result\")\n\t\treturn \"\", errors.NewInternalError(errs.Wrapf(err, \"error when unmarshal json with the create keycloak permission request result %s \", jsonString))\n\t}\n\n\treturn r.ID, nil\n}", "func createAuthorization(roleRef, userRef string) string {\n\treturn fmt.Sprintf(`{\n \"type\": \"Authorization\",\n \"user\": \"%s\",\n \"role\": \"%s\",\n \"target\": \"%s\"\n}`, userRef, roleRef, userRef)\n}", "func (permission *Permission) Concat(newPermission *Permission) *Permission {\n\tvar result = Permission{\n\t\tRole: Global,\n\t\tAllowedAny: map[string]bool{},\n\t\tAllowedRoles: map[PermissionMode][]string{},\n\t\tDeniedRoles: map[PermissionMode][]string{},\n\t\tDaniedAnotherRoles: map[PermissionMode][]string{},\n\t}\n\n\tvar appendRoles = func(p *Permission) {\n\t\tif p != nil {\n\t\t\tresult.Role = p.Role\n\n\t\t\tfor mode, roles := range p.AllowedRoles {\n\t\t\t\tresult.AllowedRoles[mode] = append(result.AllowedRoles[mode], roles...)\n\t\t\t}\n\n\t\t\tfor mode, roles := range p.DeniedRoles {\n\t\t\t\tresult.DeniedRoles[mode] = append(result.DeniedRoles[mode], roles...)\n\t\t\t}\n\n\t\t\tfor mode, roles := range p.DaniedAnotherRoles {\n\t\t\t\tresult.DaniedAnotherRoles[mode] = append(result.DaniedAnotherRoles[mode], roles...)\n\t\t\t}\n\n\t\t\tfor role, v := range p.AllowedAny {\n\t\t\t\tresult.AllowedAny[role] = v\n\t\t\t}\n\t\t}\n\t}\n\n\tappendRoles(newPermission)\n\tappendRoles(permission)\n\treturn &result\n}", "func buildIAMARN(partitionID, accountID, resourceType, resource string) string {\n\tif strings.HasPrefix(resource, \"/\") {\n\t\treturn fmt.Sprintf(\"arn:%s:iam::%s:%s%s\", partitionID, accountID, resourceType, resource)\n\t} else {\n\t\treturn fmt.Sprintf(\"arn:%s:iam::%s:%s/%s\", partitionID, accountID, resourceType, resource)\n\t}\n}", "func SetIAMPermission(memberName string, iamRole string, memberType string) (err error) {\n\tvar role string\n\n\tswitch iamRole {\n\tcase \"sync\":\n\t\trole = \"roles/apigee.synchronizerManager\"\n\tcase \"analytics\":\n\t\trole = \"roles/apigee.analyticsAgent\"\n\tcase \"analyticsViewer\":\n\t\trole = \"roles/apigee.analyticsViewer\"\n\tcase \"analyticsAgent\":\n\t\trole = \"roles/apigee.analyticsAgent\"\n\tcase \"deploy\":\n\t\trole = \"roles/apigee.deployer\"\n\tdefault: //assume this is a custom role definition\n\t\tre := regexp.MustCompile(`projects\\/([a-zA-Z0-9_-]+)\\/roles\\/([a-zA-Z0-9_-]+)`)\n\t\tresult := re.FindString(iamRole)\n\t\tif result == \"\" {\n\t\t\treturn fmt.Errorf(\"custom role must be of the format projects/{project-id}/roles/{role-name}\")\n\t\t}\n\t\trole = iamRole\n\t}\n\n\tu, _ := url.Parse(BaseURL)\n\tu.Path = path.Join(u.Path, GetApigeeOrg(), \"environments\", GetApigeeEnv()+\":getIamPolicy\")\n\tgetIamPolicyBody, err := HttpClient(false, u.String())\n\tif err != nil {\n\t\tclilog.Error.Println(err)\n\t\treturn err\n\t}\n\n\tgetIamPolicy := iamPolicy{}\n\n\terr = json.Unmarshal(getIamPolicyBody, &getIamPolicy)\n\tif err != nil {\n\t\tclilog.Error.Println(err)\n\t\treturn err\n\t}\n\n\tfoundRole := false\n\tfor i, binding := range getIamPolicy.Bindings {\n\t\tif binding.Role == role {\n\t\t\t//found members with the role already, add the new SA to the role\n\t\t\tgetIamPolicy.Bindings[i].Members = append(binding.Members, memberType+\":\"+memberName)\n\t\t\tfoundRole = true\n\t\t}\n\t}\n\n\t//no members with the role, add a new one\n\tif !foundRole {\n\t\tbinding := roleBinding{}\n\t\tbinding.Role = role\n\t\tbinding.Members = append(binding.Members, memberType+\":\"+memberName)\n\t\tgetIamPolicy.Bindings = append(getIamPolicy.Bindings, binding)\n\t}\n\n\tu, _ = url.Parse(BaseURL)\n\tu.Path = path.Join(u.Path, GetApigeeOrg(), \"environments\", GetApigeeEnv()+\":setIamPolicy\")\n\n\tsetIamPolicy := setIamPolicy{}\n\tsetIamPolicy.Policy = getIamPolicy\n\n\tsetIamPolicyBody, err := json.Marshal(setIamPolicy)\n\tif err != nil {\n\t\tclilog.Error.Println(err)\n\t\treturn err\n\t}\n\n\t_, err = HttpClient(false, u.String(), string(setIamPolicyBody))\n\n\treturn err\n}", "func generatePolicy(principalId, effect, resource string) events.APIGatewayCustomAuthorizerResponse {\n\tauthResponse := events.APIGatewayCustomAuthorizerResponse{PrincipalID: principalId}\n\n\tif effect != \"\" && resource != \"\" {\n\t\tauthResponse.PolicyDocument = events.APIGatewayCustomAuthorizerPolicy{\n\t\t\tVersion: \"2012-10-17\",\n\t\t\tStatement: []events.IAMPolicyStatement{\n\t\t\t\t{\n\t\t\t\t\tAction: []string{\"execute-api:Invoke\"},\n\t\t\t\t\tEffect: effect,\n\t\t\t\t\tResource: []string{resource},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\t// Optional output with custom properties of the String, Number or Boolean type.\n\tauthResponse.Context = map[string]interface{}{\n\t\t\"stringKey\": \"stringval\",\n\t\t\"numberKey\": 123,\n\t\t\"booleanKey\": true,\n\t}\n\treturn authResponse\n}", "func stringToAccessPerm(perm string) accessPerms {\n\tvar policy accessPerms\n\tswitch perm {\n\tcase \"none\":\n\t\tpolicy = accessNone\n\tcase \"readonly\":\n\t\tpolicy = accessDownload\n\tcase \"writeonly\":\n\t\tpolicy = accessUpload\n\tcase \"readwrite\":\n\t\tpolicy = accessPublic\n\tcase \"custom\":\n\t\tpolicy = accessCustom\n\t}\n\treturn policy\n}", "func TransformPermission(permission db.Permission) ResponsePermission {\n\treturn ResponsePermission{\n\t\tKey: permission.Key,\n\t\tDescription: permission.Description,\n\t}\n}", "func bindPermission(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(PermissionABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func GroupPermissionToPrivilege(p GroupPermission) int {\n\tpriv := 0\n\tif p.CanEditUsers {\n\t\tpriv++\n\t}\n\tpriv *= 2\n\tif p.CanAdminGroup {\n\t\tpriv++\n\t}\n\tpriv *= 2\n\tif p.CanWriteEvents {\n\t\tpriv++\n\t}\n\tpriv *= 2\n\tif p.CanWriteAnnouncements {\n\t\tpriv++\n\t}\n\tpriv *= 2\n\tif p.CanWriteComments {\n\t\tpriv++\n\t}\n\tpriv *= 2\n\tif p.CanReadComments {\n\t\tpriv++\n\t}\n\tpriv *= 2\n\tif p.CanReadMembers {\n\t\tpriv++\n\t}\n\tpriv *= 2\n\tif p.CanRead {\n\t\tpriv++\n\t}\n\treturn priv\n}", "func EncodeGrpcRespPermission(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func BuildCreatePermissionGroupIn() *model.CreatePermissionGroupIn {\n\treturn &model.CreatePermissionGroupIn{\n\t\tName: *RandomString(10),\n\t\tDescription: RandomString(20),\n\t\tPermissions: []model.Permission{\n\t\t\tmodel.PermissionUser,\n\t\t\tmodel.PermissionPermissionGroup,\n\t\t},\n\t}\n}", "func (a *Authorization) WriteTo(w io.Writer) (int64, error) {\n\tvar n int64\n\tvar err error\n\twr := base64.NewEncoder(base64.StdEncoding, w)\n\tdefer wr.Close()\n\tts := a.timestampBytes()\n\twritten, err := wr.Write(append(ts, '|'))\n\tif err != nil {\n\t\treturn n, err\n\t}\n\tn += int64(written)\n\tfor _, binBuf := range [][]byte{a.salt, a.signature, a.rawMsg} {\n\t\twritten, err = wr.Write(binBuf)\n\t\tif err != nil {\n\t\t\treturn n, err\n\t\t}\n\t\tn += int64(written)\n\t}\n\treturn n, err\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
BuildWillIAMPermissionLender builds a permission in the format expected by WillIAM handlers
func BuildWillIAMPermissionLender(action, rh string) string { return buildWillIAMPermission(OwnershipLevels.Lender, action, rh) }
[ "func buildWillIAMPermission(ro OwnershipLevel, action, rh string) string {\n\treturn fmt.Sprintf(\n\t\t\"%s::%s::%s::%s\", constants.AppInfo.Name, string(ro), action, rh,\n\t)\n}", "func BuildPermission(str string) (Permission, error) {\n\tif valid, err := ValidatePermission(str); !valid {\n\t\treturn Permission{}, err\n\t}\n\tparts := strings.Split(str, \"::\")\n\tservice := parts[0]\n\tol := OwnershipLevel(parts[1])\n\taction := BuildAction(parts[2])\n\trh := ResourceHierarchy(strings.Join(parts[3:], \"::\"))\n\treturn Permission{\n\t\tService: service,\n\t\tOwnershipLevel: ol,\n\t\tAction: action,\n\t\tResourceHierarchy: rh,\n\t}, nil\n}", "func PermissionItoA(permission int) string {\n\tif permission < PermissionDefault {\n\t\treturn PermissionBannedString\n\t} else if permission < PermissionVerified {\n\t\treturn PermissionDefaultString\n\t} else if permission < PermissionTeam {\n\t\treturn PermissionVerifiedString\n\t} else if permission < PermissionAdmin {\n\t\treturn PermissionTeamString\n\t}\n\treturn PermissionAdminString\n}", "func generateIAMPolicy(principalId string, effect string, resource string) events.APIGatewayCustomAuthorizerResponse {\n\tdefer track(time.Now(), \"generateIAMPolicy()\")\n\tauthResponse := events.APIGatewayCustomAuthorizerResponse{PrincipalID: principalId}\n\n\tif effect != \"\" && resource != \"\" {\n\t\tauthResponse.PolicyDocument = events.APIGatewayCustomAuthorizerPolicy{\n\t\t\tVersion: \"2012-10-17\",\n\t\t\tStatement: []events.IAMPolicyStatement{\n\t\t\t\t{\n\t\t\t\t\tAction: []string{\"execute-api:Invoke\"},\n\t\t\t\t\tEffect: effect,\n\t\t\t\t\tResource: []string{resource},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\tauthResponse.Context = map[string]interface{}{}\n\treturn authResponse\n}", "func CreatePermission(ctx context.Context, clientsEndpoint string, clientID string, permission KeycloakPermission, protectionAPIToken string) (string, error) {\n\tb, err := json.Marshal(permission)\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"permission\": permission,\n\t\t\t\"err\": err.Error(),\n\t\t}, \"unable to marshal keycloak permission struct\")\n\t\treturn \"\", errors.NewInternalError(errs.Wrap(err, \"unable to marshal keycloak permission struct\"))\n\t}\n\n\treq, err := http.NewRequest(\"POST\", clientsEndpoint+\"/\"+clientID+\"/authz/resource-server/policy\", strings.NewReader(string(b)))\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"err\": err.Error(),\n\t\t}, \"unable to create http request\")\n\t\treturn \"\", errors.NewInternalError(errs.Wrap(err, \"unable to create http request\"))\n\t}\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Header.Add(\"Authorization\", \"Bearer \"+protectionAPIToken)\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"client_id\": clientID,\n\t\t\t\"permission\": permission,\n\t\t\t\"err\": err.Error(),\n\t\t}, \"unable to create the Keycloak permission\")\n\t\treturn \"\", errors.NewInternalError(errs.Wrap(err, \"unable to create the Keycloak permission\"))\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != http.StatusCreated {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"client_id\": clientID,\n\t\t\t\"permission\": permission,\n\t\t\t\"response_status\": res.Status,\n\t\t\t\"response_body\": rest.ReadBody(res.Body),\n\t\t}, \"unable to update the Keycloak permission\")\n\t\treturn \"\", errors.NewInternalError(errs.New(\"unable to create the Keycloak permission. Response status: \" + res.Status + \". Responce body: \" + rest.ReadBody(res.Body)))\n\t}\n\tjsonString := rest.ReadBody(res.Body)\n\n\tvar r createPolicyRequestResultPayload\n\terr = json.Unmarshal([]byte(jsonString), &r)\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"client_id\": clientID,\n\t\t\t\"permission\": permission,\n\t\t\t\"json_string\": jsonString,\n\t\t}, \"unable to unmarshal json with the create keycloak permission request result\")\n\t\treturn \"\", errors.NewInternalError(errs.Wrapf(err, \"error when unmarshal json with the create keycloak permission request result %s \", jsonString))\n\t}\n\n\treturn r.ID, nil\n}", "func BuildWillIAMPermissionOwner(action, rh string) string {\n\treturn buildWillIAMPermission(OwnershipLevels.Owner, action, rh)\n}", "func (permission *Permission) Concat(newPermission *Permission) *Permission {\n\tvar result = Permission{\n\t\tRole: Global,\n\t\tAllowedAny: map[string]bool{},\n\t\tAllowedRoles: map[PermissionMode][]string{},\n\t\tDeniedRoles: map[PermissionMode][]string{},\n\t\tDaniedAnotherRoles: map[PermissionMode][]string{},\n\t}\n\n\tvar appendRoles = func(p *Permission) {\n\t\tif p != nil {\n\t\t\tresult.Role = p.Role\n\n\t\t\tfor mode, roles := range p.AllowedRoles {\n\t\t\t\tresult.AllowedRoles[mode] = append(result.AllowedRoles[mode], roles...)\n\t\t\t}\n\n\t\t\tfor mode, roles := range p.DeniedRoles {\n\t\t\t\tresult.DeniedRoles[mode] = append(result.DeniedRoles[mode], roles...)\n\t\t\t}\n\n\t\t\tfor mode, roles := range p.DaniedAnotherRoles {\n\t\t\t\tresult.DaniedAnotherRoles[mode] = append(result.DaniedAnotherRoles[mode], roles...)\n\t\t\t}\n\n\t\t\tfor role, v := range p.AllowedAny {\n\t\t\t\tresult.AllowedAny[role] = v\n\t\t\t}\n\t\t}\n\t}\n\n\tappendRoles(newPermission)\n\tappendRoles(permission)\n\treturn &result\n}", "func EncodeGrpcRespPermission(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func SetIAMPermission(memberName string, iamRole string, memberType string) (err error) {\n\tvar role string\n\n\tswitch iamRole {\n\tcase \"sync\":\n\t\trole = \"roles/apigee.synchronizerManager\"\n\tcase \"analytics\":\n\t\trole = \"roles/apigee.analyticsAgent\"\n\tcase \"analyticsViewer\":\n\t\trole = \"roles/apigee.analyticsViewer\"\n\tcase \"analyticsAgent\":\n\t\trole = \"roles/apigee.analyticsAgent\"\n\tcase \"deploy\":\n\t\trole = \"roles/apigee.deployer\"\n\tdefault: //assume this is a custom role definition\n\t\tre := regexp.MustCompile(`projects\\/([a-zA-Z0-9_-]+)\\/roles\\/([a-zA-Z0-9_-]+)`)\n\t\tresult := re.FindString(iamRole)\n\t\tif result == \"\" {\n\t\t\treturn fmt.Errorf(\"custom role must be of the format projects/{project-id}/roles/{role-name}\")\n\t\t}\n\t\trole = iamRole\n\t}\n\n\tu, _ := url.Parse(BaseURL)\n\tu.Path = path.Join(u.Path, GetApigeeOrg(), \"environments\", GetApigeeEnv()+\":getIamPolicy\")\n\tgetIamPolicyBody, err := HttpClient(false, u.String())\n\tif err != nil {\n\t\tclilog.Error.Println(err)\n\t\treturn err\n\t}\n\n\tgetIamPolicy := iamPolicy{}\n\n\terr = json.Unmarshal(getIamPolicyBody, &getIamPolicy)\n\tif err != nil {\n\t\tclilog.Error.Println(err)\n\t\treturn err\n\t}\n\n\tfoundRole := false\n\tfor i, binding := range getIamPolicy.Bindings {\n\t\tif binding.Role == role {\n\t\t\t//found members with the role already, add the new SA to the role\n\t\t\tgetIamPolicy.Bindings[i].Members = append(binding.Members, memberType+\":\"+memberName)\n\t\t\tfoundRole = true\n\t\t}\n\t}\n\n\t//no members with the role, add a new one\n\tif !foundRole {\n\t\tbinding := roleBinding{}\n\t\tbinding.Role = role\n\t\tbinding.Members = append(binding.Members, memberType+\":\"+memberName)\n\t\tgetIamPolicy.Bindings = append(getIamPolicy.Bindings, binding)\n\t}\n\n\tu, _ = url.Parse(BaseURL)\n\tu.Path = path.Join(u.Path, GetApigeeOrg(), \"environments\", GetApigeeEnv()+\":setIamPolicy\")\n\n\tsetIamPolicy := setIamPolicy{}\n\tsetIamPolicy.Policy = getIamPolicy\n\n\tsetIamPolicyBody, err := json.Marshal(setIamPolicy)\n\tif err != nil {\n\t\tclilog.Error.Println(err)\n\t\treturn err\n\t}\n\n\t_, err = HttpClient(false, u.String(), string(setIamPolicyBody))\n\n\treturn err\n}", "func (a *Authorization) WriteTo(w io.Writer) (int64, error) {\n\tvar n int64\n\tvar err error\n\twr := base64.NewEncoder(base64.StdEncoding, w)\n\tdefer wr.Close()\n\tts := a.timestampBytes()\n\twritten, err := wr.Write(append(ts, '|'))\n\tif err != nil {\n\t\treturn n, err\n\t}\n\tn += int64(written)\n\tfor _, binBuf := range [][]byte{a.salt, a.signature, a.rawMsg} {\n\t\twritten, err = wr.Write(binBuf)\n\t\tif err != nil {\n\t\t\treturn n, err\n\t\t}\n\t\tn += int64(written)\n\t}\n\treturn n, err\n}", "func bindPermission(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(PermissionABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func convertPMPermissions(scopedPerms map[string][]meta.Permission) map[string][]Privilege {\n\tprivileges := make(map[string][]Privilege, len(scopedPerms))\n\tfor scope, perms := range scopedPerms {\n\t\tdbResource := auth.DatabaseResource(scope)\n\t\tfor _, perm := range perms {\n\t\t\tswitch perm {\n\t\t\tcase meta.KapacitorAPIPermission:\n\t\t\t\tprivileges[rootResource] = []Privilege{AllPrivileges}\n\t\t\t\t// Do not give config API access unless specifically granted\n\t\t\t\tif _, ok := privileges[configResource]; !ok {\n\t\t\t\t\tprivileges[configResource] = []Privilege{NoPrivileges}\n\t\t\t\t}\n\t\t\tcase meta.KapacitorConfigAPIPermission:\n\t\t\t\tprivileges[pingResource] = []Privilege{AllPrivileges}\n\t\t\t\tprivileges[configResource] = []Privilege{AllPrivileges}\n\t\t\tcase meta.WriteDataPermission:\n\t\t\t\tprivileges[dbResource] = append(privileges[dbResource], WritePrivilege)\n\t\t\t\tprivileges[writeResource] = []Privilege{WritePrivilege}\n\t\t\t\tprivileges[pingResource] = []Privilege{AllPrivileges}\n\t\t\tcase meta.ReadDataPermission:\n\t\t\t\tprivileges[pingResource] = []Privilege{AllPrivileges}\n\t\t\t\tprivileges[dbResource] = append(privileges[dbResource], ReadPrivilege)\n\t\t\tdefault:\n\t\t\t\t// Ignore, user can have permissions for InfluxDB related actions.\n\t\t\t}\n\t\t}\n\t}\n\treturn privileges\n}", "func createAuthorization(roleRef, userRef string) string {\n\treturn fmt.Sprintf(`{\n \"type\": \"Authorization\",\n \"user\": \"%s\",\n \"role\": \"%s\",\n \"target\": \"%s\"\n}`, userRef, roleRef, userRef)\n}", "func buildIAMARN(partitionID, accountID, resourceType, resource string) string {\n\tif strings.HasPrefix(resource, \"/\") {\n\t\treturn fmt.Sprintf(\"arn:%s:iam::%s:%s%s\", partitionID, accountID, resourceType, resource)\n\t} else {\n\t\treturn fmt.Sprintf(\"arn:%s:iam::%s:%s/%s\", partitionID, accountID, resourceType, resource)\n\t}\n}", "func (perm *tokenPermission) MarshalJSON() ([]byte, error) {\n\tvar val []byte\n\tvar err error\n\tvar finalByte []byte\n\n\tval, err = json.Marshal(perm.Permission)\n\n\tif err == nil {\n\t\tvar stringVal = string(val)\n\t\tstringVal = strings.Replace(stringVal, \"{\", \"\", -1)\n\t\tstringVal = strings.Replace(stringVal, \"}\", \"\", -1)\n\t\telements := strings.Split(stringVal, \",\")\n\n\t\tvar permissions = make([]string, 0)\n\n\t\tfor _, element := range elements {\n\t\t\tif strings.Index(element, \"can\") >= 0 {\n\t\t\t\tpermissions = append(permissions, element)\n\t\t\t}\n\t\t}\n\n\t\tvar jsonVal = \"{\" + strings.Join(permissions, \",\") + \"}\"\n\n\t\tfinalByte = []byte(jsonVal)\n\t}\n\n\treturn finalByte, err\n}", "func (p Permission) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"actions\", p.Actions)\n\tpopulate(objectMap, \"dataActions\", p.DataActions)\n\tpopulate(objectMap, \"notActions\", p.NotActions)\n\tpopulate(objectMap, \"notDataActions\", p.NotDataActions)\n\treturn json.Marshal(objectMap)\n}", "func PipelinePermission(key string, name string, u *sdk.User) int {\n\tif u.Admin {\n\t\treturn PermissionReadWriteExecute\n\t}\n\n\treturn u.Permissions.PipelinesPerm[sdk.UserPermissionKey(key, name)]\n}", "func accessPermToString(perm accessPerms) string {\n\tpolicy := \"\"\n\tswitch perm {\n\tcase accessNone:\n\t\tpolicy = \"none\"\n\tcase accessDownload:\n\t\tpolicy = \"readonly\"\n\tcase accessUpload:\n\t\tpolicy = \"writeonly\"\n\tcase accessPublic:\n\t\tpolicy = \"readwrite\"\n\tcase accessCustom:\n\t\tpolicy = \"custom\"\n\t}\n\treturn policy\n}", "func generatePolicy(principalId, effect, resource string) events.APIGatewayCustomAuthorizerResponse {\n\tauthResponse := events.APIGatewayCustomAuthorizerResponse{PrincipalID: principalId}\n\n\tif effect != \"\" && resource != \"\" {\n\t\tauthResponse.PolicyDocument = events.APIGatewayCustomAuthorizerPolicy{\n\t\t\tVersion: \"2012-10-17\",\n\t\t\tStatement: []events.IAMPolicyStatement{\n\t\t\t\t{\n\t\t\t\t\tAction: []string{\"execute-api:Invoke\"},\n\t\t\t\t\tEffect: effect,\n\t\t\t\t\tResource: []string{resource},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\t// Optional output with custom properties of the String, Number or Boolean type.\n\tauthResponse.Context = map[string]interface{}{\n\t\t\"stringKey\": \"stringval\",\n\t\t\"numberKey\": 123,\n\t\t\"booleanKey\": true,\n\t}\n\treturn authResponse\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
BuildWillIAMPermissionOwner builds a permission in the format expected by WillIAM handlers
func BuildWillIAMPermissionOwner(action, rh string) string { return buildWillIAMPermission(OwnershipLevels.Owner, action, rh) }
[ "func buildWillIAMPermission(ro OwnershipLevel, action, rh string) string {\n\treturn fmt.Sprintf(\n\t\t\"%s::%s::%s::%s\", constants.AppInfo.Name, string(ro), action, rh,\n\t)\n}", "func BuildWillIAMPermissionLender(action, rh string) string {\n\treturn buildWillIAMPermission(OwnershipLevels.Lender, action, rh)\n}", "func BuildPermission(str string) (Permission, error) {\n\tif valid, err := ValidatePermission(str); !valid {\n\t\treturn Permission{}, err\n\t}\n\tparts := strings.Split(str, \"::\")\n\tservice := parts[0]\n\tol := OwnershipLevel(parts[1])\n\taction := BuildAction(parts[2])\n\trh := ResourceHierarchy(strings.Join(parts[3:], \"::\"))\n\treturn Permission{\n\t\tService: service,\n\t\tOwnershipLevel: ol,\n\t\tAction: action,\n\t\tResourceHierarchy: rh,\n\t}, nil\n}", "func createAuthorization(roleRef, userRef string) string {\n\treturn fmt.Sprintf(`{\n \"type\": \"Authorization\",\n \"user\": \"%s\",\n \"role\": \"%s\",\n \"target\": \"%s\"\n}`, userRef, roleRef, userRef)\n}", "func PermissionItoA(permission int) string {\n\tif permission < PermissionDefault {\n\t\treturn PermissionBannedString\n\t} else if permission < PermissionVerified {\n\t\treturn PermissionDefaultString\n\t} else if permission < PermissionTeam {\n\t\treturn PermissionVerifiedString\n\t} else if permission < PermissionAdmin {\n\t\treturn PermissionTeamString\n\t}\n\treturn PermissionAdminString\n}", "func buildIAMARN(partitionID, accountID, resourceType, resource string) string {\n\tif strings.HasPrefix(resource, \"/\") {\n\t\treturn fmt.Sprintf(\"arn:%s:iam::%s:%s%s\", partitionID, accountID, resourceType, resource)\n\t} else {\n\t\treturn fmt.Sprintf(\"arn:%s:iam::%s:%s/%s\", partitionID, accountID, resourceType, resource)\n\t}\n}", "func generateIAMPolicy(principalId string, effect string, resource string) events.APIGatewayCustomAuthorizerResponse {\n\tdefer track(time.Now(), \"generateIAMPolicy()\")\n\tauthResponse := events.APIGatewayCustomAuthorizerResponse{PrincipalID: principalId}\n\n\tif effect != \"\" && resource != \"\" {\n\t\tauthResponse.PolicyDocument = events.APIGatewayCustomAuthorizerPolicy{\n\t\t\tVersion: \"2012-10-17\",\n\t\t\tStatement: []events.IAMPolicyStatement{\n\t\t\t\t{\n\t\t\t\t\tAction: []string{\"execute-api:Invoke\"},\n\t\t\t\t\tEffect: effect,\n\t\t\t\t\tResource: []string{resource},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\tauthResponse.Context = map[string]interface{}{}\n\treturn authResponse\n}", "func BuildOwner(id ID, spec OwnerSpec, mayLogin bool) *Owner {\n\treturn &Owner{\n\t\tID: id,\n\t\tName: spec.Name,\n\t\tEmail: spec.Email,\n\t\tMayLogin: mayLogin,\n\t}\n}", "func generatePolicy(principalId, effect, resource string) events.APIGatewayCustomAuthorizerResponse {\n\tauthResponse := events.APIGatewayCustomAuthorizerResponse{PrincipalID: principalId}\n\n\tif effect != \"\" && resource != \"\" {\n\t\tauthResponse.PolicyDocument = events.APIGatewayCustomAuthorizerPolicy{\n\t\t\tVersion: \"2012-10-17\",\n\t\t\tStatement: []events.IAMPolicyStatement{\n\t\t\t\t{\n\t\t\t\t\tAction: []string{\"execute-api:Invoke\"},\n\t\t\t\t\tEffect: effect,\n\t\t\t\t\tResource: []string{resource},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\t// Optional output with custom properties of the String, Number or Boolean type.\n\tauthResponse.Context = map[string]interface{}{\n\t\t\"stringKey\": \"stringval\",\n\t\t\"numberKey\": 123,\n\t\t\"booleanKey\": true,\n\t}\n\treturn authResponse\n}", "func CreatePermission(ctx context.Context, clientsEndpoint string, clientID string, permission KeycloakPermission, protectionAPIToken string) (string, error) {\n\tb, err := json.Marshal(permission)\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"permission\": permission,\n\t\t\t\"err\": err.Error(),\n\t\t}, \"unable to marshal keycloak permission struct\")\n\t\treturn \"\", errors.NewInternalError(errs.Wrap(err, \"unable to marshal keycloak permission struct\"))\n\t}\n\n\treq, err := http.NewRequest(\"POST\", clientsEndpoint+\"/\"+clientID+\"/authz/resource-server/policy\", strings.NewReader(string(b)))\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"err\": err.Error(),\n\t\t}, \"unable to create http request\")\n\t\treturn \"\", errors.NewInternalError(errs.Wrap(err, \"unable to create http request\"))\n\t}\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Header.Add(\"Authorization\", \"Bearer \"+protectionAPIToken)\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"client_id\": clientID,\n\t\t\t\"permission\": permission,\n\t\t\t\"err\": err.Error(),\n\t\t}, \"unable to create the Keycloak permission\")\n\t\treturn \"\", errors.NewInternalError(errs.Wrap(err, \"unable to create the Keycloak permission\"))\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != http.StatusCreated {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"client_id\": clientID,\n\t\t\t\"permission\": permission,\n\t\t\t\"response_status\": res.Status,\n\t\t\t\"response_body\": rest.ReadBody(res.Body),\n\t\t}, \"unable to update the Keycloak permission\")\n\t\treturn \"\", errors.NewInternalError(errs.New(\"unable to create the Keycloak permission. Response status: \" + res.Status + \". Responce body: \" + rest.ReadBody(res.Body)))\n\t}\n\tjsonString := rest.ReadBody(res.Body)\n\n\tvar r createPolicyRequestResultPayload\n\terr = json.Unmarshal([]byte(jsonString), &r)\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"client_id\": clientID,\n\t\t\t\"permission\": permission,\n\t\t\t\"json_string\": jsonString,\n\t\t}, \"unable to unmarshal json with the create keycloak permission request result\")\n\t\treturn \"\", errors.NewInternalError(errs.Wrapf(err, \"error when unmarshal json with the create keycloak permission request result %s \", jsonString))\n\t}\n\n\treturn r.ID, nil\n}", "func (pr *PrMock) PermissionForUser(userName string) *PermissionServiceMocker {\n\treturn &PermissionServiceMocker{userName: userName, pr: pr.PullRequest}\n}", "func bindPermission(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(PermissionABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func BuildCreatePermissionGroupIn() *model.CreatePermissionGroupIn {\n\treturn &model.CreatePermissionGroupIn{\n\t\tName: *RandomString(10),\n\t\tDescription: RandomString(20),\n\t\tPermissions: []model.Permission{\n\t\t\tmodel.PermissionUser,\n\t\t\tmodel.PermissionPermissionGroup,\n\t\t},\n\t}\n}", "func (crc *CreateRoomCmd) RequiresAuthorization() {}", "func (fs *ocfs) permissionSet(ctx context.Context, owner *userpb.UserId) *provider.ResourcePermissions {\n\tif owner == nil {\n\t\treturn &provider.ResourcePermissions{\n\t\t\tStat: true,\n\t\t}\n\t}\n\tu, ok := ctxpkg.ContextGetUser(ctx)\n\tif !ok {\n\t\treturn &provider.ResourcePermissions{\n\t\t\t// no permissions\n\t\t}\n\t}\n\tif u.Id == nil {\n\t\treturn &provider.ResourcePermissions{\n\t\t\t// no permissions\n\t\t}\n\t}\n\tif u.Id.OpaqueId == owner.OpaqueId && u.Id.Idp == owner.Idp {\n\t\treturn &provider.ResourcePermissions{\n\t\t\t// owner has all permissions\n\t\t\tAddGrant: true,\n\t\t\tCreateContainer: true,\n\t\t\tDelete: true,\n\t\t\tGetPath: true,\n\t\t\tGetQuota: true,\n\t\t\tInitiateFileDownload: true,\n\t\t\tInitiateFileUpload: true,\n\t\t\tListContainer: true,\n\t\t\tListFileVersions: true,\n\t\t\tListGrants: true,\n\t\t\tListRecycle: true,\n\t\t\tMove: true,\n\t\t\tPurgeRecycle: true,\n\t\t\tRemoveGrant: true,\n\t\t\tRestoreFileVersion: true,\n\t\t\tRestoreRecycleItem: true,\n\t\t\tStat: true,\n\t\t\tUpdateGrant: true,\n\t\t}\n\t}\n\t// TODO fix permissions for share recipients by traversing reading acls up to the root? cache acls for the parent node and reuse it\n\treturn &provider.ResourcePermissions{\n\t\tAddGrant: true,\n\t\tCreateContainer: true,\n\t\tDelete: true,\n\t\tGetPath: true,\n\t\tGetQuota: true,\n\t\tInitiateFileDownload: true,\n\t\tInitiateFileUpload: true,\n\t\tListContainer: true,\n\t\tListFileVersions: true,\n\t\tListGrants: true,\n\t\tListRecycle: true,\n\t\tMove: true,\n\t\tPurgeRecycle: true,\n\t\tRemoveGrant: true,\n\t\tRestoreFileVersion: true,\n\t\tRestoreRecycleItem: true,\n\t\tStat: true,\n\t\tUpdateGrant: true,\n\t}\n}", "func generatePolicy(principalId, apiKey, effect, resource, tenant string) events.APIGatewayCustomAuthorizerResponse {\n\tauthResponse := events.APIGatewayCustomAuthorizerResponse{PrincipalID: principalId}\n\n\tallResources := allApiResources(resource)\n\n\tif effect != \"\" && resource != \"\" {\n\t\tauthResponse.PolicyDocument = events.APIGatewayCustomAuthorizerPolicy{\n\t\t\tVersion: \"2012-10-17\",\n\t\t\tStatement: []events.IAMPolicyStatement{\n\t\t\t\t{\n\t\t\t\t\tAction: []string{\"execute-api:Invoke\"},\n\t\t\t\t\tEffect: effect,\n\t\t\t\t\tResource: allResources,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\t// Optional output with custom properties of the String, Number or Boolean type.\n\tauthResponse.Context = map[string]interface{} {\n\t\t\"tenant\": tenant,\n\t}\n\n\tauthResponse.UsageIdentifierKey = apiKey\n\n\tlog.Printf(\"Authorizer response: %+v\\n\", authResponse)\n\n\treturn authResponse\n}", "func (a *IamProjectApiService) IamProjectOwnershipCreate(ctx context.Context, projectId string) ApiIamProjectOwnershipCreateRequest {\n\treturn ApiIamProjectOwnershipCreateRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tprojectId: projectId,\n\t}\n}", "func (m *DeviceManagementRequestBuilder) GetEffectivePermissionsWithScope(scope *string)(*i6b79e19af80218ca443b0983adbe0f6cdef30c9d057c37be983e59c74074ca29.GetEffectivePermissionsWithScopeRequestBuilder) {\n return i6b79e19af80218ca443b0983adbe0f6cdef30c9d057c37be983e59c74074ca29.NewGetEffectivePermissionsWithScopeRequestBuilderInternal(m.pathParameters, m.requestAdapter, scope);\n}", "func accessPermToString(perm accessPerms) string {\n\tpolicy := \"\"\n\tswitch perm {\n\tcase accessNone:\n\t\tpolicy = \"none\"\n\tcase accessDownload:\n\t\tpolicy = \"readonly\"\n\tcase accessUpload:\n\t\tpolicy = \"writeonly\"\n\tcase accessPublic:\n\t\tpolicy = \"readwrite\"\n\tcase accessCustom:\n\t\tpolicy = \"custom\"\n\t}\n\treturn policy\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
BulkInsertTrades inserts a slice of trades in the database. Trades that are already in the database (i.e. horizon_id already exists) are ignored.
func (s *TickerSession) BulkInsertTrades(ctx context.Context, trades []Trade) (err error) { if len(trades) <= 50 { return performInsertTrades(ctx, s, trades) } chunks := chunkifyDBTrades(trades, 50) for _, chunk := range chunks { err = performInsertTrades(ctx, s, chunk) if err != nil { return } } return }
[ "func (f *Fixture) InsertBulk(minIndex, maxIndex int, dataNameFmt, interestNameFmt string, makeInterestArgs ...any) (nInserted int) {\n\tfor i := minIndex; i <= maxIndex; i++ {\n\t\tinterest := makeInterest(fmt.Sprintf(interestNameFmt, i), makeInterestArgs...)\n\t\tdata := makeData(fmt.Sprintf(dataNameFmt, i), time.Second)\n\t\tif f.Insert(interest, data) {\n\t\t\tnInserted++\n\t\t}\n\t}\n\treturn nInserted\n}", "func InsertBulk(db gorp.SqlExecutor, wtb *sdk.WorkflowTemplateBulk) error {\n\treturn sdk.WrapError(gorpmapping.Insert(db, wtb), \"Unable to insert workflow template bulk task for template %d\",\n\t\twtb.WorkflowTemplateID)\n}", "func (client *Client) BulkImport(tableName string, infos []handlers.AnalysisInfo, columns ...string) error {\n\tlog.Println(\"-- Begin Bulk Import --\")\n\tdb := client.pgConn\n\ttxn, err := db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tnotNullColumns := []string{\"created_at\", \"updated_at\"}\n\tcolumns = append(notNullColumns, columns...)\n\tstmt, err := txn.Prepare(pq.CopyIn(tableName, columns...))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, info := range infos {\n\t\ttimestamp := parseTimestamp(info.Timestamp)\n\t\t// target_hash, created_at_unixtimestamp,\n\t\tjsonDurations, _ := json.Marshal(info.Durations)\n\t\t_, err := stmt.Exec(time.Now(), time.Now(), info.TargetHash, timestamp, jsonDurations)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t_, err = stmt.Exec()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = stmt.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = txn.Commit()\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"-- End Bulk Import --\")\n\treturn nil\n}", "func bulkInsert(observer rx.RxStream) {\n\tfor ch := range observer.Observe() {\n\t\tif ch.Error() {\n\t\t\tlog.Println(ch.E.Error())\n\t\t} else if ch.V != nil {\n\t\t\t// bulk insert\n\t\t\titems, ok := ch.V.([]interface{})\n\t\t\tif !ok {\n\t\t\t\tlog.Println(ok)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor _, item := range items {\n\t\t\t\tdata, ok := item.(ThermometerData)\n\t\t\t\tif !ok {\n\t\t\t\t\tlog.Println(\"Convert item to Thermometer failure\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tline := fmt.Sprintf(\"thermometer_sensor tem=%f,hum=%f %s\", data.Temperature, data.Humidity, strconv.FormatInt(time.Now().UnixNano(), 10))\n\t\t\t\t// WriteRecord adds record into the buffer which is sent on the background when it reaches the batch size.\n\t\t\t\twriteAPI.WriteRecord(line)\n\t\t\t}\n\t\t\t// Flush forces all pending writes from the buffer to be sent\n\t\t\twriteAPI.Flush()\n\t\t\tlog.Printf(\"Insert %d thermometer values into InfluxDB...\", len(items))\n\t\t}\n\t}\n}", "func bulkInsert(observer rx.RxStream) error {\n\tfor ch := range observer.Observe() {\n\t\tif ch.Error() {\n\t\t\tlog.Println(ch.E.Error())\n\t\t} else if ch.V != nil {\n\t\t\titems, ok := ch.V.([]interface{})\n\t\t\tif !ok {\n\t\t\t\tlog.Println(ok)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// bulk insert\n\t\t\t_, err := client.Query(\n\t\t\t\tf.Map(\n\t\t\t\t\titems,\n\t\t\t\t\tf.Lambda(\n\t\t\t\t\t\t\"noise\",\n\t\t\t\t\t\tf.Create(\n\t\t\t\t\t\t\tf.Collection(\"noise\"),\n\t\t\t\t\t\t\tf.Obj{\"data\": f.Obj{\"noise\": f.Var(\"noise\")}},\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\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tlog.Printf(\"Insert %d noise data into FaunaDB...\", len(items))\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o TenantSlice) InsertAll(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error {\n\tln := int64(len(o))\n\tif ln == 0 {\n\t\treturn nil\n\t}\n\tvar sql string\n\tvals := []interface{}{}\n\tfor i, row := range o {\n\t\tif !boil.TimestampsAreSkipped(ctx) {\n\t\t\tcurrTime := time.Now().In(boil.GetLocation())\n\n\t\t\tif row.CreatedAt.IsZero() {\n\t\t\t\trow.CreatedAt = currTime\n\t\t\t}\n\t\t\tif row.UpdatedAt.IsZero() {\n\t\t\t\trow.UpdatedAt = currTime\n\t\t\t}\n\t\t}\n\n\t\tif err := row.doBeforeInsertHooks(ctx, exec); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnzDefaults := queries.NonZeroDefaultSet(tenantColumnsWithDefault, row)\n\t\twl, _ := columns.InsertColumnSet(\n\t\t\ttenantAllColumns,\n\t\t\ttenantColumnsWithDefault,\n\t\t\ttenantColumnsWithoutDefault,\n\t\t\tnzDefaults,\n\t\t)\n\t\tif i == 0 {\n\t\t\tsql = \"INSERT INTO `tenants` \" + \"(`\" + strings.Join(wl, \"`,`\") + \"`)\" + \" VALUES \"\n\t\t}\n\t\tsql += strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), len(vals)+1, len(wl))\n\t\tif i != len(o)-1 {\n\t\t\tsql += \",\"\n\t\t}\n\t\tvalMapping, err := queries.BindMapping(tenantType, tenantMapping, wl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue := reflect.Indirect(reflect.ValueOf(row))\n\t\tvals = append(vals, queries.ValuesFromMapping(value, valMapping)...)\n\t}\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, vals...)\n\t}\n\n\t_, err := exec.ExecContext(ctx, sql, vals...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"dbmodel: unable to insert into tenants\")\n\t}\n\n\treturn nil\n}", "func insertUploads(t *testing.T, db *sql.DB, uploads ...Upload) {\n\tfor _, upload := range uploads {\n\t\tif upload.Commit == \"\" {\n\t\t\tupload.Commit = makeCommit(upload.ID)\n\t\t}\n\t\tif upload.State == \"\" {\n\t\t\tupload.State = \"completed\"\n\t\t}\n\t\tif upload.RepositoryID == 0 {\n\t\t\tupload.RepositoryID = 50\n\t\t}\n\t\tif upload.Indexer == \"\" {\n\t\t\tupload.Indexer = \"lsif-go\"\n\t\t}\n\n\t\tquery := sqlf.Sprintf(`\n\t\t\tINSERT INTO lsif_uploads (\n\t\t\t\tid,\n\t\t\t\tcommit,\n\t\t\t\troot,\n\t\t\t\tvisible_at_tip,\n\t\t\t\tuploaded_at,\n\t\t\t\tstate,\n\t\t\t\tfailure_summary,\n\t\t\t\tfailure_stacktrace,\n\t\t\t\tstarted_at,\n\t\t\t\tfinished_at,\n\t\t\t\ttracing_context,\n\t\t\t\trepository_id,\n\t\t\t\tindexer\n\t\t\t) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\n\t\t`,\n\t\t\tupload.ID,\n\t\t\tupload.Commit,\n\t\t\tupload.Root,\n\t\t\tupload.VisibleAtTip,\n\t\t\tupload.UploadedAt,\n\t\t\tupload.State,\n\t\t\tupload.FailureSummary,\n\t\t\tupload.FailureStacktrace,\n\t\t\tupload.StartedAt,\n\t\t\tupload.FinishedAt,\n\t\t\tupload.TracingContext,\n\t\t\tupload.RepositoryID,\n\t\t\tupload.Indexer,\n\t\t)\n\n\t\tif _, err := db.ExecContext(context.Background(), query.Query(sqlf.PostgresBindVar), query.Args()...); err != nil {\n\t\t\tt.Fatalf(\"unexpected error while inserting dump: %s\", err)\n\t\t}\n\t}\n}", "func bulkWriteDeltas(ctx context.Context, db *pgxpool.Pool, recordID uuid.UUID, deltas []schema.ExpectationDeltaRow) error {\n\tctx, span := trace.StartSpan(ctx, \"bulkWriteDeltas\")\n\tdefer span.End()\n\tconst chunkSize = 200 // Arbitrarily picked\n\terr := util.ChunkIter(len(deltas), chunkSize, func(startIdx int, endIdx int) error {\n\t\tif err := ctx.Err(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbatch := deltas[startIdx:endIdx]\n\t\tif len(batch) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\tstatement := `INSERT INTO ExpectationDeltas (expectation_record_id, grouping_id, digest,\nlabel_before, label_after) VALUES `\n\t\tconst valuesPerRow = 5\n\t\tstatement += sqlutil.ValuesPlaceholders(valuesPerRow, len(batch))\n\t\targuments := make([]interface{}, 0, valuesPerRow*len(batch))\n\t\tfor _, row := range batch {\n\t\t\targuments = append(arguments, recordID, row.GroupingID, row.Digest, row.LabelBefore, row.LabelAfter)\n\t\t}\n\t\terr := crdbpgx.ExecuteTx(ctx, db, pgx.TxOptions{}, func(tx pgx.Tx) error {\n\t\t\t_, err := tx.Exec(ctx, statement, arguments...)\n\t\t\treturn err // Don't wrap - crdbpgx might retry\n\t\t})\n\t\treturn skerr.Wrap(err)\n\t})\n\tif err != nil {\n\t\treturn skerr.Wrapf(err, \"storing %d expectation delta rows\", len(deltas))\n\t}\n\treturn nil\n}", "func BulkInsertTo(name int, db *sql.DB, records []Record) {\n\tlog.Printf(\"new batch: %v\", name)\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\tlog.Fatalln(\"could not init transaction:\", err)\n\t}\n\tstmt, err := tx.Prepare(pq.CopyIn(\"record\", \"seq_id\", \"datetime\", \"email\", \"ipv4\", \"mac\", \"country_code\", \"user_agent\"))\n\tif err != nil {\n\t\tlog.Fatalln(\"could not prepare statment\")\n\t}\n\tfor _, r := range records {\n\t\t_, err := stmt.Exec(r.ID, r.Timestamp, r.Email, r.IP, r.Mac, r.CountryCode, r.UserAgent)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"could not\")\n\t\t}\n\t}\n\t_, err = stmt.Exec()\n\tif err != nil {\n\t\tlog.Fatalln(\"unable to flush data:\", err)\n\t}\n\terr = stmt.Close()\n\tif err != nil {\n\t\tlog.Fatalln(\"unable to close prepared statment:\", err)\n\t}\n\terr = tx.Commit()\n\tif err != nil {\n\t\tlog.Fatalln(\"unable to commit:\", err)\n\t}\n\tlog.Printf(\"end batch: %v\", name)\n}", "func (tp *LocalTxPool) BatchInsert(txns SignedTxns) (err error) {\n\ttp.Lock()\n\tdefer tp.Unlock()\n\tfor _, stxn := range txns {\n\t\tif _, ok := tp.txnsMap[stxn.TxnHash]; ok {\n\t\t\treturn\n\t\t}\n\t\terr = tp.BaseCheck(stxn)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\terr = tp.TripodsCheck(stxn)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\ttp.Txns = append(tp.Txns, stxn)\n\t\ttp.txnsMap[stxn.TxnHash] = stxn\n\t}\n\treturn\n}", "func (s *Service) batchInsertDiffs(c context.Context, table string, wch chan []*model.Diff) (err error) {\n\tvar (\n\t\tbuff = make([]*model.Diff, _limit)\n\t\tbuffEnd = 0\n\t)\n\tfor ds := range wch {\n\t\tfor _, d := range ds {\n\t\t\tbuff[buffEnd] = d\n\t\t\tbuffEnd++\n\t\t\tif buffEnd >= _limit {\n\t\t\t\tvalues := diffValues(buff[:buffEnd])\n\t\t\t\tbuffEnd = 0\n\t\t\t\t_, err = s.dao.InsertTrend(c, table, values)\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\tif buffEnd > 0 {\n\t\t\tvalues := diffValues(buff[:buffEnd])\n\t\t\tbuffEnd = 0\n\t\t\t_, err = s.dao.InsertTrend(c, table, values)\n\t\t}\n\t}\n\treturn\n}", "func (se *ElasticSearch) BulkInsert(objects []ElasticObject) error {\n\tif len(objects) == 0 {\n\t\treturn errors.New(\"no object to bulk insert\")\n\t}\n\tpath, err := buildPath(objects[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\ttype index struct {\n\t\tId string `json:\"_id\"`\n\t}\n\t// Index action\n\ttype action struct {\n\t\tIndex index `json:\"index\"`\n\t}\n\tvar buf bytes.Buffer\n\tfor _, object := range objects {\n\t\t// Index action then source on next line\n\t\tfor _, d := range []interface{}{&action{index{object.Key()}}, object} {\n\t\t\tjsondata, err := json.Marshal(d)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t_, err = buf.Write(jsondata)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbuf.Write([]byte(\"\\n\")) // Required\n\t\t}\n\t}\n\treturn se.sendRequest(POST, se.serverUrl+se.basePath+path+actionBulk, &buf)\n}", "func (t *Table) AppendBulk(rows [][]string) (err error) {\n\tfor _, row := range rows {\n\t\terr = t.Append(row)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func InsertBatch(db *sql.DB, tableName string, data []map[string]interface{}) {\n\tmustNotBeInProdEnv()\n\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t_, err = tx.Exec(\"SET FOREIGN_KEY_CHECKS=0\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor _, row := range data {\n\t\tvar attributes []string\n\t\tvar valueMarks []string\n\t\tvar values []interface{}\n\t\tfor k, v := range row {\n\t\t\tattributes = append(attributes, database.QuoteName(k))\n\t\t\tvalueMarks = append(valueMarks, \"?\")\n\t\t\tvalues = append(values, v)\n\t\t}\n\t\t//nolint:gosec\n\t\tquery := fmt.Sprintf(\"INSERT INTO `%s` (%s) VALUES (%s)\",\n\t\t\ttableName, strings.Join(attributes, \", \"), strings.Join(valueMarks, \", \"))\n\t\t_, err = tx.Exec(query, values...)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\t_, err = tx.Exec(\"SET FOREIGN_KEY_CHECKS=1\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = tx.Commit()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func insertRows(rows []vmparser.Row) error {\n\t// ctx := GetInsertCtx()\n\t// defer PutInsertCtx(ctx)\n\n\tctx := &InsertCtx{mrs: model.MetricRows{}}\n\t// ctx.Reset(len(rows))\n\tfor i := range rows {\n\t\tr := &rows[i]\n\t\tctx.Labels = ctx.Labels[:0]\n\t\tctx.AddLabel(\"\", r.Metric)\n\t\tfor j := range r.Tags {\n\t\t\ttag := &r.Tags[j]\n\t\t\tctx.AddLabel(tag.Key, tag.Value)\n\t\t}\n\t\tctx.WriteDataPoint(nil, ctx.Labels, r.Timestamp, r.Value)\n\t}\n\trowsInserted.Add(len(rows))\n\trowsPerInsert.Update(float64(len(rows)))\n\treturn ctx.FlushBufs()\n}", "func (iu *IntervalUpdate) AddTrades(t ...*TradeTimeRange) *IntervalUpdate {\n\tids := make([]int, len(t))\n\tfor i := range t {\n\t\tids[i] = t[i].ID\n\t}\n\treturn iu.AddTradeIDs(ids...)\n}", "func (client *Client) CreateBulkTransaction(txn []*CreateTransaction) (_ *Response, err error) {\n\tpath := \"/transaction_bulk\"\n\turi := fmt.Sprintf(\"%s%s\", client.apiBaseURL, path)\n\n\tif len(txn) > MaxBulkPutSize {\n\t\treturn nil, ErrMaxBulkSizeExceeded\n\t}\n\n\ttxnBytes, err := json.Marshal(txn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(http.MethodPost, uri, bytes.NewBuffer(txnBytes))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := client.performRequest(req, string(txnBytes))\n\treturn resp, err\n}", "func insertRows(projectID, datasetID, tableID string) error {\n\t// projectID := \"my-project-id\"\n\t// datasetID := \"mydataset\"\n\t// tableID := \"mytable\"\n\tctx := context.Background()\n\tclient, err := bigquery.NewClient(ctx, projectID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"bigquery.NewClient: %w\", err)\n\t}\n\tdefer client.Close()\n\n\tinserter := client.Dataset(datasetID).Table(tableID).Inserter()\n\titems := []*Item{\n\t\t// Item implements the ValueSaver interface.\n\t\t{Name: \"Phred Phlyntstone\", Age: 32},\n\t\t{Name: \"Wylma Phlyntstone\", Age: 29},\n\t}\n\tif err := inserter.Put(ctx, items); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func BenchmarkBulkInsertAndLoad(b *testing.B) {\n\ttest.MeasureBulkInsertAndReload(b, provider)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GetLastTrade returns the newest Trade object in the database.
func (s *TickerSession) GetLastTrade(ctx context.Context) (trade Trade, err error) { err = s.GetRaw(ctx, &trade, "SELECT * FROM trades ORDER BY ledger_close_time DESC LIMIT 1") return }
[ "func (h *HUOBI) GetLastTrade(ctx context.Context, code currency.Pair) (LastTradeData, error) {\n\tvar resp LastTradeData\n\tcodeValue, err := h.FormatSymbol(code, asset.CoinMarginedFutures)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\tparams := url.Values{}\n\tparams.Set(\"contract_code\", codeValue)\n\tpath := common.EncodeURLValues(huobiLastTradeContract, params)\n\treturn resp, h.SendHTTPRequest(ctx, exchange.RestFutures, path, &resp)\n}", "func (m DontKnowTrade) GetLastShares() (v decimal.Decimal, err quickfix.MessageRejectError) {\n\tvar f field.LastSharesField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func (s *TradeService) QueryLast(ex types.ExchangeName, symbol string) (*types.Trade, error) {\n\tlog.Infof(\"querying last trade exchange = %s AND symbol = %s\", ex, symbol)\n\n\trows, err := s.DB.NamedQuery(`SELECT * FROM trades WHERE exchange = :exchange AND symbol = :symbol ORDER BY gid DESC LIMIT 1`, map[string]interface{}{\n\t\t\"symbol\": symbol,\n\t\t\"exchange\": ex,\n\t})\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"query last trade error\")\n\t}\n\n\tif rows.Err() != nil {\n\t\treturn nil, rows.Err()\n\t}\n\n\tdefer rows.Close()\n\n\tif rows.Next() {\n\t\tvar trade types.Trade\n\t\terr = rows.StructScan(&trade)\n\t\treturn &trade, err\n\t}\n\n\treturn nil, rows.Err()\n}", "func (t *TransactionV2) LastTx() string {\n\treturn t.lastTx\n}", "func (txmgr *LockBasedTxMgr) GetLastSavepoint() (*version.Height, error) {\n\treturn txmgr.db.GetLatestSavePoint()\n}", "func (r Records) Last() (t time.Time) {\n\tr.db.View(func(tx *bolt.Tx) (err error) {\n\t\tb := tx.Bucket([]byte(\"archive\"))\n\t\tif b == nil {\n\t\t\treturn\n\t\t}\n\n\t\tk, _ := b.Cursor().Last()\n\t\tt, err = time.Parse(time.RFC3339, string(k))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tt = t.Local()\n\n\t\treturn\n\t})\n\n\treturn\n}", "func (h *Handler) RetrieveLastSecretTx(fqId string) (*entityApi.TxResult, error) {\n\tvar txResult entityApi.TxResult\n\terr := h.GetAndFormat(fmt.Sprintf(\"%s%s/%s%s\", TxsPath, SecretsPath, fqId, LastPath), nil, &txResult)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &txResult, nil\n}", "func (t *Transaction) LastTx() string {\n\treturn t.lastTx\n}", "func (c *Cache) MostRecent(ticker string) time.Time {\n\n\t// If ticker is not known, return zero value time.\n\tif _, ok := c.ref[ticker]; !ok {\n\t\treturn time.Time{}\n\t}\n\n\tvar rr []quandl.Record\n\terr := c.DB.Model(&quandl.Record{}).\n\t\tWhere(\"serie = ?\", strings.ToUpper(ticker)).\n\t\tOrder(\"date DESC\").\n\t\tLimit(1).\n\t\tFind(&rr).Error\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif len(rr) == 0 {\n\t\treturn time.Time{}\n\t}\n\treturn rr[0].Date\n}", "func (m *API) GetLastTransaction(count int, min int) (lt LastTransaction, err error) {\n\tbody, err := m.get(fmt.Sprintf(\"%s%s\", m.BaseUrl, fmt.Sprintf(GetLastTransactions, count, min)))\n\tif err != nil {\n\t\treturn\n\t}\n\terr = json.Unmarshal(body, &lt)\n\treturn\n}", "func (c *Client) LastTransaction(ctx context.Context, address string) (string, error) {\n\tbody, err := c.get(ctx, fmt.Sprintf(\"wallet/%s/last_tx\", address))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body), nil\n}", "func (r Virtual_Guest) GetLastTransaction() (resp datatypes.Provisioning_Version1_Transaction, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getLastTransaction\", nil, &r.Options, &resp)\n\treturn\n}", "func (r Hardware_Server) GetLastTransaction() (resp datatypes.Provisioning_Version1_Transaction, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Hardware_Server\", \"getLastTransaction\", nil, &r.Options, &resp)\n\treturn\n}", "func (db *Bolt) GetLastHash() ([]byte, error) {\n\tvar lastHash []byte\n\terr := db.client.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(db.table))\n\t\tlastHash = b.Get([]byte(\"lastHash\"))\n\t\treturn nil\n\t})\n\treturn lastHash, err\n}", "func (h *History) Last() *Entry {\n\treturn &(*h)[len(*h)-1]\n}", "func (o *SmartstackBackend) GetLastChange() int32 {\n\tif o == nil || o.LastChange == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.LastChange\n}", "func (s *Repository) GetLast(ctx context.Context) (Budget, error) {\n\trow := s.pool.QueryRow(\n\t\tctx,\n\t\t`select \"ID\", \"startsAt\", \"endsAt\", \"createdAt\" from budget\n\t\t\torder by \"startsAt\" desc\n\t\t\tlimit 1`)\n\n\tb := Budget{}\n\n\terr := row.Scan(\n\t\t&b.ID,\n\t\t&b.StartsAt,\n\t\t&b.EndsAt,\n\t\t&b.CreatedAt)\n\tif err != nil {\n\t\tif err == pgx.ErrNoRows {\n\t\t\treturn Budget{}, transaction.ErrNotFound\n\t\t}\n\n\t\treturn Budget{}, err\n\t}\n\n\tconst limit = 50\n\n\trows, err := s.pool.Query(\n\t\tctx,\n\t\t`select \"categoryID\", \"amount\" from \"limit\"\n\t\t\twhere \"budgetID\" = $1\n\t\t\torder by \"amount\" desc\n\t\t\tlimit $2`,\n\t\tb.ID, limit)\n\tif err != nil {\n\t\tif err == pgx.ErrNoRows {\n\t\t\treturn Budget{\n\t\t\t\tID: b.ID,\n\t\t\t\tCreatedAt: b.CreatedAt,\n\t\t\t\tStartsAt: b.StartsAt,\n\t\t\t\tEndsAt: b.EndsAt,\n\t\t\t}, nil\n\t\t}\n\n\t\treturn Budget{}, err\n\t}\n\n\tdefer rows.Close()\n\n\tlimits, err := scanLimits(limit, rows)\n\tif err != nil {\n\t\treturn Budget{}, err\n\t}\n\n\tb.Limits = limits\n\n\treturn b, nil\n}", "func Last(d db.DB) (*db.Entry, error) {\n\titr, err := d.Query(db.Query{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer itr.Close()\n\tif entry, err := itr.Next(); err == io.EOF {\n\t\treturn nil, errors.New(\"db is empty\")\n\t} else {\n\t\treturn entry, err\n\t}\n}", "func GetLastDictionaryVersion() *DictionaryVersion {\n\titem := new(DictionaryVersion)\n\tdv := db.C(\"dictionary_versions\")\n\n\tdv.Find(nil).Sort(\"-_id\").Limit(1).One(&item)\n\treturn item\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DeleteOldTrades deletes trades in the database older than minDate.
func (s *TickerSession) DeleteOldTrades(ctx context.Context, minDate time.Time) error { _, err := s.ExecRaw(ctx, "DELETE FROM trades WHERE ledger_close_time < ?", minDate) return err }
[ "func (m *NewsyDAO) deleteOld() (int, error) {\n\tm.connect()\n\tinfo, err := db.C(m.Database).RemoveAll(bson.M{\"time\": bson.M{\"$lt\": time.Now().Add(-time.Hour * 24 * 30)}})\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\treturn info.Removed, err\n}", "func (e *elephant) deleteOldRaws(before int64) error {\n\treturn db.Unscoped().Model(&Sentiment{}).\n\t\tWhere(\"unix < ?\", before).\n\t\tDelete(&Sentiment{}).\n\t\tError\n}", "func RemoveOldActivate(days string) {\n\tproblems, err := os.OpenFile(\"logs/mainLog.txt\", os.O_APPEND|os.O_WRONLY, 0666)\n\tdefer problems.Close()\n\tlog := log.New(problems, \"\", log.LstdFlags|log.Lshortfile)\n\n\t//check if database connection is open\n\tif db.Ping() != nil {\n\t\tlog.Println(\"DATABASE DOWN!\")\n\t\treturn\n\t}\n\n\tstmt, err := db.Prepare(\"DELETE FROM activate WHERE expire < NOW() - INTERVAL \" + days + \" DAY\")\n\tdefer stmt.Close()\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\t_, err = stmt.Exec()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n}", "func (f *FileObject) DeleteOld() {\n\tfor {\n\t\tf := func() {\n\t\t\t// traverse the archived log files in the log directory and\n\t\t\t// delete the log files that exceed the maximum number of days\n\t\t\t// reserved.\n\t\t\tdir := filepath.Dir(f.path)\n\t\t\tos.Chdir(dir)\n\n\t\t\tfilepath.Walk(dir, func(path string, file os.FileInfo, err error) error {\n\t\t\t\tif file == nil {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tif !file.IsDir() {\n\t\t\t\t\tname := file.Name()\n\t\t\t\t\tif strings.HasSuffix(name, \".zip\") {\n\t\t\t\t\t\ttimestamp := name[2:16]\n\t\t\t\t\t\tif f.isDelete(timestamp) {\n\t\t\t\t\t\t\tos.Remove(name)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if strings.Index(name, \".log.\") == 1 {\n\t\t\t\t\t\ttimestamp := name[6:20]\n\t\t\t\t\t\tif f.isDelete(timestamp) {\n\t\t\t\t\t\t\tos.Remove(name)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t})\n\t\t}\n\t\tf()\n\n\t\tnow := time.Now()\n\t\tnext := now.Add(time.Hour * 24)\n\t\tnext = time.Date(next.Year(), next.Month(), next.Day(), 0, 0, 0, 0, next.Location())\n\t\tt := time.NewTimer(next.Sub(now))\n\t\t<-t.C\n\t}\n}", "func (s *Storage) DeleteOld(thresholdTime int64) error {\n\tdirs, err := getBackupDirs(s.LocalDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, dir := range dirs {\n\t\tif thresholdTime < dir.Timestamp {\n\t\t\tcontinue\n\t\t}\n\n\t\tpath := filepath.Join(s.LocalDir, dir.Info.Name())\n\t\tos.RemoveAll(path)\n\t}\n\n\treturn nil\n}", "func (q *Q) DeleteTransactionsFilteredTmpOlderThan(ctx context.Context, howOldInSeconds uint64) (int64, error) {\n\tsql := sq.Delete(\"history_transactions_filtered_tmp\").\n\t\tWhere(sq.Expr(\"now() >= (created_at + interval '1 second' * ?)\", howOldInSeconds))\n\tresult, err := q.Exec(ctx, sql)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn result.RowsAffected()\n}", "func (a *Application) DeleteOldTrainAlarms(ctx context.Context) error {\n\t// delete old trainalarms\n\tthreshold := time.Now().AddDate(0, 0, -2)\n\ta.log.Infof(\"delete old trains before %v\", threshold)\n\terr := a.repo.DeleteOldTrainAlarms(ctx, threshold)\n\tif err != nil {\n\t\ta.log.Error(err)\n\t\treturn errors.New(\"internal server error\")\n\t}\n\n\ta.log.Trace(\"old train alarms deleted\")\n\treturn nil\n}", "func DeleteOldFiles(dir string, days int) {\n\ttmpfiles, err := ioutil.ReadDir(dir)\n\tif err != nil {\n\t\treturn\n\t}\n\tfor _, file := range tmpfiles {\n\t\tif file.Mode().IsRegular() {\n\t\t\tif time.Now().Sub(file.ModTime()) > time.Duration(days*24)*time.Hour {\n\t\t\t\t// delete file\n\t\t\t\t_ = os.Remove(filepath.Join(dir, file.Name()))\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func DeleteOldSMS() error {\n\tconn, err := newDBConn()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"Error connecting to database \"+err.Error())\n\t\treturn err\n\t}\n\tdefer conn.Release()\n\n\tcutOffTime := time.Now().AddDate(0, 0, -2)\n\t_, err = conn.Query(context.Background(), deleteOldSmsQuery, cutOffTime)\n\treturn nil\n}", "func DeleteOldActions(olderThan time.Duration) (err error) {\n\tif olderThan <= 0 {\n\t\treturn nil\n\t}\n\n\t_, err = db.GetEngine(db.DefaultContext).Where(\"created_unix < ?\", time.Now().Add(-olderThan).Unix()).Delete(&Action{})\n\treturn err\n}", "func (db *Database) DeleteOldMessages(period string) error {\n\t_, err := db.db.Exec(`\n\t\tDELETE FROM melodious.messages WHERE dt < (NOW() - $1::INTERVAL);\n\t`, period)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *Store) DeleteOldJobLogs(ctx context.Context, retentionInDays int) error {\n\treturn s.Store.Exec(ctx, sqlf.Sprintf(deleteOldJobLogsFmtStr, retentionInDays))\n}", "func (s *Service) delOldDBTokens(c context.Context, mid int64, now time.Time) (err error) {\n\tif _, err = s.dao.DelOldTokenByMid(c, mid, now); err != nil {\n\t\treturn\n\t}\n\tif _, err = s.dao.DelOldTokenByMid(c, mid, monDiff(now, -1)); err != nil {\n\t\treturn\n\t}\n\tif _, err = s.dao.DelOldTokenByMid(c, mid, monDiff(now, -2)); err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func (s *AntidoteScheduler) pruneOldLiveSessions(sc ot.SpanContext) error {\n\tspan := ot.StartSpan(\"scheduler_pruneoldsessions\", ot.ChildOf(sc))\n\tdefer span.Finish()\n\n\tlsList, err := s.Db.ListLiveSessions(span.Context())\n\tif err != nil {\n\t\tspan.LogFields(log.Error(err))\n\t\text.Error.Set(span, true)\n\t\treturn err\n\t}\n\n\tlsTTL := time.Duration(s.Config.LiveSessionTTL) * time.Minute\n\n\tfor _, ls := range lsList {\n\t\tcreatedTime := time.Since(ls.CreatedTime)\n\n\t\t// No need to continue if this session hasn't even exceeded the TTL\n\t\tif createdTime <= lsTTL {\n\t\t\tcontinue\n\t\t}\n\n\t\tllforls, err := s.Db.GetLiveLessonsForSession(span.Context(), ls.ID)\n\t\tif err != nil {\n\t\t\tspan.LogFields(log.Error(err))\n\t\t\text.Error.Set(span, true)\n\t\t\treturn err\n\t\t}\n\n\t\t// We don't want/need to clean up this session if there are active livelessons that are using it.\n\t\tif len(llforls) > 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\t// TODO(mierdin): It would be pretty rare, but in the event that a livelesson is spun up between the request above\n\t\t// and the livesession deletion below, we would encounter the leak bug we saw in 0.6.0. It might be worth seeing if\n\t\t// you can lock things somehow between the two.\n\n\t\terr = s.Db.DeleteLiveSession(span.Context(), ls.ID)\n\t\tif err != nil {\n\t\t\tspan.LogFields(log.Error(err))\n\t\t\text.Error.Set(span, true)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *MockDBStore) DeleteOldIndexes(v0 context.Context, v1 time.Duration, v2 time.Time) (int, error) {\n\tr0, r1 := m.DeleteOldIndexesFunc.nextHook()(v0, v1, v2)\n\tm.DeleteOldIndexesFunc.appendCall(DBStoreDeleteOldIndexesFuncCall{v0, v1, v2, r0, r1})\n\treturn r0, r1\n}", "func (db *Database) DeleteOldKeyServerStatsDays(maxAge time.Duration) (int64, error) {\n\tif maxAge > 0 {\n\t\tmaxAge = -1 * maxAge\n\t}\n\ta := time.Now().UTC().Add(maxAge)\n\trtn := db.db.Unscoped().\n\t\tWhere(\"day < ?\", a).\n\t\tDelete(&KeyServerStatsDay{})\n\treturn rtn.RowsAffected, rtn.Error\n}", "func CleanOld() error {\n\tdb, err := bolt.Open(cfg.BoltDB, dbMode, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\n\treturn db.Update(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket([]byte(cfg.BucketForOperations))\n\t\tif bucket == nil {\n\t\t\treturn errors.New(\"Jornal bucket for operation not found\")\n\t\t}\n\n\t\tcursor := bucket.Cursor()\n\n\t\t//Calculate latest date\n\t\tlatest := time.Now().Add(time.Duration(-cfg.Capacity) * 24 * time.Hour).Format(TimeLayout)\n\n\t\tfor k, _ := cursor.Seek([]byte(\"0\")); k != nil && bytes.Compare(k, []byte(latest)) <= 0; k, _ = cursor.Next() {\n\t\t\tcursor.Delete()\n\t\t}\n\t\treturn nil\n\t})\n}", "func (m *Postgres) DeleteOlderThan(key string, t time.Time) error {\n\tdeleteOlderMem(m.cache, key, t)\n\treturn nil\n}", "func (db MySQL) DeleteExpired() {\n\n\trows1, _ := db.SimpleQuery(\"DELETE FROM recover WHERE created < (NOW() - INTERVAL 1 HOUR)\")\n\t//rows2, _ := db.SimpleQuery(\"DELETE FROM emailChange WHERE created < (NOW() - INTERVAL 1 HOUR)\")\n\trows3, _ := db.SimpleQuery(\"DELETE FROM devices WHERE created < (NOW() - INTERVAL 60 DAY)\")\n\trows4, _ := db.SimpleQuery(\"DELETE FROM refreshtokens WHERE created < (NOW() - INTERVAL \" + db.RefreshTokenDuration + \" DAY)\")\n\n\trows1.Close()\n\trows3.Close()\n\trows4.Close()\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
chunkifyDBTrades transforms a slice into a slice of chunks (also slices) of chunkSize e.g.: Chunkify([b, c, d, e, f], 2) = [[b c] [d e] [f]]
func chunkifyDBTrades(sl []Trade, chunkSize int) [][]Trade { var chunkedSlice [][]Trade numChunks := int(math.Ceil(float64(len(sl)) / float64(chunkSize))) start := 0 length := len(sl) for i := 0; i < numChunks; i++ { end := start + chunkSize if end > length { end = length } chunk := sl[start:end] chunkedSlice = append(chunkedSlice, chunk) start = end } return chunkedSlice }
[ "func chunk(slice []pointsStruct, chunkSize int) [][]pointsStruct {\n\tvar chunks [][]pointsStruct\n\n\tif chunkSize <= 0 { // Allow the size to be unlimited: 0 & -1 both achieve that\n\t\tchunkSize = len(slice)\n\t}\n\tfor i := 0; i < len(slice); i += chunkSize {\n\t\tend := i + chunkSize\n\t\tif end > len(slice) {\n\t\t\tend = len(slice)\n\t\t}\n\t\tchunks = append(chunks, slice[i:end])\n\t}\n\treturn chunks\n}", "func Chunk[T any](collection []T, size int) [][]T {\n\tif size <= 0 {\n\t\tpanic(\"Second parameter must be greater than 0\")\n\t}\n\n\tresult := make([][]T, 0, len(collection)/2+1)\n\tlength := len(collection)\n\n\tfor i := 0; i < length; i++ {\n\t\tchunk := i / size\n\n\t\tif i%size == 0 {\n\t\t\tresult = append(result, make([]T, 0, size))\n\t\t}\n\n\t\tresult[chunk] = append(result[chunk], collection[i])\n\t}\n\n\treturn result\n}", "func ChunkSlice(original []string, chunkSize int) (divided [][]string) {\n\tif chunkSize < 1 {\n\t\treturn\n\t}\n\tfor i := 0; i < len(original); i += chunkSize {\n\t\tend := i + chunkSize\n\n\t\tif end > len(original) {\n\t\t\tend = len(original)\n\t\t}\n\n\t\tdivided = append(divided, original[i:end])\n\t}\n\treturn\n}", "func Chunk[T any](ss []T, chunkLength int) [][]T {\n\tif chunkLength <= 0 {\n\t\tpanic(\"chunkLength should be greater than 0\")\n\t}\n\n\tresult := make([][]T, 0)\n\tl := len(ss)\n\tif l == 0 {\n\t\treturn result\n\t}\n\n\tvar step = l / chunkLength\n\tif step == 0 {\n\t\tresult = append(result, ss)\n\t\treturn result\n\t}\n\tvar remain = l % chunkLength\n\tfor i := 0; i < step; i++ {\n\t\tresult = append(result, ss[i*chunkLength:(i+1)*chunkLength])\n\t}\n\tif remain != 0 {\n\t\tresult = append(result, ss[step*chunkLength:l])\n\t}\n\n\treturn result\n}", "func (s *Storage) ChunkQuerier(ctx context.Context, mint, maxt int64) (storage.ChunkQuerier, error) {\n\ts.mtx.Lock()\n\tqueryables := s.queryables\n\ts.mtx.Unlock()\n\n\tqueriers := make([]storage.ChunkQuerier, 0, len(queryables))\n\tfor _, queryable := range queryables {\n\t\tq, err := queryable.ChunkQuerier(ctx, mint, maxt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tqueriers = append(queriers, q)\n\t}\n\treturn storage.NewMergeChunkQuerier(nil, queriers, storage.NewCompactingChunkSeriesMerger(storage.ChainedSeriesMerge)), nil\n}", "func splitInChunks(data []byte, chunksize uint) *[][]byte {\n\tlength := len(data)\n\tremaining := uint(length)\n\n\tchunks := make([][]byte, 0)\n\n\tvar i uint\n\tfor i = 0; remaining > 0; i += chunksize {\n\t\tj := chunksize\n\t\tif j > remaining {\n\t\t\tj = remaining\n\t\t}\n\n\t\tchunks = append(chunks, data[i:i+j])\n\t\tremaining -= j\n\t}\n\n\treturn &chunks\n}", "func Chunk(chunkSize int, length int, f func(int, int)) {\n\tfor i := 0; i < length; i += chunkSize {\n\t\tend := i + chunkSize\n\t\tif end > length {\n\t\t\tend = length\n\t\t}\n\n\t\tf(i, end)\n\t}\n}", "func makeChunks(config *core.Config, stream core.StreamId, node core.NodeId, start core.SequenceId, count int) []core.Chunk {\n\tchunks := make([]core.Chunk, count)\n\tfor i := range chunks {\n\t\tchunks[i] = core.Chunk{\n\t\t\tStream: stream,\n\t\t\tSource: node,\n\t\t\tSequence: start + core.SequenceId(i),\n\t\t\tSubsequence: core.SubsequenceIndex(i + 1),\n\t\t}\n\t\tdata := core.AppendStreamId(nil, stream)\n\t\tdata = core.AppendNodeId(data, node)\n\t\tdata = core.AppendSequenceId(data, chunks[i].Sequence)\n\t\tdata = core.AppendSubsequenceIndex(data, chunks[i].Subsequence)\n\t\tdata = append(data, make([]byte, config.MaxChunkDataSize-len(data))...)\n\t\tdata[len(data)-1] = 1\n\t\tchunks[i].Data = data\n\t}\n\tdata := chunks[len(chunks)-1].Data\n\tdata = data[0 : len(data)-1]\n\tdata[len(data)-1] = 1\n\tchunks[len(chunks)-1].Data = data\n\treturn chunks\n}", "func chunk(arr []string, size int) [][]string {\n\tif len(arr) == 0 {\n\t\treturn [][]string{}\n\t}\n\n\t// That was easy...\n\tif len(arr) < size {\n\t\treturn [][]string{arr}\n\t}\n\n\tresults := make([][]string, 0)\n\toffset := 0\n\n\tvar current []string\n\n\tfor i := range arr {\n\t\tif i%size == 0 {\n\t\t\tcurrent = make([]string, size)\n\t\t\tresults = append(results, current)\n\n\t\t\tif i > 0 {\n\t\t\t\toffset++\n\t\t\t}\n\t\t}\n\n\t\tcurrent[i%size] = arr[i]\n\t}\n\n\treturn results\n}", "func divideByChunkSize(keys []peer.ID, chunkSize int) [][]peer.ID {\n\tif len(keys) == 0 {\n\t\treturn nil\n\t}\n\n\tif chunkSize < 1 {\n\t\tpanic(fmt.Sprintf(\"fullrt: divide into groups: invalid chunk size %d\", chunkSize))\n\t}\n\n\tvar keyChunks [][]peer.ID\n\tvar nextChunk []peer.ID\n\tchunkProgress := 0\n\tfor _, k := range keys {\n\t\tnextChunk = append(nextChunk, k)\n\t\tchunkProgress++\n\t\tif chunkProgress == chunkSize {\n\t\t\tkeyChunks = append(keyChunks, nextChunk)\n\t\t\tchunkProgress = 0\n\t\t\tnextChunk = make([]peer.ID, 0, len(nextChunk))\n\t\t}\n\t}\n\tif chunkProgress != 0 {\n\t\tkeyChunks = append(keyChunks, nextChunk)\n\t}\n\treturn keyChunks\n}", "func MakeChunks(arr []string, size int) [][]string {\n\tif size == 0 {\n\t\tfmt.Println(\"WARNING: chunk size is not set, will use size 10\")\n\t\tsize = 10\n\t}\n\tvar out [][]string\n\talen := len(arr)\n\tabeg := 0\n\taend := size\n\tfor {\n\t\tif aend < alen {\n\t\t\tout = append(out, arr[abeg:aend])\n\t\t\tabeg = aend\n\t\t\taend += size\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tif abeg < alen {\n\t\t// out = append(out, arr[abeg:alen-1])\n\t\tout = append(out, arr[abeg:alen])\n\t}\n\treturn out\n}", "func SplitInBatches(docs []DataObject, batchSize int) []Batch {\n\tdefer startTimer(\"Split in batches\")()\n\tbatches := []Batch{}\n\tcount := 0\n\tvar tmpbatch Batch\n\tfor _, doc := range docs {\n\t\tif count % batchSize == 0 {\n\t\t\ttmpbatch = NewBatch()\n\t\t}\n\t\tcount++\n\t\ttmpbatch.Add(doc)\n\t\tif count % batchSize == 0 || count == len(docs) {\n\t\t\tbatches = append(batches, tmpbatch)\n\t\t}\n\t}\n\treturn batches\n}", "func DivideCustomerTableInChunk(customerTable []CustomerRow) (arrayOfCustomerTableChunk [][]CustomerRow) {\n\n\tchunkSize := 999\n\n\tfor i := 0; i < len(customerTable); i += chunkSize {\n\t\tend := i + chunkSize\n\n\t\tif end > len(customerTable) {\n\t\t\tend = len(customerTable)\n\t\t}\n\n\t\tarrayOfCustomerTableChunk = append(arrayOfCustomerTableChunk, customerTable[i:end])\n\t}\n\n\treturn arrayOfCustomerTableChunk\n}", "func breakIntoBatches(batchSize int, docs []Document) [][]Document {\n\n\tbatches := [][]Document{}\n\n\tnumBatches := len(docs) / batchSize\n\n\t// is there residue? if so, add one more to batch\n\tif len(docs)%batchSize != 0 {\n\t\tnumBatches += 1\n\t}\n\n\tfor i := 0; i < numBatches; i++ {\n\t\tbatch := []Document{}\n\t\tfor j := 0; j < batchSize; j++ {\n\t\t\tdocIndex := i*batchSize + j\n\t\t\tif docIndex >= len(docs) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tdoc := docs[docIndex]\n\t\t\tbatch = append(batch, doc)\n\t\t}\n\t\tbatches = append(batches, batch)\n\t}\n\n\treturn batches\n\n}", "func (p *Provider) chunkIDs(ids []*string) [][]*string {\n\tvar chuncked [][]*string\n\tfor i := 0; i < len(ids); i += 100 {\n\t\tsliceEnd := -1\n\t\tif i+100 < len(ids) {\n\t\t\tsliceEnd = i + 100\n\t\t} else {\n\t\t\tsliceEnd = len(ids)\n\t\t}\n\t\tchuncked = append(chuncked, ids[i:sliceEnd])\n\t}\n\treturn chuncked\n}", "func batch(slice []string, max int) [][]string {\n batches := [][]string{}\n var start, end int\n\n for start < len(slice) {\n end = start + max\n if end > len(slice) {\n end = len(slice)\n }\n batches = append(batches, slice[start:end])\n start = end\n }\n return batches\n}", "func chunkContainers(containers []*model.Container, chunks int) [][]*model.Container {\n\tperChunk := (len(containers) / chunks) + 1\n\tchunked := make([][]*model.Container, 0, chunks)\n\tchunk := make([]*model.Container, 0, perChunk)\n\n\tfor _, ctr := range containers {\n\t\tchunk = append(chunk, ctr)\n\t\tif len(chunk) == perChunk {\n\t\t\tchunked = append(chunked, chunk)\n\t\t\tchunk = make([]*model.Container, 0, perChunk)\n\t\t}\n\t}\n\tif len(chunk) > 0 {\n\t\tchunked = append(chunked, chunk)\n\t}\n\treturn chunked\n}", "func toWireChunks(descs []*chunkDesc, wireChunks []Chunk) ([]Chunk, error) {\n\tif cap(wireChunks) < len(descs) {\n\t\twireChunks = make([]Chunk, len(descs))\n\t} else {\n\t\twireChunks = wireChunks[:len(descs)]\n\t}\n\tfor i, d := range descs {\n\t\tfrom, to := d.chunk.Bounds()\n\t\twireChunk := Chunk{\n\t\t\tFrom: from,\n\t\t\tTo: to,\n\t\t\tClosed: d.closed,\n\t\t\tFlushedAt: d.flushed,\n\t\t}\n\n\t\tslice := wireChunks[i].Data[:0] // try to re-use the memory from last time\n\t\tif cap(slice) < d.chunk.CompressedSize() {\n\t\t\tslice = make([]byte, 0, d.chunk.CompressedSize())\n\t\t}\n\n\t\tout, err := d.chunk.BytesWith(slice)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\twireChunk.Data = out\n\t\twireChunks[i] = wireChunk\n\t}\n\treturn wireChunks, nil\n}", "func chunkify(chunkSize uint64, buf []byte, fn func([]byte, uint64) (uint64, error)) (uint64, error) {\n\ttoProcess := uint64(len(buf))\n\tvar (\n\t\ttotalProcessed uint64\n\t\tcurProcessed uint64\n\t\toff uint64\n\t\terr error\n\t)\n\tfor {\n\t\tif totalProcessed == toProcess {\n\t\t\treturn totalProcessed, nil\n\t\t}\n\n\t\tif totalProcessed+chunkSize > toProcess {\n\t\t\tcurProcessed, err = fn(buf[totalProcessed:], off)\n\t\t} else {\n\t\t\tcurProcessed, err = fn(buf[totalProcessed:totalProcessed+chunkSize], off)\n\t\t}\n\t\ttotalProcessed += curProcessed\n\t\toff += curProcessed\n\n\t\tif err != nil {\n\t\t\treturn totalProcessed, err\n\t\t}\n\n\t\t// Return partial result immediately.\n\t\tif curProcessed < chunkSize {\n\t\t\treturn totalProcessed, nil\n\t\t}\n\n\t\t// If we received more bytes than we ever requested, this is a problem.\n\t\tif totalProcessed > toProcess {\n\t\t\tpanic(fmt.Sprintf(\"bytes completed (%d)) > requested (%d)\", totalProcessed, toProcess))\n\t\t}\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NewSetAmountOK creates a SetAmountOK with default headers values
func NewSetAmountOK() *SetAmountOK { return &SetAmountOK{} }
[ "func newHamt(level uint8) hamt {\n\treturn hamt{level: level}\n}", "func NewSetAmountUnauthorized() *SetAmountUnauthorized {\n\treturn &SetAmountUnauthorized{}\n}", "func (app *specificTokenCodeBuilder) WithAmount(amount string) SpecificTokenCodeBuilder {\n\tapp.amount = amount\n\treturn app\n}", "func (_Supersymmetry *SupersymmetryTransactor) CreateMintRequest(opts *bind.TransactOpts, sender string, value *big.Int) (*types.Transaction, error) {\n\treturn _Supersymmetry.contract.Transact(opts, \"createMintRequest\", sender, value)\n}", "func (v *Amount) Reset() {\n\tv.Currency.Reset()\n\tv.Metadata = v.Metadata[:0]\n\tv.Value = \"\"\n}", "func (_GovernmentContract *GovernmentContractTransactor) Set(opts *bind.TransactOpts, name string, value *big.Int) (*types.Transaction, error) {\n\treturn _GovernmentContract.contract.Transact(opts, \"set\", name, value)\n}", "func (_HelloWorld *HelloWorldTransactor) Set(opts *bind.TransactOpts, v string) (*types.Transaction, *types.Receipt, error) {\n\treturn _HelloWorld.contract.Transact(opts, \"set\", v)\n}", "func (o *EstimateCoinBuyParams) SetDefaults() {\n\tvar (\n\t\tswapFromDefault = string(\"optimal\")\n\t)\n\n\tval := EstimateCoinBuyParams{\n\t\tSwapFrom: &swapFromDefault,\n\t}\n\n\tval.timeout = o.timeout\n\tval.Context = o.Context\n\tval.HTTPClient = o.HTTPClient\n\t*o = val\n}", "func NewAmount(f float64) (int64, er.R) {\n\t// The amount is only considered invalid if it cannot be represented\n\t// as an integer type. This may happen if f is NaN or +-Infinity.\n\tswitch {\n\tcase math.IsNaN(f):\n\t\tfallthrough\n\tcase math.IsInf(f, 1):\n\t\tfallthrough\n\tcase math.IsInf(f, -1):\n\t\treturn 0, er.New(\"invalid bitcoin amount\")\n\t}\n\n\treturn round(f * float64(SatoshiPerBitcoin())), nil\n}", "func NewAmount(q float64, currency string) *Amount {\n\treturn &Amount{q, currency}\n}", "func Amount(val string) Argument {\n\treturn func(request *requests.Request) error {\n\t\trequest.AddArgument(\"amount\", val)\n\t\treturn nil\n\t}\n}", "func (b *Budget) SetAmount(month time.Month, year int, amount float64) {\n\tb.months[monthsKey(month, year)] = amount\n}", "func (_Supersymmetry *SupersymmetrySession) CreateMintRequest(sender string, value *big.Int) (*types.Transaction, error) {\n\treturn _Supersymmetry.Contract.CreateMintRequest(&_Supersymmetry.TransactOpts, sender, value)\n}", "func NewAmount(symbol string, number string) (*Amount, error) {\n\tsym, err := currency.ParseISO(symbol)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tn := new(big.Rat)\n\tn.SetString(number)\n\treturn &Amount{n, sym.String()}, nil\n}", "func (vs *DefaultValueStore) newOutBulkSetMsg() *bulkSetMsg {\n\tbsm := <-vs.bulkSetState.outFreeMsgChan\n\tif vs.msgRing != nil {\n\t\tif r := vs.msgRing.Ring(); r != nil {\n\t\t\tif n := r.LocalNode(); n != nil {\n\t\t\t\tbinary.BigEndian.PutUint64(bsm.header, n.ID())\n\t\t\t}\n\t\t}\n\t}\n\tbsm.body = bsm.body[:0]\n\treturn bsm\n}", "func (args *SendTxArgs) setDefaults() error {\n\tif args.Gas == nil {\n\t\targs.Gas = (*hexutil.Big)(big.NewInt(DEFAULTGAS))\n\t}\n\t//可以发送请求\n\tif args.GasPrice == nil {\n\t\tprice := new(big.Int).SetInt64(190)\n\n\t\targs.GasPrice = (*hexutil.Big)(price)\n\t}\n\tif args.Value == nil {\n\t\targs.Value = new(hexutil.Big) // Water Egg\n\t}\n\n\tif args.Nonce == nil {\n\t\tnonce, err := getNonce(args.From)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\targs.Nonce = (*hexutil.Uint64)(&nonce)\n\t}\n\treturn nil\n}", "func newTxOut(amount int64, pkScriptVer uint16, pkScript []byte) *wire.TxOut {\n\treturn &wire.TxOut{\n\t\tValue: amount,\n\t\tVersion: pkScriptVer,\n\t\tPkScript: pkScript,\n\t}\n}", "func MoneyINIT(w http.ResponseWriter, r *http.Request) {\n\tfmt.Printf(\"inside MoneyINIT in postStockData\")\n\targ := []string{\"TRADER_$$$\", \"1000\", \"placeholder2\", \"placeholder3\", \"placeholder4\", \"placeholder5\", \"placeholder6\", \"placeholder7\", \"placeholder8\"}\n\t// chaincalls.EntryPoint(arg)\n\tbytereturn := chaincalls.NewOrMod(arg)\n\tw.Write(bytereturn)\n}", "func NewSetAmountForbidden() *SetAmountForbidden {\n\treturn &SetAmountForbidden{}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NewSetAmountUnauthorized creates a SetAmountUnauthorized with default headers values
func NewSetAmountUnauthorized() *SetAmountUnauthorized { return &SetAmountUnauthorized{} }
[ "func NewSetAmountForbidden() *SetAmountForbidden {\n\treturn &SetAmountForbidden{}\n}", "func NewUnauthorized(cause error) Unauthorized { return Unauthorized(cause.Error()) }", "func setAuthorization(req *http.Request, apiKey string) {\n\treq.SetBasicAuth(apiKey, \"\")\n}", "func newHamt(level uint8) hamt {\n\treturn hamt{level: level}\n}", "func NewSetRoleUnauthorized() *SetRoleUnauthorized {\n\treturn &SetRoleUnauthorized{}\n}", "func NewUpdateMTOShipmentStatusUnauthorized() *UpdateMTOShipmentStatusUnauthorized {\n\n\treturn &UpdateMTOShipmentStatusUnauthorized{}\n}", "func NewSetAmountOK() *SetAmountOK {\n\treturn &SetAmountOK{}\n}", "func NewUnauthorized() gin.H {\n\treturn gin.H{\"error\": \"user is not authorized\"}\n}", "func (client *blobClient) setLegalHoldCreateRequest(ctx context.Context, legalHold bool, options *blobClientSetLegalHoldOptions) (*policy.Request, error) {\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, client.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"comp\", \"legalhold\")\n\tif options != nil && options.Timeout != nil {\n\t\treqQP.Set(\"timeout\", strconv.FormatInt(int64(*options.Timeout), 10))\n\t}\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"x-ms-version\", \"2020-10-02\")\n\tif options != nil && options.RequestID != nil {\n\t\treq.Raw().Header.Set(\"x-ms-client-request-id\", *options.RequestID)\n\t}\n\treq.Raw().Header.Set(\"x-ms-legal-hold\", strconv.FormatBool(legalHold))\n\treq.Raw().Header.Set(\"Accept\", \"application/xml\")\n\treturn req, nil\n}", "func Amount(val string) Argument {\n\treturn func(request *requests.Request) error {\n\t\trequest.AddArgument(\"amount\", val)\n\t\treturn nil\n\t}\n}", "func NewUnauthorized(res calcsvc.Unauthorized) Unauthorized {\n\tbody := Unauthorized(res)\n\treturn body\n}", "func (o *ProcessorSignalDecisionReportRequest) UnsetAmountInstantlyAvailable() {\n\to.AmountInstantlyAvailable.Unset()\n}", "func (t *Transport) setRequestAuthHeader(r *http.Request, token *scm.Token) error {\n\toauthParams := t.commonOAuthParams()\n\toauthParams[\"oauth_token\"] = token.Token\n\tparams := collectParameters(r, oauthParams)\n\n\tsignatureBase := signatureBase(r, params)\n\tsignature, err := sign(t.PrivateKey, signatureBase)\n\tif err != nil {\n\t\treturn err\n\t}\n\toauthParams[\"oauth_signature\"] = signature\n\tr.Header.Set(\"Authorization\", authHeaderValue(oauthParams))\n\treturn nil\n}", "func (h *ResponseHeader) setNonSpecial(key []byte, value []byte) {\n\th.h = setArgBytes(h.h, key, value, argsHasValue)\n}", "func (client *blobClient) setTierCreateRequest(ctx context.Context, tier AccessTier, blobClientSetTierOptions *blobClientSetTierOptions, leaseAccessConditions *LeaseAccessConditions, modifiedAccessConditions *ModifiedAccessConditions) (*policy.Request, error) {\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, client.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"comp\", \"tier\")\n\tif blobClientSetTierOptions != nil && blobClientSetTierOptions.Snapshot != nil {\n\t\treqQP.Set(\"snapshot\", *blobClientSetTierOptions.Snapshot)\n\t}\n\tif blobClientSetTierOptions != nil && blobClientSetTierOptions.VersionID != nil {\n\t\treqQP.Set(\"versionid\", *blobClientSetTierOptions.VersionID)\n\t}\n\tif blobClientSetTierOptions != nil && blobClientSetTierOptions.Timeout != nil {\n\t\treqQP.Set(\"timeout\", strconv.FormatInt(int64(*blobClientSetTierOptions.Timeout), 10))\n\t}\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"x-ms-access-tier\", string(tier))\n\tif blobClientSetTierOptions != nil && blobClientSetTierOptions.RehydratePriority != nil {\n\t\treq.Raw().Header.Set(\"x-ms-rehydrate-priority\", string(*blobClientSetTierOptions.RehydratePriority))\n\t}\n\treq.Raw().Header.Set(\"x-ms-version\", \"2020-10-02\")\n\tif blobClientSetTierOptions != nil && blobClientSetTierOptions.RequestID != nil {\n\t\treq.Raw().Header.Set(\"x-ms-client-request-id\", *blobClientSetTierOptions.RequestID)\n\t}\n\tif leaseAccessConditions != nil && leaseAccessConditions.LeaseID != nil {\n\t\treq.Raw().Header.Set(\"x-ms-lease-id\", *leaseAccessConditions.LeaseID)\n\t}\n\tif modifiedAccessConditions != nil && modifiedAccessConditions.IfTags != nil {\n\t\treq.Raw().Header.Set(\"x-ms-if-tags\", *modifiedAccessConditions.IfTags)\n\t}\n\treq.Raw().Header.Set(\"Accept\", \"application/xml\")\n\treturn req, nil\n}", "func newHTTPHeader(header, value string) httpHeader {\n\treturn httpHeader{Header: header, Value: value}\n}", "func NewUnauthorized(err error, msg string) error {\n\treturn &unauthorized{wrap(err, msg, \"\")}\n}", "func (client *Client) setHeaders(req *http.Request, httpVerb, path, contentType, content string) error {\n\tif client.creds == nil {\n\t\treturn ErrNoCredentials\n\t}\n\tnow := time.Now().UTC().Format(\"2006-01-02T15:04:05.000000Z07:00\")\n\n\tif len(contentType) > 0 {\n\t\treq.Header.Set(\"Content-Type\", contentType)\n\t}\n\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treq.Header.Set(\"Dragonchain\", client.creds.GetDragonchainID())\n\treq.Header.Set(\"Timestamp\", fmt.Sprintf(\"%s\", now))\n\treq.Header.Set(\"Authorization\", client.creds.GetAuthorization(httpVerb, path, now, contentType, content))\n\treturn nil\n}", "func NewSetAuth() context.Handler {\n\treturn func(ctx context.Context) {\n\t\taddr := ctx.RemoteAddr()\n\t\tif _, ok := tempForbidRemote[addr]; ok {\n\t\t\tctx.StatusCode(404)\n\t\t\tctx.StopExecution()\n\t\t\treturn\n\t\t}\n\n\t\tkey := ctx.Params().Get(\"name\")\n\t\ttoken := ctx.GetHeader(\"token\")\n\t\tif token == \"\" || getServerToken(key) != token {\n\t\t\ttempForbidRemote[addr] = 1\n\t\t\tctx.StatusCode(404)\n\t\t\tctx.StopExecution()\n\t\t\treturn\n\t\t}\n\t\tctx.Next()\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NewSetAmountForbidden creates a SetAmountForbidden with default headers values
func NewSetAmountForbidden() *SetAmountForbidden { return &SetAmountForbidden{} }
[ "func NewSetAmountUnauthorized() *SetAmountUnauthorized {\n\treturn &SetAmountUnauthorized{}\n}", "func Amount(val string) Argument {\n\treturn func(request *requests.Request) error {\n\t\trequest.AddArgument(\"amount\", val)\n\t\treturn nil\n\t}\n}", "func (app *specificTokenCodeBuilder) WithAmount(amount string) SpecificTokenCodeBuilder {\n\tapp.amount = amount\n\treturn app\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateForbiddenForDelegationAmount(opts *bind.TransactOpts, wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateForbiddenForDelegationAmount\", wallet)\n}", "func NewSetPlanForbidden() *SetPlanForbidden {\n\treturn &SetPlanForbidden{}\n}", "func (client *blobClient) setLegalHoldCreateRequest(ctx context.Context, legalHold bool, options *blobClientSetLegalHoldOptions) (*policy.Request, error) {\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, client.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"comp\", \"legalhold\")\n\tif options != nil && options.Timeout != nil {\n\t\treqQP.Set(\"timeout\", strconv.FormatInt(int64(*options.Timeout), 10))\n\t}\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"x-ms-version\", \"2020-10-02\")\n\tif options != nil && options.RequestID != nil {\n\t\treq.Raw().Header.Set(\"x-ms-client-request-id\", *options.RequestID)\n\t}\n\treq.Raw().Header.Set(\"x-ms-legal-hold\", strconv.FormatBool(legalHold))\n\treq.Raw().Header.Set(\"Accept\", \"application/xml\")\n\treturn req, nil\n}", "func NewSetRoleForbidden() *SetRoleForbidden {\n\treturn &SetRoleForbidden{}\n}", "func NewSetEnvVarsForbidden() *SetEnvVarsForbidden {\n\treturn &SetEnvVarsForbidden{}\n}", "func (client *blobClient) setImmutabilityPolicyCreateRequest(ctx context.Context, blobClientSetImmutabilityPolicyOptions *blobClientSetImmutabilityPolicyOptions, modifiedAccessConditions *ModifiedAccessConditions) (*policy.Request, error) {\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, client.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"comp\", \"immutabilityPolicies\")\n\tif blobClientSetImmutabilityPolicyOptions != nil && blobClientSetImmutabilityPolicyOptions.Timeout != nil {\n\t\treqQP.Set(\"timeout\", strconv.FormatInt(int64(*blobClientSetImmutabilityPolicyOptions.Timeout), 10))\n\t}\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"x-ms-version\", \"2020-10-02\")\n\tif blobClientSetImmutabilityPolicyOptions != nil && blobClientSetImmutabilityPolicyOptions.RequestID != nil {\n\t\treq.Raw().Header.Set(\"x-ms-client-request-id\", *blobClientSetImmutabilityPolicyOptions.RequestID)\n\t}\n\tif modifiedAccessConditions != nil && modifiedAccessConditions.IfUnmodifiedSince != nil {\n\t\treq.Raw().Header.Set(\"If-Unmodified-Since\", modifiedAccessConditions.IfUnmodifiedSince.Format(time.RFC1123))\n\t}\n\tif blobClientSetImmutabilityPolicyOptions != nil && blobClientSetImmutabilityPolicyOptions.ImmutabilityPolicyExpiry != nil {\n\t\treq.Raw().Header.Set(\"x-ms-immutability-policy-until-date\", blobClientSetImmutabilityPolicyOptions.ImmutabilityPolicyExpiry.Format(time.RFC1123))\n\t}\n\tif blobClientSetImmutabilityPolicyOptions != nil && blobClientSetImmutabilityPolicyOptions.ImmutabilityPolicyMode != nil {\n\t\treq.Raw().Header.Set(\"x-ms-immutability-policy-mode\", string(*blobClientSetImmutabilityPolicyOptions.ImmutabilityPolicyMode))\n\t}\n\treq.Raw().Header.Set(\"Accept\", \"application/xml\")\n\treturn req, nil\n}", "func (client *blobClient) setTierCreateRequest(ctx context.Context, tier AccessTier, blobClientSetTierOptions *blobClientSetTierOptions, leaseAccessConditions *LeaseAccessConditions, modifiedAccessConditions *ModifiedAccessConditions) (*policy.Request, error) {\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, client.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"comp\", \"tier\")\n\tif blobClientSetTierOptions != nil && blobClientSetTierOptions.Snapshot != nil {\n\t\treqQP.Set(\"snapshot\", *blobClientSetTierOptions.Snapshot)\n\t}\n\tif blobClientSetTierOptions != nil && blobClientSetTierOptions.VersionID != nil {\n\t\treqQP.Set(\"versionid\", *blobClientSetTierOptions.VersionID)\n\t}\n\tif blobClientSetTierOptions != nil && blobClientSetTierOptions.Timeout != nil {\n\t\treqQP.Set(\"timeout\", strconv.FormatInt(int64(*blobClientSetTierOptions.Timeout), 10))\n\t}\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"x-ms-access-tier\", string(tier))\n\tif blobClientSetTierOptions != nil && blobClientSetTierOptions.RehydratePriority != nil {\n\t\treq.Raw().Header.Set(\"x-ms-rehydrate-priority\", string(*blobClientSetTierOptions.RehydratePriority))\n\t}\n\treq.Raw().Header.Set(\"x-ms-version\", \"2020-10-02\")\n\tif blobClientSetTierOptions != nil && blobClientSetTierOptions.RequestID != nil {\n\t\treq.Raw().Header.Set(\"x-ms-client-request-id\", *blobClientSetTierOptions.RequestID)\n\t}\n\tif leaseAccessConditions != nil && leaseAccessConditions.LeaseID != nil {\n\t\treq.Raw().Header.Set(\"x-ms-lease-id\", *leaseAccessConditions.LeaseID)\n\t}\n\tif modifiedAccessConditions != nil && modifiedAccessConditions.IfTags != nil {\n\t\treq.Raw().Header.Set(\"x-ms-if-tags\", *modifiedAccessConditions.IfTags)\n\t}\n\treq.Raw().Header.Set(\"Accept\", \"application/xml\")\n\treturn req, nil\n}", "func Forbidden(format string, a ...interface{}) *Error {\n\treturn newError(ErrForbidden, format, a)\n}", "func (m *PurchaseInvoiceLine) SetNetAmount(value *float64)() {\n err := m.GetBackingStore().Set(\"netAmount\", value)\n if err != nil {\n panic(err)\n }\n}", "func (_Locking *LockingFilterer) FilterSetLockAmount(opts *bind.FilterOpts) (*LockingSetLockAmountIterator, error) {\n\n\tlogs, sub, err := _Locking.contract.FilterLogs(opts, \"SetLockAmount\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &LockingSetLockAmountIterator{contract: _Locking.contract, event: \"SetLockAmount\", logs: logs, sub: sub}, nil\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateForbiddenForDelegationAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateForbiddenForDelegationAmount(&_DelegationController.TransactOpts, wallet)\n}", "func newDefaultDenyResponse() *admission.AdmissionResponse {\n\treturn &admission.AdmissionResponse{\n\t\tAllowed: false,\n\t\tResult: &metav1.Status{},\n\t}\n}", "func NewSetCliSecretForbidden() *SetCliSecretForbidden {\n\treturn &SetCliSecretForbidden{}\n}", "func (o *UpdateMTOShipmentStatusForbidden) WithPayload(payload *primemessages.ClientError) *UpdateMTOShipmentStatusForbidden {\n\to.Payload = payload\n\treturn o\n}", "func (m *RequisitionMutation) SetAmount(i int) {\n\tm.amount = &i\n\tm.addamount = nil\n}", "func NewIndexSetStatisticsForbidden() *IndexSetStatisticsForbidden {\n\treturn &IndexSetStatisticsForbidden{}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NewHandler makes a set of endpoints available as a gRPC Server. NOTE: At some point, request tracing support needs to be added. And since much of this service used example code from gokit, the place to start for tracing support is probably here:
func NewHandler(ctx context.Context, endpoints endpoints.Endpoints, tracer stdopentracing.Tracer, logger log.Logger) pb.VaultServer { options := []grpctransport.ServerOption{ grpctransport.ServerErrorLogger(logger), } return &grpcServer{ initstatus: grpctransport.NewServer( ctx, endpoints.InitStatusEndpoint, DecodeInitStatusRequest, EncodeInitStatusResponse, append(options, grpctransport.ServerBefore(opentracing.FromGRPCRequest(tracer, "InitStatus", logger)))..., ), init: grpctransport.NewServer( ctx, endpoints.InitEndpoint, DecodeInitRequest, EncodeInitResponse, append(options, grpctransport.ServerBefore(opentracing.FromGRPCRequest(tracer, "Init", logger)))..., ), sealstatus: grpctransport.NewServer( ctx, endpoints.SealStatusEndpoint, DecodeSealStatusRequest, EncodeSealStatusResponse, append(options, grpctransport.ServerBefore(opentracing.FromGRPCRequest(tracer, "SealStatus", logger)))..., ), unseal: grpctransport.NewServer( ctx, endpoints.UnsealEndpoint, DecodeUnsealRequest, EncodeUnsealResponse, append(options, grpctransport.ServerBefore(opentracing.FromGRPCRequest(tracer, "Unseal", logger)))..., ), configure: grpctransport.NewServer( ctx, endpoints.ConfigureEndpoint, DecodeConfigureRequest, EncodeConfigureResponse, append(options, grpctransport.ServerBefore(opentracing.FromGRPCRequest(tracer, "Configure", logger)))..., ), } }
[ "func New(e *log.Endpoints, uh goagrpc.UnaryHandler) *Server {\n\treturn &Server{\n\t\tCreateH: NewCreateHandler(e.Create, uh),\n\t\tGetH: NewGetHandler(e.Get, uh),\n\t\tUpdateH: NewUpdateHandler(e.Update, uh),\n\t\tDeleteH: NewDeleteHandler(e.Delete, uh),\n\t\tListH: NewListHandler(e.List, uh),\n\t}\n}", "func Server(l log.Logger) middleware.Middleware {\n\tlogger := log.NewHelper(\"middleware/logging\", l)\n\treturn func(handler middleware.Handler) middleware.Handler {\n\t\treturn func(ctx context.Context, req interface{}) (interface{}, error) {\n\t\t\tvar (\n\t\t\t\tpath string\n\t\t\t\tmethod string\n\t\t\t\targs string\n\t\t\t\tcomponent string\n\t\t\t\tquery string\n\t\t\t\ttraceID string\n\t\t\t)\n\t\t\ttraceID = trace.SpanContextFromContext(ctx).TraceID().String()\n\t\t\tif stringer, ok := req.(fmt.Stringer); ok {\n\t\t\t\targs = stringer.String()\n\t\t\t} else {\n\t\t\t\targs = fmt.Sprintf(\"%+v\", req)\n\t\t\t}\n\t\t\tif info, ok := http.FromServerContext(ctx); ok {\n\t\t\t\tcomponent = \"HTTP\"\n\t\t\t\tpath = info.Request.URL.Path\n\t\t\t\tmethod = info.Request.Method\n\t\t\t\tquery = info.Request.URL.RawQuery\n\t\t\t} else if info, ok := grpc.FromServerContext(ctx); ok {\n\t\t\t\tcomponent = \"gRPC\"\n\t\t\t\tpath = info.FullMethod\n\t\t\t\tmethod = \"POST\"\n\t\t\t}\n\t\t\treply, err := handler(ctx, req)\n\t\t\tif component == \"HTTP\" {\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Errorw(\n\t\t\t\t\t\t\"kind\", \"server\",\n\t\t\t\t\t\t\"component\", component,\n\t\t\t\t\t\t\"traceID\", traceID,\n\t\t\t\t\t\t\"path\", path,\n\t\t\t\t\t\t\"method\", method,\n\t\t\t\t\t\t\"args\", args,\n\t\t\t\t\t\t\"query\", query,\n\t\t\t\t\t\t\"code\", uint32(errors.Code(err)),\n\t\t\t\t\t\t\"error\", err.Error(),\n\t\t\t\t\t)\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tlogger.Infow(\n\t\t\t\t\t\"kind\", \"server\",\n\t\t\t\t\t\"component\", component,\n\t\t\t\t\t\"traceID\", traceID,\n\t\t\t\t\t\"path\", path,\n\t\t\t\t\t\"method\", method,\n\t\t\t\t\t\"args\", args,\n\t\t\t\t\t\"query\", query,\n\t\t\t\t\t\"code\", 0,\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Errorw(\n\t\t\t\t\t\t\"kind\", \"server\",\n\t\t\t\t\t\t\"component\", component,\n\t\t\t\t\t\t\"traceID\", traceID,\n\t\t\t\t\t\t\"path\", path,\n\t\t\t\t\t\t\"method\", method,\n\t\t\t\t\t\t\"args\", args,\n\t\t\t\t\t\t\"code\", uint32(errors.Code(err)),\n\t\t\t\t\t\t\"error\", err.Error(),\n\t\t\t\t\t)\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tlogger.Infow(\n\t\t\t\t\t\"kind\", \"server\",\n\t\t\t\t\t\"component\", component,\n\t\t\t\t\t\"traceID\", traceID,\n\t\t\t\t\t\"path\", path,\n\t\t\t\t\t\"method\", method,\n\t\t\t\t\t\"args\", args,\n\t\t\t\t\t\"code\", 0,\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn reply, nil\n\t\t}\n\t}\n}", "func New(e *step.Endpoints, uh goagrpc.UnaryHandler) *Server {\n\treturn &Server{\n\t\tListH: NewListHandler(e.List, uh),\n\t\tAddH: NewAddHandler(e.Add, uh),\n\t\tRemoveH: NewRemoveHandler(e.Remove, uh),\n\t\tUpdateH: NewUpdateHandler(e.Update, uh),\n\t}\n}", "func New(s services.Server, logger log.Logger, duration metrics.Histogram) Set {\n\tvar newEnforcer endpoint.Endpoint\n\t{\n\t\tnewEnforcer = MakeNewEnforcerEndpoint(s)\n\t\tnewEnforcer = LoggingMiddleware(log.With(logger, \"method\", \"NewEnforcer\"))(newEnforcer)\n\t\tnewEnforcer = InstrumentingMiddleware(duration.With(\"method\", \"NewEnforcer\"))(newEnforcer)\n\t}\n\tvar enforce endpoint.Endpoint\n\t{\n\t\tenforce = MakeEnforceEndpoint(s)\n\t\tenforce = LoggingMiddleware(log.With(logger, \"method\", \"Enforce\"))(enforce)\n\t\tenforce = InstrumentingMiddleware(duration.With(\"method\", \"Enforce\"))(enforce)\n\t}\n\tvar loadPolicy endpoint.Endpoint\n\t{\n\t\tloadPolicy = MakeLoadPolicyEndpoint(s)\n\t\tloadPolicy = LoggingMiddleware(log.With(logger, \"method\", \"LoadPolicy\"))(loadPolicy)\n\t\tloadPolicy = InstrumentingMiddleware(duration.With(\"method\", \"LoadPolicy\"))(loadPolicy)\n\t}\n\tvar savePolicy endpoint.Endpoint\n\t{\n\t\tsavePolicy = MakeSavePolicyEndpoint(s)\n\t\tsavePolicy = LoggingMiddleware(log.With(logger, \"method\", \"SavePolicy\"))(savePolicy)\n\t\tsavePolicy = InstrumentingMiddleware(duration.With(\"method\", \"SavePolicy\"))(savePolicy)\n\t}\n\tvar newAdapter endpoint.Endpoint\n\t{\n\t\tnewAdapter = MakeNewAdapterEndpoint(s)\n\t\tnewAdapter = LoggingMiddleware(log.With(logger, \"method\", \"NewAdapter\"))(newAdapter)\n\t\tnewAdapter = InstrumentingMiddleware(duration.With(\"method\", \"NewAdapter\"))(newAdapter)\n\t}\n\tvar addPolicy endpoint.Endpoint\n\t{\n\t\taddPolicy = MakeAddPolicyEndpoint(s)\n\t\taddPolicy = LoggingMiddleware(log.With(logger, \"method\", \"AddPolicy\"))(addPolicy)\n\t\taddPolicy = InstrumentingMiddleware(duration.With(\"method\", \"AddPolicy\"))(addPolicy)\n\t}\n\tvar addNamedPolicy endpoint.Endpoint\n\t{\n\t\taddNamedPolicy = MakeAddNamedPolicyEndpoint(s)\n\t\taddNamedPolicy = LoggingMiddleware(log.With(logger, \"method\", \"AddNamedPolicy\"))(addNamedPolicy)\n\t\taddNamedPolicy = InstrumentingMiddleware(duration.With(\"method\", \"AddNamedPolicy\"))(addNamedPolicy)\n\t}\n\tvar removePolicy endpoint.Endpoint\n\t{\n\t\tremovePolicy = MakeRemovePolicyEndpoint(s)\n\t\tremovePolicy = LoggingMiddleware(log.With(logger, \"method\", \"RemovePolicy\"))(removePolicy)\n\t\tremovePolicy = InstrumentingMiddleware(duration.With(\"method\", \"RemovePolicy\"))(removePolicy)\n\t}\n\tvar removeNamedPolicy endpoint.Endpoint\n\t{\n\t\tremoveNamedPolicy = MakeRemoveNamedPolicyEndpoint(s)\n\t\tremoveNamedPolicy = LoggingMiddleware(log.With(logger, \"method\", \"RemoveNamedPolicy\"))(removeNamedPolicy)\n\t\tremoveNamedPolicy = InstrumentingMiddleware(duration.With(\"method\", \"RemoveNamedPolicy\"))(removeNamedPolicy)\n\t}\n\tvar removeFilteredPolicy endpoint.Endpoint\n\t{\n\t\tremoveFilteredPolicy = MakeRemoveFilteredPolicyEndpoint(s)\n\t\tremoveFilteredPolicy = LoggingMiddleware(log.With(logger, \"method\", \"RemoveFilteredPolicy\"))(removeFilteredPolicy)\n\t\tremoveFilteredPolicy = InstrumentingMiddleware(duration.With(\"method\", \"RemoveFilteredPolicy\"))(removeFilteredPolicy)\n\t}\n\tvar removeFilteredNamedPolicy endpoint.Endpoint\n\t{\n\t\tremoveFilteredNamedPolicy = MakeRemoveFilteredNamedPolicyEndpoint(s)\n\t\tremoveFilteredNamedPolicy = LoggingMiddleware(log.With(logger, \"method\", \"RemoveFilteredNamedPolicy\"))(removeFilteredNamedPolicy)\n\t\tremoveFilteredNamedPolicy = InstrumentingMiddleware(duration.With(\"method\", \"RemoveFilteredNamedPolicy\"))(removeFilteredNamedPolicy)\n\t}\n\tvar getPolicy endpoint.Endpoint\n\t{\n\t\tgetPolicy = MakeGetPolicyEndpoint(s)\n\t\tgetPolicy = LoggingMiddleware(log.With(logger, \"method\", \"GetPolicy\"))(getPolicy)\n\t\tgetPolicy = InstrumentingMiddleware(duration.With(\"method\", \"GetPolicy\"))(getPolicy)\n\t}\n\tvar getNamedPolicy endpoint.Endpoint\n\t{\n\t\tgetNamedPolicy = MakeGetNamedPolicyEndpoint(s)\n\t\tgetNamedPolicy = LoggingMiddleware(log.With(logger, \"method\", \"GetNamedPolicy\"))(getNamedPolicy)\n\t\tgetNamedPolicy = InstrumentingMiddleware(duration.With(\"method\", \"GetNamedPolicy\"))(getNamedPolicy)\n\t}\n\tvar getFilteredPolicy endpoint.Endpoint\n\t{\n\t\tgetFilteredPolicy = MakeGetFilteredPolicyEndpoint(s)\n\t\tgetFilteredPolicy = LoggingMiddleware(log.With(logger, \"method\", \"GetFilteredPolicy\"))(getFilteredPolicy)\n\t\tgetFilteredPolicy = InstrumentingMiddleware(duration.With(\"method\", \"GetFilteredPolicy\"))(getFilteredPolicy)\n\t}\n\tvar getFilteredNamedPolicy endpoint.Endpoint\n\t{\n\t\tgetFilteredNamedPolicy = MakeGetFilteredNamedPolicyEndpoint(s)\n\t\tgetFilteredNamedPolicy = LoggingMiddleware(log.With(logger, \"method\", \"GetFilteredNamedPolicy\"))(getFilteredNamedPolicy)\n\t\tgetFilteredNamedPolicy = InstrumentingMiddleware(duration.With(\"method\", \"GetFilteredNamedPolicy\"))(getFilteredNamedPolicy)\n\t}\n\tvar addGroupingPolicy endpoint.Endpoint\n\t{\n\t\taddGroupingPolicy = MakeAddGroupingPolicyEndpoint(s)\n\t\taddGroupingPolicy = LoggingMiddleware(log.With(logger, \"method\", \"AddGroupingPolicy\"))(addGroupingPolicy)\n\t\taddGroupingPolicy = InstrumentingMiddleware(duration.With(\"method\", \"AddGroupingPolicy\"))(addGroupingPolicy)\n\t}\n\tvar addNamedGroupingPolicy endpoint.Endpoint\n\t{\n\t\taddNamedGroupingPolicy = MakeAddNamedGroupingPolicyEndpoint(s)\n\t\taddNamedGroupingPolicy = LoggingMiddleware(log.With(logger, \"method\", \"AddNamedGroupingPolicy\"))(addNamedGroupingPolicy)\n\t\taddNamedGroupingPolicy = InstrumentingMiddleware(duration.With(\"method\", \"AddNamedGroupingPolicy\"))(addNamedGroupingPolicy)\n\t}\n\tvar removeGroupingPolicy endpoint.Endpoint\n\t{\n\t\tremoveGroupingPolicy = MakeRemoveGroupingPolicyEndpoint(s)\n\t\tremoveGroupingPolicy = LoggingMiddleware(log.With(logger, \"method\", \"RemoveGroupingPolicy\"))(removeGroupingPolicy)\n\t\tremoveGroupingPolicy = InstrumentingMiddleware(duration.With(\"method\", \"RemoveGroupingPolicy\"))(removeGroupingPolicy)\n\t}\n\tvar removeNamedGroupingPolicy endpoint.Endpoint\n\t{\n\t\tremoveNamedGroupingPolicy = MakeRemoveNamedGroupingPolicyEndpoint(s)\n\t\tremoveNamedGroupingPolicy = LoggingMiddleware(log.With(logger, \"method\", \"RemoveNamedGroupingPolicy\"))(removeNamedGroupingPolicy)\n\t\tremoveNamedGroupingPolicy = InstrumentingMiddleware(duration.With(\"method\", \"RemoveNamedGroupingPolicy\"))(removeNamedGroupingPolicy)\n\t}\n\tvar removeFilteredGroupingPolicy endpoint.Endpoint\n\t{\n\t\tremoveFilteredGroupingPolicy = MakeRemoveFilteredGroupingPolicyEndpoint(s)\n\t\tremoveFilteredGroupingPolicy = LoggingMiddleware(log.With(logger, \"method\", \"RemoveFilteredGroupingPolicy\"))(removeFilteredGroupingPolicy)\n\t\tremoveFilteredGroupingPolicy = InstrumentingMiddleware(duration.With(\"method\", \"RemoveFilteredGroupingPolicy\"))(removeFilteredGroupingPolicy)\n\t}\n\tvar removeFilteredNamedGroupingPolicy endpoint.Endpoint\n\t{\n\t\tremoveFilteredNamedGroupingPolicy = MakeRemoveFilteredNamedGroupingPolicyEndpoint(s)\n\t\tremoveFilteredNamedGroupingPolicy = LoggingMiddleware(log.With(logger, \"method\", \"RemoveFilteredNamedGroupingPolicy\"))(removeFilteredNamedGroupingPolicy)\n\t\tremoveFilteredNamedGroupingPolicy = InstrumentingMiddleware(duration.With(\"method\", \"RemoveFilteredNamedGroupingPolicy\"))(removeFilteredNamedGroupingPolicy)\n\t}\n\tvar getGroupingPolicy endpoint.Endpoint\n\t{\n\t\tgetGroupingPolicy = MakeGetGroupingPolicyEndpoint(s)\n\t\tgetGroupingPolicy = LoggingMiddleware(log.With(logger, \"method\", \"GetGroupingPolicy\"))(getGroupingPolicy)\n\t\tgetGroupingPolicy = InstrumentingMiddleware(duration.With(\"method\", \"GetGroupingPolicy\"))(getGroupingPolicy)\n\t}\n\tvar getNamedGroupingPolicy endpoint.Endpoint\n\t{\n\t\tgetNamedGroupingPolicy = MakeGetNamedGroupingPolicyEndpoint(s)\n\t\tgetNamedGroupingPolicy = LoggingMiddleware(log.With(logger, \"method\", \"GetNamedGroupingPolicy\"))(getNamedGroupingPolicy)\n\t\tgetNamedGroupingPolicy = InstrumentingMiddleware(duration.With(\"method\", \"GetNamedGroupingPolicy\"))(getNamedGroupingPolicy)\n\t}\n\tvar getFilteredGroupingPolicy endpoint.Endpoint\n\t{\n\t\tgetFilteredGroupingPolicy = MakeGetFilteredGroupingPolicyEndpoint(s)\n\t\tgetFilteredGroupingPolicy = LoggingMiddleware(log.With(logger, \"method\", \"GetFilteredGroupingPolicy\"))(getFilteredGroupingPolicy)\n\t\tgetFilteredGroupingPolicy = InstrumentingMiddleware(duration.With(\"method\", \"GetFilteredGroupingPolicy\"))(getFilteredGroupingPolicy)\n\t}\n\tvar getFilteredNamedGroupingPolicy endpoint.Endpoint\n\t{\n\t\tgetFilteredNamedGroupingPolicy = MakeGetFilteredNamedGroupingPolicyEndpoint(s)\n\t\tgetFilteredNamedGroupingPolicy = LoggingMiddleware(log.With(logger, \"method\", \"GetFilteredNamedGroupingPolicy\"))(getFilteredNamedGroupingPolicy)\n\t\tgetFilteredNamedGroupingPolicy = InstrumentingMiddleware(duration.With(\"method\", \"GetFilteredNamedGroupingPolicy\"))(getFilteredNamedGroupingPolicy)\n\t}\n\tvar getAllSubjects endpoint.Endpoint\n\t{\n\t\tgetAllSubjects = MakeGetAllSubjectsEndpoint(s)\n\t\tgetAllSubjects = LoggingMiddleware(log.With(logger, \"method\", \"GetAllSubjects\"))(getAllSubjects)\n\t\tgetAllSubjects = InstrumentingMiddleware(duration.With(\"method\", \"GetAllSubjects\"))(getAllSubjects)\n\t}\n\tvar getAllNamedSubjects endpoint.Endpoint\n\t{\n\t\tgetAllNamedSubjects = MakeGetAllNamedSubjectsEndpoint(s)\n\t\tgetAllNamedSubjects = LoggingMiddleware(log.With(logger, \"method\", \"GetAllNamedSubjects\"))(getAllNamedSubjects)\n\t\tgetAllNamedSubjects = InstrumentingMiddleware(duration.With(\"method\", \"GetAllNamedSubjects\"))(getAllNamedSubjects)\n\t}\n\tvar getAllObjects endpoint.Endpoint\n\t{\n\t\tgetAllObjects = MakeGetAllObjectsEndpoint(s)\n\t\tgetAllObjects = LoggingMiddleware(log.With(logger, \"method\", \"GetAllObjects\"))(getAllObjects)\n\t\tgetAllObjects = InstrumentingMiddleware(duration.With(\"method\", \"GetAllObjects\"))(getAllObjects)\n\t}\n\tvar getAllNamedObjects endpoint.Endpoint\n\t{\n\t\tgetAllNamedObjects = MakeGetAllNamedObjectsEndpoint(s)\n\t\tgetAllNamedObjects = LoggingMiddleware(log.With(logger, \"method\", \"GetAllNamedObjects\"))(getAllNamedObjects)\n\t\tgetAllNamedObjects = InstrumentingMiddleware(duration.With(\"method\", \"GetAllNamedObjects\"))(getAllNamedObjects)\n\t}\n\tvar getAllActions endpoint.Endpoint\n\t{\n\t\tgetAllActions = MakeGetAllActionsEndpoint(s)\n\t\tgetAllActions = LoggingMiddleware(log.With(logger, \"method\", \"GetAllActions\"))(getAllActions)\n\t\tgetAllActions = InstrumentingMiddleware(duration.With(\"method\", \"GetAllActions\"))(getAllActions)\n\t}\n\tvar getAllNamedActions endpoint.Endpoint\n\t{\n\t\tgetAllNamedActions = MakeGetAllNamedActionsEndpoint(s)\n\t\tgetAllNamedActions = LoggingMiddleware(log.With(logger, \"method\", \"GetAllNamedActions\"))(getAllNamedActions)\n\t\tgetAllNamedActions = InstrumentingMiddleware(duration.With(\"method\", \"GetAllNamedActions\"))(getAllNamedActions)\n\t}\n\tvar getAllRoles endpoint.Endpoint\n\t{\n\t\tgetAllRoles = MakeGetAllRolesEndpoint(s)\n\t\tgetAllRoles = LoggingMiddleware(log.With(logger, \"method\", \"GetAllRoles\"))(getAllRoles)\n\t\tgetAllRoles = InstrumentingMiddleware(duration.With(\"method\", \"GetAllRoles\"))(getAllRoles)\n\t}\n\tvar getAllNamedRoles endpoint.Endpoint\n\t{\n\t\tgetAllNamedRoles = MakeGetAllNamedRolesEndpoint(s)\n\t\tgetAllNamedRoles = LoggingMiddleware(log.With(logger, \"method\", \"GetAllNamedRoles\"))(getAllNamedRoles)\n\t\tgetAllNamedRoles = InstrumentingMiddleware(duration.With(\"method\", \"GetAllNamedRoles\"))(getAllNamedRoles)\n\t}\n\tvar hasPolicy endpoint.Endpoint\n\t{\n\t\thasPolicy = MakeHasPolicyEndpoint(s)\n\t\thasPolicy = LoggingMiddleware(log.With(logger, \"method\", \"HasPolicy\"))(hasPolicy)\n\t\thasPolicy = InstrumentingMiddleware(duration.With(\"method\", \"HasPolicy\"))(hasPolicy)\n\t}\n\tvar hasNamedPolicy endpoint.Endpoint\n\t{\n\t\thasNamedPolicy = MakeHasNamedPolicyEndpoint(s)\n\t\thasNamedPolicy = LoggingMiddleware(log.With(logger, \"method\", \"HasNamedPolicy\"))(hasNamedPolicy)\n\t\thasNamedPolicy = InstrumentingMiddleware(duration.With(\"method\", \"HasNamedPolicy\"))(hasNamedPolicy)\n\t}\n\tvar hasGroupingPolicy endpoint.Endpoint\n\t{\n\t\thasGroupingPolicy = MakeHasGroupingPolicyEndpoint(s)\n\t\thasGroupingPolicy = LoggingMiddleware(log.With(logger, \"method\", \"HasGroupingPolicy\"))(hasGroupingPolicy)\n\t\thasGroupingPolicy = InstrumentingMiddleware(duration.With(\"method\", \"HasGroupingPolicy\"))(hasGroupingPolicy)\n\t}\n\tvar hasNamedGroupingPolicy endpoint.Endpoint\n\t{\n\t\thasNamedGroupingPolicy = MakeHasNamedGroupingPolicyEndpoint(s)\n\t\thasNamedGroupingPolicy = LoggingMiddleware(log.With(logger, \"method\", \"HasNamedGroupingPolicy\"))(hasNamedGroupingPolicy)\n\t\thasNamedGroupingPolicy = InstrumentingMiddleware(duration.With(\"method\", \"HasNamedGroupingPolicy\"))(hasNamedGroupingPolicy)\n\t}\n\tvar hasRoleForUser endpoint.Endpoint\n\t{\n\t\thasRoleForUser = MakeHasRoleForUserEndpoint(s)\n\t\thasRoleForUser = LoggingMiddleware(log.With(logger, \"method\", \"HasRoleForUser\"))(hasRoleForUser)\n\t\thasRoleForUser = InstrumentingMiddleware(duration.With(\"method\", \"HasRoleForUser\"))(hasRoleForUser)\n\t}\n\tvar addRoleForUser endpoint.Endpoint\n\t{\n\t\taddRoleForUser = MakeAddRoleForUserEndpoint(s)\n\t\taddRoleForUser = LoggingMiddleware(log.With(logger, \"method\", \"AddRoleForUser\"))(addRoleForUser)\n\t\taddRoleForUser = InstrumentingMiddleware(duration.With(\"method\", \"AddRoleForUser\"))(addRoleForUser)\n\t}\n\tvar deleteRoleForUser endpoint.Endpoint\n\t{\n\t\tdeleteRoleForUser = MakeDeleteRoleForUserEndpoint(s)\n\t\tdeleteRoleForUser = LoggingMiddleware(log.With(logger, \"method\", \"DeleteRoleForUser\"))(deleteRoleForUser)\n\t\tdeleteRoleForUser = InstrumentingMiddleware(duration.With(\"method\", \"DeleteRoleForUser\"))(deleteRoleForUser)\n\t}\n\tvar deleteRolesForUser endpoint.Endpoint\n\t{\n\t\tdeleteRolesForUser = MakeDeleteRolesForUserEndpoint(s)\n\t\tdeleteRolesForUser = LoggingMiddleware(log.With(logger, \"method\", \"DeleteRolesForUser\"))(deleteRolesForUser)\n\t\tdeleteRolesForUser = InstrumentingMiddleware(duration.With(\"method\", \"DeleteRolesForUser\"))(deleteRolesForUser)\n\t}\n\tvar deleteUser endpoint.Endpoint\n\t{\n\t\tdeleteUser = MakeDeleteUserEndpoint(s)\n\t\tdeleteUser = LoggingMiddleware(log.With(logger, \"method\", \"DeleteUser\"))(deleteUser)\n\t\tdeleteUser = InstrumentingMiddleware(duration.With(\"method\", \"DeleteUser\"))(deleteUser)\n\t}\n\tvar deleteRole endpoint.Endpoint\n\t{\n\t\tdeleteRole = MakeDeleteRoleEndpoint(s)\n\t\tdeleteRole = LoggingMiddleware(log.With(logger, \"method\", \"DeleteRole\"))(deleteRole)\n\t\tdeleteRole = InstrumentingMiddleware(duration.With(\"method\", \"DeleteRole\"))(deleteRole)\n\t}\n\tvar deletePermission endpoint.Endpoint\n\t{\n\t\tdeletePermission = MakeDeletePermissionEndpoint(s)\n\t\tdeletePermission = LoggingMiddleware(log.With(logger, \"method\", \"DeletePermission\"))(deletePermission)\n\t\tdeletePermission = InstrumentingMiddleware(duration.With(\"method\", \"DeletePermission\"))(deletePermission)\n\t}\n\tvar getRolesForUser endpoint.Endpoint\n\t{\n\t\tgetRolesForUser = MakeGetRolesForUserEndpoint(s)\n\t\tgetRolesForUser = LoggingMiddleware(log.With(logger, \"method\", \"GetRolesForUser\"))(getRolesForUser)\n\t\tgetRolesForUser = InstrumentingMiddleware(duration.With(\"method\", \"GetRolesForUser\"))(getRolesForUser)\n\t}\n\tvar getImplicitRolesForUser endpoint.Endpoint\n\t{\n\t\tgetImplicitRolesForUser = MakeGetImplicitRolesForUserEndpoint(s)\n\t\tgetImplicitRolesForUser = LoggingMiddleware(log.With(logger, \"method\", \"GetImplicitRolesForUser\"))(getImplicitRolesForUser)\n\t\tgetImplicitRolesForUser = InstrumentingMiddleware(duration.With(\"method\", \"GetImplicitRolesForUser\"))(getImplicitRolesForUser)\n\t}\n\tvar getUsersForRole endpoint.Endpoint\n\t{\n\t\tgetUsersForRole = MakeGetUsersForRoleEndpoint(s)\n\t\tgetUsersForRole = LoggingMiddleware(log.With(logger, \"method\", \"GetUsersForRole\"))(getUsersForRole)\n\t\tgetUsersForRole = InstrumentingMiddleware(duration.With(\"method\", \"GetUsersForRole\"))(getUsersForRole)\n\t}\n\tvar addPermissionForUser endpoint.Endpoint\n\t{\n\t\taddPermissionForUser = MakeAddPermissionForUserEndpoint(s)\n\t\taddPermissionForUser = LoggingMiddleware(log.With(logger, \"method\", \"AddPermissionForUser\"))(addPermissionForUser)\n\t\taddPermissionForUser = InstrumentingMiddleware(duration.With(\"method\", \"AddPermissionForUser\"))(addPermissionForUser)\n\t}\n\tvar deletePermissionForUser endpoint.Endpoint\n\t{\n\t\tdeletePermissionForUser = MakeDeletePermissionForUserEndpoint(s)\n\t\tdeletePermissionForUser = LoggingMiddleware(log.With(logger, \"method\", \"DeletePermissionForUser\"))(deletePermissionForUser)\n\t\tdeletePermissionForUser = InstrumentingMiddleware(duration.With(\"method\", \"DeletePermissionForUser\"))(deletePermissionForUser)\n\t}\n\tvar getPermissionsForUser endpoint.Endpoint\n\t{\n\t\tgetPermissionsForUser = MakeGetPermissionsForUserEndpoint(s)\n\t\tgetPermissionsForUser = LoggingMiddleware(log.With(logger, \"method\", \"GetPermissionsForUser\"))(getPermissionsForUser)\n\t\tgetPermissionsForUser = InstrumentingMiddleware(duration.With(\"method\", \"GetPermissionsForUser\"))(getPermissionsForUser)\n\t}\n\tvar getImplicitPermissionsForUser endpoint.Endpoint\n\t{\n\t\tgetImplicitPermissionsForUser = MakeGetImplicitPermissionsForUserEndpoint(s)\n\t\tgetImplicitPermissionsForUser = LoggingMiddleware(log.With(logger, \"method\", \"GetImplicitPermissionsForUser\"))(getImplicitPermissionsForUser)\n\t\tgetImplicitPermissionsForUser = InstrumentingMiddleware(duration.With(\"method\", \"GetImplicitPermissionsForUser\"))(getImplicitPermissionsForUser)\n\t}\n\tvar hasPermissionForUser endpoint.Endpoint\n\t{\n\t\thasPermissionForUser = MakeHasPermissionForUserEndpoint(s)\n\t\thasPermissionForUser = LoggingMiddleware(log.With(logger, \"method\", \"HasPermissionForUser\"))(hasPermissionForUser)\n\t\thasPermissionForUser = InstrumentingMiddleware(duration.With(\"method\", \"HasPermissionForUser\"))(hasPermissionForUser)\n\t}\n\treturn Set{NewEnforcerEndpoint: getNamedPolicy, EnforceEndpoint: enforce, LoadPolicyEndpoint: loadPolicy, SavePolicyEndpoint: savePolicy, NewAdapterEndpoint: newAdapter, AddPolicyEndpoint: addPolicy, AddNamedPolicyEndpoint: addNamedPolicy, RemovePolicyEndpoint: removePolicy, RemoveNamedPolicyEndpoint: removeNamedPolicy, RemoveFilteredPolicyEndpoint: removeFilteredPolicy, RemoveFilteredNamedPolicyEndpoint: removeFilteredNamedPolicy, GetPolicyEndpoint: getPolicy, GetNamedPolicyEndpoint: getNamedPolicy, GetFilteredPolicyEndpoint: getFilteredPolicy, GetFilteredNamedPolicyEndpoint: getFilteredNamedPolicy, AddGroupingPolicyEndpoint: addGroupingPolicy, AddNamedGroupingPolicyEndpoint: addNamedGroupingPolicy, RemoveGroupingPolicyEndpoint: removeGroupingPolicy, RemoveNamedGroupingPolicyEndpoint: removeNamedGroupingPolicy, RemoveFilteredGroupingPolicyEndpoint: removeFilteredGroupingPolicy, RemoveFilteredNamedGroupingPolicyEndpoint: removeFilteredNamedGroupingPolicy, GetGroupingPolicyEndpoint: getGroupingPolicy, GetNamedGroupingPolicyEndpoint: getNamedGroupingPolicy, GetFilteredGroupingPolicyEndpoint: getFilteredGroupingPolicy, GetFilteredNamedGroupingPolicyEndpoint: getFilteredNamedGroupingPolicy, GetAllSubjectsEndpoint: getAllSubjects, GetAllNamedSubjectsEndpoint: getAllNamedSubjects, GetAllObjectsEndpoint: getAllObjects, GetAllNamedObjectsEndpoint: getAllNamedObjects, GetAllActionsEndpoint: getAllActions, GetAllNamedActionsEndpoint: getAllNamedActions, GetAllRolesEndpoint: getAllRoles, GetAllNamedRolesEndpoint: getAllNamedRoles, HasPolicyEndpoint: hasPolicy, HasNamedPolicyEndpoint: hasNamedPolicy, HasGroupingPolicyEndpoint: hasGroupingPolicy, HasNamedGroupingPolicyEndpoint: hasNamedGroupingPolicy, HasRoleForUserEndpoint: hasRoleForUser, AddRoleForUserEndpoint: addRoleForUser, DeleteRoleForUserEndpoint: deleteRoleForUser, DeleteRolesForUserEndpoint: deleteRolesForUser, DeleteUserEndpoint: deleteUser, DeleteRoleEndpoint: deleteRole, DeletePermissionEndpoint: deletePermission, GetRolesForUserEndpoint: getRolesForUser, GetImplicitRolesForUserEndpoint: getImplicitRolesForUser, GetUsersForRoleEndpoint: getUsersForRole, AddPermissionForUserEndpoint: addPermissionForUser, DeletePermissionForUserEndpoint: deletePermissionForUser, GetPermissionsForUserEndpoint: getPermissionsForUser, GetImplicitPermissionsForUserEndpoint: getImplicitPermissionsForUser, HasPermissionForUserEndpoint: hasPermissionForUser}\n}", "func ExampleNewThriftServer() {\n\t// variables should be initialized properly in production\n\tvar (\n\t\tecImpl *edgecontext.Impl\n\t\thandler baseplate.BaseplateService\n\t\tlogger log.Wrapper\n\t)\n\n\tprocessor := baseplate.NewBaseplateServiceProcessor(handler)\n\tserver, err := thriftbp.NewThriftServer(\n\t\tthriftbp.ServerConfig{\n\t\t\tAddr: \"localhost:8080\",\n\t\t\tTimeout: time.Second,\n\t\t\tLogger: logger,\n\t\t},\n\t\tprocessor,\n\t\tedgecontext.InjectThriftEdgeContext(ecImpl, logger),\n\t\ttracing.InjectThriftServerSpan,\n\t)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlog.Fatal(server.Serve())\n}", "func New(e *calc.Endpoints, uh goagrpc.UnaryHandler) *Server {\n\treturn &Server{\n\t\tAddH: NewAddHandler(e.Add, uh),\n\t}\n}", "func handleGRPCServer(ctx context.Context, u *url.URL, healthEndpoints *health.Endpoints, adminEndpoints *admin.Endpoints, configEndpoints *config.Endpoints, keyboardEndpoints *keyboard.Endpoints, hostEndpoints *host.Endpoints, noticeEndpoints *notice.Endpoints, rtspEndpoints *rtsp.Endpoints, tokenMgrEndpoints *tokenmgr.Endpoints, wg *sync.WaitGroup, errc chan error, logger *log.Logger, debug bool) {\n\n\t// Setup goa log adapter.\n\tvar (\n\t\tadapter middleware.Logger\n\t)\n\t{\n\t\tadapter = middleware.NewLogger(logger)\n\t}\n\n\t// Wrap the endpoints with the transport specific layers. The generated\n\t// server packages contains code generated from the design which maps\n\t// the service input and output data structures to gRPC requests and\n\t// responses.\n\tvar (\n\t\thealthServer *healthsvr.Server\n\t\tadminServer *adminsvr.Server\n\t\tconfigServer *configsvr.Server\n\t\tkeyboardServer *keyboardsvr.Server\n\t\thostServer *hostsvr.Server\n\t\tnoticeServer *noticesvr.Server\n\t\trtspServer *rtspsvr.Server\n\t\ttokenMgrServer *tokenmgrsvr.Server\n\t)\n\t{\n\t\thealthServer = healthsvr.New(healthEndpoints, nil)\n\t\tadminServer = adminsvr.New(adminEndpoints, nil)\n\t\tconfigServer = configsvr.New(configEndpoints, nil)\n\t\tkeyboardServer = keyboardsvr.New(keyboardEndpoints, nil, nil)\n\t\thostServer = hostsvr.New(hostEndpoints, nil)\n\t\tnoticeServer = noticesvr.New(noticeEndpoints, nil)\n\t\trtspServer = rtspsvr.New(rtspEndpoints, nil)\n\t\ttokenMgrServer = tokenmgrsvr.New(tokenMgrEndpoints, nil)\n\t}\n\n\t// Initialize gRPC server with the middleware.\n\tsrv := grpc.NewServer(\n\t\tgrpcmiddleware.WithUnaryServerChain(\n\t\t\tgrpcmdlwr.UnaryRequestID(),\n\t\t\tgrpcmdlwr.UnaryServerLog(adapter),\n\t\t),\n\t\tgrpcmiddleware.WithStreamServerChain(\n\t\t\tgrpcmdlwr.StreamRequestID(),\n\t\t\tgrpcmdlwr.StreamServerLog(adapter),\n\t\t),\n\t)\n\n\t// Register the servers.\n\thealthpb.RegisterHealthServer(srv, healthServer)\n\tadminpb.RegisterAdminServer(srv, adminServer)\n\tconfigpb.RegisterConfigServer(srv, configServer)\n\tkeyboardpb.RegisterKeyboardServer(srv, keyboardServer)\n\thostpb.RegisterHostServer(srv, hostServer)\n\tnoticepb.RegisterNoticeServer(srv, noticeServer)\n\trtsppb.RegisterRtspServer(srv, rtspServer)\n\ttoken_mgrpb.RegisterTokenMgrServer(srv, tokenMgrServer)\n\n\tfor svc, info := range srv.GetServiceInfo() {\n\t\tfor _, m := range info.Methods {\n\t\t\tlogger.Printf(\"serving gRPC method %s\", svc+\"/\"+m.Name)\n\t\t}\n\t}\n\n\t// Register the server reflection service on the server.\n\t// See https://grpc.github.io/grpc/core/md_doc_server-reflection.html.\n\treflection.Register(srv)\n\n\t(*wg).Add(1)\n\tgo func() {\n\t\tdefer (*wg).Done()\n\n\t\t// Start gRPC server in a separate goroutine.\n\t\tgo func() {\n\t\t\tlis, err := net.Listen(\"tcp\", u.Host)\n\t\t\tif err != nil {\n\t\t\t\terrc <- err\n\t\t\t}\n\t\t\tlogger.Printf(\"gRPC server listening on %q\", u.Host)\n\t\t\terrc <- srv.Serve(lis)\n\t\t}()\n\n\t\t<-ctx.Done()\n\t\tlogger.Printf(\"shutting down gRPC server at %q\", u.Host)\n\t\tsrv.Stop()\n\t}()\n}", "func newGRPCWebProxyHandler(grpcServerAddress string) (*grpc.ClientConn, http.Handler, error) {\n\tgrpcopts := []grpc.DialOption{\n\t\tgrpc.WithInsecure(),\n\t\t// TODO: https://github.com/tendermint/starport/issues/562\n\t\t// nolint:staticcheck\n\t\tgrpc.WithCodec(proxy.Codec()),\n\t}\n\n\tgrpconn, err := grpc.Dial(grpcServerAddress, grpcopts...)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdirector := func(ctx context.Context, fullMethodName string) (context.Context, *grpc.ClientConn, error) {\n\t\tmd, _ := metadata.FromIncomingContext(ctx)\n\t\tmdCopy := md.Copy()\n\t\tdelete(mdCopy, \"user-agent\")\n\t\t// If this header is present in the request from the web client,\n\t\t// the actual connection to the backend will not be established.\n\t\t// https://github.com/improbable-eng/grpc-web/issues/568\n\t\tdelete(mdCopy, \"connection\")\n\t\tctx = metadata.NewOutgoingContext(ctx, mdCopy)\n\t\treturn ctx, grpconn, nil\n\t}\n\n\t// Server with logging and monitoring enabled.\n\tgrpcserver := grpc.NewServer(\n\t\t// TODO: https://github.com/tendermint/starport/issues/562\n\t\t// nolint:staticcheck\n\t\tgrpc.CustomCodec(proxy.Codec()), // needed for proxy to function.\n\t\tgrpc.UnknownServiceHandler(proxy.TransparentHandler(director)),\n\t\tgrpc_middleware.WithUnaryServerChain(),\n\t\tgrpc_middleware.WithStreamServerChain(),\n\t)\n\n\tgrpcwebopts := []grpcweb.Option{\n\t\tgrpcweb.WithCorsForRegisteredEndpointsOnly(false),\n\t\tgrpcweb.WithOriginFunc(func(origin string) bool { return true }),\n\t\tgrpcweb.WithWebsockets(true),\n\t\tgrpcweb.WithWebsocketOriginFunc(func(req *http.Request) bool { return true }),\n\t}\n\n\tgrpcwebserver := grpcweb.WrapServer(grpcserver, grpcwebopts...)\n\n\treturn grpconn, grpcwebserver, nil\n}", "func newRPCServer(agent *agent, listeners []net.Listener) *server {\n\tbackend := grpc.NewServer()\n\tserver := &server{agent: agent, Server: backend}\n\tpb.RegisterAgentServer(backend, server)\n\tfor _, listener := range listeners {\n\t\tgo backend.Serve(listener)\n\t}\n\treturn server\n}", "func New(e *todo.Endpoints, uh goagrpc.UnaryHandler) *Server {\n\treturn &Server{\n\t\tGetH: NewGetHandler(e.Get, uh),\n\t\tListH: NewListHandler(e.List, uh),\n\t\tAddH: NewAddHandler(e.Add, uh),\n\t\tRemoveH: NewRemoveHandler(e.Remove, uh),\n\t}\n}", "func NewGrpcServer(fns ...FunInterceptor) *GrpcServer {\n\n\tvar unaryInterceptors []grpc.UnaryServerInterceptor\n\tvar streamInterceptors []grpc.StreamServerInterceptor\n\n\t// add tracer、monitor interceptor\n\ttracer := opentracing.GlobalTracer()\n\tunaryInterceptors = append(unaryInterceptors, otgrpc.OpenTracingServerInterceptor(tracer), monitorServerInterceptor())\n\tstreamInterceptors = append(streamInterceptors, otgrpc.OpenTracingStreamServerInterceptor(tracer), monitorStreamServerInterceptor())\n\n\t// TODO 采用框架内显式注入interceptors的方式,不再进行二次包装,后续该部分功能会删除掉\n\t//for _, fn := range fns {\n\t//\t// 注册interceptor\n\t//\tvar interceptor grpc.UnaryServerInterceptor\n\t//\tinterceptor = func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {\n\t//\t\terr = fn(ctx, req, info.FullMethod)\n\t//\t\tif err != nil {\n\t//\t\t\treturn\n\t//\t\t}\n\t//\t\t// 继续处理请求\n\t//\t\treturn handler(ctx, req)\n\t//\t}\n\t//\tunaryInterceptors = append(unaryInterceptors, interceptor)\n\t//\n\t//\tvar streamInterceptor grpc.StreamServerInterceptor\n\t//\tstreamInterceptor = func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {\n\t//\t\tss.Context()\n\t//\t\terr := fn(ss.Context(), srv, info.FullMethod)\n\t//\t\tif err != nil {\n\t//\t\t\treturn err\n\t//\t\t}\n\t//\t\t// 继续处理请求\n\t//\t\treturn handler(srv, ss)\n\t//\t}\n\t//\tstreamInterceptors = append(streamInterceptors, streamInterceptor)\n\t//}\n\n\tvar opts []grpc.ServerOption\n\topts = append(opts, grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(unaryInterceptors...)))\n\topts = append(opts, grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(streamInterceptors...)))\n\n\t// 实例化grpc Server\n\tserver := grpc.NewServer(opts...)\n\treturn &GrpcServer{Server: server}\n}", "func New(e *calc.Endpoints, uh goagrpc.UnaryHandler) *Server {\n\treturn &Server{\n\t\tDivideH: NewDivideHandler(e.Divide, uh),\n\t}\n}", "func NewServer(ctx *Context, registrations ...func(server *grpc.Server)) (*GrpcServer, error) {\n\tcancel := make(chan bool)\n\n\t// Fire up a gRPC server and start listening for incomings.\n\thandle, err := rpcutil.ServeWithOptions(rpcutil.ServeOptions{\n\t\tCancel: cancel,\n\t\tInit: func(srv *grpc.Server) error {\n\t\t\tfor _, registration := range registrations {\n\t\t\t\tregistration(srv)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t\tOptions: rpcutil.OpenTracingServerInterceptorOptions(ctx.tracingSpan),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &GrpcServer{\n\t\tcancel: cancel,\n\t\thandle: handle,\n\t}, nil\n}", "func makeAddHandler(endpoints endpoint.Endpoints, options []grpc.ServerOption) grpc.Handler {\n\treturn grpc.NewServer(endpoints.AddEndpoint, decodeAddRequest, encodeAddResponse, options...)\n}", "func Server(opts ...Option) middleware.Middleware {\n\toptions := options{\n\t\tlogger: log.DefaultLogger,\n\t}\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\tlog := log.NewHelper(\"middleware/logging\", options.logger)\n\treturn func(handler middleware.Handler) middleware.Handler {\n\t\treturn func(ctx context.Context, req interface{}) (interface{}, error) {\n\t\t\tvar (\n\t\t\t\tpath string\n\t\t\t\tmethod string\n\t\t\t\tparams string\n\t\t\t\tcomponent string\n\t\t\t)\n\t\t\tif info, ok := http.FromServerContext(ctx); ok {\n\t\t\t\tcomponent = \"HTTP\"\n\t\t\t\tpath = info.Request.RequestURI\n\t\t\t\tmethod = info.Request.Method\n\t\t\t\tparams = info.Request.Form.Encode()\n\t\t\t} else if info, ok := grpc.FromServerContext(ctx); ok {\n\t\t\t\tcomponent = \"gRPC\"\n\t\t\t\tpath = info.FullMethod\n\t\t\t\tmethod = \"POST\"\n\t\t\t\tparams = req.(fmt.Stringer).String()\n\t\t\t}\n\t\t\treply, err := handler(ctx, req)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorw(\n\t\t\t\t\t\"kind\", \"server\",\n\t\t\t\t\t\"component\", component,\n\t\t\t\t\t\"path\", path,\n\t\t\t\t\t\"method\", method,\n\t\t\t\t\t\"params\", params,\n\t\t\t\t\t\"code\", errors.Code(err),\n\t\t\t\t\t\"error\", err.Error(),\n\t\t\t\t)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tlog.Infow(\n\t\t\t\t\"kind\", \"server\",\n\t\t\t\t\"component\", component,\n\t\t\t\t\"path\", path,\n\t\t\t\t\"method\", method,\n\t\t\t\t\"params\", params,\n\t\t\t\t\"code\", 0,\n\t\t\t)\n\t\t\treturn reply, nil\n\t\t}\n\t}\n}", "func (h *OpenTracing) Handler(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tvar span opentracing.Span\n\t\tvar err error\n\n\t\t// Attempt to join a trace by getting trace context from the headers.\n\t\twireContext, err := opentracing.GlobalTracer().Extract(\n\t\t\topentracing.HTTPHeaders,\n\t\t\topentracing.HTTPHeadersCarrier(r.Header))\n\t\tif err != nil {\n\t\t\t// If for whatever reason we can't join, go ahead an start a new root span.\n\t\t\tspan = opentracing.StartSpan(r.URL.Path)\n\t\t} else {\n\t\t\tspan = opentracing.StartSpan(r.URL.Path, opentracing.ChildOf(wireContext))\n\t\t}\n\t\tdefer span.Finish()\n\n\t\thost, err := os.Hostname()\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Error(\"Failed to get host name\")\n\t\t}\n\n\t\text.HTTPMethod.Set(span, r.Method)\n\t\text.HTTPUrl.Set(\n\t\t\tspan,\n\t\t\tfmt.Sprintf(\"%s://%s%s\", map[bool]string{true: \"https\", false: \"http\"}[h.https], r.Host, r.URL.Path),\n\t\t)\n\t\text.Component.Set(span, \"janus\")\n\t\text.SpanKind.Set(span, \"server\")\n\n\t\tspan.SetTag(\"peer.address\", r.RemoteAddr)\n\t\tspan.SetTag(\"host.name\", host)\n\n\t\t// Add information on the peer service we're about to contact.\n\t\tif host, portString, err := net.SplitHostPort(r.URL.Host); err == nil {\n\t\t\text.PeerHostname.Set(span, host)\n\t\t\tif port, err := strconv.Atoi(portString); err != nil {\n\t\t\t\text.PeerPort.Set(span, uint16(port))\n\t\t\t}\n\t\t} else {\n\t\t\text.PeerHostname.Set(span, r.URL.Host)\n\t\t}\n\n\t\terr = span.Tracer().Inject(\n\t\t\tspan.Context(),\n\t\t\topentracing.HTTPHeaders,\n\t\t\topentracing.HTTPHeadersCarrier(r.Header))\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Error(\"Could not inject span context into header\")\n\t\t}\n\n\t\thandler.ServeHTTP(w, base.ToContext(r, span))\n\t})\n}", "func NewTracing(next v0proto.ThumbnailServiceHandler) v0proto.ThumbnailServiceHandler {\n\treturn tracing{\n\t\tnext: next,\n\t}\n}", "func makeGetTagHandler(endpoints endpoint.Endpoints, options []grpc.ServerOption) grpc.Handler {\n\treturn grpc.NewServer(endpoints.GetTagEndpoint, decodeGetTagRequest, encodeGetTagResponse, options...)\n}", "func New(\n\te *securedservice.Endpoints,\n\tmux goahttp.Muxer,\n\tdecoder func(*http.Request) goahttp.Decoder,\n\tencoder func(context.Context, http.ResponseWriter) goahttp.Encoder,\n\terrhandler func(context.Context, http.ResponseWriter, error),\n\tformatter func(ctx context.Context, err error) goahttp.Statuser,\n) *Server {\n\treturn &Server{\n\t\tMounts: []*MountPoint{\n\t\t\t{\"Signin\", \"POST\", \"/signin\"},\n\t\t\t{\"Secure\", \"GET\", \"/secure\"},\n\t\t\t{\"DoublySecure\", \"PUT\", \"/secure\"},\n\t\t\t{\"AlsoDoublySecure\", \"POST\", \"/secure\"},\n\t\t},\n\t\tSignin: NewSigninHandler(e.Signin, mux, decoder, encoder, errhandler, formatter),\n\t\tSecure: NewSecureHandler(e.Secure, mux, decoder, encoder, errhandler, formatter),\n\t\tDoublySecure: NewDoublySecureHandler(e.DoublySecure, mux, decoder, encoder, errhandler, formatter),\n\t\tAlsoDoublySecure: NewAlsoDoublySecureHandler(e.AlsoDoublySecure, mux, decoder, encoder, errhandler, formatter),\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DecodeInitStatusRequest is a transport/grpc.DecodeRequestFunc that converts a gRPC initstatus request to a userdomain initstatus request. Primarily useful in a server.
func DecodeInitStatusRequest(_ context.Context, grpcReq interface{}) (interface{}, error) { return endpoints.InitStatusRequest{}, nil }
[ "func DecodeInitRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.InitRequest)\n\topts := service.InitOptions{\n\t\tSecretShares: int(req.SecretShares),\n\t\tSecretThreshold: int(req.SecretThreshold),\n\t\tStoredShares: int(req.StoredShares),\n\t\tPGPKeys: req.PgpKeys,\n\t\tRecoveryShares: int(req.RecoveryShares),\n\t\tRecoveryThreshold: int(req.RecoveryThreshold),\n\t\tRecoveryPGPKeys: req.RecoveryPgpKeys,\n\t\tRootTokenPGPKey: req.RootTokenPgpKey,\n\t\tRootTokenHolderEmail: req.RootTokenHolderEmail,\n\t\tSecretKeyHolderEmails: req.SecretKeyHolderEmails,\n\t}\n\treturn &endpoints.InitRequest{Opts: opts}, nil\n}", "func DecodeGRPCStatusRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.StatusRequest)\n\treturn req, nil\n}", "func EncodeInitStatusRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treturn &pb.InitStatusRequest{}, nil\n}", "func DecodeGrpcReqRadiusServerStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*RadiusServerStatus)\n\treturn req, nil\n}", "func DecodeGrpcReqLdapServerStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*LdapServerStatus)\n\treturn req, nil\n}", "func DecodeGrpcReqUserStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*UserStatus)\n\treturn req, nil\n}", "func DecodeGrpcReqArchiveRequestStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*ArchiveRequestStatus)\n\treturn req, nil\n}", "func DecodeGrpcReqRoleStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*RoleStatus)\n\treturn req, nil\n}", "func DecodeGrpcReqOperationStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*OperationStatus)\n\treturn req, nil\n}", "func DecodeGrpcReqFeatureStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*FeatureStatus)\n\treturn req, nil\n}", "func DecodeGrpcReqSnapshotRestoreStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*SnapshotRestoreStatus)\n\treturn req, nil\n}", "func DecodeStatusRequest(ctx context.Context, v interface{}, md metadata.MD) (interface{}, error) {\n\tvar (\n\t\tmessage *taskspb.StatusRequest\n\t\tok bool\n\t)\n\t{\n\t\tif message, ok = v.(*taskspb.StatusRequest); !ok {\n\t\t\treturn nil, goagrpc.ErrInvalidType(\"tasks\", \"status\", \"*taskspb.StatusRequest\", v)\n\t\t}\n\t\tif err := ValidateStatusRequest(message); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvar payload *tasks.StatusPayload\n\t{\n\t\tpayload = NewStatusPayload(message)\n\t}\n\treturn payload, nil\n}", "func DecodeGrpcReqWorkloadMigrationStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*WorkloadMigrationStatus)\n\treturn req, nil\n}", "func DecodeGrpcReqDSCProfileStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*DSCProfileStatus)\n\treturn req, nil\n}", "func DecodeGRPCInitBridgeRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.InitBridgeRequest)\n\tip, err := abstraction.NewInet(req.IP)\n\tif err != nil {\n\t\treturn InitBridgeRequest{}, err\n\t}\n\treturn InitBridgeRequest{\n\t\tIP: ip,\n\t\tNetIf: req.NetworkName,\n\t}, nil\n}", "func DecodeGrpcReqLicenseStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*LicenseStatus)\n\treturn req, nil\n}", "func DecodeSealStatusRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treturn endpoints.SealStatusRequest{}, nil\n}", "func DecodeGrpcReqAuthenticationPolicyStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*AuthenticationPolicyStatus)\n\treturn req, nil\n}", "func DecodeGrpcReqWorkloadStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*WorkloadStatus)\n\treturn req, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DecodeInitStatusResponse is a transport/grpc.DecodeResponseFunc that converts a gRPC initstatus reply to a userdomain initstatus response. Primarily useful in a client.
func DecodeInitStatusResponse(_ context.Context, grpcReply interface{}) (interface{}, error) { reply := grpcReply.(*pb.InitStatusResponse) return endpoints.InitStatusResponse{Initialized: bool(reply.Status.Initialized), Err: service.String2Error(reply.Err)}, nil }
[ "func DecodeInitStatusRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treturn endpoints.InitStatusRequest{}, nil\n}", "func DecodeInitResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.InitResponse)\n\tinit := service.InitKeys{\n\t\tKeys: reply.Keys,\n\t\tKeysB64: reply.KeysBase64,\n\t\tRecoveryKeys: reply.RecoveryKeys,\n\t\tRecoveryKeysB64: reply.RecoveryKeysBase64,\n\t\tRootToken: reply.RootToken,\n\t}\n\treturn endpoints.InitResponse{Init: init, Err: service.String2Error(reply.Err)}, nil\n}", "func EncodeInitStatusResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(endpoints.InitStatusResponse)\n\tstatus := &pb.Status{Initialized: bool(resp.Initialized)}\n\treturn &pb.InitStatusResponse{Status: status, Err: service.Error2String(resp.Err)}, nil\n}", "func DecodeGrpcRespLdapServerStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcRespArchiveRequestStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcRespRadiusServerStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcRespDSCProfileStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcRespRoleStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcRespUserStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcRespAuthenticationPolicyStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcRespFeatureStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcRespLicenseStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeStatusResponse(decoder func(*http.Response) goahttp.Decoder, restoreBody bool) func(*http.Response) (any, error) {\n\treturn func(resp *http.Response) (any, error) {\n\t\tif restoreBody {\n\t\t\tb, err := io.ReadAll(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tresp.Body = io.NopCloser(bytes.NewBuffer(b))\n\t\t\tdefer func() {\n\t\t\t\tresp.Body = io.NopCloser(bytes.NewBuffer(b))\n\t\t\t}()\n\t\t} else {\n\t\t\tdefer resp.Body.Close()\n\t\t}\n\t\tswitch resp.StatusCode {\n\t\tcase http.StatusOK:\n\t\t\tvar (\n\t\t\t\tbody StatusResponseBody\n\t\t\t\terr error\n\t\t\t)\n\t\t\terr = decoder(resp).Decode(&body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, goahttp.ErrDecodingError(\"batch\", \"status\", err)\n\t\t\t}\n\t\t\terr = ValidateStatusResponseBody(&body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, goahttp.ErrValidationError(\"batch\", \"status\", err)\n\t\t\t}\n\t\t\tres := NewStatusBatchStatusResultOK(&body)\n\t\t\treturn res, nil\n\t\tdefault:\n\t\t\tbody, _ := io.ReadAll(resp.Body)\n\t\t\treturn nil, goahttp.ErrInvalidResponse(\"batch\", \"status\", resp.StatusCode, string(body))\n\t\t}\n\t}\n}", "func DecodeGrpcRespOperationStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcRespWorkloadStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcRespSnapshotRestoreStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcReqLdapServerStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*LdapServerStatus)\n\treturn req, nil\n}", "func DecodeGrpcRespRoleBindingStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func decodeAPIStatus(res map[string]interface{}) api.Status {\n\tnow := time.Now().UTC()\n\tuptime := decoders.Duration(res[\"server_uptime\"], 0)\n\n\t// This is an approximation and maybe wrong\n\tlastReboot := now.Add(-uptime)\n\ts := api.Status{\n\t\tServerTime: decoders.TimeUTC(res[\"server_time_utc\"], time.Time{}),\n\t\tLastReboot: lastReboot,\n\t\tLastReconfig: time.Time{},\n\t\tMessage: \"openbgpd up and running\",\n\t\tVersion: \"\",\n\t\tBackend: \"openbgpd\",\n\t}\n\treturn s\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
EncodeInitStatusResponse is a transport/grpc.EncodeResponseFunc that converts a userdomain initstatus response to a gRPC initstatus reply. Primarily useful in a server.
func EncodeInitStatusResponse(_ context.Context, response interface{}) (interface{}, error) { resp := response.(endpoints.InitStatusResponse) status := &pb.Status{Initialized: bool(resp.Initialized)} return &pb.InitStatusResponse{Status: status, Err: service.Error2String(resp.Err)}, nil }
[ "func DecodeInitStatusResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.InitStatusResponse)\n\treturn endpoints.InitStatusResponse{Initialized: bool(reply.Status.Initialized), Err: service.String2Error(reply.Err)}, nil\n}", "func EncodeGRPCStatusResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(*pb.StatusResponse)\n\treturn resp, nil\n}", "func EncodeStatusResponse(ctx context.Context, v interface{}, hdr, trlr *metadata.MD) (interface{}, error) {\n\tresp := NewStatusResponse()\n\treturn resp, nil\n}", "func EncodeInitResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(endpoints.InitResponse)\n\n\treturn &pb.InitResponse{\n\t\tKeys: resp.Init.Keys,\n\t\tKeysBase64: resp.Init.KeysB64,\n\t\tRecoveryKeys: resp.Init.RecoveryKeys,\n\t\tRecoveryKeysBase64: resp.Init.RecoveryKeysB64,\n\t\tRootToken: resp.Init.RootToken,\n\t\tErr: service.Error2String(resp.Err),\n\t}, nil\n}", "func EncodeStatusResponse(encoder func(context.Context, http.ResponseWriter) goahttp.Encoder) func(context.Context, http.ResponseWriter, interface{}) error {\n\treturn func(ctx context.Context, w http.ResponseWriter, v interface{}) error {\n\t\tres := v.(*spinbroker.StatusResult)\n\t\tenc := encoder(ctx, w)\n\t\tbody := NewStatusResponseBody(res)\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn enc.Encode(body)\n\t}\n}", "func EncodeInitStatusRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treturn &pb.InitStatusRequest{}, nil\n}", "func EncodeGrpcRespLdapServerStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeGrpcRespRadiusServerStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeGrpcRespArchiveRequestStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeInitStatusRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treturn endpoints.InitStatusRequest{}, nil\n}", "func EncodeGrpcRespUserStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeGrpcRespRoleStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeGrpcRespWorkloadStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeGrpcRespFeatureStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeGrpcRespOperationStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeGrpcRespDSCProfileStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeGrpcRespAuthenticationPolicyStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeGrpcRespLicenseStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeGrpcRespWorkloadIntfStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
EncodeInitStatusRequest is a transport/grpc.EncodeRequestFunc that converts a userdomain initstatus request to a gRPC initstatus request. Primarily useful in a client.
func EncodeInitStatusRequest(_ context.Context, request interface{}) (interface{}, error) { return &pb.InitStatusRequest{}, nil }
[ "func DecodeInitStatusRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treturn endpoints.InitStatusRequest{}, nil\n}", "func EncodeInitRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treq := request.(endpoints.InitRequest)\n\treturn &pb.InitRequest{\n\t\tSecretShares: uint32(req.Opts.SecretShares),\n\t\tSecretThreshold: uint32(req.Opts.SecretThreshold),\n\t\tStoredShares: uint32(req.Opts.StoredShares),\n\t\tPgpKeys: req.Opts.PGPKeys,\n\t\tRecoveryShares: uint32(req.Opts.RecoveryShares),\n\t\tRecoveryThreshold: uint32(req.Opts.RecoveryThreshold),\n\t\tRecoveryPgpKeys: req.Opts.RecoveryPGPKeys,\n\t\tRootTokenPgpKey: req.Opts.RootTokenPGPKey,\n\t\tRootTokenHolderEmail: req.Opts.RootTokenHolderEmail,\n\t\tSecretKeyHolderEmails: req.Opts.SecretKeyHolderEmails,\n\t}, nil\n}", "func EncodeGrpcReqOperationStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*OperationStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqUserStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*UserStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqFeatureStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*FeatureStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqRadiusServerStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*RadiusServerStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqRoleStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*RoleStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqWorkloadStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*WorkloadStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqWorkloadMigrationStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*WorkloadMigrationStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqLicenseStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*LicenseStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqAuthenticationPolicyStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*AuthenticationPolicyStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqArchiveRequestStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*ArchiveRequestStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqLdapServerStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*LdapServerStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqDSCProfileStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*DSCProfileStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqWorkloadIntfStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*WorkloadIntfStatus)\n\treturn req, nil\n}", "func EncodeInitStatusResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(endpoints.InitStatusResponse)\n\tstatus := &pb.Status{Initialized: bool(resp.Initialized)}\n\treturn &pb.InitStatusResponse{Status: status, Err: service.Error2String(resp.Err)}, nil\n}", "func EncodeGrpcReqRoleBindingStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*RoleBindingStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqSnapshotRestoreStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*SnapshotRestoreStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqConfigurationSnapshotStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*ConfigurationSnapshotStatus)\n\treturn req, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DecodeInitRequest is a transport/grpc.DecodeRequestFunc that converts a gRPC init request to a userdomain init request. Primarily useful in a server.
func DecodeInitRequest(_ context.Context, grpcReq interface{}) (interface{}, error) { req := grpcReq.(*pb.InitRequest) opts := service.InitOptions{ SecretShares: int(req.SecretShares), SecretThreshold: int(req.SecretThreshold), StoredShares: int(req.StoredShares), PGPKeys: req.PgpKeys, RecoveryShares: int(req.RecoveryShares), RecoveryThreshold: int(req.RecoveryThreshold), RecoveryPGPKeys: req.RecoveryPgpKeys, RootTokenPGPKey: req.RootTokenPgpKey, RootTokenHolderEmail: req.RootTokenHolderEmail, SecretKeyHolderEmails: req.SecretKeyHolderEmails, } return &endpoints.InitRequest{Opts: opts}, nil }
[ "func DecodeInitStatusRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treturn endpoints.InitStatusRequest{}, nil\n}", "func DecodeGRPCInitBridgeRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.InitBridgeRequest)\n\tip, err := abstraction.NewInet(req.IP)\n\tif err != nil {\n\t\treturn InitBridgeRequest{}, err\n\t}\n\treturn InitBridgeRequest{\n\t\tIP: ip,\n\t\tNetIf: req.NetworkName,\n\t}, nil\n}", "func DecodeGRPCLoginRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.LoginParams)\n\treturn req, nil\n}", "func DecodeGRPCLoginRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.LoginRequest)\n\treturn req, nil\n}", "func EncodeInitRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treq := request.(endpoints.InitRequest)\n\treturn &pb.InitRequest{\n\t\tSecretShares: uint32(req.Opts.SecretShares),\n\t\tSecretThreshold: uint32(req.Opts.SecretThreshold),\n\t\tStoredShares: uint32(req.Opts.StoredShares),\n\t\tPgpKeys: req.Opts.PGPKeys,\n\t\tRecoveryShares: uint32(req.Opts.RecoveryShares),\n\t\tRecoveryThreshold: uint32(req.Opts.RecoveryThreshold),\n\t\tRecoveryPgpKeys: req.Opts.RecoveryPGPKeys,\n\t\tRootTokenPgpKey: req.Opts.RootTokenPGPKey,\n\t\tRootTokenHolderEmail: req.Opts.RootTokenHolderEmail,\n\t\tSecretKeyHolderEmails: req.Opts.SecretKeyHolderEmails,\n\t}, nil\n}", "func DecodeLoginRequest(_ context.Context, r interface{}) (interface{}, error) {\n\treq := r.(*pb.LoginRequest)\n\treturn LoginRequest{\n\t\tUsername: req.Username,\n\t\tPassword: req.Password,\n\t}, nil\n}", "func DecodeUnsealRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.UnsealRequest)\n\treturn &endpoints.UnsealRequest{Key: req.Key, Reset: req.Reset_}, nil\n}", "func DecodeGRPCGetUserConfigRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.GetUserConfigParams)\n\treturn req, nil\n}", "func decodeGRPCNameRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.NameRequest)\n\treturn loginendpoint.LoginRequest{N: string(req.N)}, nil\n}", "func DecodeGRPCDecryptRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.DecryptRequest)\n\treturn req, nil\n}", "func decodeRequest(r io.Reader) *plugin.CodeGeneratorRequest {\n\tvar req plugin.CodeGeneratorRequest\n\tinput, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\tlog.Fatal(\"unable to read stdin: \" + err.Error())\n\t}\n\tif err := proto.Unmarshal(input, &req); err != nil {\n\t\tlog.Fatal(\"unable to marshal stdin as protobuf: \" + err.Error())\n\t}\n\treturn &req\n}", "func DecodeGrpcReqConfigurationSnapshotRequest(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*ConfigurationSnapshotRequest)\n\treturn req, nil\n}", "func DecodeInitResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.InitResponse)\n\tinit := service.InitKeys{\n\t\tKeys: reply.Keys,\n\t\tKeysB64: reply.KeysBase64,\n\t\tRecoveryKeys: reply.RecoveryKeys,\n\t\tRecoveryKeysB64: reply.RecoveryKeysBase64,\n\t\tRootToken: reply.RootToken,\n\t}\n\treturn endpoints.InitResponse{Init: init, Err: service.String2Error(reply.Err)}, nil\n}", "func checkInitRequest(msg *Message, conn Conn, config *Config, log log.Logger) error {\n\tif err := msg.CheckFlags(); err != nil {\n\t\treturn err\n\t}\n\tinit, err := parseInit(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := _checkInitRequest(config, init, msg.RemoteAddr); err != nil {\n\t\t// handle errors that need reply: COOKIE or DH\n\t\tif reply := initErrorNeedsReply(init, config, msg.RemoteAddr, err); reply != nil {\n\t\t\tlog.Log(\"INIT_REPLY\", err.Error())\n\t\t\tWriteMessage(conn, reply, nil, false, log)\n\t\t}\n\t\treturn err\n\t}\n\tmsg.Params = init\n\treturn nil\n}", "func DecodeConfigureRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.ConfigureRequest)\n\treturn &endpoints.ConfigureRequest{URL: req.Url, Token: req.Token}, nil\n}", "func DecodeGrpcReqEVPNConfig(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*EVPNConfig)\n\treturn req, nil\n}", "func DecodeGrpcReqUserSpec(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*UserSpec)\n\treturn req, nil\n}", "func DecodeGrpcReqRadiusDomain(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*RadiusDomain)\n\treturn req, nil\n}", "func DecodeGrpcReqRadiusServer(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*RadiusServer)\n\treturn req, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DecodeInitResponse is a transport/grpc.DecodeResponseFunc that converts a gRPC init reply to a userdomain init response. Primarily useful in a client.
func DecodeInitResponse(_ context.Context, grpcReply interface{}) (interface{}, error) { reply := grpcReply.(*pb.InitResponse) init := service.InitKeys{ Keys: reply.Keys, KeysB64: reply.KeysBase64, RecoveryKeys: reply.RecoveryKeys, RecoveryKeysB64: reply.RecoveryKeysBase64, RootToken: reply.RootToken, } return endpoints.InitResponse{Init: init, Err: service.String2Error(reply.Err)}, nil }
[ "func DecodeInitStatusResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.InitStatusResponse)\n\treturn endpoints.InitStatusResponse{Initialized: bool(reply.Status.Initialized), Err: service.String2Error(reply.Err)}, nil\n}", "func EncodeInitResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(endpoints.InitResponse)\n\n\treturn &pb.InitResponse{\n\t\tKeys: resp.Init.Keys,\n\t\tKeysBase64: resp.Init.KeysB64,\n\t\tRecoveryKeys: resp.Init.RecoveryKeys,\n\t\tRecoveryKeysBase64: resp.Init.RecoveryKeysB64,\n\t\tRootToken: resp.Init.RootToken,\n\t\tErr: service.Error2String(resp.Err),\n\t}, nil\n}", "func (v *VMKEncryption) DecryptInitResponse(initResp *types.InitResponse) error {\n\t// Check prerequisite (key has been loaded)\n\tif !v.encrypting {\n\t\treturn fmt.Errorf(\"cannot decrypt init response as key has not been loaded\")\n\t}\n\n\tnewKeys := make([]string, len(initResp.EncryptedKeys))\n\tnewKeysBase64 := make([]string, len(initResp.EncryptedKeys))\n\n\tfor i, hexCiphertext := range initResp.EncryptedKeys {\n\t\thexNonce := initResp.Nonces[i]\n\t\tnonce, err := hex.DecodeString(hexNonce)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to decode hex bytes of nonce: %w\", err)\n\t\t}\n\n\t\tcipherText, err := hex.DecodeString(hexCiphertext)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to decode hex bytes of ciphertext: %w\", err)\n\t\t}\n\n\t\tkeyShare, err := v.gcmDecryptKeyShare(cipherText, nonce, i) // Unwrap using a unique AES key\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to unwrap key %d: %w\", i, err)\n\t\t}\n\n\t\tnewKeys[i] = hex.EncodeToString(keyShare)\n\t\tnewKeysBase64[i] = base64.StdEncoding.EncodeToString(keyShare)\n\t}\n\n\tinitResp.Keys = newKeys\n\tinitResp.KeysBase64 = newKeysBase64\n\tinitResp.EncryptedKeys = nil\n\tinitResp.Nonces = nil\n\n\treturn nil\n}", "func DecodeGRPCLoginResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.LoginResponse)\n\treturn reply, nil\n}", "func DecodeInitRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.InitRequest)\n\topts := service.InitOptions{\n\t\tSecretShares: int(req.SecretShares),\n\t\tSecretThreshold: int(req.SecretThreshold),\n\t\tStoredShares: int(req.StoredShares),\n\t\tPGPKeys: req.PgpKeys,\n\t\tRecoveryShares: int(req.RecoveryShares),\n\t\tRecoveryThreshold: int(req.RecoveryThreshold),\n\t\tRecoveryPGPKeys: req.RecoveryPgpKeys,\n\t\tRootTokenPGPKey: req.RootTokenPgpKey,\n\t\tRootTokenHolderEmail: req.RootTokenHolderEmail,\n\t\tSecretKeyHolderEmails: req.SecretKeyHolderEmails,\n\t}\n\treturn &endpoints.InitRequest{Opts: opts}, nil\n}", "func DecodeInitStatusRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treturn endpoints.InitStatusRequest{}, nil\n}", "func decodeAuthResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\tr, ok := reply.(*pb.AuthReply)\n\tif !ok {\n\t\te := errors.New(\"'AuthReply' Decoder is not impelemented\")\n\t\treturn endpoint1.AuthResponse{Err: e}, e\n\t}\n\treturn endpoint1.AuthResponse{Uuid: r.Uuid, NamespaceID: r.NamespaceID, Roles: r.Roles}, nil\n}", "func InitResponse() ValidatorResponse {\n\tvar ve = []ValidationError{}\n\tvr := ValidatorResponse{\n\t\tMessage: \"Valid\",\n\t\tValid: true,\n\t\tErrors: ve}\n\treturn vr\n}", "func (a *X509) InitRepDecode(d *Decoder) error {\n\ta.serverNonce = d.bytes()\n\tif len(a.serverNonce) != x509ServerNonceSize {\n\t\treturn fmt.Errorf(\"invalid server nonce size %d - expected %d\", len(a.serverNonce), x509ServerNonceSize)\n\t}\n\treturn nil\n}", "func DecodeLoginResponse(ctx context.Context, v interface{}, hdr, trlr metadata.MD) (interface{}, error) {\n\tmessage, ok := v.(*user_methodpb.LoginResponse)\n\tif !ok {\n\t\treturn nil, goagrpc.ErrInvalidType(\"userMethod\", \"login\", \"*user_methodpb.LoginResponse\", v)\n\t}\n\tres := NewLoginResult(message)\n\treturn res, nil\n}", "func decodeUserInfoResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\tr, ok := reply.(*pb.UserInfoReply)\n\tif !ok {\n\t\te := errors.New(\"pb UserInfoReply type assertion error\")\n\t\treturn nil, e\n\t}\n\treturn endpoint1.UserInfoResponse{Roles: r.Roles, OrgName: r.OrgName}, nil\n}", "func DecodeGrpcRespUserSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func decodeSigninResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\tr, found := reply.(*pb.SigninReply)\n\tif !found {\n\t\te := fmt.Errorf(\"pb CreateReply type assertion error\")\n\t\treturn &endpoint1.SigninResponse{\n\t\t\tE1: e,\n\t\t}, e\n\t}\n\treturn endpoint1.SigninResponse{S0: r.Token}, nil\n}", "func DecodeGrpcRespLdapServer(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeLoginResponse(_ context.Context, r interface{}) (interface{}, error) {\n\tresp := r.(*pb.LoginResponse)\n\treturn LoginResponse{\n\t\tJwt: resp.Jwt,\n\t}, nil\n}", "func DecodeGrpcRespAuthenticators(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcRespAuthenticationPolicySpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func decodeGRPCNameResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.NameReply)\n\treturn loginendpoint.LoginResponse{V: string(reply.V), Err: str2err(reply.Err)}, nil\n}", "func decodeCreateResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\treturn nil, errors.New(\"'Users' Decoder is not impelemented\")\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
EncodeInitResponse is a transport/grpc.EncodeResponseFunc that converts a userdomain init response to a gRPC init reply. Primarily useful in a server.
func EncodeInitResponse(_ context.Context, response interface{}) (interface{}, error) { resp := response.(endpoints.InitResponse) return &pb.InitResponse{ Keys: resp.Init.Keys, KeysBase64: resp.Init.KeysB64, RecoveryKeys: resp.Init.RecoveryKeys, RecoveryKeysBase64: resp.Init.RecoveryKeysB64, RootToken: resp.Init.RootToken, Err: service.Error2String(resp.Err), }, nil }
[ "func EncodeInitStatusResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(endpoints.InitStatusResponse)\n\tstatus := &pb.Status{Initialized: bool(resp.Initialized)}\n\treturn &pb.InitStatusResponse{Status: status, Err: service.Error2String(resp.Err)}, nil\n}", "func EncodeGRPCInitBridgeResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tres := response.(InitBridgeResponse)\n\tgRPCRes := &pb.InitBridgeResponse{}\n\tif res.Error != nil {\n\t\tgRPCRes.Error = res.Error.Error()\n\t}\n\treturn gRPCRes, nil\n}", "func DecodeInitResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.InitResponse)\n\tinit := service.InitKeys{\n\t\tKeys: reply.Keys,\n\t\tKeysB64: reply.KeysBase64,\n\t\tRecoveryKeys: reply.RecoveryKeys,\n\t\tRecoveryKeysB64: reply.RecoveryKeysBase64,\n\t\tRootToken: reply.RootToken,\n\t}\n\treturn endpoints.InitResponse{Init: init, Err: service.String2Error(reply.Err)}, nil\n}", "func DecodeInitStatusResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.InitStatusResponse)\n\treturn endpoints.InitStatusResponse{Initialized: bool(reply.Status.Initialized), Err: service.String2Error(reply.Err)}, nil\n}", "func (v *VMKEncryption) EncryptInitResponse(initResp *types.InitResponse) error {\n\t// Check prerequisite (key has been loaded)\n\tif !v.encrypting {\n\t\treturn fmt.Errorf(\"cannot encrypt init response as key has not been loaded\")\n\t}\n\n\tnewKeys := make([]string, len(initResp.Keys))\n\tnewNonces := make([]string, len(initResp.Keys))\n\n\tfor i, hexPlaintext := range initResp.Keys {\n\n\t\tplainText, err := hex.DecodeString(hexPlaintext)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to decode hex bytes of keyshare (details omitted): %w\", err)\n\t\t}\n\n\t\tkeyShare, nonce, err := v.gcmEncryptKeyShare(plainText, i) // Wrap using a unique AES key\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to wrap key %d: %w\", i, err)\n\t\t}\n\n\t\tnewKeys[i] = hex.EncodeToString(keyShare)\n\t\tnewNonces[i] = hex.EncodeToString(nonce)\n\n\t\twipeKey(keyShare) // Clear out binary version of encrypted key\n\t\twipeKey(nonce) // Clear out nonce\n\t}\n\n\tinitResp.EncryptedKeys = newKeys\n\tinitResp.Nonces = newNonces\n\tinitResp.Keys = nil // strings are immutable, must wait for GC\n\tinitResp.KeysBase64 = nil // strings are immutable, must wait for GC\n\treturn nil\n}", "func EncodeGRPCLoginResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(*pb.LoginResponse)\n\treturn resp, nil\n}", "func EncodeInitRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treq := request.(endpoints.InitRequest)\n\treturn &pb.InitRequest{\n\t\tSecretShares: uint32(req.Opts.SecretShares),\n\t\tSecretThreshold: uint32(req.Opts.SecretThreshold),\n\t\tStoredShares: uint32(req.Opts.StoredShares),\n\t\tPgpKeys: req.Opts.PGPKeys,\n\t\tRecoveryShares: uint32(req.Opts.RecoveryShares),\n\t\tRecoveryThreshold: uint32(req.Opts.RecoveryThreshold),\n\t\tRecoveryPgpKeys: req.Opts.RecoveryPGPKeys,\n\t\tRootTokenPgpKey: req.Opts.RootTokenPGPKey,\n\t\tRootTokenHolderEmail: req.Opts.RootTokenHolderEmail,\n\t\tSecretKeyHolderEmails: req.Opts.SecretKeyHolderEmails,\n\t}, nil\n}", "func EncodeGRPCResponse(_ context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeLoginResponse(encoder func(context.Context, http.ResponseWriter) goahttp.Encoder) func(context.Context, http.ResponseWriter, any) error {\n\treturn func(ctx context.Context, w http.ResponseWriter, v any) error {\n\t\tres, _ := v.(string)\n\t\tenc := encoder(ctx, w)\n\t\tbody := res\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn enc.Encode(body)\n\t}\n}", "func EncodeGRPCEncryptResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(*pb.Response)\n\treturn resp, nil\n}", "func EncodeInitStatusRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treturn &pb.InitStatusRequest{}, nil\n}", "func EncodeGrpcRespUserSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeInitRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.InitRequest)\n\topts := service.InitOptions{\n\t\tSecretShares: int(req.SecretShares),\n\t\tSecretThreshold: int(req.SecretThreshold),\n\t\tStoredShares: int(req.StoredShares),\n\t\tPGPKeys: req.PgpKeys,\n\t\tRecoveryShares: int(req.RecoveryShares),\n\t\tRecoveryThreshold: int(req.RecoveryThreshold),\n\t\tRecoveryPGPKeys: req.RecoveryPgpKeys,\n\t\tRootTokenPGPKey: req.RootTokenPgpKey,\n\t\tRootTokenHolderEmail: req.RootTokenHolderEmail,\n\t\tSecretKeyHolderEmails: req.SecretKeyHolderEmails,\n\t}\n\treturn &endpoints.InitRequest{Opts: opts}, nil\n}", "func InitResponse() ValidatorResponse {\n\tvar ve = []ValidationError{}\n\tvr := ValidatorResponse{\n\t\tMessage: \"Valid\",\n\t\tValid: true,\n\t\tErrors: ve}\n\treturn vr\n}", "func EncodeGRPCLogoutResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(*pb.LogoutResponse)\n\treturn resp, nil\n}", "func EncodeGrpcRespRadiusServer(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeInitStatusRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treturn endpoints.InitStatusRequest{}, nil\n}", "func EncodeGrpcRespAuthenticators(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeGRPCSetUserConfigResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(*pb.ErrCode)\n\treturn resp, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
EncodeInitRequest is a transport/grpc.EncodeRequestFunc that converts a userdomain init request to a gRPC init request. Primarily useful in a client.
func EncodeInitRequest(_ context.Context, request interface{}) (interface{}, error) { req := request.(endpoints.InitRequest) return &pb.InitRequest{ SecretShares: uint32(req.Opts.SecretShares), SecretThreshold: uint32(req.Opts.SecretThreshold), StoredShares: uint32(req.Opts.StoredShares), PgpKeys: req.Opts.PGPKeys, RecoveryShares: uint32(req.Opts.RecoveryShares), RecoveryThreshold: uint32(req.Opts.RecoveryThreshold), RecoveryPgpKeys: req.Opts.RecoveryPGPKeys, RootTokenPgpKey: req.Opts.RootTokenPGPKey, RootTokenHolderEmail: req.Opts.RootTokenHolderEmail, SecretKeyHolderEmails: req.Opts.SecretKeyHolderEmails, }, nil }
[ "func EncodeInitStatusRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treturn &pb.InitStatusRequest{}, nil\n}", "func DecodeInitRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.InitRequest)\n\topts := service.InitOptions{\n\t\tSecretShares: int(req.SecretShares),\n\t\tSecretThreshold: int(req.SecretThreshold),\n\t\tStoredShares: int(req.StoredShares),\n\t\tPGPKeys: req.PgpKeys,\n\t\tRecoveryShares: int(req.RecoveryShares),\n\t\tRecoveryThreshold: int(req.RecoveryThreshold),\n\t\tRecoveryPGPKeys: req.RecoveryPgpKeys,\n\t\tRootTokenPGPKey: req.RootTokenPgpKey,\n\t\tRootTokenHolderEmail: req.RootTokenHolderEmail,\n\t\tSecretKeyHolderEmails: req.SecretKeyHolderEmails,\n\t}\n\treturn &endpoints.InitRequest{Opts: opts}, nil\n}", "func EncodeGRPCLoginRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*pb.LoginRequest)\n\treturn req, nil\n}", "func DecodeInitStatusRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treturn endpoints.InitStatusRequest{}, nil\n}", "func EncodeGRPCJWKSRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*pb.JWKSRequest)\n\treturn req, nil\n}", "func encodeGRPCNameRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treq := request.(loginendpoint.LoginRequest)\n\treturn &pb.NameRequest{N: string(req.N)}, nil\n}", "func DecodeGRPCInitBridgeRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.InitBridgeRequest)\n\tip, err := abstraction.NewInet(req.IP)\n\tif err != nil {\n\t\treturn InitBridgeRequest{}, err\n\t}\n\treturn InitBridgeRequest{\n\t\tIP: ip,\n\t\tNetIf: req.NetworkName,\n\t}, nil\n}", "func EncodeGrpcReqUserSpec(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*UserSpec)\n\treturn req, nil\n}", "func encodeGRPCConcatRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treq := request.(loginendpoint.LoginRequest)\n\treturn &pb.NameRequest{N: req.N}, nil\n}", "func initializeRequest(c *xgb.Conn, DesiredMajorVersion byte, DesiredMinorVersion byte) []byte {\n\tsize := 8\n\tb := 0\n\tbuf := make([]byte, size)\n\n\tbuf[b] = c.Extensions[\"SYNC\"]\n\tb += 1\n\n\tbuf[b] = 0 // request opcode\n\tb += 1\n\n\txgb.Put16(buf[b:], uint16(size/4)) // write request size in 4-byte units\n\tb += 2\n\n\tbuf[b] = DesiredMajorVersion\n\tb += 1\n\n\tbuf[b] = DesiredMinorVersion\n\tb += 1\n\n\treturn buf\n}", "func EncodeGrpcReqEVPNConfig(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*EVPNConfig)\n\treturn req, nil\n}", "func EncodeInitResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(endpoints.InitResponse)\n\n\treturn &pb.InitResponse{\n\t\tKeys: resp.Init.Keys,\n\t\tKeysBase64: resp.Init.KeysB64,\n\t\tRecoveryKeys: resp.Init.RecoveryKeys,\n\t\tRecoveryKeysBase64: resp.Init.RecoveryKeysB64,\n\t\tRootToken: resp.Init.RootToken,\n\t\tErr: service.Error2String(resp.Err),\n\t}, nil\n}", "func EncodeGrpcReqAuthenticationPolicySpec(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*AuthenticationPolicySpec)\n\treturn req, nil\n}", "func EncodeRequest(er EncodeRequestFunc) ClientOption {\n\treturn func(c *Client) {\n\t\tc.encode = er\n\t}\n}", "func EncodeLoginRequest(_ context.Context, r interface{}) (interface{}, error) {\n\treq := r.(LoginRequest)\n\treturn &pb.LoginRequest{\n\t\tUsername: req.Username,\n\t\tPassword: req.Password,\n\t}, nil\n}", "func EncodeGrpcReqLicenseSpec(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*LicenseSpec)\n\treturn req, nil\n}", "func checkInitRequest(msg *Message, conn Conn, config *Config, log log.Logger) error {\n\tif err := msg.CheckFlags(); err != nil {\n\t\treturn err\n\t}\n\tinit, err := parseInit(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := _checkInitRequest(config, init, msg.RemoteAddr); err != nil {\n\t\t// handle errors that need reply: COOKIE or DH\n\t\tif reply := initErrorNeedsReply(init, config, msg.RemoteAddr, err); reply != nil {\n\t\t\tlog.Log(\"INIT_REPLY\", err.Error())\n\t\t\tWriteMessage(conn, reply, nil, false, log)\n\t\t}\n\t\treturn err\n\t}\n\tmsg.Params = init\n\treturn nil\n}", "func InitRequest() *Request {\n\treturn &Request{\n\t\tHeader: Header{},\n\t\tForm: Values{},\n\t\tPostForm: Values{},\n\t}\n}", "func (a *X509) PrepareInitReq(prms *Prms) error {\n\t// prevent auth call to hdb with invalid certificate\n\t// as hbd only allows a limited number of unsuccessful authentications\n\t// - currently only validity period is checked\n\tif err := a.certKey.Validate(time.Now()); err != nil {\n\t\treturn err\n\t}\n\tprms.addString(a.Typ())\n\tprms.addEmpty()\n\treturn nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DecodeSealStatusRequest is a transport/grpc.DecodeRequestFunc that converts a gRPC sealstatus request to a userdomain sealstatus request. Primarily useful in a server.
func DecodeSealStatusRequest(_ context.Context, grpcReq interface{}) (interface{}, error) { return endpoints.SealStatusRequest{}, nil }
[ "func EncodeSealStatusRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treturn &pb.SealStatusRequest{}, nil\n}", "func DecodeStatusRequest(ctx context.Context, v interface{}, md metadata.MD) (interface{}, error) {\n\tvar (\n\t\tmessage *taskspb.StatusRequest\n\t\tok bool\n\t)\n\t{\n\t\tif message, ok = v.(*taskspb.StatusRequest); !ok {\n\t\t\treturn nil, goagrpc.ErrInvalidType(\"tasks\", \"status\", \"*taskspb.StatusRequest\", v)\n\t\t}\n\t\tif err := ValidateStatusRequest(message); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvar payload *tasks.StatusPayload\n\t{\n\t\tpayload = NewStatusPayload(message)\n\t}\n\treturn payload, nil\n}", "func DecodeGrpcReqLdapServerStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*LdapServerStatus)\n\treturn req, nil\n}", "func DecodeGrpcReqPropagationStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*PropagationStatus)\n\treturn req, nil\n}", "func DecodeInitStatusRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treturn endpoints.InitStatusRequest{}, nil\n}", "func DecodeGRPCStatusRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.StatusRequest)\n\treturn req, nil\n}", "func DecodeGrpcReqRadiusServerStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*RadiusServerStatus)\n\treturn req, nil\n}", "func DecodeUnsealRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.UnsealRequest)\n\treturn &endpoints.UnsealRequest{Key: req.Key, Reset: req.Reset_}, nil\n}", "func DecodeGrpcReqArchiveRequestStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*ArchiveRequestStatus)\n\treturn req, nil\n}", "func DecodeSealStatusResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.SealStatusResponse)\n\tstatus := endpoints.SealStatusResponse{\n\t\tSealed: reply.SealStatus.Sealed,\n\t\tT: int(reply.SealStatus.T),\n\t\tN: int(reply.SealStatus.N),\n\t\tProgress: int(reply.SealStatus.Progress),\n\t\tVersion: reply.SealStatus.Version,\n\t\tClusterName: reply.SealStatus.ClusterName,\n\t\tClusterID: reply.SealStatus.ClusterId,\n\t\tErr: service.String2Error(reply.Err),\n\t}\n\n\treturn status, nil\n}", "func DecodeGrpcReqUserStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*UserStatus)\n\treturn req, nil\n}", "func DecodeGrpcReqLicenseStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*LicenseStatus)\n\treturn req, nil\n}", "func DecodeSigninRequest(ctx context.Context, v interface{}, md metadata.MD) (interface{}, error) {\n\tvar (\n\t\tmessage *userpb.SigninRequest\n\t\tok bool\n\t)\n\t{\n\t\tif message, ok = v.(*userpb.SigninRequest); !ok {\n\t\t\treturn nil, goagrpc.ErrInvalidType(\"user\", \"signin\", \"*userpb.SigninRequest\", v)\n\t\t}\n\t}\n\tvar payload *user.Signin\n\t{\n\t\tpayload = NewSigninPayload(message)\n\t}\n\treturn payload, nil\n}", "func DecodeGrpcReqWorkloadMigrationStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*WorkloadMigrationStatus)\n\treturn req, nil\n}", "func DecodeGrpcReqWorkloadStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*WorkloadStatus)\n\treturn req, nil\n}", "func DecodeGrpcReqFeatureStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*FeatureStatus)\n\treturn req, nil\n}", "func DecodeGrpcReqRoleStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*RoleStatus)\n\treturn req, nil\n}", "func DecodeGrpcReqAuthenticationPolicyStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*AuthenticationPolicyStatus)\n\treturn req, nil\n}", "func decodeGetUserDealByStateRequest(_ context.Context, r *http1.Request) (interface{}, error) {\n\tvars := mux.Vars(r)\n\tvals := r.URL.Query()\n\tstate := \"\"\n\tid, ok := vars[\"userId\"]\n\tif !ok {\n\t\treturn nil, errors.New(\"not a valid userId\")\n\t}\n\tstates, okk := vals[\"state\"]\n\tif okk {\n\t\tstate = states[0]\n\t}\n\treq := endpoint.GetUserDealByStateRequest{\n\t\tId: id,\n\t\tState: state,\n\t}\n\treturn req, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DecodeSealStatusResponse is a transport/grpc.DecodeResponseFunc that converts a gRPC sealstatus reply to a userdomain sealstatus response. Primarily useful in a client.
func DecodeSealStatusResponse(_ context.Context, grpcReply interface{}) (interface{}, error) { reply := grpcReply.(*pb.SealStatusResponse) status := endpoints.SealStatusResponse{ Sealed: reply.SealStatus.Sealed, T: int(reply.SealStatus.T), N: int(reply.SealStatus.N), Progress: int(reply.SealStatus.Progress), Version: reply.SealStatus.Version, ClusterName: reply.SealStatus.ClusterName, ClusterID: reply.SealStatus.ClusterId, Err: service.String2Error(reply.Err), } return status, nil }
[ "func DecodeSealStatusRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treturn endpoints.SealStatusRequest{}, nil\n}", "func DecodeUnsealResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.UnsealResponse)\n\tstatus := endpoints.UnsealResponse{\n\t\tSealed: reply.SealStatus.Sealed,\n\t\tT: int(reply.SealStatus.T),\n\t\tN: int(reply.SealStatus.N),\n\t\tProgress: int(reply.SealStatus.Progress),\n\t\tVersion: reply.SealStatus.Version,\n\t\tClusterName: reply.SealStatus.ClusterName,\n\t\tClusterID: reply.SealStatus.ClusterId,\n\t\tErr: service.String2Error(reply.Err),\n\t}\n\n\treturn status, nil\n}", "func DecodeGrpcRespLdapServerStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeSealStatusResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(endpoints.SealStatusResponse)\n\n\tstatus := &pb.SealStatus{\n\t\tSealed: resp.Sealed,\n\t\tT: uint32(resp.T),\n\t\tN: uint32(resp.N),\n\t\tProgress: uint32(resp.Progress),\n\t\tVersion: resp.Version,\n\t\tClusterName: resp.ClusterName,\n\t\tClusterId: resp.ClusterID,\n\t}\n\treturn &pb.SealStatusResponse{\n\t\tSealStatus: status,\n\t\tErr: service.Error2String(resp.Err),\n\t}, nil\n}", "func DecodeGrpcRespRadiusServerStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcRespArchiveRequestStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcRespPropagationStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcRespDSCProfileStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcRespUserStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeStatusResponse(decoder func(*http.Response) goahttp.Decoder, restoreBody bool) func(*http.Response) (any, error) {\n\treturn func(resp *http.Response) (any, error) {\n\t\tif restoreBody {\n\t\t\tb, err := io.ReadAll(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tresp.Body = io.NopCloser(bytes.NewBuffer(b))\n\t\t\tdefer func() {\n\t\t\t\tresp.Body = io.NopCloser(bytes.NewBuffer(b))\n\t\t\t}()\n\t\t} else {\n\t\t\tdefer resp.Body.Close()\n\t\t}\n\t\tswitch resp.StatusCode {\n\t\tcase http.StatusOK:\n\t\t\tvar (\n\t\t\t\tbody StatusResponseBody\n\t\t\t\terr error\n\t\t\t)\n\t\t\terr = decoder(resp).Decode(&body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, goahttp.ErrDecodingError(\"batch\", \"status\", err)\n\t\t\t}\n\t\t\terr = ValidateStatusResponseBody(&body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, goahttp.ErrValidationError(\"batch\", \"status\", err)\n\t\t\t}\n\t\t\tres := NewStatusBatchStatusResultOK(&body)\n\t\t\treturn res, nil\n\t\tdefault:\n\t\t\tbody, _ := io.ReadAll(resp.Body)\n\t\t\treturn nil, goahttp.ErrInvalidResponse(\"batch\", \"status\", resp.StatusCode, string(body))\n\t\t}\n\t}\n}", "func DecodeGrpcRespAuthenticationPolicyStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcRespLicenseStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func (c *Client) DecodeStatus(resp *http.Response) (*Status, error) {\n\tvar decoded Status\n\terr := c.Decoder.Decode(&decoded, resp.Body, resp.Header.Get(\"Content-Type\"))\n\treturn &decoded, err\n}", "func DecodeGrpcRespRoleStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcRespSnapshotRestoreStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcRespWorkloadMigrationStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func DecodeGrpcReqLdapServerStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*LdapServerStatus)\n\treturn req, nil\n}", "func decodeResponse(resp *http.Response, isSuccess SuccessDecider, decoder ResponseDecoder, successV, failureV interface{}) error {\n\tif isSuccess(resp) {\n\t\tswitch sv := successV.(type) {\n\t\tcase nil:\n\t\t\treturn nil\n\t\tcase *Raw:\n\t\t\trespBody, err := ioutil.ReadAll(resp.Body)\n\t\t\t*sv = respBody\n\t\t\treturn err\n\t\tdefault:\n\t\t\treturn decoder.Decode(resp, successV)\n\t\t}\n\t} else {\n\t\tswitch fv := failureV.(type) {\n\t\tcase nil:\n\t\t\treturn nil\n\t\tcase *Raw:\n\t\t\trespBody, err := ioutil.ReadAll(resp.Body)\n\t\t\t*fv = respBody\n\t\t\treturn err\n\t\tdefault:\n\t\t\treturn decoder.Decode(resp, failureV)\n\t\t}\n\t}\n}", "func EncodeUnsealResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(endpoints.UnsealResponse)\n\n\tstatus := &pb.SealStatus{\n\t\tSealed: resp.Sealed,\n\t\tT: uint32(resp.T),\n\t\tN: uint32(resp.N),\n\t\tProgress: uint32(resp.Progress),\n\t\tVersion: resp.Version,\n\t\tClusterName: resp.ClusterName,\n\t\tClusterId: resp.ClusterID,\n\t}\n\treturn &pb.UnsealResponse{\n\t\tSealStatus: status,\n\t\tErr: service.Error2String(resp.Err),\n\t}, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
EncodeSealStatusResponse is a transport/grpc.EncodeResponseFunc that converts a userdomain sealstatus response to a gRPC sealstatus reply. Primarily useful in a server.
func EncodeSealStatusResponse(_ context.Context, response interface{}) (interface{}, error) { resp := response.(endpoints.SealStatusResponse) status := &pb.SealStatus{ Sealed: resp.Sealed, T: uint32(resp.T), N: uint32(resp.N), Progress: uint32(resp.Progress), Version: resp.Version, ClusterName: resp.ClusterName, ClusterId: resp.ClusterID, } return &pb.SealStatusResponse{ SealStatus: status, Err: service.Error2String(resp.Err), }, nil }
[ "func DecodeSealStatusResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.SealStatusResponse)\n\tstatus := endpoints.SealStatusResponse{\n\t\tSealed: reply.SealStatus.Sealed,\n\t\tT: int(reply.SealStatus.T),\n\t\tN: int(reply.SealStatus.N),\n\t\tProgress: int(reply.SealStatus.Progress),\n\t\tVersion: reply.SealStatus.Version,\n\t\tClusterName: reply.SealStatus.ClusterName,\n\t\tClusterID: reply.SealStatus.ClusterId,\n\t\tErr: service.String2Error(reply.Err),\n\t}\n\n\treturn status, nil\n}", "func EncodeSealStatusRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treturn &pb.SealStatusRequest{}, nil\n}", "func EncodeStatusResponse(encoder func(context.Context, http.ResponseWriter) goahttp.Encoder) func(context.Context, http.ResponseWriter, interface{}) error {\n\treturn func(ctx context.Context, w http.ResponseWriter, v interface{}) error {\n\t\tres := v.(*spinbroker.StatusResult)\n\t\tenc := encoder(ctx, w)\n\t\tbody := NewStatusResponseBody(res)\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn enc.Encode(body)\n\t}\n}", "func DecodeSealStatusRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treturn endpoints.SealStatusRequest{}, nil\n}", "func EncodeStatusResponse(ctx context.Context, v interface{}, hdr, trlr *metadata.MD) (interface{}, error) {\n\tresp := NewStatusResponse()\n\treturn resp, nil\n}", "func EncodeGrpcRespLdapServerStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeGrpcRespRadiusServerStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeGrpcRespArchiveRequestStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeSecureResponse(encoder func(context.Context, http.ResponseWriter) goahttp.Encoder) func(context.Context, http.ResponseWriter, any) error {\n\treturn func(ctx context.Context, w http.ResponseWriter, v any) error {\n\t\tres, _ := v.(string)\n\t\tenc := encoder(ctx, w)\n\t\tbody := res\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn enc.Encode(body)\n\t}\n}", "func EncodeGRPCStatusResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(*pb.StatusResponse)\n\treturn resp, nil\n}", "func EncodeUnsealResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(endpoints.UnsealResponse)\n\n\tstatus := &pb.SealStatus{\n\t\tSealed: resp.Sealed,\n\t\tT: uint32(resp.T),\n\t\tN: uint32(resp.N),\n\t\tProgress: uint32(resp.Progress),\n\t\tVersion: resp.Version,\n\t\tClusterName: resp.ClusterName,\n\t\tClusterId: resp.ClusterID,\n\t}\n\treturn &pb.UnsealResponse{\n\t\tSealStatus: status,\n\t\tErr: service.Error2String(resp.Err),\n\t}, nil\n}", "func EncodeGrpcRespUserStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeGrpcRespDSCProfileStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeGrpcRespPropagationStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeDoublySecureResponse(encoder func(context.Context, http.ResponseWriter) goahttp.Encoder) func(context.Context, http.ResponseWriter, any) error {\n\treturn func(ctx context.Context, w http.ResponseWriter, v any) error {\n\t\tres, _ := v.(string)\n\t\tenc := encoder(ctx, w)\n\t\tbody := res\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn enc.Encode(body)\n\t}\n}", "func StatusToVizierResponse(id uuid.UUID, s *statuspb.Status) *vizierpb.ExecuteScriptResponse {\n\treturn &vizierpb.ExecuteScriptResponse{\n\t\tQueryID: id.String(),\n\t\tStatus: StatusToVizierStatus(s),\n\t}\n}", "func EncodeGrpcRespWorkloadMigrationStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeGrpcRespWorkloadStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeGrpcRespLicenseStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
EncodeSealStatusRequest is a transport/grpc.EncodeRequestFunc that converts a userdomain sealstatus request to a gRPC sealstatus request. Primarily useful in a client.
func EncodeSealStatusRequest(_ context.Context, request interface{}) (interface{}, error) { return &pb.SealStatusRequest{}, nil }
[ "func DecodeSealStatusRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treturn endpoints.SealStatusRequest{}, nil\n}", "func EncodeSealStatusResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(endpoints.SealStatusResponse)\n\n\tstatus := &pb.SealStatus{\n\t\tSealed: resp.Sealed,\n\t\tT: uint32(resp.T),\n\t\tN: uint32(resp.N),\n\t\tProgress: uint32(resp.Progress),\n\t\tVersion: resp.Version,\n\t\tClusterName: resp.ClusterName,\n\t\tClusterId: resp.ClusterID,\n\t}\n\treturn &pb.SealStatusResponse{\n\t\tSealStatus: status,\n\t\tErr: service.Error2String(resp.Err),\n\t}, nil\n}", "func EncodeGrpcReqArchiveRequestStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*ArchiveRequestStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqPropagationStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*PropagationStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqRadiusServerStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*RadiusServerStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqUserStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*UserStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqLdapServerStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*LdapServerStatus)\n\treturn req, nil\n}", "func EncodeInitStatusRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treturn &pb.InitStatusRequest{}, nil\n}", "func EncodeGrpcReqLicenseStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*LicenseStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqFeatureStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*FeatureStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqWorkloadStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*WorkloadStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqWorkloadMigrationStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*WorkloadMigrationStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqWorkloadIntfStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*WorkloadIntfStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqRoleStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*RoleStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqDSCProfileStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*DSCProfileStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqAuthenticationPolicyStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*AuthenticationPolicyStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqBGPAuthStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*BGPAuthStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqRouteTableStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*RouteTableStatus)\n\treturn req, nil\n}", "func EncodeGrpcReqOperationStatus(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*OperationStatus)\n\treturn req, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DecodeUnsealRequest is a transport/grpc.DecodeRequestFunc that converts a gRPC unseal request to a userdomain unseal request. Primarily useful in a server.
func DecodeUnsealRequest(_ context.Context, grpcReq interface{}) (interface{}, error) { req := grpcReq.(*pb.UnsealRequest) return &endpoints.UnsealRequest{Key: req.Key, Reset: req.Reset_}, nil }
[ "func EncodeUnsealRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treq := request.(endpoints.UnsealRequest)\n\treturn &pb.UnsealRequest{\n\t\tKey: req.Key,\n\t\tReset_: req.Reset,\n\t}, nil\n}", "func DecodeSigninRequest(ctx context.Context, v interface{}, md metadata.MD) (interface{}, error) {\n\tvar (\n\t\tmessage *userpb.SigninRequest\n\t\tok bool\n\t)\n\t{\n\t\tif message, ok = v.(*userpb.SigninRequest); !ok {\n\t\t\treturn nil, goagrpc.ErrInvalidType(\"user\", \"signin\", \"*userpb.SigninRequest\", v)\n\t\t}\n\t}\n\tvar payload *user.Signin\n\t{\n\t\tpayload = NewSigninPayload(message)\n\t}\n\treturn payload, nil\n}", "func DecodeUpdateRequest(ctx context.Context, v interface{}, md metadata.MD) (interface{}, error) {\n\tvar (\n\t\ttoken string\n\t\terr error\n\t)\n\t{\n\t\tif vals := md.Get(\"authorization\"); len(vals) == 0 {\n\t\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"authorization\", \"metadata\"))\n\t\t} else {\n\t\t\ttoken = vals[0]\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar (\n\t\tmessage *userpb.UpdateRequest\n\t\tok bool\n\t)\n\t{\n\t\tif message, ok = v.(*userpb.UpdateRequest); !ok {\n\t\t\treturn nil, goagrpc.ErrInvalidType(\"user\", \"update\", \"*userpb.UpdateRequest\", v)\n\t\t}\n\t}\n\tvar payload *user.UpdateUser\n\t{\n\t\tpayload = NewUpdatePayload(message, token)\n\t\tif strings.Contains(payload.Token, \" \") {\n\t\t\t// Remove authorization scheme prefix (e.g. \"Bearer\")\n\t\t\tcred := strings.SplitN(payload.Token, \" \", 2)[1]\n\t\t\tpayload.Token = cred\n\t\t}\n\t}\n\treturn payload, nil\n}", "func decodeDeleteIndustryRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*pb.DeleteIndustryRequest)\n\treturn endpoints.DeleteIndustryRequest{ID: req.Id}, nil\n}", "func decodeGetAllIndustriesRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*pb.GetAllIndustriesRequest)\n\tdecoded := endpoints.GetAllIndustriesRequest{\n\t\tID: req.Id,\n\t\tName: req.Name,\n\t}\n\treturn decoded, nil\n}", "func decodeLoginUPRequest(_ context.Context, r interface{}) (interface{}, error) {\n\trq := r.(*pb.LoginUPRequest)\n\treturn endpoint.LoginUPRequest{\n\t\tUsername: rq.Username,\n\t\tPassword: rq.Password,\n\t}, nil\n}", "func decodeRequest(_ context.Context, r *http.Request) (request interface{}, err error) {\n\tdefer r.Body.Close()\n\treturn nil, nil\n}", "func DecodeDoublySecureRequest(mux goahttp.Muxer, decoder func(*http.Request) goahttp.Decoder) func(*http.Request) (any, error) {\n\treturn func(r *http.Request) (any, error) {\n\t\tvar (\n\t\t\tkey string\n\t\t\ttoken string\n\t\t\terr error\n\t\t)\n\t\tkey = r.URL.Query().Get(\"k\")\n\t\tif key == \"\" {\n\t\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"key\", \"query string\"))\n\t\t}\n\t\ttoken = r.Header.Get(\"Authorization\")\n\t\tif token == \"\" {\n\t\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"token\", \"header\"))\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpayload := NewDoublySecurePayload(key, token)\n\t\tif strings.Contains(payload.Token, \" \") {\n\t\t\t// Remove authorization scheme prefix (e.g. \"Bearer\")\n\t\t\tcred := strings.SplitN(payload.Token, \" \", 2)[1]\n\t\t\tpayload.Token = cred\n\t\t}\n\n\t\treturn payload, nil\n\t}\n}", "func DecodeRequest[I any](ctx context.Context, r *http.Request) (in I, err error) {\n\tswitch r.Method {\n\tcase \"POST\", \"PUT\", \"PATCH\":\n\t\terr = magic.Decode(r, &in,\n\t\t\tmagic.JSON,\n\t\t\tmagic.ChiRouter,\n\t\t)\n\tcase \"GET\", \"DELETE\":\n\t\terr = magic.Decode(r, &in,\n\t\t\tmagic.QueryParams,\n\t\t\tmagic.ChiRouter,\n\t\t)\n\tdefault:\n\t\terr = errors.Errorf(\"method %s not supported\", r.Method)\n\t}\n\n\tif err == io.EOF {\n\t\terr = errors.New(\"empty body\")\n\t}\n\n\treturn in, errors.E(err, \"can not unmarshal request\", errors.Unmarshal)\n}", "func DecodeListenerRequest(mux goahttp.Muxer, decoder func(*http.Request) goahttp.Decoder) func(*http.Request) (any, error) {\n\treturn func(r *http.Request) (any, error) {\n\t\tvar (\n\t\t\ttoken string\n\t\t\terr error\n\t\t)\n\t\ttoken = r.Header.Get(\"Authorization\")\n\t\tif token == \"\" {\n\t\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"token\", \"header\"))\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpayload := NewListenerPayload(token)\n\t\tif strings.Contains(payload.Token, \" \") {\n\t\t\t// Remove authorization scheme prefix (e.g. \"Bearer\")\n\t\t\tcred := strings.SplitN(payload.Token, \" \", 2)[1]\n\t\t\tpayload.Token = cred\n\t\t}\n\n\t\treturn payload, nil\n\t}\n}", "func decodeGetUserDealByStateRequest(_ context.Context, r *http1.Request) (interface{}, error) {\n\tvars := mux.Vars(r)\n\tvals := r.URL.Query()\n\tstate := \"\"\n\tid, ok := vars[\"userId\"]\n\tif !ok {\n\t\treturn nil, errors.New(\"not a valid userId\")\n\t}\n\tstates, okk := vals[\"state\"]\n\tif okk {\n\t\tstate = states[0]\n\t}\n\treq := endpoint.GetUserDealByStateRequest{\n\t\tId: id,\n\t\tState: state,\n\t}\n\treturn req, nil\n}", "func DecodeGRPCDecryptRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.DecryptRequest)\n\treturn req, nil\n}", "func DecodeSigninRequest(mux goahttp.Muxer, decoder func(*http.Request) goahttp.Decoder) func(*http.Request) (any, error) {\n\treturn func(r *http.Request) (any, error) {\n\t\tpayload := NewSigninPayload()\n\t\tuser, pass, ok := r.BasicAuth()\n\t\tif !ok {\n\t\t\treturn nil, goa.MissingFieldError(\"Authorization\", \"header\")\n\t\t}\n\t\tpayload.Username = user\n\t\tpayload.Password = pass\n\n\t\treturn payload, nil\n\t}\n}", "func DecodeSealStatusRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treturn endpoints.SealStatusRequest{}, nil\n}", "func decodeCreateIndustryRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*pb.CreateIndustryRequest)\n\treturn endpoints.CreateIndustryRequest{Industry: models.IndustryToORM(req.Industry)}, nil\n}", "func DecodeGRPCLogoutRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.LogoutRequest)\n\treturn req, nil\n}", "func DecodeUnsealResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.UnsealResponse)\n\tstatus := endpoints.UnsealResponse{\n\t\tSealed: reply.SealStatus.Sealed,\n\t\tT: int(reply.SealStatus.T),\n\t\tN: int(reply.SealStatus.N),\n\t\tProgress: int(reply.SealStatus.Progress),\n\t\tVersion: reply.SealStatus.Version,\n\t\tClusterName: reply.SealStatus.ClusterName,\n\t\tClusterID: reply.SealStatus.ClusterId,\n\t\tErr: service.String2Error(reply.Err),\n\t}\n\n\treturn status, nil\n}", "func (mh *MessageHandler) decodeRequest(httpRequest *http.Request) (deviceRequest *Request, err error) {\n\tdeviceRequest, err = DecodeRequest(httpRequest.Body, mh.Decoders)\n\tif err == nil {\n\t\tdeviceRequest = deviceRequest.WithContext(httpRequest.Context())\n\t}\n\n\treturn\n}", "func DecodeRemoveRequest(_ context.Context, r *http.Request) (req interface{}, err error) {\n\treq = endpoints.RemoveRequest{Id: mux.Vars(r)[\"id\"]}\n\t//err = json.NewDecoder(r.Body).Decode(&r)\n\treturn req, err\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DecodeUnsealResponse is a transport/grpc.DecodeResponseFunc that converts a gRPC unseal reply to a userdomain unseal response. Primarily useful in a client.
func DecodeUnsealResponse(_ context.Context, grpcReply interface{}) (interface{}, error) { reply := grpcReply.(*pb.UnsealResponse) status := endpoints.UnsealResponse{ Sealed: reply.SealStatus.Sealed, T: int(reply.SealStatus.T), N: int(reply.SealStatus.N), Progress: int(reply.SealStatus.Progress), Version: reply.SealStatus.Version, ClusterName: reply.SealStatus.ClusterName, ClusterID: reply.SealStatus.ClusterId, Err: service.String2Error(reply.Err), } return status, nil }
[ "func EncodeUnsealResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(endpoints.UnsealResponse)\n\n\tstatus := &pb.SealStatus{\n\t\tSealed: resp.Sealed,\n\t\tT: uint32(resp.T),\n\t\tN: uint32(resp.N),\n\t\tProgress: uint32(resp.Progress),\n\t\tVersion: resp.Version,\n\t\tClusterName: resp.ClusterName,\n\t\tClusterId: resp.ClusterID,\n\t}\n\treturn &pb.UnsealResponse{\n\t\tSealStatus: status,\n\t\tErr: service.Error2String(resp.Err),\n\t}, nil\n}", "func DecodeUnsealRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.UnsealRequest)\n\treturn &endpoints.UnsealRequest{Key: req.Key, Reset: req.Reset_}, nil\n}", "func decodeSignoutResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\tr := reply.(*pb.SignoutReply)\n\tif r.Result {\n\t\treturn &endpoint1.SignoutResponse{E0: nil}, nil\n\t}\n\treturn nil, errors.New(\"'Account' Decoder is not impelemented\")\n}", "func (t *LeaveGroupResponse) Decode(d *Decoder, version int16) error {\n\tvar err error\n\tif version >= 1 {\n\t\tt.ThrottleTimeMs, err = d.Int32()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tt.ErrorCode, err = d.Int16()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif version >= 3 {\n\t\t// Members\n\t\tif n, err := d.ArrayLength(); err != nil {\n\t\t\treturn err\n\t\t} else if n >= 0 {\n\t\t\tt.Members = make([]MemberResponse13, n)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tvar item MemberResponse13\n\t\t\t\tif err := (&item).Decode(d, version); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tt.Members[i] = item\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n}", "func DecodeRemoveResponse(decoder func(*http.Response) goahttp.Decoder, restoreBody bool) func(*http.Response) (any, error) {\n\treturn func(resp *http.Response) (any, error) {\n\t\tif restoreBody {\n\t\t\tb, err := io.ReadAll(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tresp.Body = io.NopCloser(bytes.NewBuffer(b))\n\t\t\tdefer func() {\n\t\t\t\tresp.Body = io.NopCloser(bytes.NewBuffer(b))\n\t\t\t}()\n\t\t} else {\n\t\t\tdefer resp.Body.Close()\n\t\t}\n\t\tswitch resp.StatusCode {\n\t\tcase http.StatusNoContent:\n\t\t\treturn nil, nil\n\t\tdefault:\n\t\t\tbody, _ := io.ReadAll(resp.Body)\n\t\t\treturn nil, goahttp.ErrInvalidResponse(\"storage\", \"remove\", resp.StatusCode, string(body))\n\t\t}\n\t}\n}", "func DecodeDoublySecureResponse(decoder func(*http.Response) goahttp.Decoder, restoreBody bool) func(*http.Response) (any, error) {\n\treturn func(resp *http.Response) (any, error) {\n\t\tif restoreBody {\n\t\t\tb, err := io.ReadAll(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tresp.Body = io.NopCloser(bytes.NewBuffer(b))\n\t\t\tdefer func() {\n\t\t\t\tresp.Body = io.NopCloser(bytes.NewBuffer(b))\n\t\t\t}()\n\t\t} else {\n\t\t\tdefer resp.Body.Close()\n\t\t}\n\t\tswitch resp.StatusCode {\n\t\tcase http.StatusOK:\n\t\t\tvar (\n\t\t\t\tbody string\n\t\t\t\terr error\n\t\t\t)\n\t\t\terr = decoder(resp).Decode(&body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, goahttp.ErrDecodingError(\"secured_service\", \"doubly_secure\", err)\n\t\t\t}\n\t\t\treturn body, nil\n\t\tcase http.StatusForbidden:\n\t\t\tvar (\n\t\t\t\tbody string\n\t\t\t\terr error\n\t\t\t)\n\t\t\terr = decoder(resp).Decode(&body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, goahttp.ErrDecodingError(\"secured_service\", \"doubly_secure\", err)\n\t\t\t}\n\t\t\treturn nil, NewDoublySecureInvalidScopes(body)\n\t\tcase http.StatusUnauthorized:\n\t\t\tvar (\n\t\t\t\tbody string\n\t\t\t\terr error\n\t\t\t)\n\t\t\terr = decoder(resp).Decode(&body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, goahttp.ErrDecodingError(\"secured_service\", \"doubly_secure\", err)\n\t\t\t}\n\t\t\treturn nil, NewDoublySecureUnauthorized(body)\n\t\tdefault:\n\t\t\tbody, _ := io.ReadAll(resp.Body)\n\t\t\treturn nil, goahttp.ErrInvalidResponse(\"secured_service\", \"doubly_secure\", resp.StatusCode, string(body))\n\t\t}\n\t}\n}", "func DecodeSigninResponse(decoder func(*http.Response) goahttp.Decoder, restoreBody bool) func(*http.Response) (any, error) {\n\treturn func(resp *http.Response) (any, error) {\n\t\tif restoreBody {\n\t\t\tb, err := io.ReadAll(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tresp.Body = io.NopCloser(bytes.NewBuffer(b))\n\t\t\tdefer func() {\n\t\t\t\tresp.Body = io.NopCloser(bytes.NewBuffer(b))\n\t\t\t}()\n\t\t} else {\n\t\t\tdefer resp.Body.Close()\n\t\t}\n\t\tswitch resp.StatusCode {\n\t\tcase http.StatusOK:\n\t\t\tvar (\n\t\t\t\tbody SigninResponseBody\n\t\t\t\terr error\n\t\t\t)\n\t\t\terr = decoder(resp).Decode(&body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, goahttp.ErrDecodingError(\"secured_service\", \"signin\", err)\n\t\t\t}\n\t\t\terr = ValidateSigninResponseBody(&body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, goahttp.ErrValidationError(\"secured_service\", \"signin\", err)\n\t\t\t}\n\t\t\tres := NewSigninCredsOK(&body)\n\t\t\treturn res, nil\n\t\tcase http.StatusUnauthorized:\n\t\t\tvar (\n\t\t\t\tbody string\n\t\t\t\terr error\n\t\t\t)\n\t\t\terr = decoder(resp).Decode(&body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, goahttp.ErrDecodingError(\"secured_service\", \"signin\", err)\n\t\t\t}\n\t\t\treturn nil, NewSigninUnauthorized(body)\n\t\tdefault:\n\t\t\tbody, _ := io.ReadAll(resp.Body)\n\t\t\treturn nil, goahttp.ErrInvalidResponse(\"secured_service\", \"signin\", resp.StatusCode, string(body))\n\t\t}\n\t}\n}", "func parseUnparseResponse(out []byte, err error) []byte {\n\tb := flatbuffers.NewBuilder(1024)\n\n\tif err != nil {\n\t\toff := stdError(b, err)\n\t\t__std.ParseUnparseResponseStart(b)\n\t\t__std.ParseUnparseResponseAddRetvalType(b, __std.ParseUnparseRetvalError)\n\t\t__std.ParseUnparseResponseAddRetval(b, off)\n\t\toff = __std.ParseUnparseResponseEnd(b)\n\t\tb.Finish(off)\n\t\treturn b.FinishedBytes()\n\t}\n\n\toff := b.CreateByteString(out)\n\t__std.ParseUnparseDataStart(b)\n\t__std.ParseUnparseDataAddData(b, off)\n\toff = __std.ParseUnparseDataEnd(b)\n\t__std.ParseUnparseResponseStart(b)\n\t__std.ParseUnparseResponseAddRetvalType(b, __std.ParseUnparseRetvalParseUnparseData)\n\t__std.ParseUnparseResponseAddRetval(b, off)\n\toff = __std.ParseUnparseResponseEnd(b)\n\tb.Finish(off)\n\treturn b.FinishedBytes()\n}", "func decodeUserInfoResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\tr, ok := reply.(*pb.UserInfoReply)\n\tif !ok {\n\t\te := errors.New(\"pb UserInfoReply type assertion error\")\n\t\treturn nil, e\n\t}\n\treturn endpoint1.UserInfoResponse{Roles: r.Roles, OrgName: r.OrgName}, nil\n}", "func DecodeRemoveResponse(decoder func(*http.Response) goahttp.Decoder, restoreBody bool) func(*http.Response) (interface{}, error) {\n\treturn func(resp *http.Response) (interface{}, error) {\n\t\tif restoreBody {\n\t\t\tb, err := ioutil.ReadAll(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tresp.Body = ioutil.NopCloser(bytes.NewBuffer(b))\n\t\t\tdefer func() {\n\t\t\t\tresp.Body = ioutil.NopCloser(bytes.NewBuffer(b))\n\t\t\t}()\n\t\t} else {\n\t\t\tdefer resp.Body.Close()\n\t\t}\n\t\tswitch resp.StatusCode {\n\t\tcase http.StatusNoContent:\n\t\t\treturn nil, nil\n\t\tdefault:\n\t\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\t\treturn nil, goahttp.ErrInvalidResponse(\"blog\", \"remove\", resp.StatusCode, string(body))\n\t\t}\n\t}\n}", "func DecodeSCEPResponse(ctx context.Context, r *http.Response) (interface{}, error) {\n\tif r.StatusCode != http.StatusOK && r.StatusCode >= 400 {\n\t\tbody, _ := ioutil.ReadAll(io.LimitReader(r.Body, 4096))\n\t\treturn nil, fmt.Errorf(\"http request failed with status %s, msg: %s\",\n\t\t\tr.Status,\n\t\t\tstring(body),\n\t\t)\n\t}\n\tdata, err := ioutil.ReadAll(io.LimitReader(r.Body, maxPayloadSize))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer r.Body.Close()\n\tresp := SCEPResponse{\n\t\tData: data,\n\t}\n\theader := r.Header.Get(\"Content-Type\")\n\tif header == certChainHeader {\n\t\t// we only set it to two to indicate a cert chain.\n\t\t// the actual number of certs will be in the payload.\n\t\tresp.CACertNum = 2\n\t}\n\treturn resp, nil\n}", "func DecodeLoginResponse(ctx context.Context, v interface{}, hdr, trlr metadata.MD) (interface{}, error) {\n\tmessage, ok := v.(*user_methodpb.LoginResponse)\n\tif !ok {\n\t\treturn nil, goagrpc.ErrInvalidType(\"userMethod\", \"login\", \"*user_methodpb.LoginResponse\", v)\n\t}\n\tres := NewLoginResult(message)\n\treturn res, nil\n}", "func decodeGetResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\treturn nil, errors.New(\"'Users' Decoder is not impelemented\")\n}", "func (t *ControlledShutdownResponse) Decode(d *Decoder, version int16) error {\n\tvar err error\n\tt.ErrorCode, err = d.Int16()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// RemainingPartitions\n\tif n, err := d.ArrayLength(); err != nil {\n\t\treturn err\n\t} else if n >= 0 {\n\t\tt.RemainingPartitions = make([]RemainingPartition7, n)\n\t\tfor i := 0; i < n; i++ {\n\t\t\tvar item RemainingPartition7\n\t\t\tif err := (&item).Decode(d, version); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tt.RemainingPartitions[i] = item\n\t\t}\n\t}\n\treturn err\n}", "func DecodeGrpcRespAuthenticationPolicy(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func Unseal(auth, key, seal []byte) ([]byte, error) {\n\tif len(seal) < 56 {\n\t\treturn seal, SEAL_UNDERFLOW\n\t}\n\n\t// We copy off the seal because we're about to manipulate it destructively.\n\tseal = append(make([]byte, 0, len(seal)), seal...)\n\thash := hmac.New(sha256.New, auth)\n\n\t// Decrypt our HMAC and PLAINTEXT\n\tb, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcipher.NewCTR(b, seal[:16]).XORKeyStream(seal[16:], seal[16:])\n\n\t// Extract our Timestamp\n\texpiry := binary.LittleEndian.Uint64(seal[16:24])\n\n\t// Compare our HMAC\n\thash.Write(seal[0:24])\n\thash.Write(seal[56:])\n\tif bytes.Compare(seal[24:56], hash.Sum(nil)) != 0 {\n\t\treturn nil, SEAL_MISMATCH\n\t}\n\n\t// Compare our expiry\n\tif time.Now().After(time.Unix(int64(expiry), 0)) {\n\t\treturn nil, SEAL_EXPIRED\n\t}\n\n\treturn seal[56:], nil\n}", "func Unseal(ciphertext []byte) ([]byte, error) {\n\tif len(ciphertext) < 4 {\n\t\treturn nil, fmt.Errorf(\"ciphertext is too short\")\n\t}\n\n\tkeyInfoLength := binary.LittleEndian.Uint32(ciphertext[:4])\n\n\t// We might deal with invalid user data as input, so let's convert an potential upcoming out-of-bounds panic to an error the underlying caller can choose how to deal with this situation.\n\tif keyInfoLength == 0 || 4+int(keyInfoLength) > len(ciphertext) {\n\t\treturn nil, fmt.Errorf(\"embedded length information does not fit the given ciphertext\")\n\t}\n\n\tkeyInfo := ciphertext[4 : 4+keyInfoLength]\n\tciphertext = ciphertext[4+keyInfoLength:]\n\n\tsealKey, err := sealer.GetSealKey(keyInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn Decrypt(ciphertext, sealKey)\n}", "func DecodeSecureResponse(decoder func(*http.Response) goahttp.Decoder, restoreBody bool) func(*http.Response) (any, error) {\n\treturn func(resp *http.Response) (any, error) {\n\t\tif restoreBody {\n\t\t\tb, err := io.ReadAll(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tresp.Body = io.NopCloser(bytes.NewBuffer(b))\n\t\t\tdefer func() {\n\t\t\t\tresp.Body = io.NopCloser(bytes.NewBuffer(b))\n\t\t\t}()\n\t\t} else {\n\t\t\tdefer resp.Body.Close()\n\t\t}\n\t\tswitch resp.StatusCode {\n\t\tcase http.StatusOK:\n\t\t\tvar (\n\t\t\t\tbody string\n\t\t\t\terr error\n\t\t\t)\n\t\t\terr = decoder(resp).Decode(&body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, goahttp.ErrDecodingError(\"secured_service\", \"secure\", err)\n\t\t\t}\n\t\t\treturn body, nil\n\t\tcase http.StatusForbidden:\n\t\t\tvar (\n\t\t\t\tbody string\n\t\t\t\terr error\n\t\t\t)\n\t\t\terr = decoder(resp).Decode(&body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, goahttp.ErrDecodingError(\"secured_service\", \"secure\", err)\n\t\t\t}\n\t\t\treturn nil, NewSecureInvalidScopes(body)\n\t\tcase http.StatusUnauthorized:\n\t\t\tvar (\n\t\t\t\tbody string\n\t\t\t\terr error\n\t\t\t)\n\t\t\terr = decoder(resp).Decode(&body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, goahttp.ErrDecodingError(\"secured_service\", \"secure\", err)\n\t\t\t}\n\t\t\treturn nil, NewSecureUnauthorized(body)\n\t\tdefault:\n\t\t\tbody, _ := io.ReadAll(resp.Body)\n\t\t\treturn nil, goahttp.ErrInvalidResponse(\"secured_service\", \"secure\", resp.StatusCode, string(body))\n\t\t}\n\t}\n}", "func DecodeUpdateResponse(decoder func(*http.Response) goahttp.Decoder, restoreBody bool) func(*http.Response) (interface{}, error) {\n\treturn func(resp *http.Response) (interface{}, error) {\n\t\tif restoreBody {\n\t\t\tb, err := ioutil.ReadAll(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tresp.Body = ioutil.NopCloser(bytes.NewBuffer(b))\n\t\t\tdefer func() {\n\t\t\t\tresp.Body = ioutil.NopCloser(bytes.NewBuffer(b))\n\t\t\t}()\n\t\t} else {\n\t\t\tdefer resp.Body.Close()\n\t\t}\n\t\tswitch resp.StatusCode {\n\t\tcase http.StatusNoContent:\n\t\t\treturn nil, nil\n\t\tdefault:\n\t\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\t\treturn nil, goahttp.ErrInvalidResponse(\"color\", \"update\", resp.StatusCode, string(body))\n\t\t}\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
EncodeUnsealResponse is a transport/grpc.EncodeResponseFunc that converts a userdomain unseal response to a gRPC sealstatus reply. Primarily useful in a server.
func EncodeUnsealResponse(_ context.Context, response interface{}) (interface{}, error) { resp := response.(endpoints.UnsealResponse) status := &pb.SealStatus{ Sealed: resp.Sealed, T: uint32(resp.T), N: uint32(resp.N), Progress: uint32(resp.Progress), Version: resp.Version, ClusterName: resp.ClusterName, ClusterId: resp.ClusterID, } return &pb.UnsealResponse{ SealStatus: status, Err: service.Error2String(resp.Err), }, nil }
[ "func DecodeUnsealResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.UnsealResponse)\n\tstatus := endpoints.UnsealResponse{\n\t\tSealed: reply.SealStatus.Sealed,\n\t\tT: int(reply.SealStatus.T),\n\t\tN: int(reply.SealStatus.N),\n\t\tProgress: int(reply.SealStatus.Progress),\n\t\tVersion: reply.SealStatus.Version,\n\t\tClusterName: reply.SealStatus.ClusterName,\n\t\tClusterID: reply.SealStatus.ClusterId,\n\t\tErr: service.String2Error(reply.Err),\n\t}\n\n\treturn status, nil\n}", "func EncodeDoublySecureResponse(encoder func(context.Context, http.ResponseWriter) goahttp.Encoder) func(context.Context, http.ResponseWriter, any) error {\n\treturn func(ctx context.Context, w http.ResponseWriter, v any) error {\n\t\tres, _ := v.(string)\n\t\tenc := encoder(ctx, w)\n\t\tbody := res\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn enc.Encode(body)\n\t}\n}", "func EncodeSealStatusResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(endpoints.SealStatusResponse)\n\n\tstatus := &pb.SealStatus{\n\t\tSealed: resp.Sealed,\n\t\tT: uint32(resp.T),\n\t\tN: uint32(resp.N),\n\t\tProgress: uint32(resp.Progress),\n\t\tVersion: resp.Version,\n\t\tClusterName: resp.ClusterName,\n\t\tClusterId: resp.ClusterID,\n\t}\n\treturn &pb.SealStatusResponse{\n\t\tSealStatus: status,\n\t\tErr: service.Error2String(resp.Err),\n\t}, nil\n}", "func EncodeAlsoDoublySecureResponse(encoder func(context.Context, http.ResponseWriter) goahttp.Encoder) func(context.Context, http.ResponseWriter, any) error {\n\treturn func(ctx context.Context, w http.ResponseWriter, v any) error {\n\t\tres, _ := v.(string)\n\t\tenc := encoder(ctx, w)\n\t\tbody := res\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn enc.Encode(body)\n\t}\n}", "func EncodeSecureResponse(encoder func(context.Context, http.ResponseWriter) goahttp.Encoder) func(context.Context, http.ResponseWriter, any) error {\n\treturn func(ctx context.Context, w http.ResponseWriter, v any) error {\n\t\tres, _ := v.(string)\n\t\tenc := encoder(ctx, w)\n\t\tbody := res\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn enc.Encode(body)\n\t}\n}", "func EncodeUnsealRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treq := request.(endpoints.UnsealRequest)\n\treturn &pb.UnsealRequest{\n\t\tKey: req.Key,\n\t\tReset_: req.Reset,\n\t}, nil\n}", "func DecodeSealStatusResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.SealStatusResponse)\n\tstatus := endpoints.SealStatusResponse{\n\t\tSealed: reply.SealStatus.Sealed,\n\t\tT: int(reply.SealStatus.T),\n\t\tN: int(reply.SealStatus.N),\n\t\tProgress: int(reply.SealStatus.Progress),\n\t\tVersion: reply.SealStatus.Version,\n\t\tClusterName: reply.SealStatus.ClusterName,\n\t\tClusterID: reply.SealStatus.ClusterId,\n\t\tErr: service.String2Error(reply.Err),\n\t}\n\n\treturn status, nil\n}", "func DecodeUnsealRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.UnsealRequest)\n\treturn &endpoints.UnsealRequest{Key: req.Key, Reset: req.Reset_}, nil\n}", "func encodeGetUserDealByStateResponse(ctx context.Context, w http1.ResponseWriter, response interface{}) (err error) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\terr = json.NewEncoder(w).Encode(response)\n\treturn\n}", "func EncodeGRPCLogoutResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(*pb.LogoutResponse)\n\treturn resp, nil\n}", "func DecodeSealStatusRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treturn endpoints.SealStatusRequest{}, nil\n}", "func EncodeSigninResponse(ctx context.Context, v interface{}, hdr, trlr *metadata.MD) (interface{}, error) {\n\tvres, ok := v.(*userviews.ResponseData)\n\tif !ok {\n\t\treturn nil, goagrpc.ErrInvalidType(\"user\", \"signin\", \"*userviews.ResponseData\", v)\n\t}\n\tresult := vres.Projected\n\t(*hdr).Append(\"goa-view\", vres.View)\n\tresp := NewSigninResponse(result)\n\treturn resp, nil\n}", "func EncodeLoginResponse(encoder func(context.Context, http.ResponseWriter) goahttp.Encoder) func(context.Context, http.ResponseWriter, any) error {\n\treturn func(ctx context.Context, w http.ResponseWriter, v any) error {\n\t\tres, _ := v.(string)\n\t\tenc := encoder(ctx, w)\n\t\tbody := res\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn enc.Encode(body)\n\t}\n}", "func EncodeSigninResponse(encoder func(context.Context, http.ResponseWriter) goahttp.Encoder) func(context.Context, http.ResponseWriter, any) error {\n\treturn func(ctx context.Context, w http.ResponseWriter, v any) error {\n\t\tres, _ := v.(*securedservice.Creds)\n\t\tenc := encoder(ctx, w)\n\t\tbody := NewSigninResponseBody(res)\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn enc.Encode(body)\n\t}\n}", "func encodeDeleteIndustryResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tres := response.(endpoints.DeleteIndustryResponse)\n\terr := getError(res.Err)\n\tif err == nil {\n\t\treturn &pb.DeleteIndustryResponse{}, nil\n\t}\n\treturn nil, err\n}", "func EncodeVironMenuResponse(encoder func(context.Context, http.ResponseWriter) goahttp.Encoder) func(context.Context, http.ResponseWriter, interface{}) error {\n\treturn func(ctx context.Context, w http.ResponseWriter, v interface{}) error {\n\t\tres := v.(*vironviews.VironMenu)\n\t\tenc := encoder(ctx, w)\n\t\tbody := NewVironMenuResponseBody(res.Projected)\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn enc.Encode(body)\n\t}\n}", "func encodeGetAllIndustriesResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tres := response.(endpoints.GetAllIndustriesResponse)\n\terr := getError(res.Err)\n\tif err == nil {\n\t\tvar industries []*pb.Industry\n\t\tfor _, industry := range res.Industries {\n\t\t\tindustries = append(industries, industry.ToProto())\n\t\t}\n\t\treturn &pb.GetAllIndustriesResponse{Industries: industries}, nil\n\t}\n\treturn nil, err\n}", "func EncodeUpdateResponse(encoder func(context.Context, http.ResponseWriter) goahttp.Encoder) func(context.Context, http.ResponseWriter, interface{}) error {\n\treturn func(ctx context.Context, w http.ResponseWriter, v interface{}) error {\n\t\tres := v.(*inventoryviews.Inventory)\n\t\tenc := encoder(ctx, w)\n\t\tbody := NewUpdateResponseBody(res.Projected)\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn enc.Encode(body)\n\t}\n}", "func encodeCreateIndustryResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tres := response.(endpoints.CreateIndustryResponse)\n\terr := getError(res.Err)\n\tif err == nil {\n\t\treturn res.Industry.ToProto(), nil\n\t}\n\treturn nil, err\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
EncodeUnsealRequest is a transport/grpc.EncodeRequestFunc that converts a userdomain unseal request to a gRPC unseal request. Primarily useful in a client.
func EncodeUnsealRequest(_ context.Context, request interface{}) (interface{}, error) { req := request.(endpoints.UnsealRequest) return &pb.UnsealRequest{ Key: req.Key, Reset_: req.Reset, }, nil }
[ "func DecodeUnsealRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.UnsealRequest)\n\treturn &endpoints.UnsealRequest{Key: req.Key, Reset: req.Reset_}, nil\n}", "func EncodeUnfollowRequest(encoder func(*http.Request) goahttp.Encoder) func(*http.Request, interface{}) error {\n\treturn func(req *http.Request, v interface{}) error {\n\t\tp, ok := v.(*following.UnfollowPayload)\n\t\tif !ok {\n\t\t\treturn goahttp.ErrInvalidType(\"following\", \"unfollow\", \"*following.UnfollowPayload\", v)\n\t\t}\n\t\tif p.Auth != nil {\n\t\t\thead := *p.Auth\n\t\t\tif !strings.Contains(head, \" \") {\n\t\t\t\treq.Header.Set(\"Authorization\", \"Bearer \"+head)\n\t\t\t} else {\n\t\t\t\treq.Header.Set(\"Authorization\", head)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n}", "func encodeSignoutRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treturn nil, nil\n}", "func DecodeSigninRequest(ctx context.Context, v interface{}, md metadata.MD) (interface{}, error) {\n\tvar (\n\t\tmessage *userpb.SigninRequest\n\t\tok bool\n\t)\n\t{\n\t\tif message, ok = v.(*userpb.SigninRequest); !ok {\n\t\t\treturn nil, goagrpc.ErrInvalidType(\"user\", \"signin\", \"*userpb.SigninRequest\", v)\n\t\t}\n\t}\n\tvar payload *user.Signin\n\t{\n\t\tpayload = NewSigninPayload(message)\n\t}\n\treturn payload, nil\n}", "func EncodeUnsealResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(endpoints.UnsealResponse)\n\n\tstatus := &pb.SealStatus{\n\t\tSealed: resp.Sealed,\n\t\tT: uint32(resp.T),\n\t\tN: uint32(resp.N),\n\t\tProgress: uint32(resp.Progress),\n\t\tVersion: resp.Version,\n\t\tClusterName: resp.ClusterName,\n\t\tClusterId: resp.ClusterID,\n\t}\n\treturn &pb.UnsealResponse{\n\t\tSealStatus: status,\n\t\tErr: service.Error2String(resp.Err),\n\t}, nil\n}", "func EncodeSealStatusRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treturn &pb.SealStatusRequest{}, nil\n}", "func EncodeUpdateRequest(encoder func(*http.Request) goahttp.Encoder) func(*http.Request, interface{}) error {\n\treturn func(req *http.Request, v interface{}) error {\n\t\tp, ok := v.(*user.UpdateUser)\n\t\tif !ok {\n\t\t\treturn goahttp.ErrInvalidType(\"user\", \"update\", \"*user.UpdateUser\", v)\n\t\t}\n\t\treq.Header.Set(\"Authorization\", p.Token)\n\t\tbody := NewUpdateRequestBody(p)\n\t\tif err := encoder(req).Encode(&body); err != nil {\n\t\t\treturn goahttp.ErrEncodingError(\"user\", \"update\", err)\n\t\t}\n\t\treturn nil\n\t}\n}", "func EncodeSigninRequest(encoder func(*http.Request) goahttp.Encoder) func(*http.Request, interface{}) error {\n\treturn func(req *http.Request, v interface{}) error {\n\t\tp, ok := v.(*user.Signin)\n\t\tif !ok {\n\t\t\treturn goahttp.ErrInvalidType(\"user\", \"signin\", \"*user.Signin\", v)\n\t\t}\n\t\tbody := NewSigninRequestBody(p)\n\t\tif err := encoder(req).Encode(&body); err != nil {\n\t\t\treturn goahttp.ErrEncodingError(\"user\", \"signin\", err)\n\t\t}\n\t\treturn nil\n\t}\n}", "func EncodeDoublySecureRequest(encoder func(*http.Request) goahttp.Encoder) func(*http.Request, any) error {\n\treturn func(req *http.Request, v any) error {\n\t\tp, ok := v.(*securedservice.DoublySecurePayload)\n\t\tif !ok {\n\t\t\treturn goahttp.ErrInvalidType(\"secured_service\", \"doubly_secure\", \"*securedservice.DoublySecurePayload\", v)\n\t\t}\n\t\t{\n\t\t\thead := p.Token\n\t\t\tif !strings.Contains(head, \" \") {\n\t\t\t\treq.Header.Set(\"Authorization\", \"Bearer \"+head)\n\t\t\t} else {\n\t\t\t\treq.Header.Set(\"Authorization\", head)\n\t\t\t}\n\t\t}\n\t\tvalues := req.URL.Query()\n\t\tvalues.Add(\"k\", p.Key)\n\t\treq.URL.RawQuery = values.Encode()\n\t\treturn nil\n\t}\n}", "func DecodeUpdateRequest(ctx context.Context, v interface{}, md metadata.MD) (interface{}, error) {\n\tvar (\n\t\ttoken string\n\t\terr error\n\t)\n\t{\n\t\tif vals := md.Get(\"authorization\"); len(vals) == 0 {\n\t\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"authorization\", \"metadata\"))\n\t\t} else {\n\t\t\ttoken = vals[0]\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar (\n\t\tmessage *userpb.UpdateRequest\n\t\tok bool\n\t)\n\t{\n\t\tif message, ok = v.(*userpb.UpdateRequest); !ok {\n\t\t\treturn nil, goagrpc.ErrInvalidType(\"user\", \"update\", \"*userpb.UpdateRequest\", v)\n\t\t}\n\t}\n\tvar payload *user.UpdateUser\n\t{\n\t\tpayload = NewUpdatePayload(message, token)\n\t\tif strings.Contains(payload.Token, \" \") {\n\t\t\t// Remove authorization scheme prefix (e.g. \"Bearer\")\n\t\t\tcred := strings.SplitN(payload.Token, \" \", 2)[1]\n\t\t\tpayload.Token = cred\n\t\t}\n\t}\n\treturn payload, nil\n}", "func decodeCreateIndustryRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*pb.CreateIndustryRequest)\n\treturn endpoints.CreateIndustryRequest{Industry: models.IndustryToORM(req.Industry)}, nil\n}", "func encodeUserInfoRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treturn &pb.UserInfoRequest{}, nil\n\t// return nil, errors.New(\"'Account' Encoder is not impelemented\")\n}", "func EncryptRequest(cipher Cipher, req interface{}) (*pb.Payload, error) {\n\tres := &pb.Payload{}\n\tjson, err := json.Marshal(req)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not marshal request\")\n\t}\n\tres.Encoded, err = cipher.Encrypt(string(json))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not marshal request\")\n\t}\n\treturn res, nil\n}", "func encodeSigninRequest(_ context.Context, request interface{}) (interface{}, error) {\n\tr := request.(endpoint1.SigninRequest)\n\treturn &pb.SigninRequest{\n\t\tEmail: r.Email,\n\t\tPassword: r.Password}, nil\n}", "func decodeDeleteIndustryRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*pb.DeleteIndustryRequest)\n\treturn endpoints.DeleteIndustryRequest{ID: req.Id}, nil\n}", "func EncodeSigninRequest(encoder func(*http.Request) goahttp.Encoder) func(*http.Request, any) error {\n\treturn func(req *http.Request, v any) error {\n\t\tp, ok := v.(*securedservice.SigninPayload)\n\t\tif !ok {\n\t\t\treturn goahttp.ErrInvalidType(\"secured_service\", \"signin\", \"*securedservice.SigninPayload\", v)\n\t\t}\n\t\treq.SetBasicAuth(p.Username, p.Password)\n\t\treturn nil\n\t}\n}", "func DecodeDoublySecureRequest(mux goahttp.Muxer, decoder func(*http.Request) goahttp.Decoder) func(*http.Request) (any, error) {\n\treturn func(r *http.Request) (any, error) {\n\t\tvar (\n\t\t\tkey string\n\t\t\ttoken string\n\t\t\terr error\n\t\t)\n\t\tkey = r.URL.Query().Get(\"k\")\n\t\tif key == \"\" {\n\t\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"key\", \"query string\"))\n\t\t}\n\t\ttoken = r.Header.Get(\"Authorization\")\n\t\tif token == \"\" {\n\t\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"token\", \"header\"))\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpayload := NewDoublySecurePayload(key, token)\n\t\tif strings.Contains(payload.Token, \" \") {\n\t\t\t// Remove authorization scheme prefix (e.g. \"Bearer\")\n\t\t\tcred := strings.SplitN(payload.Token, \" \", 2)[1]\n\t\t\tpayload.Token = cred\n\t\t}\n\n\t\treturn payload, nil\n\t}\n}", "func EncodeUpdatePasswordRequest(encoder func(*http.Request) goahttp.Encoder) func(*http.Request, interface{}) error {\n\treturn func(req *http.Request, v interface{}) error {\n\t\tp, ok := v.(*user.UpdatePasswordPayload)\n\t\tif !ok {\n\t\t\treturn goahttp.ErrInvalidType(\"User\", \"UpdatePassword\", \"*user.UpdatePasswordPayload\", v)\n\t\t}\n\t\t{\n\t\t\thead := p.Token\n\t\t\tif !strings.Contains(head, \" \") {\n\t\t\t\treq.Header.Set(\"Authorization\", \"Bearer \"+head)\n\t\t\t} else {\n\t\t\t\treq.Header.Set(\"Authorization\", head)\n\t\t\t}\n\t\t}\n\t\tbody := NewUpdatePasswordRequestBody(p)\n\t\tif err := encoder(req).Encode(&body); err != nil {\n\t\t\treturn goahttp.ErrEncodingError(\"User\", \"UpdatePassword\", err)\n\t\t}\n\t\treturn nil\n\t}\n}", "func EncodeUpdateRequest(encoder func(*http.Request) goahttp.Encoder) func(*http.Request, interface{}) error {\n\treturn func(req *http.Request, v interface{}) error {\n\t\tp, ok := v.(*warehouse.UpdatePayload)\n\t\tif !ok {\n\t\t\treturn goahttp.ErrInvalidType(\"Warehouse\", \"Update\", \"*warehouse.UpdatePayload\", v)\n\t\t}\n\t\t{\n\t\t\thead := p.Token\n\t\t\tif !strings.Contains(head, \" \") {\n\t\t\t\treq.Header.Set(\"Authorization\", \"Bearer \"+head)\n\t\t\t} else {\n\t\t\t\treq.Header.Set(\"Authorization\", head)\n\t\t\t}\n\t\t}\n\t\tbody := NewUpdateRequestBody(p)\n\t\tif err := encoder(req).Encode(&body); err != nil {\n\t\t\treturn goahttp.ErrEncodingError(\"Warehouse\", \"Update\", err)\n\t\t}\n\t\treturn nil\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DecodeConfigureRequest is a transport/grpc.DecodeRequestFunc that converts a gRPC configure request to a userdomain configure request. Primarily useful in a server.
func DecodeConfigureRequest(_ context.Context, grpcReq interface{}) (interface{}, error) { req := grpcReq.(*pb.ConfigureRequest) return &endpoints.ConfigureRequest{URL: req.Url, Token: req.Token}, nil }
[ "func DecodeGRPCGetUserConfigRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.GetUserConfigParams)\n\treturn req, nil\n}", "func DecodeGrpcReqEVPNConfig(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*EVPNConfig)\n\treturn req, nil\n}", "func EncodeConfigureRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treq := request.(endpoints.ConfigureRequest)\n\treturn &pb.ConfigureRequest{\n\t\tUrl: req.URL,\n\t\tToken: req.Token,\n\t}, nil\n}", "func DecodeGRPCSetUserConfigRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.SetUserConfigParams)\n\treturn req, nil\n}", "func DecodeGrpcReqConfigurationSnapshotRequest(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*ConfigurationSnapshotRequest)\n\treturn req, nil\n}", "func DecodeGRPCLoginRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.LoginParams)\n\treturn req, nil\n}", "func DecodeRefreshConfigRequest(mux goahttp.Muxer, decoder func(*http.Request) goahttp.Decoder) func(*http.Request) (interface{}, error) {\n\treturn func(r *http.Request) (interface{}, error) {\n\t\tvar (\n\t\t\ttoken string\n\t\t\terr error\n\t\t)\n\t\ttoken = r.Header.Get(\"Authorization\")\n\t\tif token == \"\" {\n\t\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"Authorization\", \"header\"))\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpayload := NewRefreshConfigPayload(token)\n\t\tif strings.Contains(payload.Token, \" \") {\n\t\t\t// Remove authorization scheme prefix (e.g. \"Bearer\")\n\t\t\tcred := strings.SplitN(payload.Token, \" \", 2)[1]\n\t\t\tpayload.Token = cred\n\t\t}\n\n\t\treturn payload, nil\n\t}\n}", "func DecodeWSConfigurationsRequest(ctx context.Context, data interface{}) (interface{}, error) {\n\treq := &pb.ConfigurationsRequest{}\n\terr := proto.Unmarshal(data.([]byte), req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn DecodeGRPCConfigurationsRequest(ctx, req)\n}", "func DecodeGRPCLoginRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.LoginRequest)\n\treturn req, nil\n}", "func DecodeWSGetConfigRequest(ctx context.Context, data interface{}) (interface{}, error) {\n\treq := &pb.GetConfigRequest{}\n\terr := proto.Unmarshal(data.([]byte), req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn DecodeGRPCGetConfigRequest(ctx, req)\n}", "func DecodeGrpcReqPasswordChangeRequest(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*PasswordChangeRequest)\n\treturn req, nil\n}", "func DecodeGrpcReqRoutingConfig(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*RoutingConfig)\n\treturn req, nil\n}", "func DecodeWSRemoveConfigRequest(ctx context.Context, data interface{}) (interface{}, error) {\n\treq := &pb.RemoveConfigRequest{}\n\terr := proto.Unmarshal(data.([]byte), req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn DecodeGRPCRemoveConfigRequest(ctx, req)\n}", "func DecodeChangeRequest(_ context.Context, r *http.Request) (req interface{}, err error) {\n\tt := da.DA{}\n\terr = json.NewDecoder(r.Body).Decode(&t)\n\treq = endpoints.ChangeRequest{Id: mux.Vars(r)[\"id\"], Req: t}\n\treturn req, err\n}", "func DecodeGrpcReqUserPreferenceSpec(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*UserPreferenceSpec)\n\treturn req, nil\n}", "func DecodeInitRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.InitRequest)\n\topts := service.InitOptions{\n\t\tSecretShares: int(req.SecretShares),\n\t\tSecretThreshold: int(req.SecretThreshold),\n\t\tStoredShares: int(req.StoredShares),\n\t\tPGPKeys: req.PgpKeys,\n\t\tRecoveryShares: int(req.RecoveryShares),\n\t\tRecoveryThreshold: int(req.RecoveryThreshold),\n\t\tRecoveryPGPKeys: req.RecoveryPgpKeys,\n\t\tRootTokenPGPKey: req.RootTokenPgpKey,\n\t\tRootTokenHolderEmail: req.RootTokenHolderEmail,\n\t\tSecretKeyHolderEmails: req.SecretKeyHolderEmails,\n\t}\n\treturn &endpoints.InitRequest{Opts: opts}, nil\n}", "func DecodeGrpcReqRoutingConfigSpec(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*RoutingConfigSpec)\n\treturn req, nil\n}", "func DecodeGRPCGetUserInfoRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.GetUserInfoParams)\n\treturn req, nil\n}", "func DecodeGrpcReqUserSpec(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*UserSpec)\n\treturn req, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DecodeConfigureResponse is a transport/grpc.DecodeResponseFunc that converts a gRPC configure reply to a userdomain configure response. Primarily useful in a client.
func DecodeConfigureResponse(_ context.Context, grpcReply interface{}) (interface{}, error) { reply := grpcReply.(*pb.ConfigureResponse) var mounts map[string]endpoints.MountOutput var auths map[string]endpoints.AuthMountOutput var policies []string if reply.ConfigStatus != nil { // mounts if (reply.ConfigStatus.Mounts != nil) && (len(reply.ConfigStatus.Mounts) > 0) { mounts = make(map[string]endpoints.MountOutput) for k, v := range reply.ConfigStatus.Mounts { mountCfgOut := endpoints.MountConfigOutput{ DefaultLeaseTTL: int(v.Config.DefaultLeaseTtl), MaxLeaseTTL: int(v.Config.MaxLeaseTtl), } mountOut := endpoints.MountOutput{ Type: v.Type, Description: v.Description, Config: mountCfgOut, } mounts[k] = mountOut } } // auths if (reply.ConfigStatus.Auths != nil) && (len(reply.ConfigStatus.Auths) > 0) { auths = make(map[string]endpoints.AuthMountOutput) for k, v := range reply.ConfigStatus.Auths { authCfgOut := endpoints.AuthConfigOutput{ DefaultLeaseTTL: int(v.Config.DefaultLeaseTtl), MaxLeaseTTL: int(v.Config.MaxLeaseTtl), } authMountOut := endpoints.AuthMountOutput{ Type: v.Type, Description: v.Description, Config: authCfgOut, } auths[k] = authMountOut } } } // policies if (reply.ConfigStatus.Policies != nil) && (len(reply.ConfigStatus.Policies) > 0) { policies = reply.ConfigStatus.Policies } status := endpoints.ConfigureResponse{ ConfigID: reply.ConfigStatus.ConfigId, Mounts: mounts, Auths: auths, Policies: policies, Err: service.String2Error(reply.Err), } return status, nil }
[ "func DecodeConfigureRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.ConfigureRequest)\n\treturn &endpoints.ConfigureRequest{URL: req.Url, Token: req.Token}, nil\n}", "func DecodeGrpcRespEVPNConfig(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeConfigureResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(endpoints.ConfigureResponse)\n\n\t// mounts\n\tvar mounts map[string]*pb.MountOutput\n\tif (resp.Mounts != nil) && (len(resp.Mounts) > 0) {\n\t\tmounts = make(map[string]*pb.MountOutput)\n\t\tfor k, v := range resp.Mounts {\n\t\t\tmountCfgOut := &pb.MountConfigOutput{\n\t\t\t\tDefaultLeaseTtl: uint32(v.Config.DefaultLeaseTTL),\n\t\t\t\tMaxLeaseTtl: uint32(v.Config.MaxLeaseTTL),\n\t\t\t}\n\n\t\t\tmountOut := &pb.MountOutput{\n\t\t\t\tType: v.Type,\n\t\t\t\tDescription: v.Description,\n\t\t\t\tConfig: mountCfgOut,\n\t\t\t}\n\n\t\t\tmounts[k] = mountOut\n\t\t}\n\t}\n\n\t// auths\n\tvar auths map[string]*pb.AuthMountOutput\n\tif (resp.Auths != nil) && (len(resp.Auths) > 0) {\n\t\tauths = make(map[string]*pb.AuthMountOutput)\n\t\tfor k, v := range resp.Auths {\n\t\t\tauthCfgOut := &pb.AuthConfigOutput{\n\t\t\t\tDefaultLeaseTtl: uint32(v.Config.DefaultLeaseTTL),\n\t\t\t\tMaxLeaseTtl: uint32(v.Config.MaxLeaseTTL),\n\t\t\t}\n\n\t\t\tauthMountOut := &pb.AuthMountOutput{\n\t\t\t\tType: v.Type,\n\t\t\t\tDescription: v.Description,\n\t\t\t\tConfig: authCfgOut,\n\t\t\t}\n\n\t\t\tauths[k] = authMountOut\n\t\t}\n\t}\n\n\t// policies\n\tvar policies []string\n\tif (resp.Policies != nil) && (len(resp.Policies) > 0) {\n\t\tpolicies = resp.Policies\n\t}\n\n\tstatus := &pb.ConfigStatus{\n\t\tConfigId: resp.ConfigID,\n\t\tMounts: mounts,\n\t\tAuths: auths,\n\t\tPolicies: policies,\n\t}\n\treturn &pb.ConfigureResponse{\n\t\tConfigStatus: status,\n\t\tErr: service.Error2String(resp.Err),\n\t}, nil\n}", "func DecodeGrpcRespRoutingConfig(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func ParseReplacechangeaspecificPbxDeviceConfigResponse(rsp *http.Response) (*ReplacechangeaspecificPbxDeviceConfigResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &ReplacechangeaspecificPbxDeviceConfigResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\t}\n\n\treturn response, nil\n}", "func DecodeChangeEmailResponse(ctx context.Context, v interface{}, hdr, trlr metadata.MD) (interface{}, error) {\n\tmessage, ok := v.(*user_methodpb.ChangeEmailResponse)\n\tif !ok {\n\t\treturn nil, goagrpc.ErrInvalidType(\"userMethod\", \"changeEmail\", \"*user_methodpb.ChangeEmailResponse\", v)\n\t}\n\tres := NewChangeEmailResult(message)\n\treturn res, nil\n}", "func DecodeChangePasswordResponse(ctx context.Context, v interface{}, hdr, trlr metadata.MD) (interface{}, error) {\n\tmessage, ok := v.(*user_methodpb.ChangePasswordResponse)\n\tif !ok {\n\t\treturn nil, goagrpc.ErrInvalidType(\"userMethod\", \"changePassword\", \"*user_methodpb.ChangePasswordResponse\", v)\n\t}\n\tres := NewChangePasswordResult(message)\n\treturn res, nil\n}", "func (t *AlterConfigsResponse) Decode(d *Decoder, version int16) error {\n\tvar err error\n\tt.ThrottleTimeMs, err = d.Int32()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Responses\n\tif n, err := d.ArrayLength(); err != nil {\n\t\treturn err\n\t} else if n >= 0 {\n\t\tt.Responses = make([]AlterConfigsResourceResponse33, n)\n\t\tfor i := 0; i < n; i++ {\n\t\t\tvar item AlterConfigsResourceResponse33\n\t\t\tif err := (&item).Decode(d, version); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tt.Responses[i] = item\n\t\t}\n\t}\n\treturn err\n}", "func ParseResponse(mapWrapper *cmap.ConcurrentMap, command model.Command, err error, customResponse *model.CustomResponse) model.CustomResponse {\n\n\tresultWrapper := model.Wrapper{\n\t\tConfigure: model.Configure{\n\t\t\tResponse: command,\n\t\t},\n\t\tResponse: cmap.New(),\n\t}\n\n\tresultWrapper.Response.Set(\"statusCode\", 0)\n\tresultWrapper.Response.Set(\"header\", make(map[string]interface{}))\n\tresultWrapper.Response.Set(\"body\", make(map[string]interface{}))\n\n\t//* now we will set the response body based from configurex.json if there is $configure value in configureBased.\n\n\ttmpHeader := make(map[string]interface{})\n\ttmpBody := make(map[string]interface{})\n\n\tstatusCode := 400\n\tif customResponse != nil {\n\t\tif customResponse.Header != nil {\n\t\t\ttmpHeader = customResponse.Header\n\t\t}\n\t\tif customResponse.Body != nil {\n\t\t\ttmpBody = customResponse.Body\n\t\t}\n\n\t\tif customResponse.StatusCode > 0 {\n\t\t\tstatusCode = customResponse.StatusCode\n\n\t\t} else {\n\t\t\tlog.Warn(\"status code is not defined, set status code to 400\")\n\t\t\t// default\n\t\t\tstatusCode = 400\n\n\t\t}\n\t}\n\n\t// if status code is specified in configure, then set status code based on configure\n\tif command.StatusCode > 0 {\n\t\tstatusCode = command.StatusCode\n\t}\n\n\t//*header\n\ttmpHeader = service.AddToWrapper(resultWrapper.Configure.Response.Adds.Header, \"--\", tmpHeader, mapWrapper, 0)\n\t//*modify header\n\ttmpHeader = service.ModifyWrapper(resultWrapper.Configure.Response.Modifies.Header, \"--\", tmpHeader, mapWrapper, 0)\n\t//*Deletion Header\n\ttmpHeader = service.DeletionHeaderOrQuery(resultWrapper.Configure.Response.Deletes.Header, tmpHeader)\n\n\t//*add\n\ttmpBody = service.AddToWrapper(resultWrapper.Configure.Response.Adds.Body, \"--\", tmpBody, mapWrapper, 0)\n\t//*modify\n\ttmpBody = service.ModifyWrapper(resultWrapper.Configure.Response.Modifies.Body, \"--\", tmpBody, mapWrapper, 0)\n\t//* delete\n\ttmpBody = service.DeletionBody(resultWrapper.Configure.Response.Deletes, tmpBody)\n\n\t//*In case user want to log final response\n\tif len(resultWrapper.Configure.Response.LogAfterModify) > 0 {\n\t\tlogValue := make(map[string]interface{}) // v\n\t\tfor key, val := range resultWrapper.Configure.Response.LogAfterModify {\n\t\t\tlogValue[key] = service.GetFromHalfReferenceValue(val, resultWrapper.Response, 0)\n\t\t}\n\t\t//logValue := service.GetFromHalfReferenceValue(resultWrapper.Configure.Response.LogAfterModify, resultWrapper.Response, 0)\n\t\tutil.DoLoggingJson(logValue, \"after\", \"final response\", false)\n\t}\n\n\tresponse := model.CustomResponse{\n\t\tStatusCode: statusCode,\n\t\tHeader: tmpHeader,\n\t\tBody: tmpBody,\n\t\tError: err,\n\t}\n\n\treturn response\n}", "func DecodeGrpcRespRoutingConfigSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func (e *execPlugin) decodeResponse(data []byte) (*credentialproviderapi.CredentialProviderResponse, error) {\n\tobj, gvk, err := codecs.UniversalDecoder().Decode(data, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif gvk.Kind != \"CredentialProviderResponse\" {\n\t\treturn nil, fmt.Errorf(\"failed to decode CredentialProviderResponse, unexpected Kind: %q\", gvk.Kind)\n\t}\n\n\tif gvk.Group != credentialproviderapi.GroupName {\n\t\treturn nil, fmt.Errorf(\"failed to decode CredentialProviderResponse, unexpected Group: %s\", gvk.Group)\n\t}\n\n\tif internalResponse, ok := obj.(*credentialproviderapi.CredentialProviderResponse); ok {\n\t\treturn internalResponse, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"unable to convert %T to *CredentialProviderResponse\", obj)\n}", "func DecodeGRPCLoginResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.LoginResponse)\n\treturn reply, nil\n}", "func decodeAuthResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\tr, ok := reply.(*pb.AuthReply)\n\tif !ok {\n\t\te := errors.New(\"'AuthReply' Decoder is not impelemented\")\n\t\treturn endpoint1.AuthResponse{Err: e}, e\n\t}\n\treturn endpoint1.AuthResponse{Uuid: r.Uuid, NamespaceID: r.NamespaceID, Roles: r.Roles}, nil\n}", "func ParseChangeaspecificDomainPreferenceResponse(rsp *http.Response) (*ChangeaspecificDomainPreferenceResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &ChangeaspecificDomainPreferenceResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\t}\n\n\treturn response, nil\n}", "func DecodeGrpcRespBGPConfig(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func (t *AlterConfigsResourceResponse44) Decode(d *Decoder, version int16) error {\n\tvar err error\n\tt.ErrorCode, err = d.Int16()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.ErrorMessage, err = d.String()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.ResourceType, err = d.Int8()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.ResourceName, err = d.String()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func DecodeGrpcRespAuthenticationPolicySpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func (client *WebhooksClient) getCallbackConfigHandleResponse(resp *http.Response) (WebhooksClientGetCallbackConfigResponse, error) {\n\tresult := WebhooksClientGetCallbackConfigResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.CallbackConfig); err != nil {\n\t\treturn WebhooksClientGetCallbackConfigResponse{}, err\n\t}\n\treturn result, nil\n}", "func decodeUserInfoResponse(_ context.Context, reply interface{}) (interface{}, error) {\n\tr, ok := reply.(*pb.UserInfoReply)\n\tif !ok {\n\t\te := errors.New(\"pb UserInfoReply type assertion error\")\n\t\treturn nil, e\n\t}\n\treturn endpoint1.UserInfoResponse{Roles: r.Roles, OrgName: r.OrgName}, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
EncodeConfigureResponse is a transport/grpc.EncodeResponseFunc that converts a userdomain configure response to a gRPC configstatus reply. Primarily useful in a server.
func EncodeConfigureResponse(_ context.Context, response interface{}) (interface{}, error) { resp := response.(endpoints.ConfigureResponse) // mounts var mounts map[string]*pb.MountOutput if (resp.Mounts != nil) && (len(resp.Mounts) > 0) { mounts = make(map[string]*pb.MountOutput) for k, v := range resp.Mounts { mountCfgOut := &pb.MountConfigOutput{ DefaultLeaseTtl: uint32(v.Config.DefaultLeaseTTL), MaxLeaseTtl: uint32(v.Config.MaxLeaseTTL), } mountOut := &pb.MountOutput{ Type: v.Type, Description: v.Description, Config: mountCfgOut, } mounts[k] = mountOut } } // auths var auths map[string]*pb.AuthMountOutput if (resp.Auths != nil) && (len(resp.Auths) > 0) { auths = make(map[string]*pb.AuthMountOutput) for k, v := range resp.Auths { authCfgOut := &pb.AuthConfigOutput{ DefaultLeaseTtl: uint32(v.Config.DefaultLeaseTTL), MaxLeaseTtl: uint32(v.Config.MaxLeaseTTL), } authMountOut := &pb.AuthMountOutput{ Type: v.Type, Description: v.Description, Config: authCfgOut, } auths[k] = authMountOut } } // policies var policies []string if (resp.Policies != nil) && (len(resp.Policies) > 0) { policies = resp.Policies } status := &pb.ConfigStatus{ ConfigId: resp.ConfigID, Mounts: mounts, Auths: auths, Policies: policies, } return &pb.ConfigureResponse{ ConfigStatus: status, Err: service.Error2String(resp.Err), }, nil }
[ "func EncodeGRPCGetUserConfigResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(*pb.UserCofing)\n\treturn resp, nil\n}", "func EncodeGRPCSetUserConfigResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(*pb.ErrCode)\n\treturn resp, nil\n}", "func EncodeGrpcRespEVPNConfig(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeRefreshConfigResponse(encoder func(context.Context, http.ResponseWriter) goahttp.Encoder) func(context.Context, http.ResponseWriter, interface{}) error {\n\treturn func(ctx context.Context, w http.ResponseWriter, v interface{}) error {\n\t\tres, _ := v.(*admin.RefreshConfigResult)\n\t\tenc := encoder(ctx, w)\n\t\tbody := NewRefreshConfigResponseBody(res)\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn enc.Encode(body)\n\t}\n}", "func DecodeConfigureResponse(_ context.Context, grpcReply interface{}) (interface{}, error) {\n\treply := grpcReply.(*pb.ConfigureResponse)\n\n\tvar mounts map[string]endpoints.MountOutput\n\tvar auths map[string]endpoints.AuthMountOutput\n\tvar policies []string\n\n\tif reply.ConfigStatus != nil {\n\t\t// mounts\n\t\tif (reply.ConfigStatus.Mounts != nil) && (len(reply.ConfigStatus.Mounts) > 0) {\n\t\t\tmounts = make(map[string]endpoints.MountOutput)\n\t\t\tfor k, v := range reply.ConfigStatus.Mounts {\n\n\t\t\t\tmountCfgOut := endpoints.MountConfigOutput{\n\t\t\t\t\tDefaultLeaseTTL: int(v.Config.DefaultLeaseTtl),\n\t\t\t\t\tMaxLeaseTTL: int(v.Config.MaxLeaseTtl),\n\t\t\t\t}\n\n\t\t\t\tmountOut := endpoints.MountOutput{\n\t\t\t\t\tType: v.Type,\n\t\t\t\t\tDescription: v.Description,\n\t\t\t\t\tConfig: mountCfgOut,\n\t\t\t\t}\n\n\t\t\t\tmounts[k] = mountOut\n\t\t\t}\n\t\t}\n\n\t\t// auths\n\t\tif (reply.ConfigStatus.Auths != nil) && (len(reply.ConfigStatus.Auths) > 0) {\n\t\t\tauths = make(map[string]endpoints.AuthMountOutput)\n\t\t\tfor k, v := range reply.ConfigStatus.Auths {\n\n\t\t\t\tauthCfgOut := endpoints.AuthConfigOutput{\n\t\t\t\t\tDefaultLeaseTTL: int(v.Config.DefaultLeaseTtl),\n\t\t\t\t\tMaxLeaseTTL: int(v.Config.MaxLeaseTtl),\n\t\t\t\t}\n\n\t\t\t\tauthMountOut := endpoints.AuthMountOutput{\n\t\t\t\t\tType: v.Type,\n\t\t\t\t\tDescription: v.Description,\n\t\t\t\t\tConfig: authCfgOut,\n\t\t\t\t}\n\n\t\t\t\tauths[k] = authMountOut\n\t\t\t}\n\t\t}\n\t}\n\n\t// policies\n\tif (reply.ConfigStatus.Policies != nil) && (len(reply.ConfigStatus.Policies) > 0) {\n\t\tpolicies = reply.ConfigStatus.Policies\n\t}\n\n\tstatus := endpoints.ConfigureResponse{\n\t\tConfigID: reply.ConfigStatus.ConfigId,\n\t\tMounts: mounts,\n\t\tAuths: auths,\n\t\tPolicies: policies,\n\t\tErr: service.String2Error(reply.Err),\n\t}\n\n\treturn status, nil\n}", "func EncodeGrpcRespRoutingConfig(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func (t AlterConfigsResponse) Encode(e *Encoder, version int16) {\n\te.PutInt32(t.ThrottleTimeMs) // ThrottleTimeMs\n\t// Responses\n\tlen1 := len(t.Responses)\n\te.PutArrayLength(len1)\n\tfor i := 0; i < len1; i++ {\n\t\tt.Responses[i].Encode(e, version)\n\t}\n}", "func EncodeGrpcRespRoutingConfigSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeGrpcRespBGPConfig(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func (t DescribeConfigsResponse) Encode(e *Encoder, version int16) {\n\te.PutInt32(t.ThrottleTimeMs) // ThrottleTimeMs\n\t// Results\n\tlen1 := len(t.Results)\n\te.PutArrayLength(len1)\n\tfor i := 0; i < len1; i++ {\n\t\tt.Results[i].Encode(e, version)\n\t}\n}", "func EncodeConfigureRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treq := request.(endpoints.ConfigureRequest)\n\treturn &pb.ConfigureRequest{\n\t\tUrl: req.URL,\n\t\tToken: req.Token,\n\t}, nil\n}", "func EncodeOptionsResponse(encoder func(context.Context, http.ResponseWriter) goahttp.Encoder) func(context.Context, http.ResponseWriter, any) error {\n\treturn func(ctx context.Context, w http.ResponseWriter, v any) error {\n\t\tres, _ := v.(*tus.OptionsResult)\n\t\tw.Header().Set(\"Tus-Resumable\", res.TusResumable)\n\t\tw.Header().Set(\"Tus-Version\", res.TusVersion)\n\t\tw.Header().Set(\"Tus-Extension\", res.TusExtension)\n\t\tif res.TusMaxSize != nil {\n\t\t\tval := res.TusMaxSize\n\t\t\ttusMaxSizes := strconv.FormatInt(*val, 10)\n\t\t\tw.Header().Set(\"Tus-Max-Size\", tusMaxSizes)\n\t\t}\n\t\tw.Header().Set(\"Tus-Checksum-Algorithm\", res.TusChecksumAlgorithm)\n\t\tw.WriteHeader(http.StatusNoContent)\n\t\treturn nil\n\t}\n}", "func EncodeGrpcRespRoutingConfigStatus(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeGRPCChangePasswordResponse(_ context.Context, r interface{}) (interface{}, error) {\n\tresp := r.(changePasswordResponse)\n\treturn &pb.ChangePasswordResponse{\n\t\tSuccess: resp.Success,\n\t\tErr: resp.Err,\n\t}, nil\n}", "func (t IncrementalAlterConfigsResponse) Encode(e *Encoder, version int16) {\n\te.PutInt32(t.ThrottleTimeMs) // ThrottleTimeMs\n\t// Responses\n\tlen1 := len(t.Responses)\n\te.PutArrayLength(len1)\n\tfor i := 0; i < len1; i++ {\n\t\tt.Responses[i].Encode(e, version)\n\t}\n}", "func DecodeConfigureRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.ConfigureRequest)\n\treturn &endpoints.ConfigureRequest{URL: req.Url, Token: req.Token}, nil\n}", "func EncodeGrpcRespConfigurationSnapshotSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func EncodeGRPCLogoutResponse(_ context.Context, response interface{}) (interface{}, error) {\n\tresp := response.(*pb.LogoutResponse)\n\treturn resp, nil\n}", "func (o HttpFilterConfigResponseOutput) Config() pulumi.StringOutput {\n\treturn o.ApplyT(func(v HttpFilterConfigResponse) string { return v.Config }).(pulumi.StringOutput)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
EncodeConfigureRequest is a transport/grpc.EncodeRequestFunc that converts a userdomain configure request to a gRPC configure request. Primarily useful in a client.
func EncodeConfigureRequest(_ context.Context, request interface{}) (interface{}, error) { req := request.(endpoints.ConfigureRequest) return &pb.ConfigureRequest{ Url: req.URL, Token: req.Token, }, nil }
[ "func DecodeConfigureRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.ConfigureRequest)\n\treturn &endpoints.ConfigureRequest{URL: req.Url, Token: req.Token}, nil\n}", "func EncodeGrpcReqEVPNConfig(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*EVPNConfig)\n\treturn req, nil\n}", "func (r *AlterConfigsRequest) Encode() []byte {\n\trequestLength := r.length()\n\n\tpayload := make([]byte, requestLength+4)\n\toffset := 0\n\n\tbinary.BigEndian.PutUint32(payload[offset:], uint32(requestLength))\n\toffset += 4\n\n\toffset = r.RequestHeader.Encode(payload, offset)\n\n\tbinary.BigEndian.PutUint32(payload[offset:], uint32(len(r.Resources)))\n\toffset += 4\n\n\tfor _, r := range r.Resources {\n\t\toffset += r.encode(payload[offset:])\n\t}\n\n\treturn payload\n}", "func EncodeRequest(er EncodeRequestFunc) ClientOption {\n\treturn func(c *Client) {\n\t\tc.encode = er\n\t}\n}", "func EncodeGrpcReqRoutingConfig(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*RoutingConfig)\n\treturn req, nil\n}", "func EncodeRefreshConfigRequest(encoder func(*http.Request) goahttp.Encoder) func(*http.Request, interface{}) error {\n\treturn func(req *http.Request, v interface{}) error {\n\t\tp, ok := v.(*admin.RefreshConfigPayload)\n\t\tif !ok {\n\t\t\treturn goahttp.ErrInvalidType(\"admin\", \"RefreshConfig\", \"*admin.RefreshConfigPayload\", v)\n\t\t}\n\t\t{\n\t\t\thead := p.Token\n\t\t\tif !strings.Contains(head, \" \") {\n\t\t\t\treq.Header.Set(\"Authorization\", \"Bearer \"+head)\n\t\t\t} else {\n\t\t\t\treq.Header.Set(\"Authorization\", head)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n}", "func EncodeOrderConfigRequest(encoder func(*http.Request) goahttp.Encoder) func(*http.Request, interface{}) error {\n\treturn func(req *http.Request, v interface{}) error {\n\t\tp, ok := v.(*relayerapi.OrderConfigPayload)\n\t\tif !ok {\n\t\t\treturn goahttp.ErrInvalidType(\"RelayerAPI\", \"orderConfig\", \"*relayerapi.OrderConfigPayload\", v)\n\t\t}\n\t\tbody := NewOrderConfigRequestBody(p)\n\t\tif err := encoder(req).Encode(&body); err != nil {\n\t\t\treturn goahttp.ErrEncodingError(\"RelayerAPI\", \"orderConfig\", err)\n\t\t}\n\t\treturn nil\n\t}\n}", "func EncodeGRPCLoginRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*pb.LoginRequest)\n\treturn req, nil\n}", "func EncodeGrpcReqUserPreferenceSpec(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*UserPreferenceSpec)\n\treturn req, nil\n}", "func EncodeInitRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treq := request.(endpoints.InitRequest)\n\treturn &pb.InitRequest{\n\t\tSecretShares: uint32(req.Opts.SecretShares),\n\t\tSecretThreshold: uint32(req.Opts.SecretThreshold),\n\t\tStoredShares: uint32(req.Opts.StoredShares),\n\t\tPgpKeys: req.Opts.PGPKeys,\n\t\tRecoveryShares: uint32(req.Opts.RecoveryShares),\n\t\tRecoveryThreshold: uint32(req.Opts.RecoveryThreshold),\n\t\tRecoveryPgpKeys: req.Opts.RecoveryPGPKeys,\n\t\tRootTokenPgpKey: req.Opts.RootTokenPGPKey,\n\t\tRootTokenHolderEmail: req.Opts.RootTokenHolderEmail,\n\t\tSecretKeyHolderEmails: req.Opts.SecretKeyHolderEmails,\n\t}, nil\n}", "func DecodeGRPCSetUserConfigRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.SetUserConfigParams)\n\treturn req, nil\n}", "func EncodeGrpcReqRoutingConfigSpec(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*RoutingConfigSpec)\n\treturn req, nil\n}", "func EncodeGrpcReqPasswordChangeRequest(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*PasswordChangeRequest)\n\treturn req, nil\n}", "func EncodeChangeEmailRequest(ctx context.Context, v interface{}, md *metadata.MD) (interface{}, error) {\n\tpayload, ok := v.(*usermethod.ChangeEmailPayload)\n\tif !ok {\n\t\treturn nil, goagrpc.ErrInvalidType(\"userMethod\", \"changeEmail\", \"*usermethod.ChangeEmailPayload\", v)\n\t}\n\t(*md).Append(\"authorization\", payload.Token)\n\treturn NewChangeEmailRequest(payload), nil\n}", "func EncodeGrpcReqAuthenticationPolicySpec(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*AuthenticationPolicySpec)\n\treturn req, nil\n}", "func EncodeGrpcReqUserSpec(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*UserSpec)\n\treturn req, nil\n}", "func (e *execPlugin) encodeRequest(request *credentialproviderapi.CredentialProviderRequest) ([]byte, error) {\n\tdata, err := runtime.Encode(e.encoder, request)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error encoding request: %w\", err)\n\t}\n\n\treturn data, nil\n}", "func EncodeGrpcReqBGPConfig(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*BGPConfig)\n\treturn req, nil\n}", "func EncodeGrpcReqConfigurationSnapshotSpec(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*ConfigurationSnapshotSpec)\n\treturn req, nil\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
join appends a bunch of Go Code together, each on their own line.
func join(s []jen.Code) *jen.Statement { r := jen.Empty() for i, stmt := range s { if i > 0 { r.Line() } r.Add(stmt) } return r }
[ "func join(sep string, a ...string) string {\n\tswitch len(a) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn a[0]\n\t}\n\n\tres := bytes.NewBufferString(a[0])\n\tfor _, s := range a[1:] {\n\t\tres.WriteString(sep + s)\n\t}\n\n\treturn res.String()\n}", "func (ob StringsModule) Join(a []string, sep string) string {\n\treturn _strings.Join(a, sep)\n}", "func Join(parts ...[]byte) []byte {\n\tvar b bytes.Buffer\n\n\tvar lastIsNewLine bool\n\tfor _, p := range parts {\n\t\tif len(p) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif b.Len() != 0 {\n\t\t\tif !lastIsNewLine {\n\t\t\t\t_, _ = b.WriteString(\"\\n\")\n\t\t\t}\n\t\t\tb.WriteString(yamlSeparator)\n\t\t}\n\t\t_, _ = b.Write(p)\n\t\ts := string(p)\n\t\tlastIsNewLine = s[len(s)-1] == '\\n'\n\t}\n\n\treturn b.Bytes()\n}", "func join(a string, b string, separator string) string {\n\tvals := make([]byte, 0, 10)\n\tvals = append(vals, a...)\n\tvals = append(vals, separator...)\n\tvals = append(vals, b...)\n\treturn string(vals)\n}", "func Join(sep string, strs ...string) string {\n\tvar buf bytes.Buffer\n\tif len(strs) == 0 {\n\t\treturn \"\"\n\t}\n\tfor _, str := range strs {\n\t\tbuf.WriteString(str + sep)\n\t}\n\treturn strings.TrimRight(buf.String(), sep)\n}", "func Join(s []string, sep string) string {\n\tvar buf string\n\tfor _, v := range s[:len(s)-1] {\n\t\tbuf += fmt.Sprintf(\"%s%s\", v, sep)\n\t}\n\n\tbuf += s[len(s)-1]\n\treturn buf\n}", "func Join(a []string, sep string) string", "func JoinLines(lines []string) string {\n\treturn strings.Join(lines, string(newline))\n}", "func joinLits(a []*ast.BasicLit, sep string) string {\n\ts := make([]string, len(a))\n\tfor i := range a {\n\t\ts[i] = a[i].Value\n\t}\n\treturn strings.Join(s, sep)\n}", "func join(fields []string) string {\n\tvar b strings.Builder\n\tc := csv.NewWriter(&b)\n\terr := c.Write(fields)\n\tif err != nil {\n\t\tpanic(err) // this ideally shouldn't happen!\n\t}\n\tc.Flush()\n\treturn strings.TrimSpace(b.String())\n}", "func JOIN(content ...*Buffer) *Buffer {\n\tretBuf := NewBuffer(64)\n\tfor _, buf := range content {\n\t\tretBuf.Write(buf)\n\t}\n\treturn &retBuf\n}", "func Join[T any](tt []T) string {\n\tvar str []string\n\tfor _, t := range tt {\n\t\tstr = append(str, fmt.Sprintf(\"%v\", t))\n\t}\n\n\treturn strings.Join(str, \", \")\n}", "func Join(sep string, parts ...string) string {\n\treturn strings.Join(parts, sep)\n}", "func Join(inputs interface{}, separator interface{}) Generator {\n\treturn func(c *Context) interface{} {\n\t\tif c == nil {\n\t\t\tc = NewContext()\n\t\t}\n\t\tsep, ok := toStr(c, separator)\n\t\tif !ok {\n\t\t\tpanic(\"separator must be or generate a string\")\n\t\t}\n\t\txs := expand(c, inputs)\n\t\tys, ok := xs.([]string)\n\t\tif !ok {\n\t\t\tpanic(\"inputs must be or generate a slice of string\")\n\t\t}\n\t\treturn strings.Join(ys, sep)\n\t}\n}", "func (nc NamingContext) Join() string {\n\treturn strings.Join(nc, \"\")\n}", "func JoinAll(a []interface{}, sep string) string {\n\tif len(a) == 0 {\n\t\treturn \"\"\n\t}\n\tif len(a) == 1 {\n\t\treturn fmt.Sprint(a[0])\n\t}\n\n\tbuffer := &bytes.Buffer{}\n\tbuffer.WriteString(fmt.Sprint(a[0]))\n\tfor i := 1; i < len(a); i++ {\n\t\tbuffer.WriteString(sep)\n\t\tbuffer.WriteString(fmt.Sprint(a[i]))\n\t}\n\treturn buffer.String()\n}", "func (lss *ListStrings) Join(lsep string, ssep string) (s string) {\n\tlsslen := len(*lss) - 1\n\n\tfor x, ls := range *lss {\n\t\ts += strings.Join(ls, ssep)\n\n\t\tif x < lsslen {\n\t\t\ts += lsep\n\t\t}\n\t}\n\treturn\n}", "func Join(sep string, operand []string) string { return strings.Join(operand, sep) }", "func (array Array) Join(separator string) string {\n\tstr := fmt.Sprint()\n\tfor i, v := range array {\n\t\tstr += fmt.Sprintf(\"%v\", v)\n\t\tif i != len(array) - 1 {\n\t\t\tstr += fmt.Sprintf(\"%s\", separator)\n\t\t}\n\t}\n\treturn str\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
packageName returns the name of the package for the property to be generated.
func (p *PropertyGenerator) packageName() string { return p.Package }
[ "func (s Settings) PackageName() string {\n\treturn naming.SnakeCase(s.packageName)\n}", "func (m Model) PackageName() string {\n\treturn path.Base(m.Path)\n}", "func (c *common) PackageName() string { return uniquePackageOf(c.file) }", "func (g *Generator) DefaultPackageName(obj Object) string {\n\tpkg := obj.PackageName()\n\tif pkg == g.packageName {\n\t\treturn \"\"\n\t}\n\treturn pkg + \".\"\n}", "func goPackageName(pkg *protoPackage) string {\n\tif opt, ok := pkg.options[\"go_package\"]; ok {\n\t\tif i := strings.IndexByte(opt, ';'); i >= 0 {\n\t\t\treturn opt[i+1:]\n\t\t} else if i := strings.LastIndexByte(opt, '/'); i >= 0 {\n\t\t\treturn opt[i+1:]\n\t\t} else {\n\t\t\treturn opt\n\t\t}\n\t}\n\tif pkg.name != \"\" {\n\t\treturn strings.Replace(pkg.name, \".\", \"_\", -1)\n\t}\n\tif len(pkg.files) == 1 {\n\t\tfor s := range pkg.files {\n\t\t\treturn strings.TrimSuffix(s, \".proto\")\n\t\t}\n\t}\n\treturn \"\"\n}", "func (g *Generator) DefaultPackageName(obj ProtoObject) string {\n\tpkg := obj.PackageName()\n\tif pkg == g.packageName {\n\t\treturn \"\"\n\t}\n\treturn pkg + \".\"\n}", "func (p *Package) PkgName() string { return p.Name }", "func (fn *Function) PackageName() string {\n\tinst := fn.instRange()\n\treturn packageName(fn.Name[:inst[0]])\n}", "func getPackageName(datatypeName string) string {\n\tparts := strings.Split(datatypeName, \".\")\n\tif len(parts) == 1 {\n\t\treturn \"\" // no package name\n\t}\n\n\toffset := 0\n\tfor i, p := range parts {\n\t\tif unicode.IsUpper(rune(p[0])) {\n\t\t\tbreak\n\t\t}\n\n\t\toffset += len(p)\n\t\tif i > 0 {\n\t\t\toffset += 1 // also account for the '.'\n\t\t}\n\t}\n\n\treturn datatypeName[:offset]\n}", "func (e EnumSQLBuilder) PackageName() string {\n\treturn path.Base(e.Path)\n}", "func (g *Graph) PackageName() string {\n\ti := strings.LastIndex(g.PackagePath, \"/\")\n\tif i < 0 {\n\t\treturn g.PackagePath\n\t}\n\treturn g.PackagePath[i+1:]\n}", "func (project Project) Package() (string, error) {\n\n\tif project.packageName != \"\" {\n\t\treturn project.packageName, nil\n\t}\n\n\tgoModPath := project.RelPath(GoModFileName)\n\tif !project.FileExists(goModPath) {\n\t\treturn \"\", errors.New(\"Failed to determine the package name for this project\")\n\t}\n\n\tb, err := ioutil.ReadFile(goModPath)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"Failed to read the go.mod file\")\n\t}\n\n\tmod, err := gomod.Parse(goModPath, b)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"Failed to parse the go.mod file\")\n\t}\n\n\tproject.packageName = strings.TrimSuffix(mod.Name, \"/\")\n\n\treturn project.packageName, nil\n\n}", "func GoPackageTypeName(t design.DataType, versioned bool, defPkg string, tabs int) string {\n\tswitch actual := t.(type) {\n\tcase design.Primitive:\n\t\treturn GoNativeType(t)\n\tcase *design.Array:\n\t\treturn \"[]\" + GoPackageTypeRef(actual.ElemType.Type, versioned, defPkg, tabs+1)\n\tcase design.Object:\n\t\treturn GoTypeDef(&design.AttributeDefinition{Type: actual}, versioned, defPkg, tabs, false, false)\n\tcase *design.Hash:\n\t\treturn fmt.Sprintf(\n\t\t\t\"map[%s]%s\",\n\t\t\tGoPackageTypeRef(actual.KeyType.Type, versioned, defPkg, tabs+1),\n\t\t\tGoPackageTypeRef(actual.ElemType.Type, versioned, defPkg, tabs+1),\n\t\t)\n\tcase *design.UserTypeDefinition:\n\t\tpkgPrefix := PackagePrefix(actual, versioned, defPkg)\n\t\treturn pkgPrefix + Goify(actual.TypeName, true)\n\tcase *design.MediaTypeDefinition:\n\t\tpkgPrefix := PackagePrefix(actual.UserTypeDefinition, versioned, defPkg)\n\t\treturn pkgPrefix + Goify(actual.TypeName, true)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"goa bug: unknown type %#v\", actual))\n\t}\n}", "func externalPackageName(opts *options) string {\n\treturn strings.ReplaceAll(filepath.Base(opts.DefPath), \".\", \"\")\n}", "func (loc *Location) PackageName() string {\n\tif loc == nil {\n\t\treturn \"\"\n\t}\n\treturn Goify(filepath.Base(loc.RelImportPath), false)\n}", "func (t *Template) PackageName() (string, error) {\n\tpath, err := filepath.Abs(t.Path)\n\tif err != nil {\n\t\treturn \"\", ErrUnidentifiablePackage\n\t}\n\n\t// split the path by file separator, rip the first one off (it's always blank)\n\t// and then grab the last one\n\tparts := strings.Split(path, string(filepath.Separator))\n\tparts = parts[1:]\n\tif len(parts) < 2 {\n\t\treturn \"\", ErrUnidentifiablePackage\n\t}\n\treturn parts[len(parts)-2], nil\n}", "func PackageName(d *pdl.Domain) string {\n\treturn strings.ToLower(d.Domain.String())\n}", "func generatePackageName(fnName string, id string) string {\n\tvar (\n\t\tlenFnName int = len(fnName)\n\t\tlenId int = len(id)\n\t\tlastIndexOfChar int\n\t)\n\tif lenFnName+lenId <= 62 {\n\t\treturn fmt.Sprintf(\"%s-%s\", fnName, id)\n\t}\n\n\tlastIndexOfChar = lenFnName - (lenFnName + lenId - 62)\n\tpkgName := fmt.Sprintf(\"%v-%s\", fnName[:lastIndexOfChar], id)\n\tconsole.Info(fmt.Sprintf(\"Generated package %s from function to acceptable character limit\", pkgName))\n\treturn pkgName\n}", "func goPackageName(d *descriptor.FileDescriptorProto) (name string, explicit bool) {\n\t// Does the file have a \"go_package\" option?\n\tif _, pkg, ok := goPackageOption(d); ok {\n\t\treturn pkg, true\n\t}\n\n\t// Does the file have a package clause?\n\tif pkg := d.GetPackage(); pkg != \"\" {\n\t\treturn pkg, false\n\t}\n\t// Use the file base name.\n\treturn baseName(d.GetName()), false\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
StructName returns the name of the type, which may or may not be a struct, to generate.
func (p *PropertyGenerator) StructName() string { if p.asIterator { return p.Name.CamelName } return fmt.Sprintf("%sProperty", p.Name.CamelName) }
[ "func (b *Builder) GetStructName() string {\n\treturn b.name\n}", "func structName(entry *yang.Entry, forList bool) (string, error) {\n\tname, ok := entry.Annotation[\"structname\"]\n\tif !ok {\n\t\treturn \"\", status.Errorf(codes.NotFound, \"structname not found in annotations\")\n\t}\n\tif entry.IsList() && forList {\n\t\tkeys, err := listKeys(entry)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\t// if the entry is a list and we are targeting the container\n\t\t// NOTE we still need to support composite keys\n\t\treturn fmt.Sprintf(\"map[%s]*%s\", keys[0].Gotype, name), nil\n\t}\n\treturn fmt.Sprintf(\"*%s\", name), nil\n}", "func StructName(tableName string) string {\n\treturn strings.Title(strings.ReplaceAll(tableName, \"_\", \"\"))\n}", "func StructOrFuncName(obj interface{}) string {\n\tv := ValueOf(obj)\n\tvar t reflect.Type\n\tif v.Kind() != reflect.Invalid {\n\t\tt = v.Type()\n\t} else {\n\t\tt = TypeOf(obj)\n\t}\n\tvar name string\n\tswitch t.Kind() {\n\tcase reflect.Func:\n\t\tname = runtime.FuncForPC(v.Pointer()).Name()\n\tcase reflect.Struct:\n\t\tname = strings.Join([]string{t.PkgPath(), t.Name()}, \".\")\n\tdefault:\n\t\treturn \"\"\n\t}\n\treturn name[strings.LastIndex(name, \"/\")+1:]\n}", "func (st *StructValue) GetNameOfStruct(str interface{}) string {\n\tvar structName string\n\ttyp := reflect.TypeOf(str)\n\n\tswitch typ.Kind() {\n\tcase reflect.Struct:\n\t\tstructName = typ.Name()\n\tcase reflect.Ptr:\n\t\tstructName = typ.Elem().Name() // if type is ptr you must get Elem first\n\t}\n\n\treturn structName\n}", "func (s StructType) String() string {\n\tswitch s {\n\tcase StructTypeStruct:\n\t\treturn \"struct\"\n\tcase StructTypeException:\n\t\treturn \"exception\"\n\tcase StructTypeUnion:\n\t\treturn \"union\"\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unknown struct type %d\", s))\n\t}\n}", "func (s *MyStruct) Name() string {\n\treturn s.field_Name\n}", "func StructTypeString(t *dwarf.StructType,) string", "func (st SignatureType) Name() string {\n\treturn string(st)\n}", "func (t *StructType) String() string {\n\tif len(t.TypeName) > 0 {\n\t\treturn enc.TypeName(t.TypeName)\n\t}\n\treturn t.LLString()\n}", "func (t *Type) StructType() *StructType", "func (obj *object) getStructName(line string) {\n\t/*nested := false\n\tif !strings.Contains(line, \"type \") {\n\t\tnested = true\n\t}*/\n\n\tline = strings.TrimSpace(line)\n\tline = strings.TrimPrefix(strings.TrimSuffix(line, \"{\"), \"type\")\n\tline = strings.TrimSpace(line)\n\tobj.Name = strings.TrimSpace(strings.TrimSuffix(line, \"struct\"))\n\tif strings.Contains(obj.Name, \"[]\") {\n\t\tobj.Name = strings.TrimSpace(strings.TrimSuffix(obj.Name, \"[]\"))\n\t}\n\tobj.Tp = obj.Name\n\tobj.JsonKey = obj.Name\n\t/*if nested {\n\t\tobj.CommonFileds = append(obj.CommonFileds, &field{JsonKey: obj.Name, Tp: obj.Name})\n\t}*/\n}", "func StructTypeDefn(t *dwarf.StructType,) string", "func (t *SentryTaggedStruct) GetName() string {\n\treturn \"\"\n}", "func (t *Table) StructArgName() string {\n\tif t.structArgName == \"\" {\n\t\tt.structArgName = stringx.From(t.StructName()).Untitle()\n\t\tif token.IsKeyword(t.structArgName) {\n\t\t\tt.structArgName = t.structArgName + \"1\"\n\t\t}\n\t}\n\treturn t.structArgName\n}", "func (t *TypeSpecDef) Name() string {\n\tif t.TypeSpec != nil {\n\t\treturn t.TypeSpec.Name.Name\n\t}\n\n\treturn \"\"\n}", "func bindStructTypeGo(kind abi.Type, structs map[string]*tmplStruct) string {\n\tswitch kind.T {\n\tcase abi.TupleTy:\n\t\t// We compose a raw struct name and a canonical parameter expression\n\t\t// together here. The reason is before solidity v0.5.11, kind.TupleRawName\n\t\t// is empty, so we use canonical parameter expression to distinguish\n\t\t// different struct definition. From the consideration of backward\n\t\t// compatibility, we concat these two together so that if kind.TupleRawName\n\t\t// is not empty, it can have unique id.\n\t\tid := kind.TupleRawName + kind.String()\n\t\tif s, exist := structs[id]; exist {\n\t\t\treturn s.Name\n\t\t}\n\t\tvar (\n\t\t\tnames = make(map[string]bool)\n\t\t\tfields []*tmplField\n\t\t)\n\t\tfor i, elem := range kind.TupleElems {\n\t\t\tname := capitalise(kind.TupleRawNames[i])\n\t\t\tname = abi.ResolveNameConflict(name, func(s string) bool { return names[s] })\n\t\t\tnames[name] = true\n\t\t\tfields = append(fields, &tmplField{Type: bindStructTypeGo(*elem, structs), Name: name, SolKind: *elem})\n\t\t}\n\t\tname := kind.TupleRawName\n\t\tif name == \"\" {\n\t\t\tname = fmt.Sprintf(\"Struct%d\", len(structs))\n\t\t}\n\t\tname = capitalise(name)\n\n\t\tstructs[id] = &tmplStruct{\n\t\t\tName: name,\n\t\t\tFields: fields,\n\t\t}\n\t\treturn name\n\tcase abi.ArrayTy:\n\t\treturn fmt.Sprintf(\"[%d]\", kind.Size) + bindStructTypeGo(*kind.Elem, structs)\n\tcase abi.SliceTy:\n\t\treturn \"[]\" + bindStructTypeGo(*kind.Elem, structs)\n\tdefault:\n\t\treturn bindBasicTypeGo(kind)\n\t}\n}", "func SignatureStringOfStruct(prgrm *CXProgram, s *CXStruct) string {\n\tfields := \"\"\n\tfor _, typeSignatureIdx := range s.Fields {\n\t\ttypeSignature := prgrm.GetCXTypeSignatureFromArray(typeSignatureIdx)\n\t\tfields += fmt.Sprintf(\" %s %s;\", typeSignature.Name, GetFormattedType(prgrm, typeSignature))\n\t}\n\n\treturn fmt.Sprintf(\"%s struct {%s }\", s.Name, fields)\n}", "func (*StringSchema) GetName() string {\n\treturn typeString\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
deserializeFnName returns the identifier of the function that deserializes raw JSON into the generated Go type.
func (p *PropertyGenerator) deserializeFnName() string { if p.asIterator { return fmt.Sprintf("%s%s", deserializeIteratorMethod, p.Name.CamelName) } return fmt.Sprintf("%s%sProperty", deserializeMethod, p.Name.CamelName) }
[ "func (p *PropertyGenerator) serializeFnName() string {\n\tif p.asIterator {\n\t\treturn serializeIteratorMethod\n\t}\n\treturn serializeMethod\n}", "func (s *Instruction) FuncName() string {\n\tif name, ok := protoNameToFuncName[s.Protobuf.TypeName]; ok {\n\t\treturn name\n\t}\n\treturn \"?\"\n}", "func (f DeserializeFunc) Deserialize(r io.Reader) error {\n\treturn f(r)\n}", "func JSONTagNameFunc(fld reflect.StructField) string {\n\tname := strings.SplitN(fld.Tag.Get(\"json\"), \",\", 2)[0]\n\n\t// if there is no defined json tag or the tag is to be skipped fall back to the field name\n\tif name == \"\" || name == \"-\" {\n\t\treturn fld.Name\n\t}\n\n\treturn name\n}", "func (o AzureFunctionOutputDataSourceResponseOutput) FunctionName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AzureFunctionOutputDataSourceResponse) *string { return v.FunctionName }).(pulumi.StringPtrOutput)\n}", "func identifier(options SerializerOptions) runtime.Identifier {\n\tresult := map[string]string{\n\t\t\"name\": \"json\",\n\t\t\"yaml\": strconv.FormatBool(options.Yaml),\n\t\t\"pretty\": strconv.FormatBool(options.Pretty),\n\t}\n\tidentifier, err := json.Marshal(result)\n\tif err != nil {\n\t\tklog.Fatalf(\"Failed marshaling identifier for json Serializer: %v\", err)\n\t}\n\treturn runtime.Identifier(identifier)\n}", "func (v *Function) Decode(sr stream.Reader) error {\n\n\tnameIsSet := false\n\tthriftNameIsSet := false\n\targumentsIsSet := false\n\n\tif err := sr.ReadStructBegin(); err != nil {\n\t\treturn err\n\t}\n\n\tfh, ok, err := sr.ReadFieldBegin()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor ok {\n\t\tswitch {\n\t\tcase fh.ID == 1 && fh.Type == wire.TBinary:\n\t\t\tv.Name, err = sr.ReadString()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnameIsSet = true\n\t\tcase fh.ID == 2 && fh.Type == wire.TBinary:\n\t\t\tv.ThriftName, err = sr.ReadString()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tthriftNameIsSet = true\n\t\tcase fh.ID == 3 && fh.Type == wire.TList:\n\t\t\tv.Arguments, err = _List_Argument_Decode(sr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\targumentsIsSet = true\n\t\tcase fh.ID == 4 && fh.Type == wire.TStruct:\n\t\t\tv.ReturnType, err = _Type_Decode(sr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase fh.ID == 5 && fh.Type == wire.TList:\n\t\t\tv.Exceptions, err = _List_Argument_Decode(sr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase fh.ID == 6 && fh.Type == wire.TBool:\n\t\t\tvar x bool\n\t\t\tx, err = sr.ReadBool()\n\t\t\tv.OneWay = &x\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase fh.ID == 7 && fh.Type == wire.TMap:\n\t\t\tv.Annotations, err = _Map_String_String_Decode(sr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tdefault:\n\t\t\tif err := sr.Skip(fh.Type); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tif err := sr.ReadFieldEnd(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif fh, ok, err = sr.ReadFieldBegin(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := sr.ReadStructEnd(); err != nil {\n\t\treturn err\n\t}\n\n\tif !nameIsSet {\n\t\treturn errors.New(\"field Name of Function is required\")\n\t}\n\n\tif !thriftNameIsSet {\n\t\treturn errors.New(\"field ThriftName of Function is required\")\n\t}\n\n\tif !argumentsIsSet {\n\t\treturn errors.New(\"field Arguments of Function is required\")\n\t}\n\n\treturn nil\n}", "func (f *Field) Name() string {\n\tjsonTag := reflect.StructTag(f.Tag.Value[1 : len(f.Tag.Value)-1]).Get(\"json\") // Delete first and last quotation\n\tjsonTag = strings.Split(jsonTag, \",\")[0] // This can return \"-\"\n\tif jsonTag != \"\" {\n\t\treturn jsonTag\n\t}\n\n\tif f.Names != nil {\n\t\treturn f.Names[0].Name\n\t}\n\n\treturn f.Type.(*ast.Ident).Name\n}", "func nameOf(t *testing.T, f interface{}) string {\n\tt.Helper()\n\n\tv := reflect.ValueOf(f)\n\tif v.Kind() != reflect.Func {\n\t\tt.Fatalf(\"%v is not a function\", f)\n\t}\n\n\trf := runtime.FuncForPC(v.Pointer())\n\tif rf == nil {\n\t\tt.Fatalf(\"%v.Pointer() is not a known function\", f)\n\t}\n\n\tfullName := rf.Name()\n\tparts := strings.Split(fullName, \".\")\n\n\tname := parts[len(parts)-1]\n\tif !token.IsIdentifier(name) {\n\t\tt.Fatalf(\"%q is not a valid identifier\", name)\n\t}\n\treturn name\n}", "func GetName(functionType uint64) string {\n\tvar s string\n\n\tfor i := uint(0); i < 8; i++ {\n\t\tt := (functionType >> (_BFF_MAX_SHIFT - _BFF_ONE_SHIFT*i)) & _BFF_MASK\n\n\t\tif t == NONE_TYPE {\n\t\t\tcontinue\n\t\t}\n\n\t\tname := getByteFunctionNameToken(t)\n\n\t\tif len(s) != 0 {\n\t\t\ts += \"+\"\n\t\t}\n\n\t\ts += name\n\t}\n\n\tif len(s) == 0 {\n\t\ts += getByteFunctionNameToken(NONE_TYPE)\n\t}\n\n\treturn s\n}", "func (d *Decoder) NameFunc(n func(field string, locations []int) string) {\n\td.cache.nameFunc = n\n}", "func (Functions) ProtoName(obj interface{}) string {\n\treturn nameOptions{}.convert(nameOf(obj))\n}", "func (nodeLog *NodeLog) jsonFieldName(fieldName string) string {\n\trt := reflect.TypeOf(*nodeLog)\n\tfield, _ := rt.FieldByName(fieldName)\n\treturn field.Tag.Get(\"json\")\n}", "func (o FunctionEventInvokeConfigOutput) FunctionName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *FunctionEventInvokeConfig) pulumi.StringOutput { return v.FunctionName }).(pulumi.StringOutput)\n}", "func (f Function) GetName() string {\n\treturn f.ident.String()\n}", "func nameOfFunction(f interface{}) string {\n\tfun := runtime.FuncForPC(reflect.ValueOf(f).Pointer())\n\ttokenized := strings.Split(fun.Name(), \".\")\n\tlast := tokenized[len(tokenized)-1]\n\tlast = strings.TrimSuffix(last, \")·fm\") // < Go 1.5\n\tlast = strings.TrimSuffix(last, \")-fm\") // Go 1.5\n\tlast = strings.TrimSuffix(last, \"·fm\") // < Go 1.5\n\tlast = strings.TrimSuffix(last, \"-fm\") // Go 1.5\n\tif last == \"func1\" { // this could mean conflicts in API docs\n\t\tval := atomic.AddInt32(&anonymousFuncCount, 1)\n\t\tlast = \"func\" + fmt.Sprintf(\"%d\", val)\n\t\tatomic.StoreInt32(&anonymousFuncCount, val)\n\t}\n\treturn last\n}", "func decodeUserFn(ref *v1pb.UserFn) (any, error) {\n\tt, err := decodeType(ref.GetType())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn runtime.ResolveFunction(ref.Name, t)\n}", "func getFieldName(f reflect.StructField) string {\n\tn := f.Name\n\ttag, found := f.Tag.Lookup(\"json\")\n\tif found {\n\t\t// If we have a json field, and the first part of it before the\n\t\t// first comma is non-empty, that's our field name.\n\t\tparts := strings.Split(tag, \",\")\n\t\tif parts[0] != \"\" {\n\t\t\tn = parts[0]\n\t\t}\n\t}\n\treturn n\n}", "func userTypeUnmarshalerFuncName(u *design.UserTypeDefinition) string {\n\treturn fmt.Sprintf(\"Unmarshal%s\", GoTypeName(u, 0))\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getFnName returns the identifier of the function that fetches concrete types of the property.
func (p *PropertyGenerator) getFnName(i int) string { if len(p.Kinds) == 1 { return getMethod } return fmt.Sprintf("%s%s", getMethod, p.kindCamelName(i)) }
[ "func getFunctionName(fn interface{}) string {\n\treturn runtime.FuncForPC(reflect.ValueOf((fn)).Pointer()).Name()\n}", "func GetFunctionName(i interface{}) string {\n\tname := runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()\n\tsplit := strings.Split(name, \".\")\n\treturn split[len(split)-1]\n}", "func GetFuncName(i interface{}) string {\n\tfullName := runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()\n\tsplitName := strings.Split(fullName, \".\")\n\treturn splitName[len(splitName)-1]\n}", "func GetFunctionName(i interface{}) string {\n\treturn runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()\n}", "func (p *PropertyGenerator) deserializeFnName() string {\n\tif p.asIterator {\n\t\treturn fmt.Sprintf(\"%s%s\", deserializeIteratorMethod, p.Name.CamelName)\n\t}\n\treturn fmt.Sprintf(\"%s%sProperty\", deserializeMethod, p.Name.CamelName)\n}", "func getFunctionName(i interface{}) string {\n\tpcIdentifier := runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()\n\tbaseName := filepath.Base(pcIdentifier)\n\tparts := strings.SplitN(baseName, \".\", 2)\n\tif len(parts) <= 1 {\n\t\treturn parts[0]\n\t}\n\n\treturn parts[1]\n}", "func (d DocLanguageHelper) GetPropertyName(p *schema.Property) (string, error) {\n\treturn PyName(p.Name), nil\n}", "func NameOfFunc(fn interface{}) string {\n\treturn runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name()\n}", "func getterName(typeName string) string {\n\treturn fmt.Sprintf(\"Get%s\", accessorName(typeName))\n}", "func GetFuncName(f interface{}) string {\n\treturn runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()\n}", "func nameOf(t *testing.T, f interface{}) string {\n\tt.Helper()\n\n\tv := reflect.ValueOf(f)\n\tif v.Kind() != reflect.Func {\n\t\tt.Fatalf(\"%v is not a function\", f)\n\t}\n\n\trf := runtime.FuncForPC(v.Pointer())\n\tif rf == nil {\n\t\tt.Fatalf(\"%v.Pointer() is not a known function\", f)\n\t}\n\n\tfullName := rf.Name()\n\tparts := strings.Split(fullName, \".\")\n\n\tname := parts[len(parts)-1]\n\tif !token.IsIdentifier(name) {\n\t\tt.Fatalf(\"%q is not a valid identifier\", name)\n\t}\n\treturn name\n}", "func GetPropName(Type int32) (name string) {\n\tif v := GetProp(Type); v != nil {\n\t\tname = v.Name\n\t}\n\treturn\n}", "func (p *PropertyGenerator) serializeFnName() string {\n\tif p.asIterator {\n\t\treturn serializeIteratorMethod\n\t}\n\treturn serializeMethod\n}", "func (f Function) GetName() string {\n\treturn f.ident.String()\n}", "func (Functions) NameOf(obj interface{}) string {\n\treturn nameOf(obj)\n}", "func GetFuncName(f interface{}) string {\n\tfullFuncName := runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()\n\tpaths := strings.Split(fullFuncName, \"/\")\n\tparts := strings.SplitN(paths[len(paths)-1], \".\", 2)\n\treturn re.ReplaceAllString(parts[1], \"\")\n}", "func GetName(functionType uint64) string {\n\tvar s string\n\n\tfor i := uint(0); i < 8; i++ {\n\t\tt := (functionType >> (_BFF_MAX_SHIFT - _BFF_ONE_SHIFT*i)) & _BFF_MASK\n\n\t\tif t == NONE_TYPE {\n\t\t\tcontinue\n\t\t}\n\n\t\tname := getByteFunctionNameToken(t)\n\n\t\tif len(s) != 0 {\n\t\t\ts += \"+\"\n\t\t}\n\n\t\ts += name\n\t}\n\n\tif len(s) == 0 {\n\t\ts += getByteFunctionNameToken(NONE_TYPE)\n\t}\n\n\treturn s\n}", "func (d DocLanguageHelper) GetPropertyName(p *schema.Property) (string, error) {\n\treturn p.Name, nil\n}", "func (p *PropertyGenerator) setFnName(i int) string {\n\tif len(p.Kinds) == 1 {\n\t\treturn setMethod\n\t}\n\treturn fmt.Sprintf(\"%s%s\", setMethod, p.kindCamelName(i))\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }