text:
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
 // ERROR: Not supported in C#: OptionDeclaration
using Microsoft.VisualBasic.PowerPacks;
namespace _4PosBackOffice.NET
{
	internal partial class frmStockTransferItemWH : System.Windows.Forms.Form
	{
		int gStockItemID;
		int gPromotionID;
		int gQuantity;
		int WHFromA;
		int WHToB;

		private void loadLanguage()
		{

			//frmStockTransferItemWH = No Code   [Edit Stock Transfer Item]
			//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
			//If rsLang.RecordCount Then frmStockTransferItemWH.Caption = rsLang("LanguageLayoutLnk_Description"): frmStockTransferItemWH.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")

			modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1074;
			//Undo|Checked
			if (modRecordSet.rsLang.RecordCount){cmdCancel.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdCancel.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}

			modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
			//Exit|Checked
			if (modRecordSet.rsLang.RecordCount){cmdClose.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdClose.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}

			modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1139;
			//Promotion Name|Checked
			if (modRecordSet.rsLang.RecordCount){lblPComp.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;lblPComp.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}

			modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1935;
			//Stock Item Name|Checked
			if (modRecordSet.rsLang.RecordCount){_LBL_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_LBL_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}

			//_lbl_2 = No Code                   [Item Qty]
			//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
			//If rsLang.RecordCount Then _lbl_2.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_2.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")

			modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1151;
			//Price|Checked
			if (modRecordSet.rsLang.RecordCount){_LBL_3.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_LBL_3.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}

			modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
			//UPGRADE_ISSUE: Form property frmStockTransferItemWH.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
			if (modRecordSet.rsHelp.RecordCount)
				this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;

		}

		private void loadData()
		{
			ADODB.Recordset rs = default(ADODB.Recordset);
			ADODB.Recordset rj = default(ADODB.Recordset);

			rs = modRecordSet.getRS(ref "SELECT StockItem.StockItem_Name, StockItem_Quantity FROM StockItem WHERE ((StockItem.StockItemID)=" + gStockItemID + ");");
			if (rs.RecordCount) {
				lblStockItem.Text = rs.Fields("StockItem_Name").Value;
				txtPSize.Text = rs.Fields("StockItem_Quantity").Value;
				this.Height = sizeConvertors.twipsToPixels(2520, false);

				loadLanguage();
				ShowDialog();
			}

		}

//Public Sub loadItem(promotionID As Long, stockitemID As Long, Optional quantity As Long)
		public void loadItem(ref int stockitemID, ref int quantity = 0, ref int WHFrom = 0, ref int WHTo = 0)
		{
			gStockItemID = stockitemID;
			//gPromotionID = promotionID
			gQuantity = quantity;
			WHFromA = WHFrom;
			WHToB = WHTo;
			lblPComp.Text = My.MyProject.Forms.frmStockTransferWH.lblWHA.Text;
			loadData();

			//show 1

		}

		private void cmdPack_Click(System.Object eventSender, System.EventArgs eventArgs)
		{
			if (Convert.ToDouble(txtPSize.Text) != 1) {
				cmdPack.Tag = txtPSize.Text;
				txtPSize.Text = Convert.ToString(1);
			} else {
				if (!string.IsNullOrEmpty(cmdPack.Tag))
					txtPSize.Text = cmdPack.Tag;
			}

			if (string.IsNullOrEmpty(txtQtyT.Text))
				txtQtyT.Text = "0";
			if (Information.IsNumeric(txtQtyT.Text)) {
			} else {
				txtQtyT.Text = "0";
			}
			txtQty.Text = Convert.ToString(Convert.ToDouble(txtQtyT.Text) * Convert.ToDouble(txtPSize.Text));

			txtQtyT.Focus();
		}

		private void frmStockTransferItemWH_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
		{
			short KeyAscii = Strings.Asc(eventArgs.KeyChar);
			bool mbAddNewFlag = false;
			bool mbEditFlag = false;
			if (mbEditFlag | mbAddNewFlag)
				goto EventExitSub;

			switch (KeyAscii) {
				case System.Windows.Forms.Keys.Escape:
					KeyAscii = 0;
					cmdClose.Focus();
					System.Windows.Forms.Application.DoEvents();
					cmdClose_Click(cmdClose, new System.EventArgs());
					break;
			}
			EventExitSub:
			eventArgs.KeyChar = Strings.Chr(KeyAscii);
			if (KeyAscii == 0) {
				eventArgs.Handled = true;
			}
		}

		private void cmdCancel_Click(System.Object eventSender, System.EventArgs eventArgs)
		{
			 // ERROR: Not supported in C#: OnErrorStatement

			//If mbAddNewFlag Then
			this.Close();
			//Else
			//mbEditFlag = False
			//mbAddNewFlag = False
			//adoPrimaryRS.CancelUpdate
			//If mvBookMark > 0 Then
			//    adoPrimaryRS.Bookmark = mvBookMark
			//Else
			//    adoPrimaryRS.MoveFirst
			//End If
			//mbDataChanged = False
			//End If
		}

		private void ChkHandheldWHTransfer()
		{
			ADODB.Recordset rs = default(ADODB.Recordset);
			string strFldName = null;
			ChkTransTable:

			 // ERROR: Not supported in C#: OnErrorStatement

			rs = modRecordSet.getRS(ref "SELECT * FROM HandheldWHTransfer;");
			if (rs.RecordCount) {
			}

			return;
			Err_ChkTransTable:
			if (Err().Number == -2147217865 & Err().Description == "[Microsoft][ODBC Microsoft Access Driver] The Microsoft Jet database engine cannot find the input table or query 'HandheldWHTransfer'.  Make sure it exists and that its name is spelled correctly.") {
				strFldName = "HandHeldID Number,Handheld_Barcode Text(50), Quantity Currency, WHouseID Number";
				modRecordSet.cnnDB.Execute("CREATE TABLE HandheldWHTransfer (" + strFldName + ")");
				System.Windows.Forms.Application.DoEvents();
				rs = modRecordSet.getRS(ref "SELECT * FROM HandheldWHTransfer;");
				if (rs.RecordCount) {
				}

				goto ChkTransTable;
			}

		}

//UPGRADE_NOTE: update was upgraded to update_Renamed. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A9E4979A-37FA-4718-9994-97DD76ED70A7"'
		private bool update_Renamed()
		{
			bool functionReturnValue = false;
			string sql = null;
			 // ERROR: Not supported in C#: OnErrorStatement

			ChkHandheldWHTransfer();

			//UPGRADE_WARNING: Couldn't resolve default property of object sql. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
			sql = "INSERT INTO HandheldWHTransfer (HandHeldID,Handheld_Barcode,Quantity,WHouseID) VALUES (" + gStockItemID + ", 0, " + (0 - Convert.ToDecimal(txtQty.Text)) + "," + WHFromA + ")";
			//UPGRADE_WARNING: Couldn't resolve default property of object sql. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
			modRecordSet.cnnDB.Execute(sql);
			System.Windows.Forms.Application.DoEvents();

			//UPGRADE_WARNING: Couldn't resolve default property of object sql. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
			sql = "INSERT INTO HandheldWHTransfer (HandHeldID,Handheld_Barcode,Quantity,WHouseID) VALUES (" + gStockItemID + ", 0, " + Convert.ToDecimal(txtQty.Text) + "," + WHToB + ")";
			//UPGRADE_WARNING: Couldn't resolve default property of object sql. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
			modRecordSet.cnnDB.Execute(sql);
			System.Windows.Forms.Application.DoEvents();

			functionReturnValue = true;
			return functionReturnValue;
			UpdateErr:
			Interaction.MsgBox(Err().Description);
			functionReturnValue = true;
			return functionReturnValue;

		}

		private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs)
		{
			string sql = null;
			cmdClose.Focus();
			System.Windows.Forms.Application.DoEvents();
			if (Convert.ToDecimal(txtQtyT.Text) > 0) {
			} else {
				txtQtyT.Focus();
				return;
			}

			ADODB.Recordset rs = default(ADODB.Recordset);
			//UPGRADE_WARNING: Couldn't resolve default property of object sql. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
			sql = "SELECT WarehouseStockItemLnk.WarehouseStockItemLnk_StockItemID, Sum(WarehouseStockItemLnk.WarehouseStockItemLnk_Quantity) AS Warehouse_StockItemQuantity From WarehouseStockItemLnk Where (((WarehouseStockItemLnk.WarehouseStockItemLnk_WarehouseID) = " + My.MyProject.Forms.frmStockTransferWH.lWHA + ")) GROUP BY WarehouseStockItemLnk.WarehouseStockItemLnk_StockItemID HAVING (((WarehouseStockItemLnk.WarehouseStockItemLnk_StockItemID)=" + gStockItemID + "));";
			rs = modRecordSet.getRS(ref sql);
			if (rs.RecordCount) {
				if (rs.Fields("Warehouse_StockItemQuantity").Value < Convert.ToDecimal(txtQty.Text)) {
					Interaction.MsgBox("Insufficient Qty in '" + My.MyProject.Forms.frmStockTransferWH.lblWHA.Text + "'");
					txtQtyT.Focus();
					return;
				}
			} else {
				Interaction.MsgBox("Insufficient Qty in '" + My.MyProject.Forms.frmStockTransferWH.lblWHA.Text + "'");
				txtQtyT.Focus();
				return;
			}

			if (update_Renamed()) {
				this.Close();
			}
		}

		private void txtPrice_Enter(System.Object eventSender, System.EventArgs eventArgs)
		{
			modUtilities.MyGotFocusNumeric(ref txtPrice);
		}

		private void txtPrice_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
		{
			short KeyAscii = Strings.Asc(eventArgs.KeyChar);
			modUtilities.MyKeyPressNegative(ref txtPrice, ref KeyAscii);
			eventArgs.KeyChar = Strings.Chr(KeyAscii);
			if (KeyAscii == 0) {
				eventArgs.Handled = true;
			}
		}

		private void txtPrice_Leave(System.Object eventSender, System.EventArgs eventArgs)
		{
			modUtilities.MyLostFocus(ref txtPrice, ref 2);
		}

		private void txtPriceS_Enter(System.Object eventSender, System.EventArgs eventArgs)
		{
			modUtilities.MyGotFocusNumeric(ref txtPriceS);
		}

		private void txtPriceS_Leave(System.Object eventSender, System.EventArgs eventArgs)
		{
			modUtilities.MyLostFocus(ref txtPriceS, ref 2);
		}

		private void txtQty_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
		{
			short KeyAscii = Strings.Asc(eventArgs.KeyChar);
			switch (KeyAscii) {
				case Strings.Asc(Constants.vbCr):
					KeyAscii = 0;
					break;
				case 8:
					break;
				case 48:
				case 49:
				case 50:
				case 51:
				case 52:
				case 53:
				case 54:
				case 55:
				case 56:
				case 57:

					break;
			}
			eventArgs.KeyChar = Strings.Chr(KeyAscii);
			if (KeyAscii == 0) {
				eventArgs.Handled = true;
			}
		}

		private void txtQty_Enter(System.Object eventSender, System.EventArgs eventArgs)
		{
			//MyGotFocusNumeric txtQty
			txtQty.SelectionStart = 0;
			txtQty.SelectionLength = Strings.Len(txtQty.Text);
		}

		private void txtQty_Leave(System.Object eventSender, System.EventArgs eventArgs)
		{
			// LostFocus txtQty, 2
		}

		//UPGRADE_WARNING: Event txtQtyT.TextChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"'
		private void txtQtyT_TextChanged(System.Object eventSender, System.EventArgs eventArgs)
		{
			if (string.IsNullOrEmpty(txtQtyT.Text)){txtQty.Text = Convert.ToString(0);return;
}
			if (txtQtyT.Text == "0"){txtQty.Text = Convert.ToString(0);return;
}
			if (Information.IsNumeric(txtQtyT.Text)) {
			} else {
				txtQty.Text = Convert.ToString(0);
				return;
			}
			txtQty.Text = Convert.ToString(Convert.ToDouble(txtQtyT.Text) * Convert.ToDouble(txtPSize.Text));
		}

