# Port.tcl --
#
#	Tksu procedures to handle the port dialog window.
#
# Copyright (C) 2002 Henry Thorson Consulting.  All rights reserved.
#
# This program is licensed under the terms of the GNU General Public License,
# version 2 (or any later version).  See the file `COPYING' for full details,
# and for a DISCLAIMER OF ALL WARRANTIES.
#
# CVS: $Id: Port.tcl,v 1.1.1.1 2002/06/07 23:43:30 jeff Exp $

#-------------------------------------------------------------------------------
# CreatePortDialog -- create port dialog.
#
# Args:     instance	Instance number of parameter list window.
# Returns:  null
#
# The parameter and port dialogs share the space below the parameter listbox
# in the parameter list window.
#-------------------------------------------------------------------------------

proc tksu::CreatePortDialog instance {
    variable PortAction

# Variable PortAction($instance) is referenced by the radio buttons.
# It may take on the values {pipe file temp}.

    set PortAction($instance) pipe
    set bwid 5
    set lwid 10

    set w .param$instance.port
    frame $w
    label $w.title

# Port action: pipe.

    set f $w.pipe
    frame $f
    label $f.label -text " 1" -underline 1
    radiobutton $f.button -anchor w \
    			  -command "tksu::PortToggle $instance" \
    			  -variable tksu::PortAction($instance) -value pipe
    entry $f.module -relief sunken -bg white -width 14 -exportselection 0
    button $f.moduleB -image DownArrow \
    		      -command "tksu::PipeModules $instance"

    label $f.portlabel -text " port:"
    entry $f.port -relief sunken -bg white -width 10 -exportselection 0
    button $f.portB -image DownArrow \
    		    -command "tksu::PipePorts $instance"

# Port action: file.

    set f $w.file
    frame $f
    label $f.label -text " 2" -underline 1
    radiobutton $f.button -anchor w \
    			  -command "tksu::PortToggle $instance" \
    			  -variable tksu::PortAction($instance) -value file
    entry $f.entry -relief sunken -bg white -exportselection 0

# Port action: temporary or null I/O.

    set f $w.temp
    frame $f
    label $f.label -text " 3" -underline 1
    radiobutton $f.button -anchor w \
    			  -command "tksu::PortToggle $instance" \
    			  -variable tksu::PortAction($instance) -value temp
    button $w.fileDialog -text File -underline 0 -width 3 \
			 -command "tksu::PortFile $instance"

# Port default:

    set f $w.default
    frame $f
    label $f.label -text Default: -width $lwid -anchor w
    label $f.value -anchor w -justify left -wraplength 12c

# Port data type:

    set f $w.data
    frame $f
    label $f.label -text "File Type:" -width $lwid -anchor w
    label $f.value -anchor w
    button $f.color -relief sunken -foreground white -width $bwid \
    		    -takefocus 0

# Port description:

    set f $w.desc
    frame $f
    label $f.label -text Description: -width $lwid -anchor w
    label $f.value -anchor w -justify left -wraplength 14c

# Side buttons:
#
# DISABLED 5/3/02:  "-command ParamUndo $instance" replaced with
# "-command Undo", likewise for "-command ParamRedo $instance".

    button $w.enter -text Enter -underline 0 -width $bwid \
    		    -command "tksu::ParamEnter $instance"
    button $w.undo -text Undo -underline 0 -width $bwid \
    		   -command tksu::Undo
    button $w.redo -text Redo -underline 0 -width $bwid \
    		   -command tksu::Redo
    button $w.clear -text Default -underline 0 -width $bwid \
    		    -command "tksu::ParamClear $instance"

# Pack up all objects.

    pack $w.title -side top -fill x

    pack $w.pipe.label $w.pipe.button -side left
    pack $w.enter -padx 10 -side right -in $w.pipe
    pack $w.pipe.portB $w.pipe.port $w.pipe.portlabel -side right
    pack $w.pipe.moduleB -side right
    pack $w.pipe.module -fill x -pady 2
    pack $w.pipe -side top -fill x

    pack $w.file.label $w.file.button -side left
    pack $w.undo -padx 10 -side right -in $w.file
    pack $w.file.entry -fill x -pady 2
    pack $w.file -side top -fill x

    pack $w.temp.label $w.temp.button -side left
    pack $w.redo -padx 10 -side right -in $w.temp
    pack $w.fileDialog -side right -in $w.temp
    pack $w.temp -side top -fill x

    pack $w.default.label -side left -padx 2
    pack $w.clear -padx 10 -side right -in $w.default
    pack $w.default.value -side left -padx 2 -anchor w -fill x -expand 1
    pack $w.default -side top -fill x

    pack $w.data.label $w.data.value -side left -padx 2
    pack $w.data.color -padx 10 -side right
    pack $w.data -side top -fill x

    pack $w.desc.label -side left -padx 2 -anchor nw
    pack $w.desc.value -side left -padx 2 -anchor nw -fill x -expand 1
    pack $w.desc -pady 4 -side top -anchor n -fill x

    pack $w -side bottom -fill x

# Accelerator bindings:

    set f .param$instance
    bind $f <Alt-KeyPress-1> "$w.pipe.button invoke"
    bind $f <Alt-KeyPress-2> "$w.file.button invoke"
    bind $f <Alt-KeyPress-3> "$w.temp.button invoke"
    bind $f <Alt-f> "$w.fileDialog invoke"

# These bindings apply to both param and port dialogs:

    bind $f <Alt-e> "tksu::ParamEnter $instance"
    bind $f <Alt-u> tksu::Undo
    bind $f <Alt-r> tksu::Redo
    bind $f <Alt-d> "tksu::ParamClear $instance"
    return
}

#-------------------------------------------------------------------------------
# LoadPortDialog -- load settings for given port into parameter dialog.
#
# Args:     instance	Instance number of parameter list window.
#	    nlist	Port name structure, a list in the format
#			{ genericName dataType rw default description }.
#			See LoadSpecs for more details.  nlist is usually
#			stored in the Ports array.
#	    vlist	Port value structure, a list in the format
#			{ port-or-param genericName name value undo redo }.
#			See ParamList for more details.  vlist is usually
#			stored in the Values array.
# Returns:  null
#
# The port value may be in one of the following formats:
#
#   pipe		An unconnected pipe.
#   {pipe id ...}	The port has one or more pipes connected to it.
#			The id's are indexes into the Links array.
#   {pipe module port}	After the user has made changes in the port dialog,
#			and before the value has been verified and saved to
#			Values, this form holds the request to
#			create a link to the given module and port name.
#   file		An unconnected file port.
#   {file filename}	A file port, read or write to filename.
#   temp		A temp port, read DevZero or write DevNull.
#
#-------------------------------------------------------------------------------

proc tksu::LoadPortDialog {instance nlist vlist} {
    variable CurrentModule
    variable CurrentParam
    variable CurrentValue
    variable LongDefault
    variable LongDesc
    variable PortAction
    variable Instances
    variable Color

    set portName    [lindex $nlist 0]
    set portType    [lindex $nlist 1]
    set portDir     [lindex $nlist 2]
    set portDefault [lindex $nlist 3]
    set portDesc    [lrange $nlist 4 end]

# If entry widgets are linked to an EnumList window, unlink them.

    UnlinkEntries $instance
    set CurrentParam($instance) $nlist
    set CurrentValue($instance) $vlist

    set w .param$instance.port

# Set initial focus to pipe module button or file entry.

    set module $CurrentModule($instance)
    set modbase [ModBase $module]
    set f [focus]

    if {$f != ".param$instance.list" && $f != ".param$instance.scroll"} {
	if [info exists Instances($module)] {
	    set focusee $w.pipe.moduleB
	} else {
	    set focusee $w.file.entry
	}
    	focus $focusee
	if {[focus] != $focusee} update
    }
    $w.file.entry configure -state normal
    $w.file.entry delete 0 end

# Set label titles according to dir: `r' for read-only, `w' for write-only,
# or `rw' for file read-write.

    switch -- $portDir {

	"r" {

# Input port:

	    $w.title configure -text "Input port `$portName'"
	    $w.pipe.button configure -text "Pipe from module:" -state normal
	    $w.file.button configure -text "Read from file:"
	    $w.temp.button configure -text "Read zeros"
	}
	"w" {

# Output port:

	    $w.title configure -text "Output port `$portName'"
	    $w.pipe.button configure -text "Pipe to module:" -state normal
	    $w.file.button configure -text "Write to file:"
	    $w.temp.button configure -text "Discard output"
	}
	"rw" {

# Read-write port:

	    $w.title configure -text "Random access port `$portName'"
	    $w.pipe.button configure -text "Pipe to module:" -state disabled
	    $w.file.button configure -text "Read/write file:"
	    $w.temp.button configure -text "Read/write temporary file"
	}
    }

# Load port entry widgets and set radiobuttons.

    set value [lindex $vlist 3]
    LoadPortValue $instance $value

# File type description.

    set desc [EnumDesc enum-file $portType]
    if {[llength $desc] <= 0} {
	set desc "unknown"
    }
    $w.data.value configure -text [format "%s (type `%s')" $desc $portType]
    $w.data.color configure -background $Color($portType) -text $portType \
    			    -activebackground $Color($portType)

# Default description.

    if [info exists LongDefault($modbase,$portName)] {
	set desc $LongDefault($modbase,$portName)
    } else {
	set desc [DefaultValue long $portDefault]
    }
    set wraplength [expr [winfo width $w.default.value] - 40]
    if {$wraplength < 100} {
    	set wraplength 12c
    }
    $w.default.value configure -text $desc -wraplength $wraplength

# Port description.

    if [info exists LongDesc($modbase,$portName)] {
	set desc $LongDesc($modbase,$portName)
    } else {
	set desc $portDesc
    }
    set wraplength [expr [winfo width $w.desc.value] - 40]
    if {$wraplength < 100} {
    	set wraplength 12c
    }
    $w.desc.value configure -text $desc -wraplength $wraplength
    return
}

