text:
from PyQt5.QtCore import pyqtSignal, Qt, QSize
from PyQt5.QtGui import QColor, QIcon, QPixmap
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QVBoxLayout, QButtonGroup, \
    QStackedWidget, QLabel, \
    QListWidget, QPushButton

from src.model.resources_cache import ResourcesCache

class ToolBar(QWidget):
    mouseEntered = pyqtSignal()
    mouseLeft = pyqtSignal()

    toolChanged = pyqtSignal(str)
    primaryInkChanged = pyqtSignal(str)
    secondaryInkChanged = pyqtSignal(str)

    def __init__(self):

        super(ToolBar, self).__init__()

        self.setAttribute(Qt.WA_StaticContents)
        self.setAttribute(Qt.WA_NoSystemBackground)

        self.setFont(ResourcesCache.get("BigFont"))

        self._registeredTools = {}
        self._registeredInks = {}

        self._toolSlots = []
        self._inkSlots = []

        self._currentActiveToolSlot = None
        self._previousActiveToolSlot = None

        self._currentEditedInkSlot = None
        self._previousEditedInkSlot = None

        self._editMode = False

        self._backgroundColor = QColor(40, 40, 40)
        self._toolLabelColor = QColor(112, 231, 255)

        self._layout = QVBoxLayout()
        self._layout.setAlignment(Qt.AlignTop)
        self._layout.setContentsMargins(4, 4, 4, 4)

        top_layout = QHBoxLayout()

        self._layout.addLayout(top_layout)

        self._toolsLayout = QHBoxLayout()
        self._inksLayout = QHBoxLayout()

        self._toolsLayout.setContentsMargins(0, 0, 0, 0)
        self._toolsLayout.setAlignment(Qt.AlignLeft)

        self._inksLayout.setContentsMargins(0, 0, 0, 0)
        self._inksLayout.setAlignment(Qt.AlignRight)

        top_layout.addLayout(self._toolsLayout)
        top_layout.addLayout(self._inksLayout)

        self._toolsButtonGroup = QButtonGroup()
        self._toolsButtonGroup.buttonClicked.connect(
            self._on_tool_slot_triggered)

        self._inksButtonGroup = QButtonGroup()
        self._inksButtonGroup.setExclusive(False)
        self._inksButtonGroup.buttonClicked.connect(self._on_ink_slot_triggered)

        self.setLayout(self._layout)

        self._toolbarSubPanel = None
        self._toolsListWidget = None
        self._toolsOptionsPanel = None

        self._init_edit_panel()

        self._add_ink_slot(0)
        self._add_ink_slot(1)

        self.resize(0, 50)

    # -------------------------------------------------------------------------

    def get_tool_by_name(self, name):

        return self._registeredTools[name]

    def register_tool(self, tool, is_default=None):

        if tool.name not in self._registeredTools:

            self._registeredTools[tool.name] = tool
            self._toolsListWidget.addItem(tool.name)

            if is_default is True:
                self._toolsListWidget.setCurrentRow(0)

            self._build_tool_options_pane(tool)

            if len(self._toolSlots) < 4:
                slot_index = self._add_tool_slot(is_default)
                self._assign_tool_to_slot(tool, slot_index)

    def register_ink(self, ink, slot):

        if not ink.name in self._registeredInks:
            self._registeredInks[ink.name] = ink

            self._inksListWidget.addItem(ink.name)

            self._build_ink_options_pane(ink)

            if self._inkSlots[slot]['id'] is None:
                self._assign_ink_to_slot(ink, slot)

    def switch_tool_slot(self, slot):

        self._previousActiveToolSlot = self._currentActiveToolSlot

        self._currentActiveToolSlot = slot

        if self._currentActiveToolSlot == self._previousActiveToolSlot:
            return

        tool_name = self._toolSlots[slot]['id']

        self._toolSlots[slot]['button'].setChecked(True)

        self.toolChanged.emit(tool_name)

        self._select_tool_on_list(tool_name)

    # -------------------------------------------------------------------------

    def _go_back_to_last_tool(self):
        self.switch_tool_slot(self._previousActiveToolSlot)

    def _add_tool_slot(self, selected=None):

        slot_button = QPushButton()
        slot_button.setCheckable(True)

        index = len(self._toolSlots)

        if selected is not None and selected is True:
            slot_button.setChecked(True)

        slot = {

            'id': None,
            'button': slot_button
        }

        if selected:
            self._currentActiveToolSlot = index

        self._toolSlots.append(slot)

        self._toolsButtonGroup.addButton(slot_button, index)

        self._toolsLayout.addWidget(slot_button)

        return index

    def _add_ink_slot(self, slot_number):

        slot_button = QPushButton()
        slot_button.setFont(self.font())
        slot_button.setStyleSheet(
            "border-color: rgb(56,56,56); background-color: rgb(17,17,"
            "17); font-size: 12pt;")

        index = len(self._inkSlots)

        if slot_number == 0:

            icon = QIcon()
            icon.addPixmap(QPixmap(":/icons/ico_mouse_button1"), QIcon.Normal,
                           QIcon.Off)

            slot_button.setIcon(icon)
            slot_button.setIconSize(QSize(18, 23))

        elif slot_number == 1:

            icon = QIcon()
            icon.addPixmap(QPixmap(":/icons/ico_mouse_button2"), QIcon.Normal,
                           QIcon.Off)

            slot_button.setIcon(icon)
            slot_button.setIconSize(QSize(18, 23))

        slot = {

            'id': None,
            'button': slot_button
        }

        self._inkSlots.append(slot)

        self._inksButtonGroup.addButton(slot_button)

        self._inksButtonGroup.setId(slot_button, index)

        self._inksLayout.addWidget(slot_button)

        return index

    def _assign_tool_to_slot(self, tool, slot):

        if slot < 0 or slot > len(self._toolSlots) - 1:
            raise Exception(
                '[ToolBar] > _assignToolToSlot : invalid slot parameter')

        self._toolSlots[slot]['id'] = tool.name

        icon = tool.icon

        if icon is not None:
            tool_button = self._toolSlots[slot]['button']
            tool_button.setIcon(tool.icon)
            tool_button.setIconSize(QSize(24, 24))

    def _assign_ink_to_slot(self, ink, slot):

        if slot != 0 and slot != 1:
            raise Exception(
                '[ToolBar] > _assignInkToSlot : invalid slot parameter')

        ink_name = ink.name

        self._inkSlots[slot]['id'] = ink_name
        self._inkSlots[slot]['button'].setText(ink_name)

        if slot == 0:
            self.primaryInkChanged.emit(ink_name)
        elif slot == 1:
            self.secondaryInkChanged.emit(ink_name)

    def _init_edit_panel(self):

        self._toolbarSubPanel = QStackedWidget()

        # 1. Initialize Tools Control Panel -----------------------------------

        self._toolsListWidget = QListWidget()

        self._toolsListWidget.currentRowChanged.connect(
            lambda v: self._toolsOptionsPanel.setCurrentIndex(v))

        self._toolsListWidget.setMaximumSize(QSize(150, 200))

        self._toolsListWidget.itemClicked.connect(
            self._on_tool_list_item_clicked)

        # Tools Subpanel ------------------------------------------------------

        tools_control_panel = QWidget()

        tools_control_panel_layout = QHBoxLayout()

        tools_control_panel.setLayout(tools_control_panel_layout)

        tools_control_panel_layout.setAlignment(Qt.AlignLeft)

        # Tools List ----------------------------------------------------------

        tools_list_sublayout = QVBoxLayout()

        tools_list_sublayout.setAlignment(Qt.AlignTop)

        tools_list_sublayout.setContentsMargins(0, 0, 0, 0)

        tools_list_sublayout.addWidget(QLabel("Tools"))

        tools_list_sublayout.addWidget(self._toolsListWidget)

        tools_control_panel_layout.addLayout(tools_list_sublayout)

        # Tools Options -------------------------------------------------------

        tools_options_sublayout = QVBoxLayout()

        tools_options_sublayout.setAlignment(Qt.AlignTop)

        tools_control_panel_layout.addLayout(tools_options_sublayout)

        self._toolsOptionsPanel = QStackedWidget()

        tools_options_sublayout.addWidget(QLabel("Tools Options"))

        tools_options_sublayout.addWidget(self._toolsOptionsPanel)

        self._toolbarSubPanel.addWidget(tools_control_panel)

        # 2. Initialize Inks Control Panel ------------------------------------

        self._inksListWidget = QListWidget()

        self._inksListWidget.currentRowChanged.connect(
            lambda v: self._inksOptionsPanel.setCurrentIndex(v))

        self._inksListWidget.setMaximumSize(QSize(150, 200))

        self._inksListWidget.itemClicked.connect(self._on_ink_list_item_clicked)

        # Inks Subpanel -------------------------------------------------------

        inks_control_panel = QWidget()

        inks_control_panel_layout = QHBoxLayout()

        inks_control_panel.setLayout(inks_control_panel_layout)

        inks_control_panel_layout.setAlignment(Qt.AlignLeft)

        # Inks List -----------------------------------------------------------

        inks_list_sublayout = QVBoxLayout()

        inks_list_sublayout.setAlignment(Qt.AlignTop)

        inks_list_sublayout.setContentsMargins(0, 0, 0, 0)

        inks_list_sublayout.addWidget(QLabel("Inks"))

        inks_list_sublayout.addWidget(self._inksListWidget)

        inks_control_panel_layout.addLayout(inks_list_sublayout)

        # Inks Options --------------------------------------------------------

        inks_options_sublayout = QVBoxLayout()

        inks_options_sublayout.setAlignment(Qt.AlignTop)

        inks_control_panel_layout.addLayout(inks_options_sublayout)

        self._inksOptionsPanel = QStackedWidget()

        inks_options_sublayout.addWidget(QLabel("Ink Options"))

        inks_options_sublayout.addWidget(self._inksOptionsPanel)

        self._toolbarSubPanel.addWidget(inks_control_panel)

        # ---------------------------------------------------------------------

        self._layout.addWidget(self._toolbarSubPanel)

        self._toolbarSubPanel.setVisible(False)

    def _build_tool_options_pane(self, tool):

        pane = QWidget()

        pane_layout = QVBoxLayout()
        pane_layout.setAlignment(Qt.AlignTop)
        pane.setLayout(pane_layout)

        for prop in tool.properties.values():
            field_layout = QHBoxLayout()

            field_layout.addWidget(QLabel(prop.description))

            prop_widget = prop.build_property_widget()

            field_layout.addWidget(prop_widget)

            pane_layout.addLayout(field_layout)

        self._toolsOptionsPanel.addWidget(pane)

    def _build_ink_options_pane(self, ink):

        pane = QWidget()

        pane_layout = QVBoxLayout()
        pane_layout.setAlignment(Qt.AlignTop)
        pane.setLayout(pane_layout)

        for prop in ink.properties.values():
            field_layout = QHBoxLayout()
            field_layout.addWidget(QLabel(prop.description))

            prop_widget = prop.build_property_widget()

            field_layout.addWidget(prop_widget)

            pane_layout.addLayout(field_layout)

        self._inksOptionsPanel.addWidget(pane)

    def _select_tool_on_list(self, tool_name):

        tool_list_item = \
            self._toolsListWidget.findItems(tool_name, Qt.MatchExactly)[0]

        if tool_list_item is not None:
            self._toolsListWidget.setCurrentItem(tool_list_item)

    def _select_ink_on_list(self, ink_name):

        ink_list_item = \
            self._inksListWidget.findItems(ink_name, Qt.MatchExactly)[0]

        if ink_list_item is not None:
            self._inksListWidget.setCurrentItem(ink_list_item)

    def _toggle_edit_mode(self):

        if not self._editMode:

            self._show_sub_panel()

        else:

            self._hide_sub_panel()

        self.update()

    def _show_sub_panel(self):

        self._editMode = True
        self.resize(self.width(), 300)
        self._toolbarSubPanel.setVisible(True)

    def _hide_sub_panel(self):

        self._editMode = False
        self.resize(self.width(), 50)
        self._toolbarSubPanel.setVisible(False)

        self._finish_ink_edit_mode()

    def _finish_ink_edit_mode(self):

        if self._currentEditedInkSlot is not None:
            self._inksButtonGroup.button(self._currentEditedInkSlot). \
                setStyleSheet("border-color: rgb(56,56,56);")
            self._currentEditedInkSlot = None
            self._previousEditedInkSlot = None
            self._inksListWidget.setCurrentRow(0)
            self._toolbarSubPanel.setCurrentIndex(0)

    # -------------------------------------------------------------------------

    def mousePressEvent(self, e):

        self._toggle_edit_mode()

        e.accept()

    def wheelEvent(self, e):

        e.accept()

    def enterEvent(self, e):

        self.mouseEntered.emit()
        self.setCursor(Qt.PointingHandCursor)

    def leaveEvent(self, e):

        self.mouseLeft.emit()

    def _on_tool_slot_triggered(self):

        self._toolbarSubPanel.setCurrentIndex(0)

        triggered_slot = self._toolsButtonGroup.checkedId()

        if self._currentEditedInkSlot is not None:
            self._finish_ink_edit_mode()

        self.switch_tool_slot(triggered_slot)

        self.update()

    def _on_ink_slot_triggered(self, slot_button):

        if not self._editMode:
            self._show_sub_panel()

        triggered_slot_id = self._inksButtonGroup.id(slot_button)

        if triggered_slot_id != self._currentEditedInkSlot:

            self._previousEditedInkSlot = self._currentEditedInkSlot

            self._currentEditedInkSlot = triggered_slot_id

            if self._previousEditedInkSlot is not None:
                self._inksButtonGroup. \
                    button(self._previousEditedInkSlot). \
                    setStyleSheet("border-color: rgb(56,56,56);")

            slot_button.setStyleSheet("border-color: rgb(255,0,0);")

            self._toolbarSubPanel.setCurrentIndex(1)

            ink_name = self._inkSlots[triggered_slot_id]['id']

            self._select_ink_on_list(ink_name)

            if triggered_slot_id == 0:
                self.primaryInkChanged.emit(ink_name)
            elif triggered_slot_id == 1:
                self.secondaryInkChanged.emit(ink_name)

        else:

            self._hide_sub_panel()

    def _on_tool_list_item_clicked(self, new_item):

        new_item_name = new_item.text()
        self._assign_tool_to_slot(self.get_tool_by_name(new_item_name),
                                  self._currentActiveToolSlot)
        self.toolChanged.emit(new_item_name)
        self._toolbarSubPanel.update()

    def _on_ink_list_item_clicked(self, item):

        item_name = item.text()

        ink = self._registeredInks[item_name]

        if ink is not None:
            self._assign_ink_to_slot(ink, self._currentEditedInkSlot)