		private void txtQtyT_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
		{
			short KeyAscii = Strings.Asc(eventArgs.KeyChar);
			switch (KeyAscii) {
				case Strings.Asc(Constants.vbCr):
					KeyAscii = 0;
					break;
				case 8:
				case 46:
					break;
				case 48:
				case 49:
				case 50:
				case 51:
				case 52:
				case 53:
				case 54:
				case 55:
				case 56:
				case 57:
					break;
				default:
					KeyAscii = 0;
					break;
			}
			eventArgs.KeyChar = Strings.Chr(KeyAscii);
			if (KeyAscii == 0) {
				eventArgs.Handled = true;
			}
		}

		private void txtQtyT_Enter(System.Object eventSender, System.EventArgs eventArgs)
		{
			//MyGotFocusNumeric txtQty
			txtQtyT.SelectionStart = 0;
			txtQtyT.SelectionLength = Strings.Len(txtQtyT.Text);
		}

		private void txtQtyT_Leave(System.Object eventSender, System.EventArgs eventArgs)
		{
			// LostFocus txtQty, 2
		}
	}
}


text:
/*global cspace:true, jQuery, fluid, window*/
"use strict";

cspace = cspace || {};

(function ($, fluid) {

    fluid.defaults("cspace.searchTips", {
        gradeNames: ["autoInit", "fluid.rendererComponent"],
        protoTree: {
            searchTips: {decorators: {"addClass": "{styles}.searchTips"}},
            title: {
                decorators: {"addClass": "{styles}.title"},
                messagekey: "searchTips-title"
            },
            expander: {
                repeatID: "instructions",
                type: "fluid.renderer.repeat",
                pathAs: "row",
                controlledBy: "messagekeys",
                tree: {
                    messagekey: "${{row}}"
                }
            }
	    },
	    model: {
	        messagekeys: [
	            "searchTips-instructionsFirst",
	            "searchTips-instructionsSecond",
	            "searchTips-instructionsThird",
	            "searchTips-instructionsFourth",
	            "searchTips-instructionsFifth"
	        ]
	    },
        selectors: {
            searchTips: ".csc-searchTips-template",
            title: ".csc-searchTips-title",
            instructions: ".csc-searchTips-instructions"
	    },
	    repeatingSelectors: ["instructions"],
        styles: {
            searchTips: "cs-searchTips-template",
            title: "cs-searchTips-title"
        },
        resources: {
            template: cspace.resourceSpecExpander({
                fetchClass: "fastTemplate",
                url: "%webapp/html/components/SearchTipsTemplate.html",
                options: {
                    dataType: "html"
                }
            })
        },
        strings: {},
        parentBundle: "{globalBundle}",
        renderOnInit: true
    });

    fluid.fetchResources.primeCacheFromResources("cspace.searchTips");

})(jQuery, fluid);

redpajama_set_name: RedPajamaGithub


text:
! { dg-do compile }
! { dg-options "-std=f95" }

! Parsing of finalizer procedure definitions.
! While ALLOCATABLE scalars are not implemented, this even used to ICE.
! Thanks Tobias Burnus for the test!

integer, allocatable :: x ! { dg-error "may not be ALLOCATABLE" }

end