#-------------------------------------------------------------------------------
# GetPortValue -- retrieve correctly formatted value from port dialog entries.
#
# Args:     instance	Instance number of parameter list window.
# Returns:  value	A port value in one of the following forms:
#			(a) pipe ?module port? (but NOT pipe ?id ...?)
#			(b) file ?filename?
#			(c) temp
#-------------------------------------------------------------------------------

proc tksu::GetPortValue instance {
    variable PortAction

    set w .param$instance.port
    set value $PortAction($instance)

    switch -- $value {

	pipe {
	    set module [string trim [$w.pipe.module get]]
	    set port   [string trim [$w.pipe.port get]]

	    if {$module != "" && $module != "NONE" && $port != ""} {
		set value "pipe $module $port"
	    }
	}
	file {
	    set filename [string trim [$w.file.entry get]]
	    set value "file $filename"
	}
	temp {
	}
    }
    return $value
}

#-------------------------------------------------------------------------------
# FormatPortValue -- return formatted port value.
#
# Args:     rw		I/O direction of port: `r', `w', or `rw'.
#	    value	Port value (see LoadPortDialog for format).
# Returns:  string	A formatted string suitable for the parameter list.
#-------------------------------------------------------------------------------

proc tksu::FormatPortValue {rw value} {
    variable DevNull
    variable DevZero

    set action [lindex $value 0]
    set target [lindex $value 1]

    switch -- $action {
    	pipe {
	    if {$target == "" || $rw == "rw"} {
	    	return <pipe>
	    }

# Pipe value is a list of link ids:

	    switch -- $rw {
	    	r {set direction w}
		w {set direction r}
	    }
	    if {[GetModPort $target $direction] != ""} {
	    	foreach id [lrange $value 1 end] {
		    set modport [join [GetModPort $id $direction] :]
		    if {$id != $target} {append str ,}
		    append str $modport
		}

# Pipe value is {module port}:

	    } else {
		set str [join [lrange $value 1 2] :]
	    }
	    return $str
	}

	file {
	    return $target
	}

	temp {
	    switch -- $rw {
	    	r  {return $DevZero}
		w  {return $DevNull}
		rw {return "temp file"}
	    }
	}
    }
    return
}

#-------------------------------------------------------------------------------
# LoadPortValue -- load given port value to dialog entries.
#
# Args:     instance	Instance number of parameter list window.
#	    value	A port value (see LoadPortDialog for details).
# Returns:  null
#
# Dialog widgets are filled and radiobuttons are set.
#-------------------------------------------------------------------------------

proc tksu::LoadPortValue {instance value} {
    variable CurrentParam
    variable CurrentModule
    variable PortAction

    set w .param$instance.port

# If the focus is in one of the following widgets, change it to the new
# active entry.

    set changeFocus 0
    foreach f "$w.pipe.button $w.pipe.moduleB $w.pipe.portB $w.file.button \
    	       $w.file.entry $w.temp.button $w.fileDialog" {
	if {[focus] == $f} {
	    set changeFocus 1
	}
    }
    set action [lindex $value 0]
    set target [lindex $value 1]
    set rw [lindex $CurrentParam($instance) 2]

# If null, set action from default.

    if {$action == ""} {
	set action [lindex [NewValue port $CurrentParam($instance)] 3]
	set target ""
    }
    set PortAction($instance) $action

    $w.pipe.module configure -state normal
    $w.pipe.module delete 0 end
    $w.pipe.module configure -state disabled
    $w.pipe.moduleB configure -state disabled

    $w.pipe.port configure -state normal
    $w.pipe.port delete 0 end
    $w.pipe.port configure -state disabled
    $w.pipe.portB configure -state disabled

    $w.file.entry configure -state normal
    $w.file.entry delete 0 end
    $w.file.entry configure -state disabled
    $w.fileDialog configure -state disabled

    switch -- $action {
        pipe {

# For preset parameter dialogs, disable the module and port entries.

	    set module $CurrentModule($instance)
	    if {$module == [ModBase $module]} {
		if $changeFocus {focus $w.pipe.button}
		return
	    }

	    switch -- $rw {
	    	r  {set direction w}
		w  {set direction r}
		rw {return}
	    }

# If a link is present, show the module and port of the link.

	    set modport [GetModPort $target $direction]
	    if {$modport != ""} {
	    	set module [lindex $modport 0]
		set port [lindex $modport 1]
	    } else {
	    	set module [lindex $value 1]
		set port [lindex $value 2]
	    }
	    $w.pipe.moduleB configure -state normal
	    $w.pipe.module configure -state normal
	    $w.pipe.module insert 0 $module
	    $w.pipe.module configure -state disabled

	    $w.pipe.portB  configure -state normal
	    $w.pipe.port   configure -state normal
	    $w.pipe.port   insert 0 $port
	    $w.pipe.port   configure -state disabled

	    if $changeFocus {focus $w.pipe.moduleB}
	}

	file {
	    $w.fileDialog configure -state normal
	    $w.file.entry configure -state normal
	    $w.file.entry insert 0 $target
	    if $changeFocus {focus $w.file.entry}
	}

	temp {
	    if $changeFocus {focus $w.temp.button}
	}
    }
    return
}

#-------------------------------------------------------------------------------
# PipeModules -- select module from a modal list of modules.
#
# Args:     instance	Instance number for this dialog.
# Returns:  null
#
# ModalList is called to display current module instances in a listbox below
# the module entry.  When a selection is made and the listbox is withdrawn,
# the module entry holds the new selection (but remains disabled).
#
# After selection, look for an existing link to the selected module.  If
# found, set the port entry to the connecting port.  Otherwise set the
# port entry blank.
#-------------------------------------------------------------------------------

proc tksu::PipeModules instance {
    variable CurrentParam
    variable CurrentValue
    variable Instances

# Provide blank line at top of list for deleting a link.

    lappend modules {}
    eval lappend modules [lsort [array names Instances]]
    set w .param$instance.port.pipe

    ModalList $w.module $modules

# If a link is present to the shown module, show the link's port.

    set rw [lindex $CurrentParam($instance) 2]
    switch -- $rw {
    	r  {set direction w}
	w  {set direction r}
    }
    set module [string trim [$w.module get]]
    set port ""
    set value [lindex $CurrentValue($instance) 3]

    if {[lindex $value 0] == "pipe"} {
	foreach id [lrange $value 1 end] {
	    set modport [GetModPort $id $direction]

	    # Looking for a module name match ...
	    if {$modport == "" || [lindex $modport 0] != $module} continue

	    # Got one ...
	    set port [lindex $modport 1]
	    break
	}
    }

# Load the port name.

    $w.port configure -state normal
    $w.port delete 0 end
    $w.port insert 0 $port
    $w.port configure -state disabled
    return
}

#-------------------------------------------------------------------------------
# PipePorts -- select port from a modal list of ports.
#
# Args:     instance	Instance number for this dialog.
# Returns:  null
#
# ModalList is called to display current ports in a listbox below the port
# entry.  When a selection is made and the listbox is withdrawn, the port
# entry holds the new selection (but remains disabled).
#
# The ports listed are those that belong to the module currently shown in
# the module entry widget, and have the opposite I/O sense of the current
# port in the dialog window.  If no ports apply, the port list contains a
# single blank entry.
#-------------------------------------------------------------------------------

proc tksu::PipePorts instance {
    variable CurrentParam
    variable Ports

    lappend ports {}
    set rw1 [lindex $CurrentParam($instance) 2]
    set w .param$instance.port.pipe
    set module [string trim [$w.module get]]

    if {$module != ""} {
	set modbase [ModBase $module]
	if [info exists Ports($modbase)] {
	    foreach nlist $Ports($modbase) {
		set rw2 [lindex $nlist 2]
		if {$rw2 == "rw" || $rw2 == $rw1} continue
		lappend ports [lindex $nlist 0]
	    }
	}
    }
    ModalList $w.port $ports
    return
}

#-------------------------------------------------------------------------------
# PortToggle -- handler for port dialog radio buttons.
#
# Args:     instance	Instance number of parameter list window.
# Returns:  null
#-------------------------------------------------------------------------------