text:
package persistencia;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;

public class AgenteLocal {
	private static AgenteLocal instancia;

	private AgenteLocal(){}

	public static AgenteLocal getAgente(){
		if (instancia == null)
			instancia = new AgenteLocal();
		return instancia;

	}

	public String load(String url){

		String resultado = "";

			try (BufferedReader fileIn = new BufferedReader(new FileReader(new File(url)))) {
	            for(String linea = fileIn.readLine() ; linea!=null ; linea = fileIn.readLine())
	                resultado += linea;
	            fileIn.close();
	        }
	        catch (Exception e) { System.out.println("Agente "+e); }
	        return resultado;
	}
	public boolean save (String contenido,String url){
	   try{
				PrintWriter fileOut=new PrintWriter(new FileWriter(new File(url)));
	    	    fileOut.print(contenido);
	        	fileOut.close();
	       		return true;
	   }catch(Exception e){}
	   return false;
	}
}

redpajama_set_name: RedPajamaGithub


text:
There are many different ways to connect to a XBee Radio. One that works with both OSX and Linux is screen.

## screen

* First connect the XBee to a usb port using a adaptor, breakout board, or sheild.
* Next find where it is attached in the terminal.

```
ls /dev/tty.*
```

* It should appear and look something like this ex: `
* /dev/tty.usbserial-FTH144JL`
* Then use screen and the baudrate to connect through terminal.

```
screen /dev/tty.usbserial-FTH144JL 9600
```

* You can enter command mode by typing `+++` and not pressing return.
 * After a few moments the XBee should report back and say `OK`.
 * In command mode the Xbee will be able to recieve commands.

Note: There are two modes for the XBee, command and transparent mode. In transparent mode the XBee sends all data through. Command mode is used to talk directly to the XBee. Transparent mode is the default state and an XBee will return to transparent mode after 10 seconds of inactivity while in command mode.

* To exit screen press `control-a` then `control-\` then `y`.

## CoolTerm

* CoolTerm is another option. Edit the connection options to connect to the correct usb.
* Once connected use `+++` to enter command mode.
* You can use AT commands, "attention commands", to find out more.

```
AT    >>  Asking "Are you there?". You should get the response "OK".
ATID  >>  Shows the Personal Area Network ID that is currently assigned.
          The PAN address defines the network the radio will connect to.
          The number is in hex in the range 0x0 to 0xFFFF.
ATSH  >>  The high part of a 64-bit serial number that serves as a permanent address for the XBee.
ATSL  >>  The low part of a 64-bit serial number that serves as a permanent address for the XBee.
ATDH  >>  This shows the destination address for the radio to send information to.
ATDL  >>  This is used to assign the destination address for the radio to send information to.
ATCN  >>  This command instantly drops you out of command mode.
ATWR  >>  This writes the complete configuration to firmware so it sticks through a powercycle.
          This is similar to a "save" command that saves the state before shutdown.
ATMY  >>  This shows the current 16-bit addresses. The coordinator assigns this address dynamically
          so it can be displayed but not set for Series 2 ZigBee radios.
```

* The response from ATSH is the Coordinator address. That is always '0013A200'.
* The response from ATSL is the Router address. This is different for every radio. ex: `40B96CF2`.
* Every network must have a coordinator radio and not multiple.
* The coordinator must be configured.

```
|Function|                    |Command|           |Parameter|
PAN ID                        ATID                2001 (anything from 0 to FFFF)
Destination address high      ATDH                0013A200
Destination address low       ATDL                <Router Address>
```

* Use the `ATWR` command to save the configuration

* The router must also be configured

```
|Function|                    |Command|           |Parameter|
PAN ID                        ATID                2001 (Same as all other radios in the network)
Destination address high      ATDH                0013A200
Destination address low       ATDL                <Coordinator Address>
```

* To check the edited values use the commands without parameters.
* Remember to save before disconnecting.

## Updating XBee Firmware

Before you can connect your XBee radios you have to update the firmware appropriately.

Unfortunately you have to use a seperate program to update the XBee firmware. This will allow you to configure your device as a coordinator or a router. Fortunately it is now available for OSX.

* Download and install X-CTU
* Open the program and go to the Radio Configuration Tab
* Add the device attached to the serial port, ex: usbserial*
* Once the device is found select it and select update firmware.
* Update to the latest firmware
 * One device must be a coordinator and so on to form your mesh network
* Once the update is complete you can exit the software.

## XBee I/O Features

The XBee radios can be used alone or with an additional microcomputer. When used alone they have limited capabilities. They have no PWM outputs but have a few pins that can be used as digintal inputs, digital outputs, and analog inputs.

* Some configurable pins have other hardware applications for optional duties.

```
|Pin name|          |Physical pin #|    |AT command|        |Other functions|
DIO0,AD0            20                  D0                  Analog input, Commissioning Button
DIO1,AD1            19                  D1                  Analog input
DIO2,AD2            18                  D2                  Analog input
DIO3,AD3            17                  D3                  Analog input
DIO4                11                  D4
DIO5                15                  D5                  Association indicator
DIO6                16                  D6                  RTS
DIO7                12                  D7                  CTS
(DIO8)              9                   None                Pin sleep control,DTR
(DIO9)              13                  None                On/Sleep indicator
DIO10               6                   P0                  Received Signal Strength Indicator (RSSI)
DIO11               7                   P1
DIO12               4                   P2
```

* To configure the XBee for direct input(s) and output(s) you must use AT commands.

```
|Command Sets|      |Purpose|
ATD0 to ATD7        Configures pins 0-7 (8 and 9 not supported currently)
ATP0 to ATP1        Configures pins 10-11 (12 is not currently supported)
ATIR                Sets I/O sample rate (miliseconds in hex)
                    ex: 10 times/second = every 100ms = 0x64 = ATIR64
                    To disable periodic sampling set ATIR to zero.