text:
A PHP library for [Irish Rail's Realtime API](http://api.irishrail.ie/realtime/).

## Usage

The main class exported by this package is `\Railtime\API`.

First, create a new `API` object:

```php
use \Railtime\API;

$api = new API;
```

Then, call the various API methods:

```php
$stations = $api->stations();
```

The `API` class exposes the following methods:

    Station[]           stations([$station_type])
    RunningTrain[]      current_trains([$train_type])
    StationPassing[]    station_passings($name_or_code[, $minutes = null])
    TrainMovement[]     train_movements($train_id, $train_date)

Make sure to check out the [Examples](#examples) below.

## Installing

This package is [available from Packagist](https://packagist.org/packages/daviddoran/railtime).

To install using Composer, add this to the `"require":` section of your `composer.json` file:

    "daviddoran/railtime": "dev-master"

Once you've [installed Composer](http://getcomposer.org/doc/00-intro.md#installation-nix) simply run:

    php composer.phar install

Or, if you installed composer globally:

    composer install

## Tests

The unit tests are contained in `test` and the configuration in `phpunit.xml`.

After installing dependencies with composer, the following should run the tests:

    ./vendor/bin/phpunit

## Examples

#### Get a list of all the Dart stations

```php
$stations = $api->stations(\Railtime\StationTypeDart);
```

#### Get the currently running Mainline trains

```php
$trains = $api->current_trains(\Railtime\TrainTypeMainline);
```

#### Get a list of the trains passing Howth Junction (default next 90 minutes)

```php
//You can use the station's full name
$passings = $api->station_passings("Howth Junction");

//Or use the station's code
$passings = $api->station_passings("HWTHJ");
```

#### Get a list of the trains passing Connolly in the next 15 minutes

```php
//You can also use the station code "CNLLY"
$passings = $api->station_passings("Dublin Connolly", 15);
```

#### Get a list of a train's movements on a particular day

```php
$movements = $api->train_movements("E815", "25 Aug 2013");
```

#### Check how early/late a train was at each station

```php
$movements = $api->train_movements("E815", "18 Aug 2013");
foreach ($movements as $stop) {
    if (!$stop->is_origin()) {
        $mins = round($stop->arrival_diff_seconds() / 60);
        echo "-- ", abs($mins), " min ", ($mins > 0 ? "late" : "early"), " --> ";
    } else {
        echo "-- set off --> ";
    }
    echo $stop->location_fullname, "\n";
}
```

This will output something like:

    -- set off --> Greystones
    -- 0 min early --> Bray
    -- 0 min early --> Shankill
    -- 1 min late --> Killiney
    -- 1 min late --> Dalkey
    -- 2 min late --> Glenageary
    -- 2 min late --> Sandycove
    -- ✂ -- ✂ -- snip -- ✂ -- ✂ --
    -- 3 min late --> Kilbarrack
    -- 3 min late --> Howth Junction
    -- 2 min late --> Clongriffin
    -- 2 min late --> Portmarnock
    -- 2 min late --> Malahide

## License

This project is released under the MIT License - see the LICENSE file for details.


text:
ILboolean ilConvertPal(ILenum DestFormat);

// Does not account for converting luminance...
BITMAP* ILAPIENTRY ilutConvertToAlleg(PALETTE Pal)
{
	BITMAP *Bitmap;
	ILimage *TempImage;
	ILuint i = 0, j = 0;

	ilutCurImage = ilGetCurImage();

	if (ilutCurImage == NULL) {
		ilSetError(ILUT_ILLEGAL_OPERATION);
		return NULL;
	}

	// Should be IL_BGR(A), but Djgpp screws up somewhere along the line.
	if (ilutCurImage->Format == IL_RGB || ilutCurImage->Format == IL_RGBA) {
		iluSwapColours();
	}

	if (ilutCurImage->Origin == IL_ORIGIN_LOWER_LEFT)
		iluFlipImage();
	if (ilutCurImage->Type > IL_UNSIGNED_BYTE) {}  // Can't do anything about this right now...
	if (ilutCurImage->Type == IL_BYTE) {}  // Can't do anything about this right now...

	Bitmap = create_bitmap_ex(ilutCurImage->Bpp * 8, ilutCurImage->Width, ilutCurImage->Height);
	if (Bitmap == NULL) {
		return IL_FALSE;
	}
	memcpy(Bitmap->dat, ilutCurImage->Data, ilutCurImage->SizeOfData);

	// Should we make this toggleable?
	if (ilutCurImage->Bpp == 8 && ilutCurImage->Pal.PalType != IL_PAL_NONE) {
		// Use the image's palette if there is one

		// ilConvertPal is destructive to the original image
		// @TODO:  Use new ilCopyPal!!!
		TempImage = ilNewImage(ilutCurImage->Width, ilutCurImage->Height, ilutCurImage->Depth, ilutCurImage->Bpp, 1);
		ilCopyImageAttr(TempImage, ilutCurImage);
		ilSetCurImage(TempImage);

		if (!ilConvertPal(IL_PAL_RGB24)) {
			destroy_bitmap(Bitmap);
			ilSetError(ILUT_ILLEGAL_OPERATION);
			return NULL;
		}

		for (; i < ilutCurImage->Pal.PalSize && i < 768; i += 3, j++) {
			Pal[j].r = TempImage->Pal.Palette[i+0];
			Pal[j].g = TempImage->Pal.Palette[i+1];
			Pal[j].b = TempImage->Pal.Palette[i+2];
			Pal[j].filler = 255;
		}

		ilCloseImage(TempImage);
		ilSetCurImage(ilutCurImage);
	}

	return Bitmap;
}

#ifndef _WIN32_WCE
BITMAP* ILAPIENTRY ilutAllegLoadImage(ILstring FileName)
{
	ILuint	ImgId;
	PALETTE	Pal;

	ilGenImages(1, &ImgId);
	ilBindImage(ImgId);
	if (!ilLoadImage(FileName)) {
		ilDeleteImages(1, &ImgId);
		return 0;
	}

	ilDeleteImages(1, &ImgId);

	return ilutConvertToAlleg(Pal);
}
#endif//_WIN32_WCE

// Unfinished
ILboolean ILAPIENTRY ilutAllegFromBitmap(BITMAP *Bitmap)
{
	ilutCurImage = ilGetCurImage();
	if (ilutCurImage == NULL) {
		ilSetError(ILUT_ILLEGAL_OPERATION);
		return IL_FALSE;
	}

	if (Bitmap == NULL || Bitmap->w == 0 || Bitmap->h == 0) {
		ilSetError(ILUT_INVALID_PARAM);
		return IL_FALSE;
	}

	if (!ilTexImage(Bitmap->w, Bitmap->h, 1, 3, IL_RGB, IL_UNSIGNED_BYTE, NULL))
		return IL_FALSE;

	ilutCurImage->Origin = IL_ORIGIN_LOWER_LEFT;  // I have no idea.

	return IL_TRUE;
}

#endif//ILUT_USE_ALLEGRO


text:
import threading

import rospy
from axis_camera.msg import Axis
from std_msgs.msg import Bool
from dynamic_reconfigure.server import Server
from axis_camera.cfg import PTZConfig

from axis_camera.vapix import VAPIX
from axis_camera.position_streaming import PositionStreamingThread
from axis_camera.camera_control import AxisCameraController

StateThread = PositionStreamingThread  # deprecated

class AxisPTZ:
    """This class is a node to manage the PTZ functions of an Axis PTZ camera. The most of its work is done by
     :py:class:`AxisCameraController <axis_camera.camera_control.AxisCameraController>` and this is just a ROS node
     envelope.
    """

    def __init__(self, hostname, username, password, flip, speed_control, frame_id="axis_camera",
                 use_encrypted_password=False, state_publishing_frequency=50, camera_id=1):
        """Initialize the PTZ driver and start publishing positional data.

        :param hostname: Hostname of the camera (without http://, can be an IP address).
        :type hostname: basestring
        :param username: If login is needed, provide a username here.
        :type username: basestring|None
        :param password: If login is needed, provide a password here.
        :type password: basestring|None
        :param flip: Whether to flip the controls (for ceiling-mounted cameras). Deprecated.
        :type flip: bool
        :param speed_control: Use speed control instead of positional. Deprecated.
        :type speed_control: bool
        :param frame_id: Id of the frame in which positinal data should be published.
        :type frame_id: basestring
        :param use_encrypted_password: Whether to use Plain HTTP Auth (False) or Digest HTTP Auth (True).
        :type use_encrypted_password: bool
        :param state_publishing_frequency: The frequency at which joint states should be published.
        :type state_publishing_frequency: int
        :param camera_id: ID (number) of the camera. Can be 1 to 4.
        :type camera_id: int
        """

        self._hostname = hostname
        self._camera_id = camera_id
        self._frame_id = frame_id

        self._state_publishing_frequency = state_publishing_frequency

        self._executing_reconfigure = False
        self._reconfigure_mutex = threading.Lock()

        self._api = None
        # autodetect the VAPIX API and connect to it; try it forever
        while self._api is None and not rospy.is_shutdown():
            try:
                self._api = VAPIX.get_api_for_camera(hostname, username, password, camera_id, use_encrypted_password)
            except (IOError, ValueError):
                rospy.loginfo(
                    "Retrying connection to VAPIX on host %s, camera %d in 2 seconds." % (hostname, camera_id))
                rospy.sleep(2)
        if rospy.is_shutdown():
            return

        if not self._api.has_ptz():
            raise RuntimeError("Camera %d on host %s doesn't have a Pan-Tilt-Zoom unit." % (self._camera_id, self._hostname))

        # Create a controller of the camera
        self._camera_controller = AxisCameraController(self._api, self, flip_vertically=flip, flip_horizontally=flip)

        # BACKWARDS COMPATIBILITY LAYER
        self.username = username  # deprecated
        self.password = password  # deprecated
        self.flip = flip  # deprecated
        self.speedControl = speed_control  # deprecated
        self.mirror = False  # deprecated

        self.msg = None  # deprecated
        self.cmdString = ""  # deprecated

        self.pub = rospy.Publisher("state", Axis, queue_size=100)  # deprecated
        self.command_subscriber = rospy.Subscriber("cmd", Axis, self.cmd, queue_size=100)  # deprecated
        self.mirror_subscriber = rospy.Subscriber("mirror", Bool, self.mirrorCallback, queue_size=100)  # deprecated

        self.srv = Server(PTZConfig, self.callback)  # deprecated

        # Needs to be after the backwards compatibility setup
        # start the publisher thread
        self._publisher_thread = PositionStreamingThread(self, self._api)
        self.st = self._publisher_thread  # deprecated
        self._publisher_thread.start()

    # BACKWARDS COMPATIBILITY LAYER

    def cmd(self, message):
        """Deprecated."""
        self.msg = message

        self.sanitisePTZCommands()

        if self._api.has_capabilities('AbsolutePan', 'AbsoluteTilt', 'AbsoluteZoom'):
            self._camera_controller.set_ptz(message.pan, message.tilt, message.zoom)
        else:
            rospy.loginfo("Camera on host %s doesn't support PTZ control." % self._hostname)

        if self._api.has_capability('AbsoluteFocus'):
            self._camera_controller.set_focus(message.focus, set_also_autofocus=False)
        else:
            rospy.loginfo("Camera on host %s doesn't support absolute focus control." % self._hostname)

        if self._api.has_capability('AutoFocus'):
            if message.focus != self._camera_controller._focus:
                self._camera_controller.set_autofocus(False)
            else:
                self._camera_controller.set_autofocus(message.autofocus)
        else:
            rospy.loginfo("Camera on host %s doesn't support autofocus." % self._hostname)

        if self._api.has_capability('AutoIris'):
            self._camera_controller.set_autoiris(True)
        else:
            rospy.loginfo("Camera on host %s doesn't support autoiris." % self._hostname)

        # there is no capability for brightness
        self._camera_controller.set_brightness(message.brightness)

    def adjustForFlippedOrientation(self):
        """Deprecated."""
        self.msg.tilt = -self.msg.tilt
        if self.speedControl:
            self.msg.pan = -self.msg.pan
        else:
            self.msg.pan = 180.0 - self.msg.pan

    def sanitisePTZCommands(self):
        """Deprecated."""
        if not self.speedControl:
            self.msg.pan = self._api.ptz_limits['Pan'].absolute.crop_value(self.msg.pan)
            self.msg.tilt = self._api.ptz_limits['Tilt'].absolute.crop_value(self.msg.tilt)
            self.msg.zoom = self._api.ptz_limits['Zoom'].absolute.crop_value(self.msg.zoom)
            self.msg.focus = self._api.ptz_limits['Focus'].absolute.crop_value(self.msg.focus)
            self.msg.brightness = self._api.ptz_limits['Brightness'].absolute.crop_value(self.msg.brightness)
            self.msg.iris = self._api.ptz_limits['Iris'].absolute.crop_value(self.msg.iris)
        else:
            self.msg.pan = self._api.ptz_limits['Pan'].velocity.crop_value(self.msg.pan)
            self.msg.tilt = self._api.ptz_limits['Tilt'].velocity.crop_value(self.msg.tilt)
            self.msg.zoom = self._api.ptz_limits['Zoom'].velocity.crop_value(self.msg.zoom)
            self.msg.focus = self._api.ptz_limits['Focus'].velocity.crop_value(self.msg.focus)
            self.msg.brightness = self._api.ptz_limits['Brightness'].velocity.crop_value(self.msg.brightness)
            self.msg.iris = self._api.ptz_limits['Iris'].velocity.crop_value(self.msg.iris)

    def sanitisePan(self):
        """Deprecated."""
        if self.speedControl:
            self.msg.pan = self._api.ptz_limits['Pan'].velocity.crop_value(self.msg.pan)
        else:
            self.msg.pan = self._api.ptz_limits['Pan'].absolute.crop_value(self.msg.pan)

    def sanitiseTilt(self):
        """Deprecated."""
        if self.speedControl:
            self.msg.tilt = self._api.ptz_limits['Tilt'].velocity.crop_value(self.msg.tilt)
        else:
            self.msg.tilt = self._api.ptz_limits['Tilt'].absolute.crop_value(self.msg.tilt)

    def sanitiseZoom(self):
        """Deprecated."""
        if self.speedControl:
            self.msg.zoom = self._api.ptz_limits['Zoom'].velocity.crop_value(self.msg.zoom)
        else:
            self.msg.zoom = self._api.ptz_limits['Zoom'].absolute.crop_value(self.msg.zoom)

    def sanitiseFocus(self):
        """Deprecated."""
        if self.speedControl:
            self.msg.focus = self._api.ptz_limits['Focus'].velocity.crop_value(self.msg.focus)
        else:
            self.msg.focus = self._api.ptz_limits['Focus'].absolute.crop_value(self.msg.focus)

    def sanitiseBrightness(self):
        """Deprecated."""
        if self.speedControl:
            self.msg.brightness = self._api.ptz_limits['Brightness'].velocity.crop_value(self.msg.brightness)
        else:
            self.msg.brightness = self._api.ptz_limits['Brightness'].absolute.crop_value(self.msg.brightness)

    def sanitiseIris(self):
        """Deprecated."""
        if self.msg.iris > 0.000001:
            rospy.logwarn("Iris value is read-only.")

    def applySetpoints(self):
        """Deprecated."""
        """Apply the command to the camera using the HTTP API"""
        self._camera_controller.set_ptz(self.msg.pan, self.msg.tilt, self.msg.zoom)
        self._camera_controller.set_autofocus(self.msg.autofocus)
        if not self.msg.autofocus:
            self._camera_controller.set_focus(self.msg.focus)
        self._camera_controller.set_autoiris(True)
        self._camera_controller.set_brightness(self.msg.brightness)

    def createCmdString(self):
        """Deprecated."""
        """Created tje HTTP API string to command PTZ camera"""
        self.cmdString = '/axis-cgi/com/ptz.cgi?'
        if self.speedControl:
            self.cmdString += 'continuouspantiltmove=%d,%d&' % (int(self.msg.pan), int(self.msg.tilt))
            self.cmdString += 'continuouszoommove=%d&' % self.msg.zoom
            self.cmdString += 'continuousbrightnessmove=%d&' % self.msg.brightness
            # Note that brightness adjustment has no effect for Axis 214PTZ.
            if self.msg.autofocus:
                self.cmdString += 'autofocus=on&'
            else:
                self.cmdString += 'autofocus=off&continuousfocusmove=%d&' % self.msg.focus
            self.cmdString += 'autoiris=on'
        else: # position control:
            self.cmdString += 'pan=%f&tilt=%f&' % (self.msg.pan, self.msg.tilt)
            self.cmdString += 'zoom=%d&' % self.msg.zoom
            self.cmdString += 'brightness=%d&' % self.msg.brightness
            if self.msg.autofocus:
                self.cmdString += 'autofocus=on&'
            else:
                self.cmdString += 'autofocus=off&focus=%d&' % self.msg.focus
            self.cmdString += 'autoiris=on'

    def mirrorCallback(self, msg):
        """Deprecated."""
        '''Command the camera with speed control or position control commands'''
        self.mirror = msg.data
        self._camera_controller.mirror_horizontally = self.mirror

    def callback(self, config, level):
        """Deprecated."""
        #self.speedControl = config.speed_control

        if self._executing_reconfigure or (hasattr(self, '_camera_controller') and (self._camera_controller._executing_parameter_update or self._camera_controller._executing_reconfigure)):
            return config

        with self._reconfigure_mutex:
            self._executing_reconfigure = True

            # create temporary message and fill with data from dynamic reconfigure
            command = Axis()
            command.pan = config.pan
            command.tilt = config.tilt
            command.zoom = config.zoom
            command.focus = config.focus
            command.brightness = config.brightness
            command.autofocus = config.autofocus

            # check sanity and apply values
            self.cmd(command)

            # read sanitized values and update GUI
            config.pan = command.pan
            config.tilt = command.tilt
            config.zoom = command.zoom
            config.focus = self._camera_controller._focus
            config.brightness = self._camera_controller._brightness
            config.autofocus = self._camera_controller._autofocus

            self._executing_reconfigure = False

            # update GUI with sanitized values
            return config

def main():
    rospy.init_node("axis_ptz_driver")

    arg_defaults = {
        'hostname': '192.168.0.90',
        'username': None,
        'password': None,
        'flip': False,
        'speed_control': False,
        'frame_id': 'axis_camera',
        'use_encrypted_password': False,
        'state_publishing_frequency': 50,
        'camera_id': 1,
        }
    args = read_args_with_defaults(arg_defaults)

    # Start the driver
    my_ptz = AxisPTZ(**args)

    rospy.spin()

def read_args_with_defaults(arg_defaults):
    """Look up parameters starting in the driver's private parameter space, but
    also searching outer namespaces.  Defining them in a higher namespace allows
    the axis_ptz.py script to share parameters with the driver."""
    args = {}
    for name, val in arg_defaults.iteritems():
        full_name = rospy.search_param(name)
        if full_name is None:
            args[name] = val
        else:
            args[name] = rospy.get_param(full_name, val)
    # resolve frame_id with tf_prefix (unless already absolute)
    if 'frame_id' in args and args['frame_id'][0] != '/':  # not absolute?
        tf_prefix = rospy.search_param('tf_prefix')
        prefix_val = ''
        if tf_prefix is not None:  # prefix defined?
            prefix_val = rospy.get_param(tf_prefix)
            if prefix_val[0] != '/':  # prefix not absolute?
                prefix_val = '/' + prefix_val
        args['frame_id'] = prefix_val + '/' + args['frame_id']
    return args

if __name__ == "__main__":
    main()


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import * as Common from '../common/common.js';
import * as DataGrid from '../data_grid/data_grid.js';
import * as SDK from '../sdk/sdk.js';
import * as UI from '../ui/ui.js';
import * as Workspace from '../workspace/workspace.js';

import {SamplingHeapProfileNode} from './HeapProfileView.js';  // eslint-disable-line no-unused-vars

/**
 * @extends {UI.Widget.VBox}
 */
export class LiveHeapProfileView extends UI.Widget.VBox {
  constructor() {
    super(true);
    /** @type {!Map<string, !GridNode>} */
    this._gridNodeByUrl = new Map();
    this.registerRequiredCSS('profiler/liveHeapProfile.css');

    this._setting = Common.Settings.Settings.instance().moduleSetting('memoryLiveHeapProfile');
    const toolbar = new UI.Toolbar.Toolbar('live-heap-profile-toolbar', this.contentElement);

    this._toggleRecordAction =
        /** @type {!UI.Action.Action }*/ (self.UI.actionRegistry.action('live-heap-profile.toggle-recording'));
    this._toggleRecordButton = UI.Toolbar.Toolbar.createActionButton(this._toggleRecordAction);
    this._toggleRecordButton.setToggled(this._setting.get());
    toolbar.appendToolbarItem(this._toggleRecordButton);

    const mainTarget = SDK.SDKModel.TargetManager.instance().mainTarget();
    if (mainTarget && mainTarget.model(SDK.ResourceTreeModel.ResourceTreeModel)) {
      const startWithReloadAction =
          /** @type {!UI.Action.Action }*/ (self.UI.actionRegistry.action('live-heap-profile.start-with-reload'));
      this._startWithReloadButton = UI.Toolbar.Toolbar.createActionButton(startWithReloadAction);
      toolbar.appendToolbarItem(this._startWithReloadButton);
    }

    this._dataGrid = this._createDataGrid();
    this._dataGrid.asWidget().show(this.contentElement);

    this._currentPollId = 0;
  }

  /**
   * @return {!DataGrid.SortableDataGrid.SortableDataGrid}
   */
  _createDataGrid() {
    const columns = [
      {
        id: 'size',
        title: ls`JS Heap`,
        width: '72px',
        fixedWidth: true,
        sortable: true,
        align: DataGrid.DataGrid.Align.Right,
        sort: DataGrid.DataGrid.Order.Descending,
        tooltip: ls`Allocated JS heap size currently in use`,
      },
      {
        id: 'isolates',
        title: ls`VMs`,
        width: '40px',
        fixedWidth: true,
        align: DataGrid.DataGrid.Align.Right,
        tooltip: ls`Number of VMs sharing the same script source`
      },
      {id: 'url', title: ls`Script URL`, fixedWidth: false, sortable: true, tooltip: ls`URL of the script source`}
    ];
    const dataGrid = new DataGrid.SortableDataGrid.SortableDataGrid({displayName: ls`Heap Profile`, columns});
    dataGrid.setResizeMethod(DataGrid.DataGrid.ResizeMethod.Last);
    dataGrid.element.classList.add('flex-auto');
    dataGrid.element.addEventListener('keydown', this._onKeyDown.bind(this), false);
    dataGrid.addEventListener(DataGrid.DataGrid.Events.OpenedNode, this._revealSourceForSelectedNode, this);
    dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged, this._sortingChanged, this);
    for (const info of columns) {
      const headerCell = dataGrid.headerTableHeader(info.id);
      if (headerCell) {
        headerCell.setAttribute('title', info.tooltip);
      }
    }
    return dataGrid;
  }

  /**
   * @override
   */
  wasShown() {
    this._poll();
    this._setting.addChangeListener(this._settingChanged, this);
  }

  /**
   * @override
   */
  willHide() {
    ++this._currentPollId;
    this._setting.removeChangeListener(this._settingChanged, this);
  }

  /**
   * @param {!Common.EventTarget.EventTargetEvent} value
   */
  _settingChanged(value) {
    this._toggleRecordButton.setToggled(/** @type {boolean} */ (value.data));
  }

  async _poll() {
    const pollId = this._currentPollId;
    do {
      const isolates = Array.from(self.SDK.isolateManager.isolates());
      const profiles = await Promise.all(
          isolates.map(isolate => isolate.heapProfilerModel() && isolate.heapProfilerModel().getSamplingProfile()));
      if (this._currentPollId !== pollId) {
        return;
      }
      this._update(isolates, profiles);
      await new Promise(r => setTimeout(r, 3000));
    } while (this._currentPollId === pollId);
  }

  /**
   * @param {!Array<!SDK.IsolateManager.Isolate>} isolates
   * @param {!Array<?Protocol.HeapProfiler.SamplingHeapProfile>} profiles
   */
  _update(isolates, profiles) {
    /** @type {!Map<string, !{size: number, isolates: !Set<!SDK.IsolateManager.Isolate>}>} */
    const dataByUrl = new Map();
    profiles.forEach((profile, index) => {
      if (profile) {
        processNodeTree(isolates[index], '', profile.head);
      }
    });

    const rootNode = this._dataGrid.rootNode();
    const exisitingNodes = new Set();
    for (const pair of dataByUrl) {
      const url = /** @type {string} */ (pair[0]);
      const size = /** @type {number} */ (pair[1].size);
      const isolateCount = /** @type {number} */ (pair[1].isolates.size);
      if (!url) {
        console.info(`Node with empty URL: ${size} bytes`);  // eslint-disable-line no-console
        continue;
      }
      let node = this._gridNodeByUrl.get(url);
      if (node) {
        node.updateNode(size, isolateCount);
      } else {
        node = new GridNode(url, size, isolateCount);
        this._gridNodeByUrl.set(url, node);
        rootNode.appendChild(node);
      }
      exisitingNodes.add(node);
    }

    for (const node of rootNode.children.slice()) {
      if (!exisitingNodes.has(node)) {
        node.remove();
      }
      this._gridNodeByUrl.delete(node);
    }

    this._sortingChanged();

    /**
     * @param {!SDK.IsolateManager.Isolate} isolate
     * @param {string} parentUrl
     * @param {!Protocol.HeapProfiler.SamplingHeapProfileNode} node
     */
    function processNodeTree(isolate, parentUrl, node) {
      const url = node.callFrame.url || parentUrl || systemNodeName(node) || anonymousScriptName(node);
      node.children.forEach(processNodeTree.bind(null, isolate, url));
      if (!node.selfSize) {
        return;
      }
      let data = dataByUrl.get(url);
      if (!data) {
        data = {size: 0, isolates: new Set()};
        dataByUrl.set(url, data);
      }
      data.size += node.selfSize;
      data.isolates.add(isolate);
    }

    /**
     * @param {!Protocol.HeapProfiler.SamplingHeapProfileNode} node
     * @return {string}
     */
    function systemNodeName(node) {
      const name = node.callFrame.functionName;
      return name.startsWith('(') && name !== '(root)' ? name : '';
    }

    /**
     * @param {!Protocol.HeapProfiler.SamplingHeapProfileNode} node
     * @return {string}
     */
    function anonymousScriptName(node) {
      return Number(node.callFrame.scriptId) ?
          Common.UIString.UIString('(Anonymous Script %s)', node.callFrame.scriptId) :
          '';
    }
  }

  /**
   * @param {!Event} event
   */
  _onKeyDown(event) {
    if (!isEnterKey(event)) {
      return;
    }
    event.consume(true);
    this._revealSourceForSelectedNode();
  }

  _revealSourceForSelectedNode() {
    const node = this._dataGrid.selectedNode;
    if (!node || !node._url) {
      return;
    }
    const sourceCode = Workspace.Workspace.WorkspaceImpl.instance().uiSourceCodeForURL(node._url);
    if (sourceCode) {
      Common.Revealer.reveal(sourceCode);
    }
  }

  _sortingChanged() {
    const columnId = this._dataGrid.sortColumnId();
    if (!columnId) {
      return;
    }
    const sortByUrl = (a, b) => b._url.localeCompare(a._url);
    const sortBySize = (a, b) => b._size - a._size;
    const sortFunction = columnId === 'url' ? sortByUrl : sortBySize;
    this._dataGrid.sortNodes(sortFunction, this._dataGrid.isSortOrderAscending());
  }

  _toggleRecording() {
    const enable = !this._setting.get();
    if (enable) {
      this._startRecording(false);
    } else {
      this._stopRecording();
    }
  }

  /**
   * @param {boolean=} reload
   */
  _startRecording(reload) {
    this._setting.set(true);
    if (!reload) {
      return;
    }
    const mainTarget = SDK.SDKModel.TargetManager.instance().mainTarget();
    if (!mainTarget) {
      return;
    }
    const resourceTreeModel = /** @type {?SDK.ResourceTreeModel.ResourceTreeModel} */ (
        mainTarget.model(SDK.ResourceTreeModel.ResourceTreeModel));
    if (resourceTreeModel) {
      resourceTreeModel.reloadPage();
    }
  }

  async _stopRecording() {
    this._setting.set(false);
  }
}

export class GridNode extends DataGrid.SortableDataGrid.SortableDataGridNode {
  /**
   * @param {string} url
   * @param {number} size
   * @param {number} isolateCount
   */
  constructor(url, size, isolateCount) {
    super();
    this._url = url;
    this._size = size;
    this._isolateCount = isolateCount;
  }

  /**
   * @param {number} size
   * @param {number} isolateCount
   */
  updateNode(size, isolateCount) {
    if (this._size === size && this._isolateCount === isolateCount) {
      return;
    }
    this._size = size;
    this._isolateCount = isolateCount;
    this.refresh();
  }

  /**
   * @override
   * @param {string} columnId
   * @return {!Element}
   */
  createCell(columnId) {
    const cell = this.createTD(columnId);
    switch (columnId) {
      case 'url':
        cell.textContent = this._url;
        break;
      case 'size':
        cell.textContent = Number.withThousandsSeparator(Math.round(this._size / 1e3));
        cell.createChild('span', 'size-units').textContent = ls`KB`;
        break;
      case 'isolates':
        cell.textContent = this._isolateCount;
        break;
    }
    return cell;
  }
}

/**
 * @implements {UI.ActionDelegate.ActionDelegate}
 */
export class ActionDelegate {
  /**
   * @override
   * @param {!UI.Context.Context} context
   * @param {string} actionId
   * @return {boolean}
   */
  handleAction(context, actionId) {
    (async () => {
      const profileViewId = 'live_heap_profile';
      await UI.ViewManager.ViewManager.instance().showView(profileViewId);
      const widget = await UI.ViewManager.ViewManager.instance().view(profileViewId).widget();
      this._innerHandleAction(/** @type {!LiveHeapProfileView} */ (widget), actionId);
    })();
    return true;
  }

  /**
   * @param {!LiveHeapProfileView} profilerView
   * @param {string} actionId
   */
  _innerHandleAction(profilerView, actionId) {
    switch (actionId) {
      case 'live-heap-profile.toggle-recording':
        profilerView._toggleRecording();
        break;
      case 'live-heap-profile.start-with-reload':
        profilerView._startRecording(true);
        break;
      default:
        console.assert(false, `Unknown action: ${actionId}`);
    }
  }
}


text:
Transform a Sun GridEngine accounting file from a flat file to an RDBMS.
Database output is done via the Sequel library. PostgreSQL and MySQL adapters are installed as part of this gem.
If you need other adapters you need to install them on your own.

Data is pumped into the database as a single table with the following fields:

    qname hostname group owner jobname jobnumber account priority qsub_time start_time end_time failed exit_status
    ru_wallclock ru_utime ru_stime ru_maxrss ru_ixrss ru_ismrss ru_idrss ru_isrss ru_minflt ru_majflt ru_nswap
    ru_inblock ru_oublock ru_msgsnd ru_msgrcv ru_nsignals ru_nvcsw ru_nivcsw project department granted_pe slots
    taskid cpu mem io category iow pe_taskid maxvmem arid ar_submission_time

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'sge_transform'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install sge_transform

## Usage

./bin/sge_transform -h


text:
(function( $ ) {
	var border_color_styles = ['border-top-color','border-left-color','border-bottom-color','border-right-color'];

	var addBorderColor = function (attr){
		//Remove 'border-color' attribute
		attr = $.removeFromArray('border-color', attr);

		// Add css styles
		$.each(border_color_styles, function(key, ele) { attr.push(ele); });
		return attr;
	};

	var buildStyleObject = function (obj){
		var tmpObj = {};

		$.each(obj, function(index, element){
			if ($.inArray(index, border_color_styles) >= 0 ){
				if (typeof tmpObj['border-color'] == 'undefined'){ tmpObj['border-color'] = []; }
				$(element).each(function(){ $.merge(tmpObj['border-color'], element) });
				return true;
			}

			if (typeof tmpObj[index] == 'undefined'){ tmpObj[index] = []; }
			$.merge(tmpObj[index], element)
		});

		return tmpObj;
	};

	$.styleExtractor = function( el, styles ) {
		var obj = {};

		// Computed styles doesn't have border-color
		if ($.inArray("border-color", styles) >= 0) {
			styles = addBorderColor(styles);
		}

		var props = $(el).curStyles.apply($(el), styles)

		$.each(props, function(element, key) {
			if (key && key != undefined && key != ''){
				if (typeof obj[element] == 'undefined'){
					obj[element] = [];
				}
				obj[element].push($.rgb2Hex(key));
			}
		});

		return buildStyleObject(obj);
	};

	$.fn.styleExtractor = function() {
		return $.styleExtractor(this[0], $.makeArray(arguments));
	};
})(jQuery)


text:
% sja1105-conf(5) | SJA1105-TOOL

NAME
====

_/etc/sja1105/sja1105.conf_ - Configuration File for NXP sja1105-tool

DESCRIPTION
===========

_/etc/sja1105/sja1105.conf_ is the configuration file for _sja1105-tool_. It is
read on every invocation of the tool and used to describe part of its behavior.

Syntactically it follows the INI file format, with section names marked between
square brackets, and key-value pairs written one per line, separated by the "="
(equal) sign and an arbitrary amount of whitespace (tabs or spaces). Lines may
be ignored completely if the first non-whitespace character is "#" (hash).
Comments at the end of the line are not allowed and will lead to incorrect
parsing of the file.

If the file does not exist or syntax errors are present, the **sja1105-tool**
throws an error and loads default values.

THE SPI SETUP SECTION
---------------------

This section begins when a line contains the string "[spi-setup]" and ends
at the beginning of a different section or at the end of file. Values should
conform to UM10944.pdf "Chapter 3. SPI interface". The following keys are
allowed in this section:

staging-area

:   This is the filename used to store the staging, binary configuration
    employed by the command family **sja1105-tool config**. If not
    specified, it defaults to "_/etc/sja1105/.staging_". It should be
    specified without quotes even if spaces are present in the filename.

device

:   This is the filename used to communicate with the SJA1105. It must
    be a character device that supports the following ioctl calls:
    SPI_IOC_RD_MODE, SPI_IOC_WR_MODE, SPI_IOC_WR_BITS_PER_WORD,
    SPI_IOC_RD_BITS_PER_WORD, SPI_IOC_RD_MAX_SPEED_HZ,
    SPI_IOC_WR_MAX_SPEED_HZ, SPI_IOC_MESSAGE. If not specified, it
    defaults to "_/dev/spidev0.1_". The same restrictions apply as
    above.

bits

:   Number of bits per word for the SPI communication. Should be set to 8.

delay

:   Number of microseconds for how long to delay after sending the last bit
    of this transfer before optionally deselecting the chip until the next one.
    Defaults to zero.

cs_change

:   Set to 1 to deactivate Chip Select for the SPI device before starting
    the next transfer, or 0 to keep Chip Select always active. Defaults
    to zero.

mode

:   Used to describe the Clock Polarity and Clock Phase for the SPI
    transmission. May be set to "0" or "SPI_CPHA" or "SPI_CPOL" or "SPI_CPHA |
    SPI_CPOL". Should be set (and defaults) to SPI_CPHA.

speed

:   Maximum SPI clock speed, in Hz. Should be set higher than 700 Hz and
    lower than 17.8 MHz. Defaults to 1 MHz.

dry_run

:   If set to "true" then instead of sending a SPI_IOC_MESSAGE ioctl to
    the SPI character device, commands such as "**sja1105-tool config upload**"
    just print the SPI messages as a hexdump to stdout. No communication
    is performed over SPI.

auto_flush

: - Sets the flush condition to true for some of the sja1105-tool commands
    that perform modifications to the staging area, and after which the
    configuration is still likely to be valid. Commands in this category
    are: "**sja1105-tool config modify**", "**sja1105-tool config
    load**", "**sja1105-tool config default**", but not "**sja1105-tool
    config new**". Also see sja1105-tool-config(1).

  - Even if "auto_flush" is set to false here, the flush condition can
    be forced to true by invoking the commands mentioned above with the
    -f|--flush argument.

  - If the flush condition is set to true, care must be taken that all
    intermediate configurations are valid, or else the respective
    sja1105-tool command will fail. For a list of the checks performed
    on the configuration by the sja1105-tool see
    sja1105-tool-config-format(5).

THE GENERAL SECTION
-------------------

This section begins when a line contains the string "[general-setup]" and ends
at the beginning of a different section or at the end of file. The following
keys are allowed in this section:

debug

:   If set to "true", debugging output is produced for bit-level access to the
    switch configuration tables. Recommended "false".

verbose

:   If set to "false", nothing is printed to stdout, only error messages are
    printed to stderr.

screen-width

:   Used for the following commands:

* **sja1105-tool config show**
* **sja1105-tool status ports**

    The idea is to make better use of screen space by fitting more entries on
    separate vertical columns. The total width of the vertical columns does not
    exceed the "screen-width" value. Set "screen-width" to a value greater or
    equal to 80, and less than the output of ```tput cols```.

entries-per-line

:   See "screen-width" above. Additionally, no more than "entries-per-line"
    vertical columns are allowed to be concatenated. The result is that each
    line will contain the minimum of "entries-per-line" and how many columns
    physically fit in "screen-width" characters.

EXAMPLE
=======

```conf
[spi-setup]
	staging-area = FILE
	device       = FILE
	bits         = 8
	speed        = 1000000
	delay        = 0
	cs_change    = 0
	mode         = SPI_CPHA
	dry_run      = false
	auto_flush   = false

[general]
	screen-width     = 120
	entries-per-line = 10
	verbose          = false

```

BUGS
====

**sja1105-tool status ports** currently ignores the values "entries-per-line"
and "screen-width".

AUTHOR
======

sja1105-tool was written by Vladimir Oltean <vladimir.oltean@nxp.com>

SEE ALSO
========

sja1105-tool(1)
sja1105-tool-config(1)
sja1105-tool-config-format(5)

COMMENTS
========

This man page was written using [pandoc](http://pandoc.org/) by the same author.


text:
(function() {
  // Multiple instances of lodash should not be instantiated because lodash uses an internal counter, idCounter,
  // to generate unique IDs. This may result in collisions because the foreground and background pages share
  // references with each other. i.e. 'foo_100' could appear on both pages.
  // Force the foreground to leverage the background's lodash instance.
  var getBackgroundPageExists = window.chrome && chrome.extension && chrome.extension.getBackgroundPage;
  var backgroundPage = getBackgroundPageExists ? chrome.extension.getBackgroundPage() : null;
  var isForeground = backgroundPage && backgroundPage.window !== window;
  var _ = isForeground ? backgroundPage.window._ : require('lodash');
  // TODO: Global can be removed once BB upgraded to 1.2.3 (which seems buggy) or SystemJS supports 'format cjs' + deps injection.
  window._ = _;
  module.exports = _;
}(this));


text:
layout: post
title: 'January Meeting @ Noon: Telligen''s Agile Journey'
---

Cost: Free (Registration is required to pre-print visitor badges)

Picture ID Required for entry

Date/Time: Thursday, Jan 16, 2014 from 11:45 AM - 1:00 PM

Lunch is *not* provided. Please bring a bag lunch.

Location:

Telligen

1776 West Lakes Parkway

West Des Moines, Iowa 50266

South building. Enter through East doors.

Topic:Telligen's Agile Journey

Telligen, a West Des Moines-based Health IT company, began its foray into the agile space back in 2009. Since then Telligen has gone through several evolutions on its processes. It has teams that have cut their teeth on automated testing, TDD, point estimation, and other agile practices. The employee-owned company has been appraised at CMMI level 3 in both waterfall and agile SDLCs.

In this session, cross disciplinary team members from Telligen will provide a brief background on their experience with agile. The remaining time will be a Q&A period discussing a wide variety of agile topics. Audience participation encouraged.


text:
/* We need to tell jshint which are our global variables */
/* global $:false,
    Rickshaw: false,
    moment: false,
    navigator: false,
    theme: false
*/
(function() {
  'use strict';

  var app = angular.module('winderfulApp',
    [
      'turbine-directives',
      'winderful-filters',
      'ngBootstrap',
      'angular-rickshaw'
    ]);

  app.controller('turbineController', ['$scope', '$http', function($scope, $http) {
    var firstLoad = true;

    $scope.rotationSpeed = 10;

    this.graph = {};
    this.percentage = 0;
    this.speed = 0;
    $scope.wattage = 0;
    this.displayDate = new Date();
    this.loaded = false;

    this.hoverDeets = {};

    this.iosSafari = /(iPhone|iPod|iPad).*AppleWebKit/i.test(navigator.userAgent);

    this.usageExamples = [
      { action: 'Powering', consumption: (0.000483 * 26400000) / 100, object: '% of UK homes' },
      { action: 'Or making', consumption: 0.00006, object: 'cups of tea' },
      { action: 'Or making', consumption: 0.000033, object: 'slices of toast' },
      { action: 'Or driving', consumption: 0.00038, object: 'miles in a Tesla Model S' },
      { action: 'Or watching', consumption: 0.000055, object: 'hours of telly' },
      { action: 'Or powering', consumption: 0.0005, object: 'fridge-freezers for a day' }
    ];

    if (typeof (theme) !== 'undefined' &&
        typeof (theme.usageExamples) !== 'undefined') {
      this.usageExamples = theme.usageExamples;
    }

    this.updateStats = function(date, power, percent) {
      // change animation speed
      setTurbineSpeed(power);

      // update variables for stats
      $scope.wattage = power;
      this.displayDate = new Date(date * 1000);
      this.percentage = percent;

      // winterful only
      if (typeof (theme) !== 'undefined' &&
          typeof (theme.onUpdate) !== 'undefined') {
        theme.onUpdate(power);
      }

      // if details is from less than 30 mins ago for wording in stats
      this.isCurrent = (new Date() - this.displayDate) / 60000 < 30;

      // show random "equivalent of" stat
      this.showExample = Math.round(Math.random() * (this.usageExamples.length - 2)) + 1;

      if (this.iosSafari) {
        // IOS not triggering ngclick for some reason on the graph, so temp fix
        $scope.$apply();
      }
    };

    this.setStats = function() {
      this.updateStats(this.hoverDeets.x, this.hoverDeets.y, this.hoverDeets.z);
    };

    var hoverGraph = function(series, x, y, z, a, b) {
      // Rickshaw doesn't have a click event
      // temp store the details of where we hover in case the user clicks here
      this.hoverDeets.x = x;
      this.hoverDeets.y = y;
      this.hoverDeets.z = b.value.z;

      if (this.iosSafari) {
        // IOS not triggering ngclick for some reason on the graph, so temp fix
        this.setStats();
      }

      // return format for hover tooltip on graph
      return y + 'MW';
    };

    var graphSetup = function() {
    };

    var setTurbineSpeed = function(power) {
      var $rContainer = $('#turbine-rotor-container');
      var $rotor = $('#turbine-rotor').eq(0);
      var value = powerToSpeed(power);
      var degPerS = power * 1.9;
      var oldTransform = matrixToDeg($rotor.css('transform'));
      var parentTransform = matrixToDeg($rContainer.css('transform'));

      // set the rotation speed of the wind turbine
      $scope.rotationSpeed = value;

      // unfortunately CSS animation speeds do not update automagically
      // so we need to remove .animated from the $rotor and add it again
      // in order to trigger the speed change
      // we could use keyframeanimation in JS but it didn't give as smooth
      // results as css animation
      $rotor.removeClass('animated').hide();

      // add rotation to the container so that the $rotor is at the same angle
      // as it was when animation stops momenteraly
      var newRotation = oldTransform + parentTransform + degPerS;
      $rContainer.css('transform', 'rotateZ(' + newRotation + 'deg)');

      // must add class on a time out to trigger the change in speed
      setTimeout(function() {
        $rotor.addClass('animated').show();
      }, 0);
    };

    var powerToSpeed = function(power) {
      // if no power, stop the mill
      return power ? (6500 / power) : 3000000;
    };

    var matrixToDeg = function(tr) {
      // grab the matrix CSS and transform into degrees
      var angle = 0;

      if (tr !== 'none') {
        var values = tr.split('(')[1];
        values = values.split(')')[0];
        values = values.split(',');

        var a = values[0];
        var b = values[1];

        var radians = Math.atan2(b, a);

        if (radians < 0) {
          radians += (2 * Math.PI);
        }

        angle = Math.round(radians * (180 / Math.PI));
      }

      return angle;
    };

    this.graph.options = {
      renderer: 'area',
      height: 200
    };

    this.graph.features = {
      hover: {
        formatter: hoverGraph.bind(this),
        xFormatter: function(x) {
          var now = moment().format('X');
          var time = '';

          if ($scope.delta <= 3600 * 8 * 24) {
            // date range < 10 hours : show every 5 mins
            if (now - x > 6 * 24 * 3600) {
              time = moment.unix(x).format('LLL');
            } else {
              time = moment.unix(x).calendar();
            }
          } else if ($scope.delta <= 3600 * 24 * 30) {
            // date range < 1 week : show every hour
            time = moment.unix(x).format('LLL');
          } else if ($scope.delta <= 3600 * 24 * 30 * 12) {
            // date range < 1 month : show daily average
            time = moment.unix(x).format('LL');
          } else {
            // date range < 1 year : show weekly average
            time = 'week ' + moment.unix(x).format('w') + ' of ' + moment.unix(x).format('YYYY');
          }

          return time;
        }
      },
      yAxis: {
      },
      xAxis: {
        timeFixture: new Rickshaw.Fixtures.Time.Local()
      },
      complete: graphSetup.bind(this)
    };

    this.graph.series = [{name: 'Wind', color: '#007232', data: [{x: 0, y: 0}]}];
    this.daterange = { startDate: moment().subtract('days', 7), endDate: moment() };

    function dateChanged(start, end) {
      var dateRange = moment.unix(start).format('Do MMMM YYYY') + ' - ' + moment.unix(end).format('Do MMMM YYYY');
      var dateChangedEvent = {
        hitType: 'event',
        eventCategory: 'dates',
        eventAction: 'change',
        eventLabel: dateRange
      };

      if (typeof ga !== 'undefined') {
        ga('send', dateChangedEvent);
      }
    }

    $scope.loadInData = function() {
      if (typeof (this.daterange) !== 'undefined') {
        if (!firstLoad) {
          dateChanged(this.daterange.startDate.unix(), this.daterange.endDate.unix());
        }

        firstLoad = false;

        var _this = this;
        var startDate = this.daterange.startDate.unix();
        var endDate = this.daterange.endDate.unix();

        $scope.delta = endDate - startDate;

        $http.get('./json/', { params: { start: startDate, end: endDate }})
          .success(function(data) {
            _this.graph.series = data;
            var lastValue = data[0].data.pop();

            _this.updateStats(lastValue.x, lastValue.y, lastValue.z);

            _this.loaded = true;

            if (typeof (theme) !== 'undefined' &&
                typeof (theme.onStart) !== 'undefined') {
              theme.onStart();
            }
          });
      }

    }.bind(this);

    $scope.$watch(function() { return this.daterange; }.bind(this), function() {
      $scope.loadInData();
    });

  }]);

})();


text:
<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\Route;

/**
 * RouteSearch represents the model behind the search form about `backend\models\Route`.
 */
class RouteSearch extends Route
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id'], 'integer'],
            [['starting_point', 'end_point'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Route::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
        ]);

        $query->andFilterWhere(['like', 'starting_point', $this->starting_point])
            ->andFilterWhere(['like', 'end_point', $this->end_point]);

        return $dataProvider;
    }
}


text:
(function() {

    // Set 0: Selectors.

    /**
     * Problem 1: Write a function that selects all the images in the .selection-images div.
     * (All following problems refer to the .selection-images div unless otherwise specified.)
     *
     * Hint: You must complete Problem 0 in index.html first.
     * Hint: Use $('your selector') to select a set of elements.
     * Hint: Use $('some elements').addClass('selected') to verify that you've selected the right elements.
     * Hint: http://learn.jquery.com/using-jquery-core/selecting-elements/
     * Hint: http://api.jquery.com/category/selectors/
     */
    function selectAllImages() {

    }

    /**
     * Problem 2: Write a function that selects the first image.
     *
     * Hint: Check out the :first pseudo-selector
     * Hint: http://learn.jquery.com/using-jquery-core/selecting-elements/#pseudo-selectors
     * Hint: Check out the .eq() method. You can use it to select just one of a set of matched elements:
     *      $('many elements').eq(1) // select the element at index 1
     * Hint: https://api.jquery.com/eq/
     */
    function selectFirstImage() {

    }

    /**
     * Problem 3: Write a function that selects images after the first one.
     *
     * Hint: Check out the :gt() pseudo-selector
     * Hint: http://learn.jquery.com/using-jquery-core/selecting-elements/#pseudo-selectors
     */
    function selectImagesAfterFirst() {

    }

    /**
     * Problem 4: Write a function that selects all images with a given alt tag.
     *
     * Hint: Check out the [attribute=value] selector syntax.
     * Hint: http://learn.jquery.com/using-jquery-core/selecting-elements/#selecting-elements-by-attribute
     */
    function selectImagesWithAltTag(altTag) {

    }

    /**
     * Problem 5: Write a function that shuffles the image `src`s. So after calling this function,
     * the second image will have the `src` that was originally of the first image, the third
     * image will have the `src` that was originally of the second image, and the first image
     * will have the `src` that was originally of the third image.
     *
     * Hint: It's ok to hardcode the assumption that there are three images.
     * Hint: Use $('selection').attr('src') to get src attr of the first selected element.
     * Hint: Use $('selection').attr('src', 'new value') to set src attr for every matched element.
     * Hint: Use $('selection').eq(index) to select an element at a specific index.
     * Hint: http://api.jquery.com/attr/
     * Hint: http://learn.jquery.com/using-jquery-core/working-with-selections/
     */
    function shuffleSrcs() {

    }

    /**
     * Set 1: Events
     *
     * In browser programming, events are a central part of your application,
     * since you're probably spending most of your time responding to user input.
     * jQuery provides a number of utilities to manage events.
     *
     * http://learn.jquery.com/events/
     * http://learn.jquery.com/events/introduction-to-events/
     * https://api.jquery.com/category/events/
     */

    /**
     * Problem 1: Write a function that adds the .selected class to an image when the image is clicked.
     *
     * Hint: Use $('selector').click(function() { }) to set up a click handler.
     * Hint: https://api.jquery.com/click/
     * Hint: http://learn.jquery.com/events/event-basics/#setting-up-event-responses-on-dom-elements
     */
    function selectImageOnClick() {

    }

    /**
     * Problem 1: Write a function that adds the .selected class to an image when the image is clicked,
     * only the first time but not subsequent times the image is clicked.
     *
     * Hint: Use $('selector').off('eventName') to remove event listeners from an event.
     * Hint: https://api.jquery.com/off/
     * Hint: http://learn.jquery.com/events/event-basics/#tearing-down-event-listeners
     */
    function selectImageOnClickOnce() {

    }

    /**
     * Problem 2: In the .events div there is a table. Each row of this table contains an event
     * name. Write a function that sets up handlers such that the cell in the "Count" column
     * is the number of times that event has occurred on the table.
     *
     * Hint: Use $('selector').text(newVal) to set the text of all selected elements.
     * Hint: http://api.jquery.com/text/
     * Hint: You may wish to have some variables in this function to keep track of how many times
     *       each event has fired.
     * Hint: If you want to get fancy, you can set up multiple event handlers with a single .on() call
     * Hint: http://learn.jquery.com/events/event-basics/#setting-up-multiple-event-responses
     */
    function setUpTableEvents() {

    }

    /**
     * Problem 3: In the .events-names div there is a list of names. There is also a span with class
     * .most-recently-clicked. Write a function that inserts the most recently clicked name into
     * that span.
     *
     * Hint: Use $('selector').text(newVal) to set the text of all selected elements.
     * Hint: Use $('selector').text() to get the text of the first of the selected elements.
     * Hint: In an event handler, use event.target to see the element that triggered the event.
     *       (Just for fun, check out the event object to see what else you get on it!)
     *
     *       For example:
     *          $('p').click(function(event) {
     *              $(event.target).attr('id') // get the id attribute of the clicked element.
     *          })
     * Hint: https://api.jquery.com/event.target/
     * Hint: http://learn.jquery.com/events/inside-event-handling-function/
     */
    function setUpNamesEvents() {

    }

    /**
     * Problem 4: In the .events-coordinates div, there is are some spans showing where the most
     * recent mousemove event was. Add a mousemove listener to the entire page that updates
     * these spans with the most recent values.
     *
     * Hint: I don't know but I think you'll find that 'body' covers pretty much everything.
     * Hint: In an event handler, use event.pageX and event.pageY to get the coordinates of where
     *       the event occurred.
     * Hint: http://learn.jquery.com/events/inside-event-handling-function/
     * Hint: https://api.jquery.com/event.pageX/
     * Hint: https://api.jquery.com/event.pageY/
     */
    function setUpMousemoveEvents() {

    }

    /**
     * Problem 5: In the .events-triggers div, there are three buttons. Each button contains the name
     * of an event that was referenced in the table in an earlier problem. Wire up event handlers
     * such that clicking a button manually triggers that event on the table.
     *
     * Hint: Use $('selector').trigger('eventName') to manually execute handlers for the selected elements.
     * Hint: http://learn.jquery.com/events/triggering-event-handlers/
     * Hint: https://api.jquery.com/trigger/
     */
    function setUpTriggers() {

    }
})();


text:
package main

type ImplicitCastExpr struct {
	Address  string
	Position string
	Type     string
	Kind     string
	Children []interface{}
}

func parseImplicitCastExpr(line string) *ImplicitCastExpr {
	groups := groupsFromRegex(
		"<(?P<position>.*)> '(?P<type>.*)' <(?P<kind>.*)>",
		line,
	)

	return &ImplicitCastExpr{
		Address:  groups["address"],
		Position: groups["position"],
		Type:     groups["type"],
		Kind:     groups["kind"],
		Children: []interface{}{},
	}
}

func (n *ImplicitCastExpr) Render() []string {
	return renderExpression(n.Children[0])
}


text:
package com.crm.product.cache;

import java.util.Date;

import com.crm.kernel.index.IndexNode;

public class ProductScore extends IndexNode
{
	private long	productId		= 0;
	private long	segmentId		= 0;

	private String	actionType		= "";
	private int		minQuantity		= 0;
	private int		maxQuantity		= 999999999;
	private int		minAmount		= 0;
	private int		maxAmount		= 999999999;

	private String	balanceType		= "charge";
	private boolean	flatCharge		= true;
	private double	scoreRate		= 0;
	private double	scoreUnit		= 0;
	private long	campaignId		= 0;

	public ProductScore()
	{
		super();
	}

	public long getProductId()
	{
		return productId;
	}

	public void setProductId(long productId)
	{
		this.productId = productId;
	}

	public long getSegmentId()
	{
		return segmentId;
	}

	public void setSegmentId(long segmentId)
	{
		this.segmentId = segmentId;
	}

	public String getActionType()
	{
		return actionType;
	}

	public void setActionType(String actionType)
	{
		this.actionType = actionType;
	}

	public int getMinQuantity()
	{
		return minQuantity;
	}

	public void setMinQuantity(int minQuantity)
	{
		this.minQuantity = minQuantity;
	}

	public int getMaxQuantity()
	{
		return maxQuantity;
	}

	public void setMaxQuantity(int maxQuantity)
	{
		this.maxQuantity = maxQuantity;
	}

	public int getMinAmount()
	{
		return minAmount;
	}

	public void setMinAmount(int minAmount)
	{
		this.minAmount = minAmount;
	}

	public int getMaxAmount()
	{
		return maxAmount;
	}

	public void setMaxAmount(int maxAmount)
	{
		this.maxAmount = maxAmount;
	}

	public String getBalanceType()
	{
		return balanceType;
	}

	public void setBalanceType(String balanceType)
	{
		this.balanceType = balanceType;
	}

	public boolean isFlatCharge()
	{
		return flatCharge;
	}

	public void setFlatCharge(boolean flatCharge)
	{
		this.flatCharge = flatCharge;
	}

	public double getScoreRate()
	{
		return scoreRate;
	}

	public void setScoreRate(double scoreRate)
	{
		this.scoreRate = scoreRate;
	}

	public double getScoreUnit()
	{
		return scoreUnit;
	}

	public void setScoreUnit(double scoreUnit)
	{
		this.scoreUnit = scoreUnit;
	}

	public long getCampaignId()
	{
		return campaignId;
	}

	public void setCampaignId(long campaignId)
	{
		this.campaignId = campaignId;
	}

	public boolean equals(long productId, long segmentId, int quantity, double amount, Date date)
	{
		boolean result = (getProductId() == productId)
				&& (getSegmentId() == segmentId)
				&& (getMinQuantity() <= quantity)
				&& (getMaxQuantity() >= quantity)
				&& (getMinAmount() <= amount)
				&& (getMaxAmount() >= amount)
				&& isRange(date);;

		return result;
	}
}


text:
def require_migration
  spec_name = caller_locations.first.path
  migration_name = spec_name.sub("spec/migrations", "db/migrate").sub("_spec.rb", ".rb")

  require migration_name
end


text:
order: 28
title:
  zh-CN: 弹出位置
  en-US: Placement
---

## zh-CN

可以通过 `placement` 手动指定弹出的位置。

## en-US

You can manually specify the position of the popup via `placement`.

```tsx
import type { DatePickerProps, RadioChangeEvent } from 'antd';
import { DatePicker, Radio } from 'antd';
import React, { useState } from 'react';

const { RangePicker } = DatePicker;

const App: React.FC = () => {
  const [placement, SetPlacement] = useState<DatePickerProps['placement']>('topLeft');

  const placementChange = (e: RadioChangeEvent) => {
    SetPlacement(e.target.value);
  };

  return (
    <>
      <Radio.Group value={placement} onChange={placementChange}>
        <Radio.Button value="topLeft">topLeft</Radio.Button>
        <Radio.Button value="topRight">topRight</Radio.Button>
        <Radio.Button value="bottomLeft">bottomLeft</Radio.Button>
        <Radio.Button value="bottomRight">bottomRight</Radio.Button>
      </Radio.Group>
      <br />
      <br />
      <DatePicker placement={placement} />
      <br />
      <br />
      <RangePicker placement={placement} />
    </>
  );
};

export default App;
```


text:
class CPlayerManager {
  public:
    irr::core::map<int, TeamList*> teams;
    irr::core::array<Vote*, irr::core::irrAllocator<Vote*> > votes;
    int lastvote_time;
    int lastvote_minimum_time;
    static int server_votepacket_size;
    static int client_votepacket_size;
    irr::core::array<CPlayer*, irr::core::irrAllocator<CPlayer*> > players;

    irr::core::array<historical_player*, irr::core::irrAllocator<historical_player*> > historical_players;
    int playerslist_y;

    CPlayerManager(void);
    ~CPlayerManager(int);
    CPlayer * getPlayer(ENetPeer *);
    CPlayer * getPlayer(irr::s32);
    CPlayer * GetPlayerByControls(CControls *);
    CPlayer * getPlayerBySessionID(enet_uint32);
    CPlayer * getPlayerByHost(enet_uint32);
    CPlayer * getPlayerByNetworkID(enet_uint32);
    bool playerExists(CPlayer *);
    CPlayer * getPlayerByUsername(const char *);
    CPlayer * getPlayerByCharname(const char *);
    CPlayer * AddPlayer(ENetPeer *, CPlayer *);
    void RemovePlayer(ENetPeer *);
    void RemovePlayer(CPlayer *);
    void DumpToConsole(void);
    void Update(void);
    void KillemAll(void);
    void RespawnAll(bool);
    irr::s32 getPlayersNum(void);
    irr::s32 getHumanPlayersNum(void);
    irr::s32 getHumanPlayersNum_NotSpectator(void);
    irr::s32 getHumanPlayersNum_Spectator(void);
    void Sort(void);
    int PlayersPartition(irr::core::array<CPlayer*, irr::core::irrAllocator<CPlayer*> > &,
    int, int);
    void PlayersQuicksort(irr::core::array<CPlayer*, irr::core::irrAllocator<CPlayer*> > &,
    int, int);
    String getPlayerName(ENetPeer *);
    irr::s32 getTeamSize(irr::s16);
    irr::s32 getLowestTeamSize(void);
    int getSmallestTeam(void);
    int getPlayersOnTeam(int);
    irr::s32 getTeamPlayersPlaying(int);
    void Render(void);
    bool teamsHaveAtleastPlayers(int);
    bool teamPlayerDifferFromPlayers(void);
	void CastVote(irr::u8, irr::u16, const wchar_t *);
    void CastVote(bool);
    void RenderVotes(void);
    bool recdVote(CBitStream &, ENetPeer *);
    void VotePass(int, int, int, Vote *);
    void CalculateVotePassNumber(int, int, int, CPlayer *, int &);
    void client_SendMarkPlayer(enet_uint32, irr::u8);
    bool server_RecdMarkPlayer(CBitStream &, ENetPeer *);
    void CheckGrieferKick(enet_uint32, int, CPlayer *);
    void Kick(CPlayer *, int, int);
    void MakeUniqueName(String &, CPlayer *, int, bool);
    void KickForStuff(void);
    void SwapTeam(CPlayer *);
    void BalanceTeams(void);
    historical_player * getHistoricalPlayer(const char *);
    void MakePartyList(CPlayer *,
    irr::core::array<CPlayer*, irr::core::irrAllocator<CPlayer*> > &);
}


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>L-Index</title>
<meta name="date" content="2017-05-10">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D G H I L M P R S T U V

L

listarAvisos(int) - Static method in class Modelo.Aviso

Consultar todos los avisos correspondientes a ese trabajador

listarCentros() - Static method in class Modelo.Centro

Método que muestra una lista de todos los centros pero con sólo 3 datos.

listarTrabajadores() - Static method in class Modelo.Trabajador

Método que conecta con la base de datos para listar trabajadores mediante llamada a un procedimiento dentro de un paquete

listarTrabajadoresCentro(int) - Static method in class Modelo.Trabajador

Método que conecta con la base de datos para listar trabajadores según su centro mediante llamada a un procedimiento dentro de un paquete

listarTrabajadoresTrans() - Static method in class Modelo.Trabajador

Método que conecta con la base de datos para listar trabajadores transportistas mediante llamada a un procedimiento dentro de un paquete

listarUsuarios() - Static method in class Modelo.Usuario

Método que conecta con la base de datos para listar todos los usuarios mediante una sentencia preparada

listarVehiculos() - Static method in class Modelo.Vehiculo

Método que conecta con la base de datos para ver todos los vehículos mediante una sentencia preparada

Login - Class in Ventanas

Login() - Constructor for class Ventanas.Login

Creates new form Login

A B C D G H I L M P R S T U V

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
{-# LANGUAGE OverloadedStrings #-}
module Test.Sunlight
  ( Description
  , Compiler
  , GhcPkg
  , Cabal
  , TestInputs(..)
  , runTests
  ) where

import Distribution.Package
import Distribution.Text
import Test.Sunlight.Shell
import System.Directory
import Distribution.PackageDescription
import Distribution.PackageDescription.Parse
import Distribution.Simple.Utils
import Distribution.Verbosity
import Distribution.Version
import Data.Tuple.Select
import qualified Data.ByteString.Char8 as BS8
import Data.Monoid
import Data.Time
import System.Locale (defaultTimeLocale)
import Data.List (intersperse)
import System.Random
import Control.Monad
import System.Exit

-- | Result from installing the package's dependencies.
data InstallResult = InstallResult
  { drOutput :: CmdResult
  , drGhcPkg :: CmdResult
  } deriving Show

instance CheckOk InstallResult where
  isOk r = all isOk . map ($ r) $ [drOutput, drGhcPkg]

-- | Install a package's dependencies.

-- Preconditions:
--
-- * current directory has the unpacked tarball.
--
-- Side effects:
--
-- * dependencies are fully or partially installed.  If partially
-- installed, the ExitCode should be non-zero.
installDeps
  :: [PackageIdentifier]
  -- ^ Optional constraints.  Currently constraints may only be tied
  -- to specific versions (for instance, flag constraints or
  -- constraints tied to a range of versions are not allowed.)
  -> FilePath
  -- ^ Install using this compiler (full path to compiler).
  -> FilePath
  -- ^ Full path to ghc-pkg.
  -> FilePath
  -- ^ Path to cabal executable
  -> FilePath
  -- ^ Path to directory to use for user package DB.
  -> FilePath
  -- ^ Directory to use for installation prefix
  -> IO InstallResult
installDeps cs ghc pkg cabal db dir = do
  let opts =
        [ "install"
        , "--verbose=2"
        , "--with-compiler=" ++ ghc
        , "--with-hc-pkg=" ++ pkg
        , "--prefix=" ++ dir
        , "--disable-library-profiling"
        , "--disable-executable-profiling"
        , "--package-db=clear"
        , "--package-db=global"
        , "--package-db=" ++ db
        , "--enable-tests"
        , "--disable-documentation"
        , "--only-dependencies"
        ] ++ map constraint cs
  out <- tee cabal opts
  let pkgOpts = [ "list", "--global", "--package-conf=" ++ db ]
  pkgOut <- tee pkg pkgOpts
  return $ InstallResult out pkgOut

-- | Makes a PackageIdentifier into a version constraint option.
constraint :: PackageIdentifier -> String
constraint i = "--constraint=" ++ name ++ "==" ++ ver
  where
    name = display . pkgName $ i
    ver = display . pkgVersion $ i

data PackageInstResult = PackageInstResult
  { piSetup :: CmdResult
  , piConfigure :: CmdResult
  , piBuild :: CmdResult
  , piInst :: CmdResult
  , piGhcPkg :: CmdResult
  } deriving Show

instance CheckOk PackageInstResult where
  isOk r = all isOk . map ($ r) $
    [ piSetup, piConfigure, piBuild, piInst, piGhcPkg ]

-- | Install a package.
--
-- Preconditions:
--
-- * dependencies have already been installed at the given prefix
-- and registered in the given db
--
-- * current directory has the unpacked tarball.
--
-- Side effects:
--
-- * package should be installed, or exit code is non-zero
installPackage
  :: FilePath
  -- ^ Install using this compiler (full path to compiler)
  -> FilePath
  -- ^ Full path to ghc-pkg
  -> FilePath
  -- ^ User DB
  -> FilePath
  -- ^ Installation prefix
  -> IO PackageInstResult
installPackage ghc pkg db pfx = do
  let opts =
        [ "configure"
        , "--verbose=2"
        , "--with-compiler=" ++ ghc
        , "--with-hc-pkg=" ++ pkg
        , "--prefix=" ++ pfx
        , "--package-db=clear"
        , "--package-db=global"
        , "--package-db=" ++ db
        , "--enable-tests"
        ]
  rBuildSetup <- tee "ghc" ["--make", "Setup.hs"]
  rConf <- tee "./Setup" opts
  let bOpts =
        [ "build", "--verbose=2" ]
  rBuild <- tee "./Setup" bOpts
  rInst <- tee "./Setup" ["install", "--verbose=2"]
  rPkg <- tee pkg
    [ "list"
    , "--global"
    , "--package-conf=" ++ db
    ]
  return $ PackageInstResult rBuildSetup rConf rBuild rInst rPkg

-- | Test a package.
--
-- Preconditions:
--
-- * Package has already been built.
testPackage
  :: [(String, [String])]
  -- ^ From the package root directory, these are the commands and
  -- arguments to run to test the package.
  -> IO [CmdResult]
testPackage = mapM (uncurry tee)

data InstallAndTestResult = InstallAndTestResult
  { itDate :: UTCTime
  -- ^ Current time
  , itGhcVersion :: CmdResult
  -- ^ Result of ghc --version
  , itPkgVersion :: CmdResult
  -- ^ Result of ghc-pkg --version
  , itCabalVersion :: CmdResult
  -- ^ Result of cabal --version
  , itCompileSetup :: CmdResult
  -- ^ Result from compiling Setup.hs
  , itSdistDeps :: CmdResult
  -- ^ Result from running sdist to create tree from which to
  -- install dependencies
  , itSdistPkg :: CmdResult
  -- ^ Result from running sdist to create tree from which to
  -- install package
  , itInit :: CmdResult
  -- ^ Result from initializing user package DB
  , itDeps :: InstallResult
  , itPackage :: PackageInstResult
  , itTest :: [CmdResult]
  } deriving Show

instance CheckOk InstallAndTestResult where
  isOk r = and [ rsltsOk, testsOk,
    isOk (itDeps r), isOk (itPackage r) ]
    where
      rsltsOk = all isOk . map ($ r) $
        [ itGhcVersion, itPkgVersion, itCabalVersion, itCompileSetup,
          itSdistDeps, itSdistPkg, itInit ]
      testsOk = all isOk . itTest $ r

-- | Performs test installation.
--
-- Preconditions:
--
-- * is run from root package directory.  A temporary directory is
-- created inside this directory.  All work is done within the
-- temporary directory.
--
-- Postconditions:
--
-- * cleans up after itself; no temporary files should remain.
installAndTest
  :: [PackageIdentifier]
  -- ^ Constraints
  -> UTCTime
  -> FilePath
  -- ^ Path to compiler
  -> FilePath
  -- ^ Path to ghc-pkg
  -> FilePath
  -- ^ Path to cabal executable
  -> [(String, [String])]
  -- ^ How to test the package
  -> IO InstallAndTestResult
installAndTest cs date ghc pkg cabal test =
  withTempDirectory verbose "." "sunlight" $ \relDir -> do
    dir <- canonicalizePath relDir
    let setup = dir ++ "/Setup"
        distDeps = dir ++ "/distDeps"
        distPkg = dir ++ "/distPkg"
        db = dir ++ "/db"
        pfx = dir ++ "/prefix"
    ghcVer <- tee ghc ["--version"]
    pkgVer <- tee pkg ["--version"]
    cblVer <- tee "cabal" ["--version"]
    rSetup <- tee ghc ["--make", "-outputdir", dir,
      "-o", setup, "Setup.hs"]
    rDistDeps <- tee setup
      ["sdist", "--output-directory=" ++ distDeps ]
    rDistPkg <- tee setup
      ["sdist", "--output-directory=" ++ distPkg ]
    createDirectory pfx
    rInit <- tee pkg ["init", db]
    rDeps <- inDirectory distDeps $
      installDeps cs ghc pkg cabal db pfx
    rInst <- inDirectory distPkg
      $ installPackage ghc pkg db pfx
    rTest <- inDirectory distPkg $ testPackage test
    return $ InstallAndTestResult date ghcVer pkgVer cblVer
      rSetup rDistDeps rDistPkg
      rInit rDeps rInst rTest

-- | Gets a list of PackageIdentifier with the lowest possible
-- versions.  Fails if a package has a dependency range with no
-- minimum.
lowestVersions
  :: GenericPackageDescription
  -> Either Dependency [PackageIdentifier]
  -- ^ Left with the bad dependency if there is one; Right
  -- otherwise.
lowestVersions pd = mapM lowestVersion ls
  where
    ls = depsLib ++ depsExe ++ depsTest ++ depsBench
    depsLib = case condLibrary pd of
      Nothing -> []
      Just deps -> getDependencies deps
    getDeps = getDepsList pd
    depsExe = getDeps condExecutables
    depsTest = getDeps condTestSuites
    depsBench = getDeps condBenchmarks

getDepsList
  :: GenericPackageDescription
  -> (GenericPackageDescription -> [(a, CondTree b [Dependency] c)])
  -> [Dependency]
getDepsList d f = concatMap getDependencies . map snd . f $ d

getDependencies
  :: CondTree v [Dependency] a
  -> [Dependency]
getDependencies t =
  let this = condTreeConstraints t
      rest = concatMap getDependencies . map sel2
        . condTreeComponents $ t
  in this ++ rest

lowestVersion :: Dependency -> Either Dependency PackageIdentifier
lowestVersion d@(Dependency n r) = case asVersionIntervals r of
  [] -> Left d
  (LowerBound v b, _):_
    | b == ExclusiveBound -> Left d
    | otherwise -> Right $ PackageIdentifier n v

testLowestVersions
  :: UTCTime
  -> FilePath
  -- ^ Path to compiler
  -> FilePath
  -- ^ Path to ghc-pkg
  -> FilePath
  -- ^ Path to cabal executable
  -> [(String, [String])]
  -- ^ How to test the package
  -> GenericPackageDescription
  -> Either Dependency (IO InstallAndTestResult)
testLowestVersions date ghc pkg cabal test d = case lowestVersions d of
  Left e -> Left e
  Right ps -> Right $ installAndTest ps date ghc pkg cabal test

testDefaultVersions
  :: UTCTime
  -> FilePath
  -- ^ Path to compiler
  -> FilePath
  -- ^ Path to ghc-pkg
  -> FilePath
  -- ^ Path to cabal executable
  -> [(String, [String])]
  -- ^ How to test the package
  -> IO InstallAndTestResult
testDefaultVersions date ghc pkg cabal test =
  installAndTest [] date ghc pkg cabal test

testMultipleVersions
  :: UTCTime
  -> (FilePath, FilePath)
  -- ^ Compiler and ghc-pkg to use when testing lowest version
  -> [(FilePath, FilePath)]
  -- ^ Compilers and ghc-pkg to use to test default versions
  -> FilePath
  -- ^ Path to cabal executable
  -> [(String, [String])]
  -- ^ How to test package
  -> GenericPackageDescription
  -> Either Dependency
            (IO (InstallAndTestResult, [InstallAndTestResult]))
testMultipleVersions date (lowestGhc, lowestPkg) rest cabal test pd =
  case testLowestVersions date lowestGhc lowestPkg cabal test pd of
    Left d -> Left d
    Right g -> Right $ do
      r1 <- g
      let testRest (c, p) = testDefaultVersions date c p cabal test
      rs <- mapM testRest rest
      return (r1, rs)

-- Sample test directory structure:
-- minimum-versions.txt
-- current-versions.txt
-- sunlight
--  - 2014
--    - 02
--      - 22
--        - UTCtime
--          - [random string]
--            - lowest-7.4.2-passed.txt
--            - current-7.4.2-passed.txt
--            - current-7.6.1-passed.txt

versionsReport
  :: BS8.ByteString
  -- ^ Description of dependencies
  -> Compiler
  -> Description
  -> UTCTime
  -> InstallAndTestResult
  -> BS8.ByteString
versionsReport desc c d t r = BS8.concat
  [ "This package was tested to work with these dependency\n"
  , "versions and compiler version.\n"
  , desc
  , "Tested as of: " <> (BS8.pack . show $ t) <> "\n"
  , "Path to compiler: " <> BS8.pack c <> "\n"
  , "Compiler description: " <> BS8.pack d <> "\n"
  , "\n"
  ] <>
  (crStdOut . piGhcPkg . itPackage $ r)

minimumVersionsReport
  :: Compiler
  -> Description
  -> UTCTime
  -> InstallAndTestResult
  -> BS8.ByteString
minimumVersionsReport = versionsReport
  "These are the minimum versions given in the .cabal file.\n"

writeMinimumVersionsReport :: BS8.ByteString -> IO ()
writeMinimumVersionsReport = BS8.writeFile "minimum-versions.txt"

currentVersionsReport
  :: UTCTime
  -> [(Description, Compiler, a)]
  -> [InstallAndTestResult]
  -> Maybe BS8.ByteString
currentVersionsReport t ds ts
  | null ds || null ts = Nothing
  | otherwise = Just $ versionsReport dep comp desc t r
  where
    dep = "These are the default versions fetched by cabal install.\n"
    (desc, comp, _) = last ds
    r = last ts

writeCurrentVersionsReport :: BS8.ByteString -> IO ()
writeCurrentVersionsReport = BS8.writeFile "current-versions.txt"

instance ShowBS InstallResult where
  showBS r = showBS (drOutput r)
    <> showBS (drGhcPkg r)

instance ShowBS PackageInstResult where
  showBS r =
    showBS (piSetup r)
    <> showBS (piConfigure r)
    <> showBS (piBuild r)
    <> showBS (piInst r)
    <> showBS (piGhcPkg r)

instance ShowBS InstallAndTestResult where
  showBS i =
    "Current time: " <> showBS (itDate i) <> "\n"
    <> showBS (itGhcVersion i)
    <> showBS (itPkgVersion i)
    <> showBS (itCabalVersion i)
    <> showBS (itCompileSetup i)
    <> showBS (itSdistDeps i)
    <> showBS (itSdistPkg i)
    <> showBS (itInit i)
    <> showBS (itDeps i)
    <> showBS (itPackage i)
    <> (BS8.concat . map showBS . itTest $ i)

-- | Gets four-character random string.
randomString :: IO String
randomString =
  fmap (map toEnum)
  $ replicateM 4 (getStdRandom (randomR (fromEnum 'a', fromEnum 'z')))

makeResultFile
  :: UTCTime
  -> String
  -- ^ Random string
  -> String
  -- ^ Description string, e.g. "lowest" or "current"
  -> String
  -- ^ Compiler version description
  -> InstallAndTestResult
  -> IO ()
makeResultFile utct rand desc comp res = do
  let dir = resultDirectory utct rand
  createDirectoryIfMissing True dir
  let fn = dir ++ "/" ++ desc ++ "-" ++ comp ++ "-"
        ++ passFail ++ ".txt"
      passFail
        | isOk res = "passed"
        | otherwise = "FAILED"
  BS8.writeFile fn . showBS $ res

resultDirectory
  :: UTCTime
  -> String
  -- ^ Random string
  -> String
resultDirectory t s = concat . intersperse "/" $
  ["sunlight", yr, mo, dy, ti, s ]
  where
    (y, m, d) = toGregorian . utctDay $ t
    yr = show y
    mo = pad . show $ m
    dy = pad . show $ d
    pad str
      | length str > 1 = str
      | otherwise = '0':str
    ti = formatTime defaultTimeLocale "%H%M%S" t

-- | A description for this compiler version.  This will be used in
-- the directory name in the tree that is written to disk.  I simply
-- use a compiler version, such as @7.4@.
type Description = String

-- | Path to GHC compiler.  You can use a full path name or, if you use
-- just an executable name, the PATH will be searched.
type Compiler = String

-- | Path to ghc-pkg.  If you use just an executable name, the PATH
-- will be searched.
type GhcPkg = String

-- | Path to cabal executable.  Used to install package
-- dependencies.  If you use just an executable name, the PATH will
-- be searched.
type Cabal = String

data TestInputs = TestInputs
  { tiDescription :: Maybe GenericPackageDescription
  -- ^ If Just, use this package description.  Handy if you write
  -- your own package description in Haskell rather than in the
  -- cabal format.  Otherwise, use Nothing and sunlight will look
  -- for the default cabal file and parse that.

  , tiCabal :: Cabal
  -- ^ Which @cabal@ executable to use.

  , tiLowest :: (Description, Compiler, GhcPkg)
  -- ^ Test the minimum dependency bounds using this compiler.  A
  -- report is left in the main package directory showing which
  -- package versions worked with this compiler and with the minimum
  -- bounds.

  , tiDefault :: [(Description, Compiler, GhcPkg)]
  -- ^ Test the default dependencies using these compilers.  Since
  -- cabal-install will eagerly get the most recent dependencies it
  -- can find, this will test the highest possible versions.  The
  -- compiler specified in 'tiLowest' is not automatically retried
  -- here, so if you want to use that compiler specify it as well.
  --
  -- The last compiler in this list is assumed to be the most recent
  -- compiler.  A report is left in the main package directory
  -- showing the dependencies that worked with this compiler
  -- version.

  , tiTest :: [(String, [String])]
  --  ^ How to test the package.  Each pair is a command to run,
  --  and the arguments to that command.  The command is run from
  --  the resulting package root directory after the package is
  --  unpacked and compiled.  So, if your test suite is an
  --  executable called @myTest@ and it requires the argument
  --  @--verbose@, you would use something like this:
  --
  -- > [("dist/build/myTest/myTest", ["--verbose"])]
  --
  -- The tests are considered to pass if all these commands exit
  -- with a zero exit status.
  --
  -- You can also abuse this option to get output in the record of
  -- the test; for instance, maybe you want to record the current
  -- git HEAD:
  --
  -- > [("git", ["rev-parse", "HEAD"])]
  } deriving Show

runTests :: TestInputs -> IO ()
runTests i = do
  desc <- case tiDescription i of
    Just pd -> return pd
    Nothing -> do
      path <- defaultPackageDesc verbose
      readPackageDescription verbose path
  date <- getCurrentTime
  randStr <- randomString
  let last2 (_, b, c) = (b, c)
      eiRes = testMultipleVersions date
        (last2 . tiLowest $ i) (map last2 . tiDefault $ i)
        (tiCabal i) (tiTest i) desc
  (r1, rs) <- case eiRes of
    Left e -> dependencyError e
    Right g -> g
  makeResultFile date randStr "lowest" (sel1 . tiLowest $ i) r1
  let makeRest r (d, _, _) = makeResultFile date randStr "current" d r
  _ <- zipWithM makeRest rs (tiDefault i)
  when (not $ isOk r1 && all isOk rs) exitFailure
  writeMinimumVersionsReport $ minimumVersionsReport
    (sel2 . tiLowest $ i) (sel1 . tiLowest $ i) date r1
  maybe (return ()) writeCurrentVersionsReport $ currentVersionsReport
    date (tiDefault i) rs
  exitSuccess

dependencyError :: Dependency -> IO a
dependencyError d = putStrLn s >> exitFailure
  where
    s = "dependency invalid: " ++ show d ++ " sunlight requires "
      ++ "that you specify a fixed lower bound for each dependency."


text:
desc="""several flavors of connect"""

setup="""
"""

cleanup="""
"""

notes="""
connect() returns a connection, cursor() returns a cursor.  These are the
two basic objects you will use.  SYSDBA is needed for system accounts.
"""

output="""
"""

import sys
import cx_Oracle

def demo(conn,curs):
    # normal user connect -- connstr looks like scott/tiger@orcl
    conn = cx_Oracle.connect(connstr)

    # normal user connect, three parms
    conn = cx_Oracle.connect('scott', 'tiger', 'orcl')

    # connect to the database as sysdba
    conn = cx_Oracle.connect('sys/secret@mydb', mode=cx_Oracle.SYSDBA)

if __name__ == '__main__':
    connstr = sys.argv[1]
    conn = cx_Oracle.connect(connstr)
    curs = conn.cursor()
    demo(conn,curs)
    conn.close()