proc tksu::PortToggle instance {
    variable PortAction
    variable CurrentModule

    set w .param$instance.port
    set action $PortAction($instance)
    set module $CurrentModule($instance)

    set changeFocus 0
    foreach f "$w.pipe.button $w.pipe.moduleB $w.pipe.portB $w.file.button \
    	       $w.file.entry $w.temp.button $w.fileDialog" {
	if {[focus] == $f} {set changeFocus 1}
    }
    $w.pipe.moduleB configure -state disabled
    $w.pipe.portB   configure -state disabled
    $w.file.entry   configure -state disabled
    $w.fileDialog   configure -state disabled

    switch -- $action {
        pipe {
	    if {$module == [ModBase $module]} {
		if $changeFocus {focus $w.pipe.button}
	    } else {
		$w.pipe.moduleB configure -state normal
		$w.pipe.portB   configure -state normal
		if $changeFocus {focus $w.pipe.moduleB}
	    }
	}
	file {
	    $w.fileDialog configure -state normal
	    $w.file.entry configure -state normal
	    if $changeFocus {focus $w.file.entry}
	}
	temp {
	    if $changeFocus {focus $w.temp.button}
	}
    }
    return
}

#-------------------------------------------------------------------------------
# PortFile -- raise dialog for selecting input or output file.
#
# Args:     instance	Instance number of parameter list window.
# Returns:  null
#
# If non-null filename is returned from dialog, it is stored in the file
# entry widget.
#-------------------------------------------------------------------------------

proc tksu::PortFile instance {
    variable CurrentParam
    variable DataDir

    set w .param$instance.port.file.entry
    set rw [lindex $CurrentParam($instance) 2]

    if {$rw == "r"} {
    	set filename [tk_getOpenFile -initialdir $DataDir]
    } else {
    	set filename [tk_getSaveFile -initialdir $DataDir]
    }

    if {$filename != ""} {
	PushDialog $instance
    	$w delete 0 end
	$w insert 0 $filename
	set DataDir [file dirname $filename]
	ParamEnter $instance
    }
    return
}


// Copyright 2014 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package api

import (
	"encoding/json"
	"github.com/tsuru/tsuru/iaas"
	"launchpad.net/gocheck"
	"net/http"
	"net/http/httptest"
)

type TestIaaS struct{}

func (TestIaaS) DeleteMachine(m *iaas.Machine) error {
	m.Status = "destroyed"
	return nil
}

func (TestIaaS) CreateMachine(params map[string]string) (*iaas.Machine, error) {
	m := iaas.Machine{
		Id:      params["id"],
		Status:  "running",
		Address: params["id"] + ".somewhere.com",
	}
	return &m, nil
}

func (s *S) TestMachinesList(c *gocheck.C) {
	iaas.RegisterIaasProvider("test-iaas", TestIaaS{})
	_, err := iaas.CreateMachineForIaaS("test-iaas", map[string]string{"id": "myid1"})
	defer (&iaas.Machine{Id: "myid1"}).Destroy()
	c.Assert(err, gocheck.IsNil)
	_, err = iaas.CreateMachineForIaaS("test-iaas", map[string]string{"id": "myid2"})
	defer (&iaas.Machine{Id: "myid2"}).Destroy()
	c.Assert(err, gocheck.IsNil)
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("GET", "/iaas/machines", nil)
	c.Assert(err, gocheck.IsNil)
	request.Header.Set("Authorization", "bearer "+s.admintoken.GetValue())
	m := RunServer(true)
	m.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, gocheck.Equals, http.StatusOK)
	var machines []iaas.Machine
	err = json.NewDecoder(recorder.Body).Decode(&machines)
	c.Assert(err, gocheck.IsNil)
	c.Assert(machines[0].Id, gocheck.Equals, "myid1")
	c.Assert(machines[0].Address, gocheck.Equals, "myid1.somewhere.com")
	c.Assert(machines[0].CreationParams, gocheck.DeepEquals, map[string]string{
		"id": "myid1",
	})
	c.Assert(machines[1].Id, gocheck.Equals, "myid2")
	c.Assert(machines[1].Address, gocheck.Equals, "myid2.somewhere.com")
	c.Assert(machines[1].CreationParams, gocheck.DeepEquals, map[string]string{
		"id": "myid2",
	})
}

func (s *S) TestMachinesDestroy(c *gocheck.C) {
	iaas.RegisterIaasProvider("test-iaas", TestIaaS{})
	_, err := iaas.CreateMachineForIaaS("test-iaas", map[string]string{"id": "myid1"})
	c.Assert(err, gocheck.IsNil)
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("DELETE", "/iaas/machines/myid1", nil)
	c.Assert(err, gocheck.IsNil)
	request.Header.Set("Authorization", "bearer "+s.admintoken.GetValue())
	m := RunServer(true)
	m.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, gocheck.Equals, http.StatusOK)
}

func (s *S) TestMachinesDestroyError(c *gocheck.C) {
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("DELETE", "/iaas/machines/myid1", nil)
	c.Assert(err, gocheck.IsNil)
	request.Header.Set("Authorization", "bearer "+s.admintoken.GetValue())
	m := RunServer(true)
	m.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, gocheck.Equals, http.StatusNotFound)
	c.Assert(recorder.Body.String(), gocheck.Equals, "machine not found\n")
}


/**
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for
 * license information.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 */

package com.microsoft.azure.cognitiveservices.search.customsearch.models;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Defines the error that occurred.
 */
public class Error {
    /**
     * The error code that identifies the category of error. Possible values
     * include: 'None', 'ServerError', 'InvalidRequest', 'RateLimitExceeded',
     * 'InvalidAuthorization', 'InsufficientAuthorization'.
     */
    @JsonProperty(value = "code", required = true)
    private ErrorCode code;

    /**
     * The error code that further helps to identify the error. Possible values
     * include: 'UnexpectedError', 'ResourceError', 'NotImplemented',
     * 'ParameterMissing', 'ParameterInvalidValue', 'HttpNotAllowed',
     * 'Blocked', 'AuthorizationMissing', 'AuthorizationRedundancy',
     * 'AuthorizationDisabled', 'AuthorizationExpired'.
     */
    @JsonProperty(value = "subCode", access = JsonProperty.Access.WRITE_ONLY)
    private ErrorSubCode subCode;

    /**
     * A description of the error.
     */
    @JsonProperty(value = "message", required = true)
    private String message;

    /**
     * A description that provides additional information about the error.
     */
    @JsonProperty(value = "moreDetails", access = JsonProperty.Access.WRITE_ONLY)
    private String moreDetails;

    /**
     * The parameter in the request that caused the error.
     */
    @JsonProperty(value = "parameter", access = JsonProperty.Access.WRITE_ONLY)
    private String parameter;

    /**
     * The parameter's value in the request that was not valid.
     */
    @JsonProperty(value = "value", access = JsonProperty.Access.WRITE_ONLY)
    private String value;

    /**
     * Get the code value.
     *
     * @return the code value
     */
    public ErrorCode code() {
        return this.code;
    }

    /**
     * Set the code value.
     *
     * @param code the code value to set
     * @return the Error object itself.
     */
    public Error withCode(ErrorCode code) {
        this.code = code;
        return this;
    }

    /**
     * Get the subCode value.
     *
     * @return the subCode value
     */
    public ErrorSubCode subCode() {
        return this.subCode;
    }

    /**
     * Get the message value.
     *
     * @return the message value
     */
    public String message() {
        return this.message;
    }

    /**
     * Set the message value.
     *
     * @param message the message value to set
     * @return the Error object itself.
     */
    public Error withMessage(String message) {
        this.message = message;
        return this;
    }

    /**
     * Get the moreDetails value.
     *
     * @return the moreDetails value
     */
    public String moreDetails() {
        return this.moreDetails;
    }

    /**
     * Get the parameter value.
     *
     * @return the parameter value
     */
    public String parameter() {
        return this.parameter;
    }

    /**
     * Get the value value.
     *
     * @return the value value
     */
    public String value() {
        return this.value;
    }

}


<!doctype html>

<title>CodeMirror: Turtle mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">

<link rel="stylesheet" href="../../lib/codemirror.css">

Home

Manual

Code

Language modes

Turtle

Turtle mode

<form><textarea id="code" name="code">
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix geo: <http://www.w3.org/2003/01/geo/wgs84_pos#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .

<http://purl.org/net/bsletten>
    a foaf:Person;
    foaf:interest <http://www.w3.org/2000/01/sw/>;
    foaf:based_near [
        geo:lat "34.0736111" ;
        geo:lon "-118.3994444"
   ]

</textarea></form>

MIME types defined: text/turtle.


#import <Flutter/Flutter.h>
#import <UIKit/UIKit.h>
#import "AppDelegate.h"

int main(int argc, char* argv[]) {
  @autoreleasepool {
    return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
  }
}


.. _pages/widget/datefield#datefield:

DateField
*********
A DateField widget can be used for date input. The input can be done in to kinds. The first kind is to chose a date from a date chose, which is a part of the DateField. The second kind is to write the date direct in the input field.
.. _pages/widget/datefield#preview_image:

Preview Image
-------------

|DateField|

.. |DateField| image:: /pages/widget/datefield.png

.. _pages/widget/datefield#features:

Features
--------
* Pointer and keyboard support.
* Custom date format.

.. _pages/widget/datefield#description:

Description
-----------
A DateField has a ``qx.util.format.DateFormat`` which is used to format the date to a string. The formatted string is show in the input field. The input can be edit directly in the input filed or selecting a date with the data chooser. The date chooser can be pop up by tapping the calendar icon.

.. _pages/widget/datefield#demos:

Demos
-----
Here are some links that demonstrate the usage of the widget:

* `DateField Demo <http://demo.qooxdoo.org/%{version}/demobrowser/#widget~DateField.html>`_
* `Form demo <http://demo.qooxdoo.org/%{version}/demobrowser/#showcase~Form.html>`_

.. _pages/widget/datefield#api:

API
---
| Here is a link to the API of the Widget:
| `qx.ui.form.DateField <http://demo.qooxdoo.org/%{version}/apiviewer/#qx.ui.form.DateField>`_


//
//  ChartDefaultFillFormatter.swift
//  Charts
//
//  Created by Daniel Cohen Gindi on 04/02/2016.
//
//  Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
//  A port of MPAndroidChart for iOS
//  Licensed under Apache License 2.0
//
//  https://github.com/danielgindi/ios-charts
//

import Foundation
import CoreGraphics

#if !os(OSX)
    import UIKit
#endif

/// Default formatter that calculates the position of the filled line.
public class ChartDefaultFillFormatter: NSObject, ChartFillFormatter
{
    public override init()
    {
    }

    public func getFillLinePosition(dataSet dataSet: ILineChartDataSet, dataProvider: LineChartDataProvider) -> CGFloat
    {
        var fillMin = CGFloat(0.0)

        if (dataSet.yMax > 0.0 && dataSet.yMin < 0.0)
        {
            fillMin = 0.0
        }
        else
        {
            if let data = dataProvider.data
            {
                var max: Double, min: Double

                if (data.yMax > 0.0)
                {
                    max = 0.0
                }
                else
                {
                    max = dataProvider.chartYMax
                }

                if (data.yMin < 0.0)
                {
                    min = 0.0
                }
                else
                {
                    min = dataProvider.chartYMin
                }

                fillMin = CGFloat(dataSet.yMin >= 0.0 ? min : max)
            }
        }

        return fillMin
    }
}


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.apache.sysds.runtime.controlprogram.paramserv Class Hierarchy (SystemDS 2.0.0-SNAPSHOT API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.apache.sysds.runtime.controlprogram.paramserv

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

org.apache.sysds.runtime.controlprogram.paramserv.ParamServer

org.apache.sysds.runtime.controlprogram.paramserv.LocalParamServer

org.apache.sysds.runtime.controlprogram.paramserv.SparkPSProxy

org.apache.sysds.runtime.controlprogram.paramserv.ParamservUtils

org.apache.sysds.runtime.controlprogram.paramserv.PSWorker (implements java.io.Serializable)

org.apache.sysds.runtime.controlprogram.paramserv.LocalPSWorker (implements java.util.concurrent.Callable<V>)

org.apache.sysds.runtime.controlprogram.paramserv.SparkPSWorker (implements org.apache.spark.api.java.function.VoidFunction<T>)

org.apache.sysds.runtime.controlprogram.paramserv.SparkPSBody

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2020 The Apache Software Foundation. All rights reserved.


/*
 * Copyright (c) Nordic Semiconductor ASA
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *   1. Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 *   2. Redistributions in binary form must reproduce the above copyright notice, this
 *   list of conditions and the following disclaimer in the documentation and/or
 *   other materials provided with the distribution.
 *
 *   3. Neither the name of Nordic Semiconductor ASA nor the names of other
 *   contributors to this software may be used to endorse or promote products
 *   derived from this software without specific prior written permission.
 *
 *   4. This software must only be used in a processor manufactured by Nordic
 *   Semiconductor ASA, or in a processor manufactured by a third party that
 *   is used in combination with a processor manufactured by Nordic Semiconductor.
 *
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

/**
  @addtogroup BLE_GATTS Generic Attribute Profile (GATT) Server
  @{
  @brief  Definitions and prototypes for the GATTS interface.
 */

#ifndef BLE_GATTS_H__
#define BLE_GATTS_H__

#include "ble_types.h"
#include "ble_ranges.h"
#include "ble_l2cap.h"
#include "ble_gap.h"
#include "ble_gatt.h"
#include "nrf_svc.h"

/** @addtogroup BLE_GATTS_ENUMERATIONS Enumerations
 * @{ */

/**
 * @brief GATTS API SVC numbers.
 */
enum BLE_GATTS_SVCS
{
  SD_BLE_GATTS_SERVICE_ADD = BLE_GATTS_SVC_BASE, /**< Add a service. */
  SD_BLE_GATTS_INCLUDE_ADD,                      /**< Add an included service. */
  SD_BLE_GATTS_CHARACTERISTIC_ADD,               /**< Add a characteristic. */
  SD_BLE_GATTS_DESCRIPTOR_ADD,                   /**< Add a generic attribute. */
  SD_BLE_GATTS_VALUE_SET,                        /**< Set an attribute value. */
  SD_BLE_GATTS_VALUE_GET,                        /**< Get an attribute value. */
  SD_BLE_GATTS_HVX,                              /**< Handle Value Notification or Indication. */
  SD_BLE_GATTS_SERVICE_CHANGED,                  /**< Perform a Service Changed Indication to one or more peers. */
  SD_BLE_GATTS_RW_AUTHORIZE_REPLY,               /**< Reply to an authorization request for a read or write operation on one or more attributes. */
  SD_BLE_GATTS_SYS_ATTR_SET,                     /**< Set the persistent system attributes for a connection. */
  SD_BLE_GATTS_SYS_ATTR_GET,                     /**< Retrieve the persistent system attributes. */
};

/**
 * @brief GATT Server Event IDs.
 */
enum BLE_GATTS_EVTS
{
  BLE_GATTS_EVT_WRITE = BLE_GATTS_EVT_BASE,       /**< Write operation performed. @ref ble_gatts_evt_write_t */
  BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST,             /**< Read/Write Authorization request.@ref ble_gatts_evt_rw_authorize_request_t */
  BLE_GATTS_EVT_SYS_ATTR_MISSING,                 /**< A persistent system attribute access is pending, awaiting a sd_ble_gatts_sys_attr_set(). @ref ble_gatts_evt_sys_attr_missing_t */
  BLE_GATTS_EVT_HVC,                              /**< Handle Value Confirmation. @ref ble_gatts_evt_hvc_t */
  BLE_GATTS_EVT_SC_CONFIRM,                       /**< Service Changed Confirmation. No additional event structure applies. */
  BLE_GATTS_EVT_TIMEOUT                           /**< Timeout. @ref ble_gatts_evt_timeout_t */
};
/** @} */

/** @addtogroup BLE_GATTS_DEFINES Defines
 * @{ */

/** @defgroup BLE_ERRORS_GATTS SVC return values specific to GATTS
 * @{ */
#define BLE_ERROR_GATTS_INVALID_ATTR_TYPE   (NRF_GATTS_ERR_BASE + 0x000) /**< Invalid attribute type. */
#define BLE_ERROR_GATTS_SYS_ATTR_MISSING    (NRF_GATTS_ERR_BASE + 0x001) /**< System Attributes missing. */
/** @} */

/** @defgroup BLE_GATTS_ATTR_LENS_MAX Maximum attribute lengths
 * @{ */
#define BLE_GATTS_FIX_ATTR_LEN_MAX (510)  /**< Maximum length for fixed length Attribute Values. */
#define BLE_GATTS_VAR_ATTR_LEN_MAX (512)  /**< Maximum length for variable length Attribute Values. */
/** @} */

/** @defgroup BLE_GATTS_SRVC_TYPES GATT Server Service Types
 * @{ */
#define BLE_GATTS_SRVC_TYPE_INVALID          0x00  /**< Invalid Service Type. */
#define BLE_GATTS_SRVC_TYPE_PRIMARY          0x01  /**< Primary Service. */
#define BLE_GATTS_SRVC_TYPE_SECONDARY        0x02  /**< Secondary Type. */
/** @} */

/** @defgroup BLE_GATTS_ATTR_TYPES GATT Server Attribute Types
 * @{ */
#define BLE_GATTS_ATTR_TYPE_INVALID         0x00  /**< Invalid Attribute Type. */
#define BLE_GATTS_ATTR_TYPE_PRIM_SRVC_DECL  0x01  /**< Primary Service Declaration. */
#define BLE_GATTS_ATTR_TYPE_SEC_SRVC_DECL   0x02  /**< Secondary Service Declaration. */
#define BLE_GATTS_ATTR_TYPE_INC_DECL        0x03  /**< Include Declaration. */
#define BLE_GATTS_ATTR_TYPE_CHAR_DECL       0x04  /**< Characteristic Declaration. */
#define BLE_GATTS_ATTR_TYPE_CHAR_VAL        0x05  /**< Characteristic Value. */
#define BLE_GATTS_ATTR_TYPE_DESC            0x06  /**< Descriptor. */
#define BLE_GATTS_ATTR_TYPE_OTHER           0x07  /**< Other, non-GATT specific type. */
/** @} */

/** @defgroup BLE_GATTS_OPS GATT Server Operations
 * @{ */
#define BLE_GATTS_OP_INVALID                0x00  /**< Invalid Operation. */
#define BLE_GATTS_OP_WRITE_REQ              0x01  /**< Write Request. */
#define BLE_GATTS_OP_WRITE_CMD              0x02  /**< Write Command. */
#define BLE_GATTS_OP_SIGN_WRITE_CMD         0x03  /**< Signed Write Command. */
#define BLE_GATTS_OP_PREP_WRITE_REQ         0x04  /**< Prepare Write Request. */
#define BLE_GATTS_OP_EXEC_WRITE_REQ_CANCEL  0x05  /**< Execute Write Request: Cancel all prepared writes. */
#define BLE_GATTS_OP_EXEC_WRITE_REQ_NOW     0x06  /**< Execute Write Request: Immediately execute all prepared writes. */
/** @} */

/** @defgroup BLE_GATTS_VLOCS GATT Value Locations
 * @{ */
#define BLE_GATTS_VLOC_INVALID       0x00  /**< Invalid Location. */
#define BLE_GATTS_VLOC_STACK         0x01  /**< Attribute Value is located in stack memory, no user memory is required. */
#define BLE_GATTS_VLOC_USER          0x02  /**< Attribute Value is located in user memory. This requires the user to maintain a valid buffer through the lifetime of the attribute, since the stack
                                                will read and write directly to the memory using the pointer provided in the APIs. There are no alignment requirements for the buffer. */
/** @} */

/** @defgroup BLE_GATTS_AUTHORIZE_TYPES GATT Server Authorization Types
 * @{ */
#define BLE_GATTS_AUTHORIZE_TYPE_INVALID    0x00  /**< Invalid Type. */
#define BLE_GATTS_AUTHORIZE_TYPE_READ       0x01  /**< Authorize a Read Operation. */
#define BLE_GATTS_AUTHORIZE_TYPE_WRITE      0x02  /**< Authorize a Write Request Operation. */
/** @} */

/** @defgroup BLE_GATTS_SYS_ATTR_FLAGS System Attribute Flags
 * @{ */
#define BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS (1 << 0)  /**< Restrict system attributes to system services only. */
#define BLE_GATTS_SYS_ATTR_FLAG_USR_SRVCS (1 << 1)  /**< Restrict system attributes to user services only. */
/** @} */

/** @defgroup BLE_GATTS_ATTR_TAB_SIZE Attribute Table size
 * @{
 */
#define BLE_GATTS_ATTR_TAB_SIZE_MIN         216    /**< Minimum Attribute Table size */
#define BLE_GATTS_ATTR_TAB_SIZE_DEFAULT     0x0000 /**< Default Attribute Table size (0x700 bytes for this version of the SoftDevice). */
/** @} */

/** @} */

/** @addtogroup BLE_GATTS_STRUCTURES Structures
 * @{ */

/**
 * @brief BLE GATTS init options
 */
typedef struct
{
  uint8_t   service_changed:1;             /**< Include the Service Changed characteristic in the Attribute Table. */
  uint32_t  attr_tab_size;                 /**< Attribute Table size in bytes. The size must be a multiple of 4. @ref BLE_GATTS_ATTR_TAB_SIZE_DEFAULT is used to set the default size. */
} ble_gatts_enable_params_t;

/**@brief Attribute metadata. */
typedef struct
{
  ble_gap_conn_sec_mode_t read_perm;       /**< Read permissions. */
  ble_gap_conn_sec_mode_t write_perm;      /**< Write permissions. */
  uint8_t                 vlen       :1;   /**< Variable length attribute. */
  uint8_t                 vloc       :2;   /**< Value location, see @ref BLE_GATTS_VLOCS.*/
  uint8_t                 rd_auth    :1;   /**< Read authorization and value will be requested from the application on every read operation. */
  uint8_t                 wr_auth    :1;   /**< Write authorization will be requested from the application on every Write Request operation (but not Write Command). */
} ble_gatts_attr_md_t;

/**@brief GATT Attribute. */
typedef struct
{
  ble_uuid_t          *p_uuid;          /**< Pointer to the attribute UUID. */
  ble_gatts_attr_md_t *p_attr_md;       /**< Pointer to the attribute metadata structure. */
  uint16_t             init_len;        /**< Initial attribute value length in bytes. */
  uint16_t             init_offs;       /**< Initial attribute value offset in bytes. If different from zero, the first init_offs bytes of the attribute value will be left uninitialized. */
  uint16_t             max_len;         /**< Maximum attribute value length in bytes, see @ref BLE_GATTS_ATTR_LENS_MAX for maximum values. */
  uint8_t*             p_value;         /**< Pointer to the attribute data. Please note that if the @ref BLE_GATTS_VLOC_USER value location is selected in the attribute metadata, this will have to point to a buffer
                                             that remains valid through the lifetime of the attribute. This excludes usage of automatic variables that may go out of scope or any other temporary location.
                                             The stack may access that memory directly without the application's knowledge. For writable characteristics, this value must not be a location in flash memory.*/
} ble_gatts_attr_t;

/**@brief GATT Attribute Value. */
typedef struct
{
  uint16_t  len;        /**< Length in bytes to be written or read. Length in bytes written or read after successful return.*/
  uint16_t  offset;     /**< Attribute value offset. */
  uint8_t   *p_value;   /**< Pointer to where value is stored or will be stored.
                             If value is stored in user memory, only the attribute length is updated when p_value == NULL.
                             Set to NULL when reading to obtain the complete length of the attribute value */
} ble_gatts_value_t;

/**@brief GATT Attribute Context. */
typedef struct
{
  ble_uuid_t           srvc_uuid;       /**< Service UUID. */
  ble_uuid_t           char_uuid;       /**< Characteristic UUID if applicable (BLE_UUID_TYPE_UNKNOWN otherwise). */
  ble_uuid_t           desc_uuid;       /**< Descriptor UUID if applicable (BLE_UUID_TYPE_UNKNOWN otherwise). */
  uint16_t             srvc_handle;     /**< Service Handle. */
  uint16_t             value_handle;    /**< Characteristic Value Handle if applicable (BLE_GATT_HANDLE_INVALID otherwise). */
  uint8_t              type;            /**< Attribute Type, see @ref BLE_GATTS_ATTR_TYPES. */
} ble_gatts_attr_context_t;

/**@brief GATT Characteristic Presentation Format. */
typedef struct
{
  uint8_t          format;      /**< Format of the value, see @ref BLE_GATT_CPF_FORMATS. */
  int8_t           exponent;    /**< Exponent for integer data types. */
  uint16_t         unit;        /**< Unit from Bluetooth Assigned Numbers. */
  uint8_t          name_space;  /**< Namespace from Bluetooth Assigned Numbers, see @ref BLE_GATT_CPF_NAMESPACES. */
  uint16_t         desc;        /**< Namespace description from Bluetooth Assigned Numbers, see @ref BLE_GATT_CPF_NAMESPACES. */
} ble_gatts_char_pf_t;

/**@brief GATT Characteristic metadata. */
typedef struct
{
  ble_gatt_char_props_t       char_props;               /**< Characteristic Properties. */
  ble_gatt_char_ext_props_t   char_ext_props;           /**< Characteristic Extended Properties. */
  uint8_t                    *p_char_user_desc;         /**< Pointer to a UTF-8 encoded string (non-NULL terminated), NULL if the descriptor is not required. */
  uint16_t                    char_user_desc_max_size;  /**< The maximum size in bytes of the user description descriptor. */
  uint16_t                    char_user_desc_size;      /**< The size of the user description, must be smaller or equal to char_user_desc_max_size. */
  ble_gatts_char_pf_t*        p_char_pf;                /**< Pointer to a presentation format structure or NULL if the CPF descriptor is not required. */
  ble_gatts_attr_md_t*        p_user_desc_md;           /**< Attribute metadata for the User Description descriptor, or NULL for default values. */
  ble_gatts_attr_md_t*        p_cccd_md;                /**< Attribute metadata for the Client Characteristic Configuration Descriptor, or NULL for default values. */
  ble_gatts_attr_md_t*        p_sccd_md;                /**< Attribute metadata for the Server Characteristic Configuration Descriptor, or NULL for default values. */
} ble_gatts_char_md_t;

/**@brief GATT Characteristic Definition Handles. */
typedef struct
{
  uint16_t          value_handle;       /**< Handle to the characteristic value. */
  uint16_t          user_desc_handle;   /**< Handle to the User Description descriptor, or @ref BLE_GATT_HANDLE_INVALID if not present. */
  uint16_t          cccd_handle;        /**< Handle to the Client Characteristic Configuration Descriptor, or @ref BLE_GATT_HANDLE_INVALID if not present. */
  uint16_t          sccd_handle;        /**< Handle to the Server Characteristic Configuration Descriptor, or @ref BLE_GATT_HANDLE_INVALID if not present. */
} ble_gatts_char_handles_t;

/**@brief GATT HVx parameters. */
typedef struct
{
  uint16_t          handle;             /**< Characteristic Value Handle. */
  uint8_t           type;               /**< Indication or Notification, see @ref BLE_GATT_HVX_TYPES. */
  uint16_t          offset;             /**< Offset within the attribute value. */
  uint16_t         *p_len;              /**< Length in bytes to be written, length in bytes written after successful return. */
  uint8_t          *p_data;             /**< Actual data content, use NULL to use the current attribute value. */
} ble_gatts_hvx_params_t;

/**@brief GATT Read Authorization parameters. */
typedef struct
{
  uint16_t          gatt_status;        /**< GATT status code for the operation, see @ref BLE_GATT_STATUS_CODES. */
  uint8_t           update : 1;         /**< If set, data supplied in p_data will be used in the ATT response. */
  uint16_t          offset;             /**< Offset of the attribute value being updated. */
  uint16_t          len;                /**< Length in bytes of the value in p_data pointer, see @ref BLE_GATTS_ATTR_LENS_MAX. */
  uint8_t          *p_data;             /**< Pointer to new value used to update the attribute value. */
} ble_gatts_read_authorize_params_t;

/**@brief GATT Write Authorization parameters. */
typedef struct
{
  uint16_t          gatt_status;        /**< GATT status code for the operation, see @ref BLE_GATT_STATUS_CODES. */
} ble_gatts_write_authorize_params_t;

/**@brief GATT Read or Write Authorize Reply parameters. */
typedef struct
{
  uint8_t                               type;   /**< Type of authorize operation, see @ref BLE_GATTS_AUTHORIZE_TYPES. */
  union {
    ble_gatts_read_authorize_params_t   read;   /**< Read authorization parameters. */
    ble_gatts_write_authorize_params_t  write;  /**< Write authorization parameters. */
  } params;                                     /**< Reply Parameters. */
} ble_gatts_rw_authorize_reply_params_t;

/**@brief Event structure for @ref BLE_GATTS_EVT_WRITE. */
typedef struct
{
  uint16_t                    handle;             /**< Attribute Handle. */
  uint8_t                     op;                 /**< Type of write operation, see @ref BLE_GATTS_OPS. */
  ble_gatts_attr_context_t    context;            /**< Attribute Context. */
  uint16_t                    offset;             /**< Offset for the write operation. */
  uint16_t                    len;                /**< Length of the received data. */
  uint8_t                     data[1];            /**< Received data, variable length. */
} ble_gatts_evt_write_t;

/**@brief Event substructure for authorized read requests, see @ref ble_gatts_evt_rw_authorize_request_t. */
typedef struct
{
  uint16_t                    handle;             /**< Attribute Handle. */
  ble_gatts_attr_context_t    context;            /**< Attribute Context. */
  uint16_t                    offset;             /**< Offset for the read operation. */
} ble_gatts_evt_read_t;

/**@brief Event structure for @ref BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST. */
typedef struct
{
  uint8_t                     type;             /**< Type of authorize operation, see @ref BLE_GATTS_AUTHORIZE_TYPES. */
  union {
    ble_gatts_evt_read_t      read;             /**< Attribute Read Parameters. */
    ble_gatts_evt_write_t     write;            /**< Attribute Write Parameters. */
  } request;                                    /**< Request Parameters. */
} ble_gatts_evt_rw_authorize_request_t;

/**@brief Event structure for @ref BLE_GATTS_EVT_SYS_ATTR_MISSING. */
typedef struct
{
  uint8_t hint;                                 /**< Hint (currently unused). */
} ble_gatts_evt_sys_attr_missing_t;

/**@brief Event structure for @ref BLE_GATTS_EVT_HVC. */
typedef struct
{
  uint16_t          handle;                       /**< Attribute Handle. */
} ble_gatts_evt_hvc_t;

/**@brief Event structure for @ref BLE_GATTS_EVT_TIMEOUT. */
typedef struct
{
  uint8_t          src;                       /**< Timeout source, see @ref BLE_GATT_TIMEOUT_SOURCES. */
} ble_gatts_evt_timeout_t;

/**@brief GATT Server event callback event structure. */
typedef struct
{
  uint16_t conn_handle;                                       /**< Connection Handle on which the event occurred. */
  union
  {
    ble_gatts_evt_write_t                 write;              /**< Write Event Parameters. */
    ble_gatts_evt_rw_authorize_request_t  authorize_request;  /**< Read or Write Authorize Request Parameters. */
    ble_gatts_evt_sys_attr_missing_t      sys_attr_missing;   /**< System attributes missing. */
    ble_gatts_evt_hvc_t                   hvc;                /**< Handle Value Confirmation Event Parameters. */
    ble_gatts_evt_timeout_t               timeout;            /**< Timeout Event. */
  } params;                                                   /**< Event Parameters. */
} ble_gatts_evt_t;

/** @} */

/** @addtogroup BLE_GATTS_FUNCTIONS Functions
 * @{ */

/**@brief Add a service declaration to the Attribute Table.
 *
 * @param[in] type      Toggles between primary and secondary services, see @ref BLE_GATTS_SRVC_TYPES.
 * @param[in] p_uuid    Pointer to service UUID.
 * @param[out] p_handle Pointer to a 16-bit word where the assigned handle will be stored.
 *
 * @note Secondary Services are only relevant in the context of the entity that references them, it is therefore forbidden to
 *       add a secondary service declaration that is not referenced by another service later in the Attribute Table.
 *
 * @retval ::NRF_SUCCESS Successfully added a service declaration.
 * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
 * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, Vendor Specific UUIDs need to be present in the table.
 * @retval ::NRF_ERROR_FORBIDDEN Forbidden value supplied, certain UUIDs are reserved for the stack.
 * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation.
 */
SVCALL(SD_BLE_GATTS_SERVICE_ADD, uint32_t, sd_ble_gatts_service_add(uint8_t type, ble_uuid_t const *p_uuid, uint16_t *p_handle));

/**@brief Add an include declaration to the Attribute Table.
 *
 * @note It is currently only possible to add an include declaration to the last added service (i.e. only sequential population is supported at this time).
 *
 * @note The included service must already be present in the Attribute Table prior to this call.
 *
 * @param[in] service_handle    Handle of the service where the included service is to be placed, if @ref BLE_GATT_HANDLE_INVALID is used, it will be placed sequentially.
 * @param[in] inc_srvc_handle   Handle of the included service.
 * @param[out] p_include_handle Pointer to a 16-bit word where the assigned handle will be stored.
 *
 * @retval ::NRF_SUCCESS Successfully added an include declaration.
 * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
 * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, handle values need to match previously added services.
 * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation.
 * @retval ::NRF_ERROR_FORBIDDEN Forbidden value supplied, self inclusions are not allowed.
 * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation.
 * @retval ::NRF_ERROR_NOT_FOUND Attribute not found.
 */
SVCALL(SD_BLE_GATTS_INCLUDE_ADD, uint32_t, sd_ble_gatts_include_add(uint16_t service_handle, uint16_t inc_srvc_handle, uint16_t *p_include_handle));

/**@brief Add a characteristic declaration, a characteristic value declaration and optional characteristic descriptor declarations to the Attribute Table.
 *
 * @note It is currently only possible to add a characteristic to the last added service (i.e. only sequential population is supported at this time).
 *
 * @note Several restrictions apply to the parameters, such as matching permissions between the user description descriptor and the writeable auxiliaries bits,
 *       readable (no security) and writeable (selectable) CCCDs and SCCDs and valid presentation format values.
 *
 * @note If no metadata is provided for the optional descriptors, their permissions will be derived from the characteristic permissions.
 *
 * @param[in] service_handle    Handle of the service where the characteristic is to be placed, if @ref BLE_GATT_HANDLE_INVALID is used, it will be placed sequentially.
 * @param[in] p_char_md         Characteristic metadata.
 * @param[in] p_attr_char_value Pointer to the attribute structure corresponding to the characteristic value.
 * @param[out] p_handles        Pointer to the structure where the assigned handles will be stored.
 *
 * @retval ::NRF_SUCCESS Successfully added a characteristic.
 * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
 * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, service handle, Vendor Specific UUIDs, lengths, and permissions need to adhere to the constraints.
 * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation, a service context is required.
 * @retval ::NRF_ERROR_FORBIDDEN Forbidden value supplied, certain UUIDs are reserved for the stack.
 * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation.
 * @retval ::NRF_ERROR_DATA_SIZE Invalid data size(s) supplied, attribute lengths are restricted by @ref BLE_GATTS_ATTR_LENS_MAX.
 */
SVCALL(SD_BLE_GATTS_CHARACTERISTIC_ADD, uint32_t, sd_ble_gatts_characteristic_add(uint16_t service_handle, ble_gatts_char_md_t const *p_char_md, ble_gatts_attr_t const *p_attr_char_value, ble_gatts_char_handles_t *p_handles));

/**@brief Add a descriptor to the Attribute Table.
 *
 * @note It is currently only possible to add a descriptor to the last added characteristic (i.e. only sequential population is supported at this time).
 *
 * @param[in] char_handle   Handle of the characteristic where the descriptor is to be placed, if @ref BLE_GATT_HANDLE_INVALID is used, it will be placed sequentially.
 * @param[in] p_attr        Pointer to the attribute structure.
 * @param[out] p_handle     Pointer to a 16-bit word where the assigned handle will be stored.
 *
 * @retval ::NRF_SUCCESS Successfully added a descriptor.
 * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
 * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, characteristic handle, Vendor Specific UUIDs, lengths, and permissions need to adhere to the constraints.
 * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation, a characteristic context is required.
 * @retval ::NRF_ERROR_FORBIDDEN Forbidden value supplied, certain UUIDs are reserved for the stack.
 * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation.
 * @retval ::NRF_ERROR_DATA_SIZE Invalid data size(s) supplied, attribute lengths are restricted by @ref BLE_GATTS_ATTR_LENS_MAX.
 */
SVCALL(SD_BLE_GATTS_DESCRIPTOR_ADD, uint32_t, sd_ble_gatts_descriptor_add(uint16_t char_handle, ble_gatts_attr_t const *p_attr, uint16_t *p_handle));

/**@brief Set the value of a given attribute.
 *
 * @param[in] conn_handle  Connection handle. If the value does not belong to a system attribute then @ref BLE_CONN_HANDLE_INVALID can be used.
 * @param[in] handle       Attribute handle.
 * @param[in,out] p_value  Attribute value information.
 *
 * @note Values other than system attributes can be set at any time, regardless of wheter any active connections exist.
 *
 * @retval ::NRF_SUCCESS Successfully set the value of the attribute.
 * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
 * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
 * @retval ::NRF_ERROR_NOT_FOUND Attribute not found.
 * @retval ::NRF_ERROR_FORBIDDEN Forbidden handle supplied, certain attributes are not modifiable by the application.
 * @retval ::NRF_ERROR_DATA_SIZE Invalid data size(s) supplied, attribute lengths are restricted by @ref BLE_GATTS_ATTR_LENS_MAX.
 * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied.
 * @retval ::BLE_ERROR_GATTS_INVALID_ATTR_TYPE @ref BLE_CONN_HANDLE_INVALID supplied on a system attribute.
 */
#ifndef __RFduino__
SVCALL(SD_BLE_GATTS_VALUE_SET, uint32_t, sd_ble_gatts_value_set(uint16_t conn_handle, uint16_t handle, ble_gatts_value_t *p_value));
#else
SVCALL(SD_BLE_GATTS_VALUE_SET, uint32_t, sd_ble_gatts_value_set(uint16_t handle, uint16_t offset, uint16_t* const p_len, uint8_t const * const p_value));
#endif

/**@brief Get the value of a given attribute.
 *
 * @param[in] conn_handle  Connection handle. If the value does not belong to a system attribute then @ref BLE_CONN_HANDLE_INVALID can be used.
 * @param[in] handle       Attribute handle.
 * @param[in,out] p_value  Attribute value information.
 *
 * @note                 If the attribute value is longer than the size of the supplied buffer,
 *                       p_len will return the total attribute value length (excluding offset),
 *                       and not the number of bytes actually returned in p_data.
 *                       The application may use this information to allocate a suitable buffer size.
 *
 * @note                 When retrieving system attribute values with this function, the connection handle
 *                       may refer to an already disconnected connection. Refer to the documentation of
 *                       @ref sd_ble_gatts_sys_attr_get for further information.
 *
 * @retval ::NRF_SUCCESS Successfully retrieved the value of the attribute.
 * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
 * @retval ::NRF_ERROR_NOT_FOUND Attribute not found.
 * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied.
 * @retval ::BLE_ERROR_GATTS_INVALID_ATTR_TYPE @ref BLE_CONN_HANDLE_INVALID supplied on a system attribute.
 */
SVCALL(SD_BLE_GATTS_VALUE_GET, uint32_t, sd_ble_gatts_value_get(uint16_t conn_handle, uint16_t handle, ble_gatts_value_t *p_value));

/**@brief Notify or Indicate an attribute value.
 *
 * @details This function checks for the relevant Client Characteristic Configuration descriptor value to verify that the relevant operation
 *          (notification or indication) has been enabled by the client. It is also able to update the attribute value before issuing the PDU, so that
 *          the application can atomically perform a value update and a server initiated transaction with a single API call.
 *          If the application chooses to indicate an attribute value, a @ref BLE_GATTS_EVT_HVC event will be issued as soon as the confirmation arrives from
 *          the peer.
 *
 * @note    The local attribute value may be updated even if an outgoing packet is not sent to the peer due to an error during execution.
 *          When receiveing the error codes @ref NRF_ERROR_INVALID_STATE, @ref NRF_ERROR_BUSY, @ref BLE_ERROR_GATTS_SYS_ATTR_MISSING and
 *          @ref BLE_ERROR_NO_TX_BUFFERS the Attribute Table has been updated.
 *          The caller can check whether the value has been updated by looking at the contents of *(p_hvx_params->p_len).
 *
 * @note    It is important to note that a notification will <b>consume an application buffer</b>, and will therefore
 *          generate a @ref BLE_EVT_TX_COMPLETE event when the packet has been transmitted. An indication on the other hand will use the
 *          standard server internal buffer and thus will only generate a @ref BLE_GATTS_EVT_HVC event as soon as the confirmation
 *          has been received from the peer. Please see the documentation of @ref sd_ble_tx_buffer_count_get for more details.
 *
 * @param[in] conn_handle  Connection handle.
 * @param[in] p_hvx_params Pointer to an HVx parameters structure. If the p_data member contains a non-NULL pointer the attribute value will be updated with
 *                         the contents pointed by it before sending the notification or indication.
 *
 * @retval ::NRF_SUCCESS Successfully queued a notification or indication for transmission, and optionally updated the attribute value.
 * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
 * @retval ::NRF_ERROR_INVALID_STATE Invalid Connection State or notifications and/or indications not enabled in the CCCD.
 * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
 * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
 * @retval ::BLE_ERROR_INVALID_ATTR_HANDLE Invalid attribute handle(s) supplied. Only attributes added directly by the application are available to notify and indicate.
 * @retval ::BLE_ERROR_GATTS_INVALID_ATTR_TYPE Invalid attribute type(s) supplied, only characteristic values may be notified and indicated.
 * @retval ::NRF_ERROR_NOT_FOUND Attribute not found.
 * @retval ::NRF_ERROR_DATA_SIZE Invalid data size(s) supplied.
 * @retval ::NRF_ERROR_BUSY Procedure already in progress.
 * @retval ::BLE_ERROR_GATTS_SYS_ATTR_MISSING System attributes missing, use @ref sd_ble_gatts_sys_attr_set to set them to a known value.
 * @retval ::BLE_ERROR_NO_TX_BUFFERS There are no available buffers to send the data, applies only to notifications.
 */
SVCALL(SD_BLE_GATTS_HVX, uint32_t, sd_ble_gatts_hvx(uint16_t conn_handle, ble_gatts_hvx_params_t const *p_hvx_params));

/**@brief Indicate the Service Changed attribute value.
 *
 * @details This call will send a Handle Value Indication to one or more peers connected to inform them that the Attribute
 *          Table layout has changed. As soon as the peer has confirmed the indication, a @ref BLE_GATTS_EVT_SC_CONFIRM event will
 *          be issued.
 *
 * @note    Some of the restrictions and limitations that apply to @ref sd_ble_gatts_hvx also apply here.
 *
 * @param[in] conn_handle  Connection handle.
 * @param[in] start_handle Start of affected attribute handle range.
 * @param[in] end_handle   End of affected attribute handle range.
 *
 * @retval ::NRF_SUCCESS Successfully queued the Service Changed indication for transmission.
 * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
 * @retval ::NRF_ERROR_INVALID_STATE Invalid Connection State or notifications and/or indications not enabled in the CCCD.
 * @retval ::NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied.
 * @retval ::BLE_ERROR_INVALID_ATTR_HANDLE Invalid attribute handle(s) supplied, handles must be in the range populated by the application.
 * @retval ::NRF_ERROR_INVALID_STATE Invalid state to perform operation, notifications or indications must be enabled in the CCCD.
 * @retval ::NRF_ERROR_BUSY Procedure already in progress.
 * @retval ::BLE_ERROR_GATTS_SYS_ATTR_MISSING System attributes missing, use @ref sd_ble_gatts_sys_attr_set to set them to a known value.
 */
SVCALL(SD_BLE_GATTS_SERVICE_CHANGED, uint32_t, sd_ble_gatts_service_changed(uint16_t conn_handle, uint16_t start_handle, uint16_t end_handle));

/**@brief Respond to a Read/Write authorization request.
 *
 * @note This call should only be used as a response to a @ref BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST event issued to the application.
 *
 * @param[in] conn_handle                 Connection handle.
 * @param[in] p_rw_authorize_reply_params Pointer to a structure with the attribute provided by the application.
 *
 * @retval ::NRF_SUCCESS               Successfully queued a response to the peer, and in the case of a write operation, Attribute Table updated.
 * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
 * @retval ::NRF_ERROR_INVALID_STATE   Invalid Connection State or no authorization request pending.
 * @retval ::NRF_ERROR_INVALID_PARAM   Authorization op invalid,
 *                                         or for Read Authorization reply: requested handles not replied with,
 *                                         or for Write Authorization reply: handle supplied does not match requested handle.
 * @retval ::NRF_ERROR_BUSY The stack is busy. Retry at later time.
 */
SVCALL(SD_BLE_GATTS_RW_AUTHORIZE_REPLY, uint32_t, sd_ble_gatts_rw_authorize_reply(uint16_t conn_handle, ble_gatts_rw_authorize_reply_params_t const *p_rw_authorize_reply_params));

/**@brief Update persistent system attribute information.
 *
 * @details Supply information about persistent system attributes to the stack,
 *          previously obtained using @ref sd_ble_gatts_sys_attr_get.
 *          This call is only allowed for active connections, and is usually
 *          made immediately after a connection is established with an known bonded device,
 *          often as a response to a @ref BLE_GATTS_EVT_SYS_ATTR_MISSING.
 *
 *          p_sysattrs may point directly to the application's stored copy of the system attributes
 *          obtained using @ref sd_ble_gatts_sys_attr_get.
 *          If the pointer is NULL, the system attribute info is initialized, assuming that
 *          the application does not have any previously saved system attribute data for this device.
 *
 * @note The state of persistent system attributes is reset upon connection establishment and then remembered for its duration.
 *
 * @note If this call returns with an error code different from @ref NRF_SUCCESS, the storage of persistent system attributes may have been completed only partially.
 *       This means that the state of the attribute table is undefined, and the application should either provide a new set of attributes using this same call or
 *       reset the SoftDevice to return to a known state.
 *
 * @note When the @ref BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS is used with this function, only the system attributes included in system services will be modified.
 * @note When the @ref BLE_GATTS_SYS_ATTR_FLAG_USR_SRVCS is used with this function, only the system attributes included in user services will be modified.
 *
 * @param[in]  conn_handle        Connection handle.
 * @param[in]  p_sys_attr_data    Pointer to a saved copy of system attributes supplied to the stack, or NULL.
 * @param[in]  len                Size of data pointed by p_sys_attr_data, in octets.
 * @param[in]  flags              Optional additional flags, see @ref BLE_GATTS_SYS_ATTR_FLAGS
 *
 * @retval ::NRF_SUCCESS Successfully set the system attribute information.
 * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
 * @retval ::NRF_ERROR_INVALID_STATE   Invalid Connection State.
 * @retval ::NRF_ERROR_INVALID_DATA Invalid data supplied, the data should be exactly the same as retrieved with @ref sd_ble_gatts_sys_attr_get.
 * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation.
 * @retval ::NRF_ERROR_BUSY The stack is busy. Retry at later time.
 */
#ifndef __RFduino__
SVCALL(SD_BLE_GATTS_SYS_ATTR_SET, uint32_t, sd_ble_gatts_sys_attr_set(uint16_t conn_handle, uint8_t const *p_sys_attr_data, uint16_t len, uint32_t flags));
#else
SVCALL(SD_BLE_GATTS_SYS_ATTR_SET, uint32_t, sd_ble_gatts_sys_attr_set(uint16_t conn_handle, uint8_t const*const p_sys_attr_data, uint16_t len));
#endif

/**@brief Retrieve persistent system attribute information from the stack.
 *
 * @details This call is used to retrieve information about values to be stored perisistently by the application
 *          during the lifetime of a connection or after it has been terminated. When a new connection is established with the same bonded device,
 *          the system attribute information retrieved with this function should be restored using using @ref sd_ble_gatts_sys_attr_set.
 *          If retrieved after disconnection, the data should be read before a new connection established. The connection handle for
 *          the previous, now disconnected, connection will remain valid until a new one is created to allow this API call to refer to it.
 *          Connection handles belonging to active connections can be used as well, but care should be taken since the system attributes
 *          may be written to at any time by the peer during a connection's lifetime.
 *
 * @note When the @ref BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS is used with this function, only the system attributes included in system services will be returned.
 * @note When the @ref BLE_GATTS_SYS_ATTR_FLAG_USR_SRVCS is used with this function, only the system attributes included in user services will be returned.
 *
 * @param[in]     conn_handle       Connection handle of the recently terminated connection.
 * @param[out]    p_sys_attr_data   Pointer to a buffer where updated information about system attributes will be filled in. NULL can be provided to
 *                                  obtain the length of the data
 * @param[in,out] p_len             Size of application buffer if p_sys_attr_data is not NULL. Unconditially updated to actual length of system attribute data.
 * @param[in]     flags             Optional additional flags, see @ref BLE_GATTS_SYS_ATTR_FLAGS
 *
 * @retval ::NRF_SUCCESS Successfully retrieved the system attribute information.
 * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle.
 * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied.
 * @retval ::NRF_ERROR_DATA_SIZE The system attribute information did not fit into the provided buffer.
 * @retval ::NRF_ERROR_NOT_FOUND No system attributes found.
 */
SVCALL(SD_BLE_GATTS_SYS_ATTR_GET, uint32_t, sd_ble_gatts_sys_attr_get(uint16_t conn_handle, uint8_t *p_sys_attr_data, uint16_t *p_len, uint32_t flags));

/** @} */

#endif // BLE_GATTS_H__

/**
  @}
*/


//  (C) Copyright Gennadiy Rozental 2001.
//  Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/libs/test for the library home page.
//
//  File        : $RCSfile$
//
//  Version     : $Revision$
//
//  Description : model of actual argument (both typed and abstract interface)
// ***************************************************************************

#ifndef BOOST_TEST_UTILS_RUNTIME_ARGUMENT_HPP
#define BOOST_TEST_UTILS_RUNTIME_ARGUMENT_HPP

// Boost.Test Runtime parameters
#include <boost/test/utils/runtime/fwd.hpp>
#include <boost/test/utils/runtime/errors.hpp>

// Boost.Test
#include <boost/test/utils/class_properties.hpp>
#include <boost/test/utils/rtti.hpp>
#include <boost/test/utils/basic_cstring/compare.hpp>
#include <boost/test/detail/throw_exception.hpp>

// STL
#include <cassert>

#include <boost/test/detail/suppress_warnings.hpp>

namespace boost {
namespace runtime {

// ************************************************************************** //
// **************              runtime::argument               ************** //
// ************************************************************************** //

class argument {
public:
    // Constructor
    argument( rtti::id_t value_type )
    : p_value_type( value_type )
    {}

    // Destructor
    virtual     ~argument()  {}

    // Public properties
    rtti::id_t const    p_value_type;
};

// ************************************************************************** //
// **************             runtime::typed_argument          ************** //
// ************************************************************************** //

template<typename T>
class typed_argument : public argument {
public:
    // Constructor
    explicit typed_argument( T const& v )
    : argument( rtti::type_id<T>() )
    , p_value( v )
    {}

    unit_test::readwrite_property<T>    p_value;
};

// ************************************************************************** //
// **************           runtime::arguments_store          ************** //
// ************************************************************************** //

class arguments_store {
public:
    typedef std::map<cstring, argument_ptr> storage_type;

    /// Returns number of arguments in the store; mostly used for testing
    std::size_t size() const        { return m_arguments.size(); }

    /// Clears the store for reuse
    void        clear()             { m_arguments.clear(); }

    /// Returns true if there is an argument corresponding to the specified parameter name
    bool        has( cstring parameter_name ) const
    {
        return m_arguments.find( parameter_name ) != m_arguments.end();
    }

    /// Provides types access to argument value by parameter name
    template<typename T>
    T const&    get( cstring parameter_name ) const {
        return const_cast<arguments_store*>(this)->get<T>( parameter_name );
    }

    template<typename T>
    T&          get( cstring parameter_name ) {
        storage_type::const_iterator found = m_arguments.find( parameter_name );
        BOOST_TEST_I_ASSRT( found != m_arguments.end(),
                            access_to_missing_argument()
                                << "There is no argument provided for parameter "
                                << parameter_name );

        argument_ptr arg = found->second;

        BOOST_TEST_I_ASSRT( arg->p_value_type == rtti::type_id<T>(),
                            arg_type_mismatch()
                                << "Access with invalid type for argument corresponding to parameter "
                                << parameter_name );

        return static_cast<typed_argument<T>&>( *arg ).p_value.value;
    }

    /// Set's the argument value for specified parameter name
    template<typename T>
    void        set( cstring parameter_name, T const& value )
    {
        m_arguments[parameter_name] = argument_ptr( new typed_argument<T>( value ) );
    }

private:
    // Data members
    storage_type            m_arguments;
};

} // namespace runtime
} // namespace boost

#include <boost/test/detail/enable_warnings.hpp>

#endif // BOOST_TEST_UTILS_RUNTIME_ARGUMENT_HPP


# go-winio

This repository contains utilities for efficiently performing Win32 IO operations in
Go. Currently, this is focused on accessing named pipes and other file handles, and
for using named pipes as a net transport.

This code relies on IO completion ports to avoid blocking IO on system threads, allowing Go
to reuse the thread to schedule another goroutine. This limits support to Windows Vista and
newer operating systems. This is similar to the implementation of network sockets in Go's net
package.

Please see the LICENSE file for licensing information.

This project has adopted the [Microsoft Open Source Code of
Conduct](https://opensource.microsoft.com/codeofconduct/). For more information
see the [Code of Conduct
FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact
[opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional
questions or comments.

Thanks to natefinch for the inspiration for this library. See https://github.com/natefinch/npipe
for another named pipe implementation.


#ifndef __APPLYRENDERGROUPS_H__
#define __APPLYRENDERGROUPS_H__

bool ApplyRenderGroups(CEditRegion* pRegion);

#endif


export async function initErrorString(tag: string, id: string, foundVia?: string): Promise<string> {
	if (tag == null) tag = 'element-tag'
	let estr = `<${tag.toLowerCase()}`
	if (id != null) {
		estr += ` id='#${id}'`
	}

	if (foundVia !== null) {
		estr += ` found using '${foundVia}'`
	}

	estr += '>'
	return estr
}