ATWR                Saves configuration
```

* Each command set needs a setting code directly following it for something to be set.
 * for ATIR that setting code is a hex number. For ATDx or ATPx it is as follows

```
|Setting Code|      |Purpose|
0                   Disables I/O on selected pin
1                   Built in function, if available on that pin
2                   Analog input, only on pins D0-D3
3                   Digital input
4                   Digital output, low (0 volts)
5                   Digital output, high (3.3 volts)
```

Note: Analog inputs top out at 1.2V. All inputs higher than 1.2 volts will be read as a 1.2 volt signal.

* There are a few other advanced commands.

```
|Command|           |Purpose|
AT%V                Returns current supply voltage (Useful to monitor battery status)
ATPR                Configures the 30K pullup resistors (binary value sets) (By default all enabled)
ATIC                Configures digital I/O pins to monitor for changes in state.
```


text:
var Datatable = new function(){

	var self = this;

	//attribs
	this.users_DT = {};

	//methods
	this.init_components = function(){
		self.init_properties();
		self.init_events();
		self.init_datatable();
		self.init_datatable_events();

	}

	this.init_properties = function(){

	}

	this.init_events = function(){
		self.events();
	}

	//events
	this.events = function(){

		//datable column settings
		$('#dt_settings').on('click', function(){

			var body = '';
			body = '<form class="form-horizontal"> ' +
						'
' +
							'Student Number:'+
							'
'+
								'<input type="text" class="form-control" id="student_number" name="student_number">'+
							'
'+
						'
'+
						'
' +
							'Firstname:'+
							'
'+
								'<input type="text" class="form-control" id="first_name" name="first_name">'+
							'
'+
						'
'+
						'
' +
							'Middlename:'+
							'
'+
								'<input type="text" class="form-control" id="middle_name" name="middle_name">'+
							'
'+
						'
'+
						'
' +
							'Lastname:'+
							'
'+
								'<input type="text" class="form-control" id="last_name" name="last_name">'+
							'
'+
						'
'+
					'</form>'

			bootbox.dialog({
			  message: body,
			  title: "Settings",
			  buttons: {
				cancel: {
				  label: "Cancel",
				  className: "btn-default",
				  callback: function() {
					//close dialog
				  }
				},
				apply: {
				  label: "Apply",
				  className: "btn-primary",
				  callback: function() {

					//refresh DT based on filter
					self.users_DT.draw();

					/* //hide or show columns
					var column = self.users_DT.column( 1 );

					// Toggle the visibility
					column.visible( ! column.visible() ); */

				  }
				}
			  }
			});
		});

	}

	//datatable
	this.init_datatable = function(){
		self.users_DT = $('#example').DataTable({
			"responsive":true,
			"dom": '<"row dt-top"<"col-sm-6 dt-limit"l><"col-sm-6 dt-search"f>><"row dt-middle"<"col-sm-12"t>><"row dt-bottom"<"col-sm-6 dt-info"i><"col-sm-6 dt-paginator"p>>',
			"processing": false,
			"serverSide": true,
			"ajax": {
				"url": "datatable/Demo/get_summary",
				"type": "POST",
				"data": function( filter){
					filter.student_number = $('#student_number').val();
					filter.first_name = $('#first_name').val();
					filter.middle_name = $('#middle_name').val();
					filter.last_name = $('#last_name').val();
				}
			},
			"order": [[ 0, "desc" ]],
			"columnDefs": [{
				"orderable": false, "targets": [4],
				"searcheable": false, "targets": [4]
			}],
			"language": {
				"lengthMenu": "Display _MENU_ records per page"
			}
		});
	}

	//datatable events
	this.init_datatable_events = function(){
		$('#example tbody').on('click', 'tr', function () {
			var data = self.users_DT.row( this ).data();
			alert( 'You clicked on ' + data[0] + '\'s row' );
		} );
	}

	//util methods

}

Datatable.init_components();


text:
namespace process
{
	enum class ProcessPriority {
		input			= 100,
		ai				= 200,
		collision		= 600,
		action			= 700,
		world			= 800,
		gui			    = 850,
		render			= 900
	};

	// abstract system interface
	class process
	{
	public:
		explicit process(ProcessPriority priority);
		virtual ~process();
		virtual void start() {}
		virtual void end() {}
		virtual void update(engine& eng, double t, const entity_list& elist) = 0;

		bool process_event(const SDL_Event& evt);
		ProcessPriority get_priority() const { return priority_; }
	private:
		process();
		virtual bool handle_event(const SDL_Event& evt) { return false; }
		ProcessPriority priority_;
	};

	typedef std::shared_ptr<process> process_ptr;
}


text:
<?php

namespace lembdev\WorldPay\Message;

use Omnipay\Common\CreditCard;
use Omnipay\Tests\TestCase;

class PurchaseRequestTest extends TestCase
{
    /** @var PurchaseRequest */
    protected $request;

    public function testSetters()
    {
        $this->initRequest([
            'amount'      => '10.00',
            'currency'    => 'USD',
            'token'       => 'your-token',
            'description' => 'order-description'
        ]);

        $this->assertEquals('ECOM', $this->request->getOrderType());
        $this->request->setOrderType('RECURRING');
        $this->assertEquals('RECURRING', $this->request->getOrderType());
        try {
            $this->request->setOrderType('INCORRECT');
        } catch (\Exception $e) {
            $this->getExpectedException();
        }
    }

    public function testSendTokenSuccess()
    {
        $this->initRequest([
            'amount'      => '10.00',
            'currency'    => 'USD',
            'token'       => 'your-token',
            'description' => 'order-description'
        ]);

        $this->setMockHttpResponse('PurchaseSuccessToken.txt');

        /** @var PurchaseResponse $response */
        $response = $this->request->send();

        $this->assertTrue($response->isSuccessful());
        $this->assertFalse($response->isRedirect());
        $this->assertSame('TEST_RU_1239706c-7d15-4819-89cc-b409390a63e9', $response->getToken());
        $this->assertEquals(500, $response->getAmount());
        $this->assertEquals(2, $response->getCard()->getExpiryMonth());
        $this->assertEquals(2015, $response->getCard()->getExpiryYear());
        $this->assertEquals('Example User', $response->getCard()->getName());
        $this->assertEquals(1111, $response->getCard()->getNumberLastFour());
    }

    public function testSendCardSuccess()
    {
        $creditCard = new CreditCard(array(
            'name'        => 'EXAMPLE CUSTOMER',
            'number'      => '4444 3333 2222 1111',
            'expiryMonth' => 2,
            'expiryYear'  => 2025,
            'cvv'         => '123',
        ));

        $this->initRequest([
            'amount'        => '10.00',
            'currency'      => 'USD',
            'description'   => 'order-description',
            'card'          => $creditCard
        ]);

        $this->setMockHttpResponse('PurchaseSuccessCard.txt');

        /** @var PurchaseResponse $response */
        $response = $this->request->send();

        $this->assertTrue($response->isSuccessful());
        $this->assertFalse($response->isRedirect());
        $this->assertSame('TEST_RU_1239706c-7d15-4819-89cc-b409390a63e9', $response->getToken());
        $this->assertEquals(500, $response->getAmount());
        $this->assertEquals(2, $response->getCard()->getExpiryMonth());
        $this->assertEquals(2020, $response->getCard()->getExpiryYear());
        $this->assertEquals('Example User', $response->getCard()->getName());
        $this->assertEquals(1111, $response->getCard()->getNumberLastFour());
    }

    public function testSendFail()
    {
        $this->initRequest([
            'amount'      => '10.00',
            'currency'    => 'USD',
            'token'       => 'your-token',
            'description' => 'order-description'
        ]);
        $this->setMockHttpResponse('PurchaseFail.txt');

        /** @var PurchaseResponse $response */
        $response = $this->request->send();

        $this->assertFalse($response->isSuccessful());
        $this->assertFalse($response->isRedirect());
        $this->assertEquals('TKN_NOT_FOUND', $response->getCode());
        $this->assertNull($response->getCard());
    }

    protected function initRequest(array $options)
    {
        $_SERVER['REMOTE_ADDR'] = '254.254.254.254';
        $this->request = new PurchaseRequest($this->getHttpClient(), $this->getHttpRequest());
        $this->request->initialize($options);
        $this->request->setServiceKey('test_service_key');
    }
}


text:
from marshmallow import validate

from rdr_service.participant_enums import WorkbenchResearcherEthnicity, \
    WorkbenchWorkspaceAge, WorkbenchWorkspaceStatus, WorkbenchWorkspaceSexAtBirth, WorkbenchWorkspaceGenderIdentity, \
    WorkbenchWorkspaceSexualOrientation, WorkbenchWorkspaceGeography, WorkbenchWorkspaceDisabilityStatus, \
    WorkbenchWorkspaceAccessToCare, WorkbenchWorkspaceEducationLevel, WorkbenchWorkspaceIncomeLevel, \
    WorkbenchWorkspaceUserRole, WorkbenchWorkspaceAccessTier
from rdr_service.resource import Schema, fields
from rdr_service.resource.constants import SchemaID

class WorkspaceRaceEthnicitySchema(Schema):
    race_ethnicity = fields.EnumString(enum=WorkbenchResearcherEthnicity, required=True)
    race_ethnicity_id = fields.EnumInteger(enum=WorkbenchResearcherEthnicity, required=True)

    class Meta:
        schema_id = SchemaID.workbench_workspace_ethnicity
        resource_uri = 'WorkbenchWorkspace/{id}/Ethnicities'
        # Exclude fields and/or functions to strip PII information from fields.
        pii_fields = ()  # List fields that contain PII data.
        pii_filter = {}  # dict(field: lambda function).

class WorkspaceAgeSchema(Schema):
    age = fields.EnumString(enum=WorkbenchWorkspaceAge, required=True)
    age_id = fields.EnumInteger(enum=WorkbenchWorkspaceAge, required=True)

    class Meta:
        schema_id = SchemaID.workbench_workspace_age
        resource_uri = 'WorkbenchWorkspace/{id}/Ages'
        # Exclude fields and/or functions to strip PII information from fields.
        pii_fields = ()  # List fields that contain PII data.
        pii_filter = {}  # dict(field: lambda function).

class WorkbenchWorkspaceSchema(Schema):
    """
    Represents the workbench_workspace_snapshot table.
    """
    workspace_source_id = fields.Int32(required=True)
    name = fields.String(validate=validate.Length(max=1000), required=True)
    creation_time = fields.DateTime(required=True)
    modified_time = fields.DateTime(required=True)
    status = fields.EnumString(enum=WorkbenchWorkspaceStatus, required=True)
    status_id = fields.EnumInteger(enum=WorkbenchWorkspaceStatus, required=True)
    exclude_from_public_directory = fields.Boolean()
    review_requested = fields.Boolean()

    disease_focused_research = fields.Boolean()
    disease_focused_research_name = fields.String(validate=validate.Length(max=1000))
    other_purpose_details = fields.String(validate=validate.Length(max=1000))

    methods_development = fields.Boolean()
    control_set = fields.Boolean()
    ancestry = fields.Boolean()
    social_behavioral = fields.Boolean()
    population_health = fields.Boolean()
    drug_development = fields.Boolean()
    commercial_purpose = fields.Boolean()
    educational = fields.Boolean()
    other_purpose = fields.Boolean()
    ethical_legal_social_implications = fields.Boolean()

    scientific_approaches = fields.Text()
    intend_to_study = fields.Text()
    findings_from_study = fields.Text()

    focus_on_underrepresented_populations = fields.Boolean()

    race_ethnicities = fields.Nested(WorkspaceRaceEthnicitySchema, many=True)
    ages = fields.Nested(WorkspaceAgeSchema, many=True)

    sex_at_birth = fields.EnumString(enum=WorkbenchWorkspaceSexAtBirth, required=True)
    sex_at_birth_id = fields.EnumInteger(enum=WorkbenchWorkspaceSexAtBirth, required=True)
    gender_identity = fields.EnumString(enum=WorkbenchWorkspaceGenderIdentity, required=True)
    gender_identity_id = fields.EnumInteger(enum=WorkbenchWorkspaceGenderIdentity, required=True)
    sexual_orientation = fields.EnumString(enum=WorkbenchWorkspaceSexualOrientation, required=True)
    sexual_orientation_id = fields.EnumInteger(enum=WorkbenchWorkspaceSexualOrientation, required=True)
    geography = fields.EnumString(enum=WorkbenchWorkspaceGeography, required=True)
    geography_id = fields.EnumInteger(enum=WorkbenchWorkspaceGeography, required=True)
    disability_status = fields.EnumString(enum=WorkbenchWorkspaceDisabilityStatus, required=True)
    disability_status_id = fields.EnumInteger(enum=WorkbenchWorkspaceDisabilityStatus, required=True)
    access_to_care = fields.EnumString(enum=WorkbenchWorkspaceAccessToCare, required=True)
    access_to_care_id = fields.EnumInteger(enum=WorkbenchWorkspaceAccessToCare, required=True)
    education_level = fields.EnumString(enum=WorkbenchWorkspaceEducationLevel, required=True)
    education_level_id = fields.EnumInteger(enum=WorkbenchWorkspaceEducationLevel, required=True)
    income_level = fields.EnumString(enum=WorkbenchWorkspaceIncomeLevel, required=True)
    income_level_id = fields.EnumInteger(enum=WorkbenchWorkspaceIncomeLevel, required=True)

    others = fields.String(validate=validate.Length(max=2000))
    is_reviewed = fields.Boolean()

    cdr_version = fields.String(validate=validate.Length(max=200))
    access_tier = fields.EnumString(enum=WorkbenchWorkspaceAccessTier)
    access_tier_id = fields.EnumInteger(enum=WorkbenchWorkspaceAccessTier)

    orig_id = fields.Int32()
    orig_created = fields.DateTime()
    orig_modified = fields.DateTime()

    class Meta:
        schema_id = SchemaID.workbench_workspace
        resource_uri = 'WorkbenchWorkspace'
        resource_pk_field = 'workspace_source_id'
        pii_fields = ()  # List fields that contain PII data.
        pii_filter = {}  # dict(field: lambda function)

class WorkbenchWorkspaceUsersSchema(Schema):

    workspace_id = fields.Int32(required=True)
    researcher_id = fields.Int32(required=True)
    user_id = fields.Int32(required=True)

    role = fields.EnumString(enum=WorkbenchWorkspaceUserRole, required=True)
    role_id = fields.EnumInteger(enum=WorkbenchWorkspaceUserRole, required=True)
    status = fields.EnumString(enum=WorkbenchWorkspaceStatus, required=True)
    status_id = fields.EnumInteger(enum=WorkbenchWorkspaceStatus, required=True)

    is_creator = fields.Boolean()

    orig_id = fields.Int32()
    orig_created = fields.DateTime()
    orig_modified = fields.DateTime()

    class Meta:
        schema_id = SchemaID.workbench_workspace_users
        resource_uri = 'WorkbenchWorkspaceUsers'
        resource_pk_field = 'user_id'
        pii_fields = ()  # List fields that contain PII data.
        pii_filter = {}  # dict(field: lambda function).


text:
from engine.Reloadable import reloadable
from engine.Event import Event

import traceback

@reloadable
class GameObject:
    '''Base class for all entities in the game'''
    def __init__(self, proxy):
        self.components = []
        self._enabled = True
        self.OnEnable = Event()
        self._proxy = proxy

    @property
    def enabled(self):
        return self._enabled

    @enabled.setter
    def enabled(self, value):
        if value:
            if not self._enabled:
                self.OnEnable(self._proxy, True)
        else:
            if self._enabled:
                self.OnEnable(self._proxy, False)
        self._enabled = value

    def addComponent(self, cmp, proxy):
        self.components.append(cmp)
        cmp.owner = proxy
        self.OnEnable.append(cmp._mproxy('onOwnerEnable'))

    def removeComponent(self, cmp):
        self.components.remove(cmp)
        cmp.owner = None
        try:
            self.OnEnable.remove(cmp._mproxy('onOwnerEnable'))
        except Exception:
            traceback.print_exc()

    def _reload(self, other, proxy):
        self._proxy = proxy
        self.components = other.components
        self._enabled = other._enabled
        self.OnEnable = other.OnEnable

@reloadable
class Component:
    '''
        Base class for all components in the game.
        Component can't exist without owner.
    '''
    def __init__(self, proxy, owner = None):
        self._enabled = True
        self.owner = owner
        self.OnEnable = Event()
        self._proxy = proxy

    @property
    def enabled(self):
        return self._enabled and self.owner.enabled

    @enabled.setter
    def enabled(self, value):
        if value:
            if self.owner.enabled:
                self.OnEnable(self._proxy, True)
        else:
            if self.enabled:
                self.OnEnable(self._proxy, False)
        self._enabled = value

    def onOwnerEnable(self, owner, val):
        if val and self._enabled:
            self.OnEnable(self._proxy, True)
        if not val and self.enabled:
            self.OnEnable(self._proxy, False)

    def _reload(self, other, proxy):
        self._proxy = proxy
        self.OnEnable = other.OnEnable
        self._enabled = other._enabled
        self.owner = other.owner


text:
package com.rtg.util.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import com.rtg.util.gzip.GzipUtils;

/**
 * An input stream that does the GZIP deflation in a separate thread.
 * It also does buffering, before and after the Gzip deflation and
 * within the pipe used to connect the GZIP thread to this thread.
 *
 * This class is final, because the helper thread starts in the
 * constructor.
 *
 */
public final class GzipAsynchInputStream extends AsynchInputStream {

  /** Modern disks have about 64 Kb blocks, so make it that size? */
  public static final int DEFAULT_GZIP_BUFFER_SIZE = 64 * 1024;

  // This is so we can do some parameter checking before calling super()
  private static InputStream makeInputStream(File file, int gzipSize) throws IOException {
    if (file == null) {
      throw new IllegalArgumentException("File cannot be null");
    }
    final FileInputStream is = new FileInputStream(file);
    try {
      return GzipUtils.createGzipInputStream(is, gzipSize);
    } catch (IOException e) {
      is.close();
      throw e;
    }
  }

  /**
   * Create an asynchronous GZIP input stream to read the given file.
   *
   * @param file the input file
   * @param pipeSize the size of the buffer between the threads.  At least 1 Kb.
   * @param gzipSize the buffer size of the decompression object.
   * @throws IOException on IO error.
   */
  public GzipAsynchInputStream(File file, int pipeSize, int gzipSize) throws IOException {
    super(makeInputStream(file, gzipSize), pipeSize, gzipSize);
  }

  /**
   * Create an asynchronous GZIP input stream with DEFAULT_GZIP_BUFFER_SIZE.
   *
   * @param file the input file.
   * @throws IOException on IO error.
   */
  public GzipAsynchInputStream(File file) throws IOException {
    this(file, DEFAULT_PIPE_SIZE, DEFAULT_GZIP_BUFFER_SIZE);
  }

  /**
   * Create an asynchronous GZIP input stream with DEFAULT_GZIP_BUFFER_SIZE.
   * @param is the input stream.
   * @throws IOException on IO error.
   */
  public GzipAsynchInputStream(InputStream is) throws IOException {
    super(GzipUtils.createGzipInputStream(is));
  }

}


text:
import json
import os
import os.path
import abc
import argparse
from shutil import copy, rmtree
from test_settings import (virtual_device_host, device_types, config_dir,
                           volttron_install, master_driver_file,
                           host_config_location)

class DeviceConfig(object):
    __metaclass__ = abc.ABCMeta
    def __init__(self, host_address, instance_number, registry_config, interval=60, heart_beat_point=None):
        self.configuration = {"registry_config": registry_config,
                              "driver_type": self.device_type(),
                              "timezone": 'US/Pacific',
                              "interval": interval}

        if heart_beat_point is not None:
            self.configuration["heart_beat_point"] = heart_beat_point

        self.configuration["driver_config"] = self.get_driver_config(host_address, instance_number)

    def __str__(self):
        return json.dumps(self.configuration,
                          indent=4, separators=(',', ': '))

    @abc.abstractmethod
    def device_type(self):
        pass

    @staticmethod
    @abc.abstractmethod
    def get_driver_config(host_address, instance_number):
        pass

    @abc.abstractmethod
    def get_virtual_driver_commandline(self):
        pass

class BACnetConfig(DeviceConfig):
    starting_port = 47808

    def device_type(self):
        return "bacnet"

    @staticmethod
    def get_driver_config(host_address, instance_number):
        return {"device_address": host_address + ":" + str(BACnetConfig.starting_port + instance_number)}

    def get_virtual_driver_commandline(self):
        config_file = os.path.basename(self.configuration["registry_config"])
        interface = self.configuration["driver_config"]["device_address"]
        return "bacnet.py {config} {interface}".format(config=config_file, interface=interface)

class ModbusConfig(DeviceConfig):
    starting_port = 50200

    def device_type(self):
        return "modbus"

    @staticmethod
    def get_driver_config(host_address, instance_number):
        return {"device_address": host_address,
                "port": ModbusConfig.starting_port + instance_number}

    def get_virtual_driver_commandline(self):
        config_file = os.path.basename(self.configuration["registry_config"])
        port = self.configuration["driver_config"]["port"]
        host_address = self.configuration["driver_config"]["device_address"]
        return "modbus.py {config} {interface} --port={port}".format(config=config_file,
                                                                     interface=host_address,
                                                                     port=port)

class FakeConfig(DeviceConfig):
    def device_type(self):
        return "fakedriver"

    @staticmethod
    def get_driver_config(host_address, instance_number):
        return {}

    def get_virtual_driver_commandline(self):
        return ""

device_config_classes = {"bacnet":BACnetConfig,
                         "modbus":ModbusConfig,
                         "fake":FakeConfig}

def build_device_configs(device_type, host_address, count, reg_config_ref, config_dir, interval, output_path):
    #command line to start virtual devices.
    command_lines = []

    try:
        os.makedirs(output_path)
    except os.error:
        pass

    klass = device_config_classes[device_type]
    for i in range(count):
        config_instance = klass(host_address, i, reg_config_ref,
                                interval=interval)

        file_name = device_type + str(i)
        file_path = os.path.join(output_path, file_name)

        with open(file_path, 'w') as f:
            f.write(str(config_instance)+'\n')

        command_lines.append(config_instance.get_virtual_driver_commandline())

    return command_lines

def build_all_configs(device_type, host_address, count, reg_config, config_dir,
                      scalability_test, scalability_test_iterations, driver_scrape_interval,
                      publish_only_depth_all, interval, campus, building):
    '''For command line interface'''
    print(config_dir)

    config_dir = os.path.abspath(config_dir)

    registry_config_dir = os.path.join(config_dir, "registry_configs")
    devices_dir = os.path.join(config_dir, 'devices', campus, building)

    if os.path.exists(devices_dir):
        rmtree(devices_dir, ignore_errors=True)

    if os.path.exists(registry_config_dir):
        rmtree(registry_config_dir, ignore_errors=True)

    try:
        os.makedirs(registry_config_dir)
    except os.error:
        pass

    copy(reg_config, registry_config_dir)

    reg_config_ref = "config://registry_configs/" + os.path.basename(reg_config)

    command_lines = build_device_configs(device_type, host_address, count, reg_config_ref, config_dir, interval, devices_dir)

    build_master_config(config_dir,
                        scalability_test, scalability_test_iterations,
                        driver_scrape_interval, publish_only_depth_all)

def build_master_config(config_dir,
                        scalability_test, scalability_test_iterations,
                        driver_scrape_interval, publish_only_depth_all):
    """Takes the input from multiple called to build_device_configs and create the master config."""
    configuration = {}
    configuration['scalability_test'] = scalability_test
    configuration['scalability_test_iterations'] = scalability_test_iterations
    configuration['driver_scrape_interval'] = driver_scrape_interval

    if publish_only_depth_all:
        configuration["publish_breadth_first_all"] = False
        configuration["publish_depth_first"] = False
        configuration["publish_breadth_first"] = False

    config_str = json.dumps(configuration, indent=4, separators=(',', ': '))

    agent_config = os.path.join(config_dir, "config")

    with open(agent_config, 'w') as f:
        f.write(config_str+'\n')

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Create driver configuration files for scalability test.")

    parser.add_argument('--count', type=int, default=1,
                        help='number of devices to configure')

    parser.add_argument('--scalability-test', action='store_true',
                        help='Configure master driver for a scalability test')

    parser.add_argument('--publish-only-depth-all', action='store_true',
                        help='Configure drivers to only publish depth first all.')

    parser.add_argument('--driver-scrape-interval', type=float, default=0.02,
                        help='Configure interval between individual device publishes.')

    parser.add_argument('--scalability-test-iterations', type=int, default=5,
                        help='Scalability test iterations')

    parser.add_argument('device_type', choices=['bacnet', 'modbus', 'fake'],
                        help='type of device to use for testing')

    parser.add_argument('registry_config',
                        help='registry configuration to use for test devices')

    parser.add_argument('virtual_device_host',
                        help='host of the test devices',
                        default=virtual_device_host)

    parser.add_argument('--config-dir', help='output directory for configurations',
                        default=config_dir)

    parser.add_argument('--interval', help='Scrape interval setting for all drivers',
                        type=float,
                        default=60.0)

    parser.add_argument('--campus',
                        help='campus name used for testing',
                        default='')

    parser.add_argument('--building',
                        help='building name used for testing',
                        default='')

    args = parser.parse_args()
    build_all_configs(args.device_type,
                      args.virtual_device_host, args.count, args.registry_config,
                      args.config_dir, args.scalability_test, args.scalability_test_iterations,
                      args.driver_scrape_interval, args.publish_only_depth_all,
                      args.interval, args.campus, args.building)


text:
if [ -e $1 ]; then
  QUERY_NAME=builtin
else
  QUERY_NAME=$1
fi

OUTPUT_DIR=gen

cd `dirname $0`/..

echo "Generating C++ code from SQL query expression tree"

mkdir -p $OUTPUT_DIR
cd CodeGenerator && ./bin/generate from-query $QUERY_NAME ../$OUTPUT_DIR

echo "Done. Now run 'make' to build the C++ code."


text:
''' Module for Level Tests '''
import json

import requests

from karmaserver.constants import ENDPOINT
from karmaserver.tests.test import TestAbstract
from karmaserver.utils import generate_test_name

class CalculateDefaultPolicyTest(TestAbstract):
    ''' Creates one Observation '''
    def __init__(self):
        self.error_message = ''

    def run(self):
        status, response, _ = _call_server_calculate('default', 1000)
        if not response['code'] == 200:
            self.error_message = response['description']
        return status and response['code'] == 200

    def get_result(self):
        if self.error_message:
            return self.error_message
        return ''

class CalculateNonExistingPolicyTest(TestAbstract):
    ''' Creates one Observation '''
    def __init__(self):
        self.error_message = ''
        self.test_name = generate_test_name()

    def run(self):
        status, response, _ = _call_server_calculate(self.test_name, 1000)
        if not response['code'] == 404:
            self.error_message = response['description']
        return status and response['code'] == 404

    def get_result(self):
        if self.error_message:
            return self.error_message
        return ''

class CalculateExistingPolicyTest(TestAbstract):
    ''' Creates one Observation '''
    def __init__(self):
        self.error_message = ''
        self.policy = _get_policy_data('correct')
        self.test_name = generate_test_name()

    def run(self):
        status, response, _ = _call_server_crud('POST', self.test_name, self.policy)
        status, response, _ = _call_server_calculate(self.test_name, 1000)
        if not response['code'] == 200:
            self.error_message = response['description']
        return status and response['code'] == 200

    def get_result(self):
        if self.error_message:
            return self.error_message
        return ''

class CreateCorrectPolicyTest(TestAbstract):
    ''' Creates one Observation '''
    def __init__(self):
        self.error_message = ''
        self.test_name = generate_test_name()
        self.policy = _get_policy_data('correct')

    def run(self):
        status, response, _ = _call_server_crud('POST', self.test_name, self.policy)
        if not response['code'] == 201:
            self.error_message = response['description']
        return status and response['code'] == 201

    def get_result(self):
        if self.error_message:
            return self.error_message
        return ''

class CreateDefaultPolicyTest(TestAbstract):
    ''' Creates one Observation '''
    def __init__(self):
        self.error_message = ''
        self.policy = _get_policy_data('correct')

    def run(self):
        status, response, _ = _call_server_crud('POST', 'default', self.policy)
        if not response['code'] == 400:
            self.error_message = response['description']
        return status and response['code'] == 400

    def get_result(self):
        if self.error_message:
            return self.error_message
        return ''

class CreateEmptyPolicyTest(TestAbstract):
    ''' Creates one Observation '''
    def __init__(self):
        self.error_message = ''
        self.test_name = generate_test_name()
        self.policy = _get_policy_data('empty')

    def run(self):
        status, response, _ = _call_server_crud('POST', self.test_name, self.policy)
        if not response['code'] == 400:
            self.error_message = response['description']
        return status and response['code'] == 400

    def get_result(self):
        if self.error_message:
            return self.error_message
        return ''

class CreateInvalidFormulaPolicyTest(TestAbstract):
    ''' Creates one Observation '''
    def __init__(self):
        self.error_message = ''
        self.test_name = generate_test_name()
        self.policy = _get_policy_data('bad_formula')

    def run(self):
        status, response, _ = _call_server_crud('POST', self.test_name, self.policy)
        if not response['code'] == 400:
            self.error_message = response['description']
        return status and response['code'] == 400

    def get_result(self):
        if self.error_message:
            return self.error_message
        return ''

class CreateInvalidMaxLevelPolicyTest(TestAbstract):
    ''' Creates one Observation '''
    def __init__(self):
        self.error_message = ''
        self.test_name = generate_test_name()
        self.policy = _get_policy_data('nan')

    def run(self):
        status, response, _ = _call_server_crud('POST', self.test_name, self.policy)
        if not response['code'] == 400:
            self.error_message = response['description']
        return status and response['code'] == 400

    def get_result(self):
        if self.error_message:
            return self.error_message
        return ''

class CreateRepeatedPolicyTest(TestAbstract):
    ''' Creates one Observation '''
    def __init__(self):
        self.error_message = ''
        self.test_name = generate_test_name()
        self.policy = _get_policy_data('correct')

    def run(self):
        status, response, _ = _call_server_crud('POST', self.test_name, self.policy)
        status, response, _ = _call_server_crud('POST', self.test_name, self.policy)
        if not response['code'] == 400:
            self.error_message = response['description']
        return status and response['code'] == 400

    def get_result(self):
        if self.error_message:
            return self.error_message
        return ''

class UpdateBadFormulaTest(TestAbstract):
    ''' Creates one Observation '''
    def __init__(self):
        self.error_message = ''
        self.policy = _get_policy_data('only_bad_formula')

    def run(self):
        status, response, _ = _call_server_crud('PUT', 'default', self.policy)
        if not response['code'] == 400:
            self.error_message = response['description']
        return status and response['code'] == 400

    def get_result(self):
        if self.error_message:
            return self.error_message
        return ''

class UpdateInvalidMaxLevelTest(TestAbstract):
    ''' Creates one Observation '''
    def __init__(self):
        self.error_message = ''
        self.policy = _get_policy_data('only_bad_level')

    def run(self):
        status, response, _ = _call_server_crud('PUT', 'default', self.policy)
        if not response['code'] == 400:
            self.error_message = response['description']
        return status and response['code'] == 400

    def get_result(self):
        if self.error_message:
            return self.error_message
        return ''

class UpdateMaxLevelTest(TestAbstract):
    ''' Creates one Observation '''
    def __init__(self):
        self.error_message = ''
        self.policy = _get_policy_data('only_level')

    def run(self):
        status, response, _ = _call_server_crud('PUT', 'default', self.policy)
        if not response['code'] == 200:
            self.error_message = response['description']
        return status and response['code'] == 200

    def get_result(self):
        if self.error_message:
            return self.error_message
        return ''

class DeleteNonExistingPolicy(TestAbstract):
    ''' Creates one Observation '''
    def __init__(self):
        self.error_message = ''
        self.test_name = generate_test_name()

    def run(self):
        status, response, _ = _call_server_crud('DELETE', self.test_name)
        if not response['code'] == 404:
            self.error_message = response['description']
        return status and response['code'] == 404

    def get_result(self):
        if self.error_message:
            return self.error_message
        return ''

class DeleteExistingPolicy(TestAbstract):
    ''' Creates one Observation '''
    def __init__(self):
        self.error_message = ''
        self.test_name = generate_test_name()
        self.policy = _get_policy_data('correct')

    def run(self):
        status, response, _ = _call_server_crud('POST', self.test_name, self.policy)
        status, response, _ = _call_server_crud('DELETE', self.test_name)
        if not response['code'] == 200:
            self.error_message = response['description']
        return status

    def get_result(self):
        if self.error_message:
            return self.error_message
        return ''

class GetInfoExistingPolicy(TestAbstract):
    ''' Creates one Observation '''
    def __init__(self):
        self.error_message = ''
        self.test_name = generate_test_name()
        self.policy = _get_policy_data('correct')

    def run(self):
        status, response, _ = _call_server_crud('POST', self.test_name, self.policy)
        status, response, _ = _call_server_crud('GET', self.test_name)
        if not response['code'] == 200:
            self.error_message = response['description']
        return status and response['code'] == 200

    def get_result(self):
        if self.error_message:
            return self.error_message
        return ''

class GetInfoNonExistingPolicy(TestAbstract):
    ''' Creates one Observation '''
    def __init__(self):
        self.error_message = ''
        self.test_name = generate_test_name()

    def run(self):
        status, response, _ = _call_server_crud('GET', self.test_name)
        if not response['code'] == 404:
            self.error_message = response['description']
        return status and response['code'] == 404

    def get_result(self):
        if self.error_message:
            return self.error_message
        return ''

class GetInfoDeletedPolicy(TestAbstract):
    ''' Creates one Observation '''
    def __init__(self):
        self.error_message = ''
        self.test_name = generate_test_name()
        self.policy = _get_policy_data('correct')

    def run(self):
        status, response, _ = _call_server_crud('POST', self.test_name, self.policy)
        status, response, _ = _call_server_crud('DELETE', self.test_name)
        status, response, _ = _call_server_crud('GET', self.test_name)
        if not response['code'] == 404:
            self.error_message = response['description']
        return status and response['code'] == 404

    def get_result(self):
        if self.error_message:
            return self.error_message
        return ''

def _call_server_crud(method, policy_id, policy_data=None):
    try:
        if method == 'POST':
            response = requests.post(f'{ENDPOINT}/level/{policy_id}', json=policy_data)
        if method == 'GET':
            response = requests.get(f'{ENDPOINT}/level/{policy_id}')
        if method == 'PUT':
            response = requests.put(f'{ENDPOINT}/level/{policy_id}', json=policy_data)
        if method == 'DELETE':
            response = requests.delete(f'{ENDPOINT}/level/{policy_id}')
        time_ = float(response.headers['Request-Time'].replace(" ns", ""))
        return True, response.json(), time_
    except requests.exceptions.ConnectionError:
        return False, 'Could not connect to the server', None

def _call_server_calculate(policy_id, points):
    try:
        response = requests.get(f'{ENDPOINT}/level/{policy_id}/{points}')
        time_ = float(response.headers['Request-Time'].replace(" ns", ""))
        return True, response.json(), time_
    except requests.exceptions.ConnectionError:
        return False, 'Could not connect to the server', None

def _get_policy_data(json_name):
    with open(f'examples/level/{json_name}.json') as data_file:
        return json.load(data_file)


text:
demo-consumer
=============

A sample consumer application


text:
import msgpack

class MsgPackRenderer(object):
    def __init__(self, info):
        pass
    def __call__(self, value, system):
        request = system.get('request')
        if request is not None:
            response = request.response
            ct = response.content_type
            if ct == response.default_content_type:
                response.content_type = 'application/x-msgpack'
        return msgpack.packb(value)

import ujson
class UjsonRenderer(object):
    def __init__(self, info):
        pass
    def __call__(self, value, system):
        request = system.get('request')
        if request is not None:
            response = request.response
            ct = response.content_type
            if ct == response.default_content_type:
                response.content_type = 'application/x-json'
        return ujson.dumps(value)


text:
var theBody = document.body;
// create a para and insert it at the top of the body
var element = document.createElement("p");
element.id = "status";
element.style.cssText = "float:right; color:red";
element.textContent = "Waiting...";
theBody.insertBefore(element, theBody.firstChild);

function replyToMessage(aMessageEvent: SafariExtensionMessageEvent) {
   if (aMessageEvent.name === "hey") {
    document.getElementById("status").textContent="Message received.";
    safari.self.tab.dispatchMessage("gotIt","Message acknowledged.");
    }
}
// register for message events
safari.self.addEventListener("message", replyToMessage, false);

// https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/AddingContextualMenuItems/AddingContextualMenuItems.html#//apple_ref/doc/uid/TP40009977-CH4-SW15
document.addEventListener("contextmenu", handleContextMenu, false);

function handleContextMenu(event: MouseEvent) {
    safari.self.tab.setContextMenuEventUserInfo(event, (<Node>event.target).nodeName);
}

// https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/AddingContextualMenuItems/AddingContextualMenuItems.html#//apple_ref/doc/uid/TP40009977-CH4-SW16
document.addEventListener("contextmenu", handleContextMenu2, false);

function handleContextMenu2(event: MouseEvent) {
    if ((<Node>event.target).nodeName == "VIDEO") {
        event.preventDefault();
    }
}

// https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/MessagesandProxies/MessagesandProxies.html#//apple_ref/doc/uid/TP40009977-CH14-SW2
var initialVal=1;
var calculatedVal=0 ;

function doBigCalc(theData: number) {
    safari.self.tab.dispatchMessage("calcThis",theData);
}

function getAnswer(theMessageEvent: SafariExtensionMessageEvent) {
    if (theMessageEvent.name === "theAnswer") {
        calculatedVal=theMessageEvent.message;
        console.log(calculatedVal);
    }
}
safari.self.addEventListener("message", getAnswer, false);

doBigCalc(initialVal);

//https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/MessagesandProxies/MessagesandProxies.html#//apple_ref/doc/uid/TP40009977-CH14-SW9
function isItOkay(event: BeforeLoadEvent) {
    var myMessageData = event.url;
    var theAnswer = safari.self.tab.canLoad(event, myMessageData);
    if (theAnswer == "block") {
        event.preventDefault();
    }
}

document.addEventListener("beforeload", isItOkay, true);


text:
package org.reliable.infrastructure.entities_controllers.util;

import javax.persistence.AssociationOverride;
import javax.persistence.AssociationOverrides;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.reliable.infrastructure.entities_controllers.alert.Alert;
import org.reliable.infrastructure.entities_controllers.client.Client;

import com.fasterxml.jackson.annotation.JsonIgnore;

@Entity
@Table(name ="alert_client")
@AssociationOverrides({
@AssociationOverride(name ="pk.alert", joinColumns = @JoinColumn(name ="alert_idalert")),
@AssociationOverride(name ="pk.client", joinColumns = @JoinColumn(name ="client_idclient"))
        })
public class AlertClient {

	@EmbeddedId
	private AlertClientPk pk = new AlertClientPk();

	@Basic(optional = false)
    @Column(name = "status")
	private String status;

	public AlertClient() {
	}

	@Transient
	@JsonIgnore
	public Alert getAlert() {
		return pk.getAlert();
	}

	public void setAlert(Alert alert) {
		pk.setAlert(alert);
	}

	@Transient
	public Client getClient() {
		return pk.getClient();
	}

	public void setClient(Client client) {
		pk.setClient(client);
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

}


text:
<!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>
Uses of Class org.apache.solr.core.CoreDescriptor (Solr 4.3.1 API)
</TITLE>

<META NAME="date" CONTENT="2013-06-09">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.solr.core.CoreDescriptor

Packages that use CoreDescriptor

org.apache.solr.cloud

Classes for dealing with ZooKeeper when operating in SolrCloud mode.

org.apache.solr.core

Core classes implementin Solr internals and the management of SolrCores

org.apache.solr.update

APIs and classes for managing index updates

Uses of CoreDescriptor in org.apache.solr.cloud

Methods in org.apache.solr.cloud that return types with arguments of type CoreDescriptor

abstract  List<CoreDescriptor>
CurrentCoreDescriptorProvider.getCurrentDescriptors()

Methods in org.apache.solr.cloud with parameters of type CoreDescriptor

 String
ZkController.getCoreNodeName(CoreDescriptor descriptor)

 void
ZkController.publish(CoreDescriptor cd,
        String state)

 void
ZkController.publish(CoreDescriptor cd,
        String state,
        boolean updateLastState)

          Publish core state to overseer.

 String
ZkController.register(String coreName,
         CoreDescriptor desc)

          Register shard with ZooKeeper.

 String
ZkController.register(String coreName,
         CoreDescriptor desc,
         boolean recoverReloadedCores,
         boolean afterExpiration)

          Register shard with ZooKeeper.

 void
ZkController.unregister(String coreName,
           CoreDescriptor cd)

Constructors in org.apache.solr.cloud with parameters of type CoreDescriptor

RecoveryStrategy(CoreContainer cc,
                 CoreDescriptor cd,
                 RecoveryStrategy.RecoveryListener recoveryListener)

Uses of CoreDescriptor in org.apache.solr.core

Methods in org.apache.solr.core that return CoreDescriptor

 CoreDescriptor
SolrCore.getCoreDescriptor()

 CoreDescriptor
CoreContainer.getUnloadedCoreDescriptor(String cname)

          Gets a solr core descriptor for a core that is not loaded.

Methods in org.apache.solr.core with parameters of type CoreDescriptor

 SolrCore
CoreContainer.create(CoreDescriptor dcore)

          Creates a new core based on a descriptor but does not register it.

Constructors in org.apache.solr.core with parameters of type CoreDescriptor

CoreDescriptor(CoreDescriptor descr)

SolrCore(String name,
         CoreDescriptor cd)

          Creates a new core that is to be loaded lazily.

SolrCore(String name,
         String dataDir,
         SolrConfig config,
         IndexSchema schema,
         CoreDescriptor cd)

          Creates a new core and register it in the list of cores.

SolrCore(String name,
         String dataDir,
         SolrConfig config,
         IndexSchema schema,
         CoreDescriptor cd,
         UpdateHandler updateHandler,
         IndexDeletionPolicyWrapper delPolicy,
         SolrCore prev)

          Creates a new core and register it in the list of cores.

Uses of CoreDescriptor in org.apache.solr.update

Methods in org.apache.solr.update with parameters of type CoreDescriptor

abstract  void
SolrCoreState.doRecovery(CoreContainer cc,
           CoreDescriptor cd)

 void
DefaultSolrCoreState.doRecovery(CoreContainer cc,
           CoreDescriptor cd)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

          Copyright © 2000-2013 Apache Software Foundation.  All Rights Reserved.


text:
============
Installation
============

At the command line::

    $ easy_install booksforcha

Or, if you have virtualenvwrapper installed::

    $ mkvirtualenv booksforcha
    $ pip install booksforcha


text:
class Profile;
class UserContext;

namespace gfx {
class Rect;
class Size;
}  // namespace gfx

namespace content {
class StoragePartition;
}

namespace network {
namespace mojom {
class NetworkContext;
}
class SharedURLLoaderFactory;
}

namespace ash {

// Returns bounds of the screen to use for login wizard.
// The rect is centered within the default monitor and sized accordingly if
// `size` is not empty. Otherwise the whole monitor is occupied.
gfx::Rect CalculateScreenBounds(const gfx::Size& size);

// Returns the size of user image required for proper display under current DPI.
int GetCurrentUserImageSize();

// Define the constants in `login` namespace to avoid potential
// conflict with other chromeos components.
namespace login {

// Maximum size of user image, in which it should be saved to be properly
// displayed under all possible DPI values.
const int kMaxUserImageSize = 512;

// Returns true if lock/login should scroll user pods into view itself when
// virtual keyboard is shown and disable vk overscroll.
bool LoginScrollIntoViewEnabled();

// A helper class for easily mocking out Network*Handler calls for tests.
class NetworkStateHelper {
 public:
  NetworkStateHelper();

  NetworkStateHelper(const NetworkStateHelper&) = delete;
  NetworkStateHelper& operator=(const NetworkStateHelper&) = delete;

  virtual ~NetworkStateHelper();

  // Returns name of the currently connected network.
  // If there are no connected networks, returns name of the network
  // that is in the "connecting" state. Otherwise empty string is returned.
  // If there are multiple connected networks, network priority:
  // Ethernet > WiFi > Cellular. Same for connecting network.
  virtual std::u16string GetCurrentNetworkName() const;

  // Returns true if the default network is in connected state.
  virtual bool IsConnected() const;

  // Returns true if the ethernet network is in connected state.
  virtual bool IsConnectedToEthernet() const;

  // Returns true if the default network is in connecting state.
  virtual bool IsConnecting() const;

 private:
  void OnCreateConfiguration(base::OnceClosure success_callback,
                             network_handler::ErrorCallback error_callback,
                             const std::string& service_path,
                             const std::string& guid) const;
};

//
// Webview based login helpers.
//

// Returns the storage partition for the sign-in webview. Note the function
// returns nullptr if the sign-in partition is not available yet, or if sign-in
// webui is torn down.
content::StoragePartition* GetSigninPartition();

// Returns the storage partition for the lock screen webview. Can return nullptr
// if the lock screen partition is not available.
content::StoragePartition* GetLockScreenPartition();

// Returns the network context for the sign-in webview. Note the function
// returns nullptr if the sign-in partition is not available yet, or if sign-in
// webui is torn down.
network::mojom::NetworkContext* GetSigninNetworkContext();

// Returns the URLLoaderFactory that contains sign-in cookies. For old iframe
// based flow, the URLLoaderFactory of the sign-in profile is returned. For
// webview basedflow, the URLLoaderFactory of the sign-in webview storage
// partition is returned.
scoped_refptr<network::SharedURLLoaderFactory> GetSigninURLLoaderFactory();

// Saves sync password hash and salt to profile prefs. These will be used to
// detect Gaia password reuses.
void SaveSyncPasswordDataToProfile(const UserContext& user_context,
                                   Profile* profile);

// Returns time remaining to the next online login. The value can be negative
// which means that online login should have been already happened in the past.
base::TimeDelta TimeToOnlineSignIn(base::Time last_online_signin,
                                   base::TimeDelta offline_signin_limit);

}  // namespace login
}  // namespace ash

#endif  // CHROME_BROWSER_ASH_LOGIN_HELPER_H_


text:
// Generated source.
// Generator: org.chromium.sdk.internal.wip.tools.protocolgenerator.Generator
// Origin: http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/inspector/Inspector.json@135591

package org.chromium.sdk.internal.wip.protocol.output.runtime;

/**
Evaluates expression on global object.
 */
public class EvaluateParams extends org.chromium.sdk.internal.wip.protocol.output.WipParamsWithResponse<org.chromium.sdk.internal.wip.protocol.input.runtime.EvaluateData> {
  /**
   @param expression Expression to evaluate.
   @param objectGroupOpt Symbolic group name that can be used to release multiple objects.
   @param includeCommandLineAPIOpt Determines whether Command Line API should be available during the evaluation.
   @param doNotPauseOnExceptionsAndMuteConsoleOpt Specifies whether evaluation should stop on exceptions and mute console. Overrides setPauseOnException state.
   @param contextIdOpt Specifies in which isolated context to perform evaluation. Each content script lives in an isolated context and this parameter may be used to specify one of those contexts. If the parameter is omitted or 0 the evaluation will be performed in the context of the inspected page.
   @param returnByValueOpt Whether the result is expected to be a JSON object that should be sent by value.
   @param generatePreviewOpt Whether preview should be generated for the result.
   */
  public EvaluateParams(String expression, String objectGroupOpt, Boolean includeCommandLineAPIOpt, Boolean doNotPauseOnExceptionsAndMuteConsoleOpt, Long/*See org.chromium.sdk.internal.wip.protocol.common.runtime.ExecutionContextIdTypedef*/ contextIdOpt, Boolean returnByValueOpt, Boolean generatePreviewOpt) {
    this.put("expression", expression);
    if (objectGroupOpt != null) {
      this.put("objectGroup", objectGroupOpt);
    }
    if (includeCommandLineAPIOpt != null) {
      this.put("includeCommandLineAPI", includeCommandLineAPIOpt);
    }
    if (doNotPauseOnExceptionsAndMuteConsoleOpt != null) {
      this.put("doNotPauseOnExceptionsAndMuteConsole", doNotPauseOnExceptionsAndMuteConsoleOpt);
    }
    if (contextIdOpt != null) {
      this.put("contextId", contextIdOpt);
    }
    if (returnByValueOpt != null) {
      this.put("returnByValue", returnByValueOpt);
    }
    if (generatePreviewOpt != null) {
      this.put("generatePreview", generatePreviewOpt);
    }
  }

  public static final String METHOD_NAME = org.chromium.sdk.internal.wip.protocol.BasicConstants.Domain.RUNTIME + ".evaluate";

  @Override protected String getRequestName() {
    return METHOD_NAME;
  }

  @Override public org.chromium.sdk.internal.wip.protocol.input.runtime.EvaluateData parseResponse(org.chromium.sdk.internal.wip.protocol.input.WipCommandResponse.Data data, org.chromium.sdk.internal.wip.protocol.input.WipGeneratedParserRoot parser) throws org.chromium.sdk.internal.protocolparser.JsonProtocolParseException {
    return parser.parseRuntimeEvaluateData(data.getUnderlyingObject());
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-model href="http://docbook.org/xml/5.1/rng/docbook.rng" schematypens="http://relaxng.org/ns/structure/1.0"?>
<?xml-model href="http://docbook.org/xml/5.1/sch/docbook.sch" type="application/xml" schematypens="http://purl.oclc.org/dsdl/schematron"?>
<chapter xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink" version="5.1">
    <title><?oxy_comment_start author="timowilliams" timestamp="20190823T110530-0500" comment="Add ISO 1087, and Chute et al requirements as well."?>Terminology
        Intro<?oxy_comment_end?></title>
    <para>The desiderata for the design of a controlled
        healthcare<?oxy_comment_start author="kec" timestamp="20190516T104634-0700" comment="We need to be consistent in our use of language. Interchanging Terminology and Vocabulary can be confusing to those that are not used to blocking out the distinctions. I recommend we stick with terminology, and not include the title of Jim's paper in the text. Just say someting like Cimino published criterion upon which terminologies should be evaluated in 1989." flag="done"?><?oxy_comment_end?>
        terminology
        <?oxy_comment_start author="kec" timestamp="20190516T104401-0700" comment="I'd be very cautious about the phrasing of "first published" implying that no one else published anything prior.  " flag="done"?>was
        published in 1989<?oxy_comment_end?> with seven items and was expanded in 1998 to a list of
        twelve desiderata in the paper by JJ Cimino.<citation>desiderata</citation> These desiderata are used to describe desirable
        characteristics of controlled medical terminologies. They are:<itemizedlist>
            <listitem>
                <para>Content</para>
                <para>While missing content is expected, formally stated processes for requesting
                    and adding content is required. SNOMED CT, LOINC and RxNorm all have formal
                    processes in place for requesting changes to the terminologies either through
                    the organization that maintains them or through a national release center in the
                    case of SNOMED CT. While content can be added using these formal processes,
                    there is usually a delay before a formal
                    <?oxy_comment_start author="steph" timestamp="20191016T103843-0600" comment="Should this be "edition" instead?"?>addition<?oxy_comment_end?>
                    is available for use. In addition to the formal processes available through the
                    standards development organizations (SDOs), SNOMED CT includes formal mechanisms
                    for users to extend the terminology and add missing content locally.</para>
            </listitem>
            <listitem>
                <para>Concept orientation</para>
                <para>The most granular piece of a terminology must be a concept with a single
                    coherent meaning. Terms associated with a code should represent a single
                    concept.</para>
                <para>In the 1998 paper <citation>Representing Thoughts, Words, and Things in the
                        UMLS</citation> the authors describe that the Ogden Richards' semiotic
                        triangle<quote> shows that, although written or spoken symbols (words)
                        cannot completely capture the essence of a reference (thought) or of a
                        referent (thing), there is a correspondence among them. Either a word or an
                        object can inspire a thought, and people may endeavor to express their
                        thoughts with words or by identifying objects in the world. The relationship
                        between a word and a thing is indirect, however. The link can be completed
                        only when an interpreter (usually a person) processes the word, which
                        invokes a corresponding thought, and then links that thought to a thing in
                        the world (the "referent"). This diagram is seductive in its
                        simplicity.</quote></para>
                <para><quote>By implying a one-to-one relationship between each pair of members in
                        the triangle, this simple diagram masks hidden complexity. Ogden and
                        Richards alluded to this complexity by the dotted line between a symbol and
                        a referent, indicating that the link between a symbol and a referent can
                        only be made indirectly through an interpreter, but the notion that a symbol
                        does—or could—refer to a single thought and that a thought does—or
                        could—refer to a single referent is a fallacy. Thus, it has been
                        historically recognized that multiple terms may refer to the same object or
                        idea, a single term may refer ambiguously to more than one object or idea,
                        and terms may be confusing because they are out of date. It is within this
                        context that we seek solutions to improve our ability to communicate about
                        biomedical concepts.</quote></para>
                <para>
                    <figure>
                        <title>Ogden and Richards semiotic triangle</title>
                        <mediaobject>
                            <imageobject>
                                <?oxy_comment_start author="timowilliams" timestamp="20190430T200411-0500" comment="Convert image to svg"?>
                                <imagedata fileref="images/terminology_semiotictriangle.jpg"/><?oxy_comment_end?>
                            </imageobject>
                        </mediaobject>
                    </figure>
                </para>
            </listitem>
            <listitem>
                <para>Concept permanence</para>
                <para>A concept's meaning cannot change, and concepts cannot be deleted after they
                    have been released. Once added to a terminology, concepts and their identifiers
                    should persist. However, a mechanism to make concepts inactive when they are
                    deemed to be duplicate or erroneous should be available. Terminologies like
                    SNOMED CT and LOINC both have mechanisms for inactivating concepts after they
                    have been deemed to be in error.</para>
            </listitem>
            <listitem>
                <para>Meaningless concept identifiers</para>
                <para>Concepts should use unique identifiers that do not contain any contextual
                    information about a concept. Identifiers should not include any hierarchical
                    information that would prevent changes in the concepts hierarchy without
                    retirement.</para>
            </listitem>
            <listitem>
                <para>Polyhierarchy</para>
                <para>In traditional classification systems, categories are only allowed to exist in
                    a single monohierarchical representation. For example, in ICD-10 A39.0
                    Meningococcal meningitis only exists as a subtype of A39 Meningococcal
                    infection.  In this representation you can easily find all meningococcal
                    infections, but if you need to find all types of meningitis you are required to
                    know all the various codes that represent the different classifications of meningitis.<figure>
                        <title><?oxy_comment_start author="steph" timestamp="20190903T155353-0600" comment="Can you center the text in the boxes below and fix the first box where the text is cutoff?" flag="done"?><?oxy_comment_start author="steph" timestamp="20191016T113247-0600" comment="This is still a problem - the text is cutoff." mid="6"?>Monohierarchy
                            Example<?oxy_comment_end?><?oxy_comment_end mid="6"?></title>
                        <mediaobject>
                            <imageobject>
                                <imagedata fileref="images/meningitis_monohierarchy.svg"
                                    scalefit="1" width="100%" contentdepth="100%"/>
                            </imageobject>
                        </mediaobject>
                    </figure></para>
                <para>In a well designed terminology, concepts should be allowed to exist in
                    multiple hierarchies if multiple parent concepts are appropriate. For example,
                    <?oxy_comment_start author="timowilliams" timestamp="20190430T201423-0500" comment="Add image representing the polyhierarchy" id="m3l_gb2_xhb" flag="done" mid="4"?><?oxy_comment_start author="rcholan" timestamp="20190528T215454-0400" comment="Adding initial image. Will re-create." parentID="m3l_gb2_xhb" flag="done" mid="5"?><?oxy_comment_start author="steph" timestamp="20190806T085004-0600" comment="Recommend removing most of the white space around the image that isn't needed and is forcing "hierarchies" to be hyphenated and shown before and after the image." flag="done"?>Bacterial
                    meningitis is both a subtype of Bacterial Meningitis and Meningococcal
                    infectious disease and should exist in both hierarchies.<?oxy_comment_end?><?oxy_comment_end mid="5"?><?oxy_comment_end mid="4"?>
                    <figure>
                        <title>Polyhierarchy Example</title>
                        <mediaobject>
                            <imageobject>
                                <imagedata fileref="images/meningitis_polyhierarchy.svg"
                                    scalefit="1" width="100%" contentdepth="100%"/>
                            </imageobject>
                        </mediaobject>
                    </figure></para>
            </listitem>
            <listitem>
                <para><?oxy_comment_start author="timowilliams" timestamp="20190430T201919-0500" comment="Should we add a comparison of stated vs inferred definitions here?
" flag="done" mid="7"?><?oxy_comment_start author="steph" timestamp="20190507T163331-0600" comment="I think that would be helpful." id="p3x_b22_xhb" flag="done" mid="8"?><?oxy_comment_start author="rcholan" timestamp="20190528T221625-0400" comment="Added some draft explanation. Need example to help." parentID="p3x_b22_xhb" flag="done" mid="9"?><?oxy_comment_start author="steph" timestamp="20190812T161629-0600" comment="I think it needs to be more "in your face," where you have the each term of stated and inferred, followed by their own definitions." flag="done"?>Formal
                    definitions<?oxy_comment_end?><?oxy_comment_end mid="9"?><?oxy_comment_end mid="8"?><?oxy_comment_end mid="7"?></para>
                <para>While hierarchical information is paramount, the inclusion of additional
                    definitional knowledge can help maintain and correctly place concepts within the
                    appropriate hierarchy. Allowing computers to use this additional information can
                    aid in properly placing concepts in hierarchies that developers did not
                    originally add to a concept.</para>
                <para>When content modelers add new content to a terminology, the relationships they
                    create are sometimes called stated relationships. These stated relationships
                    help to give concepts a formal definition and can be used to correctly place a
                    concept in new hierarchies the content modeler did not originally assign. In
                    large terminologies, correctly adding all the possible valid hierarchical
                    relationships can be difficult as it requires the content modeler to think of
                    all the possible parents. By adding the additional information, like Finding
                    Site in the example below, additional hierarchical relationships can be inferred.<figure>
                        <?oxy_comment_start author="steph" timestamp="20190903T164307-0600" comment="Need to fix the text in circles to make it fit fully and not be cutoff, as it currently is.  With the text being white on a white background, the cutoff text cannot be read outside of the circles.  Same for the second diagram for inferred below." flag="done"?>
                        <?oxy_comment_start author="steph" timestamp="20191016T113507-0600" comment="Still not fixed.  I think it needs to be fixed; otherwise, it appears as sloppy work." mid="15"?>
                        <title>Relationships Stated by a Content
                            Modeler<?oxy_comment_end?><?oxy_comment_end mid="15"?></title>
                        <mediaobject>
                            <imageobject>
                                <imagedata fileref="images/stated_relationships.svg" scalefit="1"
                                    width="100%" contentdepth="100%"/>
                            </imageobject>
                        </mediaobject>
                    </figure></para>
                <para>DL ontologies can be classified (i.e., some relationships between concepts are
                    inferred from the asserted class descriptions) using a DL classifier and a new
                    set of inferred relationships is created for concepts. Solor provides both views
                    of stated and inferred relationships, and allow users to compare the
                    differences. Solor has blocks of necessary & sufficient, necessary, and
                    inherited (i.e., inferred) relationships. <figure>
                        <title>Inferred Relationships by DL Classifier</title>
                        <mediaobject>
                            <imageobject>
                                <imagedata fileref="images/inferred_relationships.svg" scalefit="1"
                                    width="100%" contentdepth="100%"/>
                            </imageobject>
                        </mediaobject>
                    </figure></para>
            </listitem>
            <listitem>
                <para>No residual categories (Reject "Not Elsewhere Classified")</para>
                <para>Since terminologies will never be completely finished, it is easy to reject
                    the concept orientation desiderata and begin to create or use concepts as
                    grouper categories for missing content. Doing so introduces a "semantic drift"
                    that will cause problems with properly identifying historical data. By assigning
                    meaning to a category or using a less specific concept to represent your
                    intended meaning, information is lost. Rejecting these categories requires the
                    capability to extend content as described in the first desiderata.</para>
            </listitem>
            <listitem>
                <para>Multiple granularities</para>
                <para>The ability to represent meaning occurs at various levels, depending on the
                    setting of care and users of the terminology. As care progresses, a more finer
                    grained concept may be required to more accurately represent the diagnosis.
                </para>
            </listitem>
            <listitem>
                <para>Multiple consistent views</para>
                <?oxy_comment_start author="timowilliams" timestamp="20190430T202611-0500" comment="Insert Cranial Nerve example here" id="bwk_122_xhb" flag="done" mid="14"?>
                <?oxy_comment_start author="rcholan" timestamp="20190528T221559-0400" comment="Inserting initial image. Will re-create." parentID="bwk_122_xhb" flag="done" mid="16"?>
                <?oxy_comment_start author="steph" timestamp="20190806T085156-0600" comment="Recommend removing most of the white space around the image that isn't needed and is forcing "usable" to be hyphenated and shown before and after the image." flag="done"?>
                <?oxy_comment_start author="steph" timestamp="20190903T164556-0600" comment="There is still a lot of unnecessary white space above/below the diagram that should be deleted." mid="15"?>
                <para>In addition to representing meaning at various levels, the display of the
                    concepts that are relevant to certain users should be able to be customized.
                    Allowing users to view concepts in a way that is intuitive will support the
                    adoption of terminologies by making the terminology more usable.<?oxy_comment_end mid="15"?><?oxy_comment_end?><?oxy_comment_end mid="16"?><?oxy_comment_end mid="14"?>
                    <figure>
                        <title>Multiple Consistent Views</title>
                        <mediaobject>
                            <imageobject>
                                <?oxy_comment_start author="steph" timestamp="20190610T132412-0600" comment="In the PDF, the "After" image is not shown, only the before image.  Either need to resize or move the "After" image below the "Before" image." flag="done"?>
                                <?oxy_comment_start author="timowilliams" timestamp="20190814T134943-0500" comment="convert to SVG" mid="18"?>
                                <imagedata fileref="images/CranialNerves.svg" scalefit="1"
                                    width="100%" contentdepth="100%"
                                ><?oxy_comment_end?></imagedata><?oxy_comment_end mid="18"?>
                            </imageobject>
                        </mediaobject>
                    </figure>
                </para>
            </listitem>
            <listitem>
                <para>Representing context</para>
                <para>Terminologies should allow for the representation of the context in which the
                    concepts should be used. While some contextual information should not be
                    supported in the terminology (like date, time, names, etc), other contextual
                    information should be supported (for example severity and laterality).</para>
            </listitem>
            <listitem>
                <para>Graceful evolution</para>
                <para><?oxy_comment_start author="steph" timestamp="20190402T125215-0600" comment="This sentence reads awkwardly to me, specifically re: the last part about testing.  Recommend revising it." flag="done"?>Change
                    in terminologies is inevitable but should not be done radically or without clear
                    documented reasons for the change. Changes should be carefully tested and vetted
                    by end-users. <?oxy_comment_end?></para>
            </listitem>
            <listitem>
                <para>Recognize redundancy</para>
                <para>Duplicate concepts should not exist in the terminology and processes should be
                    in place to both prevent and detect them. With large terminologies, it is
                    inevitable that duplicate and erroneous concepts are added. Robust terminologies
                    need processes and procedures in place to identify and retire duplicate and
                    erroneous concepts. Multiple processes can be utilized to ensure redundant
                    concepts are not added to terminologies. For example:<itemizedlist>
                        <listitem>
                            <para>Standardized naming conventions should be in place to eliminate
                                the possibility of creating redundant concepts</para>
                        </listitem>
                        <listitem>
                            <para>Description Logic classifiers that utilize formal concept
                                definitions to detect equivalent concepts</para>
                        </listitem>
                    </itemizedlist></para>
            </listitem>
        </itemizedlist></para>

</chapter>