Note: This documentation is preliminary and subject to change.
This document describes how to write a software program to send data to WorldWide Telescope, using the Layer Control API (LCAPI). For a large amount of data the program might be a tool that reads data from a spreadsheet file, and then sends the appropriate fields of the data to WorldWide Telescope in appropriately sized buffers for visualization. For a smaller amount of data the entire file could be loaded in one go, or images or 3D models could be loaded. Time series data would typically be time-and-location dependent event data such as:
The time-series system does not lend itself to data that varies either its location or has a complex intensity - such as weather systems, or forest fires - though it is possible a limited approach to this sort of data may be useful. The system does lend itself to events that occur over an extended period of time, given the ability to greatly accelerate simulated time, and also events that decay very rapidly (lightning) or quite slowly (diseases) given the ability to control the decay time of the rendered graphic. Although most examples are of time series events on the Earth, the events can be on any of the supported Solar System bodies, or simply the Sky.
There are a number of constraints on the use of the LCAPI that should be understood before commencing with the design of the tool:
For more information on WorldWide Telescope, refer to:
The Windows client version of WorldWide Telescope listens continuously, and without any setup process, for a certain format of communication on a particular port. The format of this communication is in the form of strings, that themselves are formatted in a specific way. An application may be quite short and only need a load call, or perhaps just need the new and update commands. Typically a simple application will go through the following steps, after WorldWide Telescope has been started:
A more complex application may initialize several layers, or a layer group, within WorldWide Telescope, or may transmit the data under user control - enabling the user to have some choice over which data is rendered, the speed and time of the simulation, and other similar controls.
The samples and examples described in this document have been developed using Microsoft Visual Studio (2008 or 2010) and the .NET framework, and written in C#.
The suggested development approach is first to get the sample application working, then to modify it as required using the code examples for each command. Note that the code examples themselves are not run-able code, but just guidelines on how the calls can be made.
The following commands can be used to control layers from the application. Note that command names are not case-sensitive, and that the general parameters can be included along with any other command.
Command | Description |
| activate | Highlights the selected layer in the layer manager. |
| delete | Specifies that a layer should be permanently deleted. |
| getprop |
Used to retrieve a value of a single layer property. Remarks include the Table of Properties. |
| getprops | Used to retrieve all the properties for a specified layer. Includes lists for Spreadsheet, 3d Model, Shapefile and ImageSet. |
| group | Specifies that a layer group should be added. |
| layerlist | Returns the structure of the layers and layer group names (in an XML document format) that are currently in the layer manager. |
| load | Specifies a data file, and and some optional parameters, to apply to a new layer. |
| mode | Changes the view to one of Earth, Planet, Sky, Panorama, SolarSystem. |
| move | Changes the view depending on the supplied parameter. |
| new | Specifies that a new layer should be created. |
| setprop | Used to specify a value of a single layer property. |
| setprops | Used to specify multiple properties for a layer. |
| state | Requests some details of the current view. |
| uisettings | Used to change user interface settings, without altering the layer data. |
| update | Specifies that the data attached to this command should be added to the layer. |
| version | Returns the version number of the running version of the LCAPI. |
| general parameters | Parameters that can be applied to any of the commands. |
The activate layer command will highlight the selected layer in the layer manager.
Required Parameter | Description |
| &id | Specifies the id number of the layer. |
The following string will be included in the response if the call is successful:
<Status>Success</Status>
If the call is not successful the following string may be included in the response, or other errors may be returned:
<Status>Error - Invalid layer ID</Status>
The delete command specifies that a layer should be permanently deleted.
All sub-components of the layer will also be deleted.
Required Parameter | Description |
| &id | Specifies the id number of the layer. |
The following string will be included in the response if the call is successful:
<Status>Success</Status>
If the call is not successful the following string may be included in the response, or other errors may be returned:
<Status>Error - Invalid layer ID</Status>
|
// // Send a DELETE command // WebClient client = new WebClient(); string url = string.Format("http://{0}:5050/layerApi.aspx?cmd=delete&id={1}", getIP().ToString(), layerId); string response = client.UploadString(url, ""); XmlDocument doc = new XmlDocument(); doc.LoadXml(response); XmlNode node = doc["LayerApi"]; string s = node.InnerText; // // Handle an error situation // if (s.Contains("Error")) { throw new Exception(s); } |
The getprop command is used to retrieve a value of a single layer property.
Required Parameters | Description |
| &id | Specifies the id number of the layer. |
| &propname | Property name, one from the table below. |
The following table lists the properties that can be get or set on a layer (note that the property names and Enum values are case-sensitive). Also refer to the Notes below the table.
Property |
Type | Description |
Layer Type |
Default |
| AltColumn | Int | Column number containing the altitude/depth data. | Spreadsheet | -1 |
| AltType | Enum | One of: Depth, Altitude, SeaLevel, Terrain. | Spreadsheet | SeaLevel |
| AltUnit | Enum | One of: Meters, Feet, Inches, Miles, Kilometers, AstronomicalUnits, LightYears, Parsecs, MegaParsecs. | Spreadsheet | Meters for altitude and kilometers for depth. |
| Astronomical | Boolean | True if the data is astronomical rather than terrestrial. If this is set to true the declination will be by default the Latitude column, and the right ascension the Longitude column. | All | False |
| BeginRange | DateTime | Date and time of
the first data entry in a time series, in one the formats (month/day/year): "1/1/2010 11:00:00 PM" "1/1/2010 11:30 AM" "1/1/2010 11 am" "1/1/2000" "1/2000" | Spreadsheet | Maximum system value |
| CartesianCustomScale | Double | Used to divide the Cartesian co-ordinate values to a custom scale. If this value was set to "0.01" and the scale to Meters, the custom scale would be "centimeters". | Spreadsheet | 1 |
| CartesianScale | Enum | If the
CoordinatesType is not Spherical then the
co-ordinate system uses X,Y and Z values. One of: Meters, Feet, Inches, Miles, Kilometers, AstronomicalUnits, LightYears, Parsecs, MegaParsecs, Custom. | Spreadsheet | Meters |
| ColorMap | Enum | One of: Same_For_All, Group_by_Values. | Spreadsheet | Same_For_All |
| ColorMapColumn | Int | Column number containing the color map data. Columns are numbered from zero, -1 indicates there is no data for this. | Spreadsheet | -1 |
| ColorValue | String | String containing
ARGB value of the color, in the format: "ARGBColor:255:255:255:255". | All | White |
| CoordinatesType | Enum | One of:
Spherical, Rectangular, Orbital. Spherical applies when the reference frame is a sphere, and the coordinates will be Lat/Lng or RA/Dec. Rectangular applies if there are X,Y and Z coordinates. 0,0,0 in this case is the center of the reference frame. | Spreadsheet | Spherical |
| Decay | Float | Decay rate of the visualization, in days, in the range 0.00025 to 4096. | Spreadsheet | 16 |
| Enabled | Boolean | True if the layer is enabled. | All | True |
| EndDateColumn | Int | Column containing the end date/time data. | Spreadsheet | -1 |
| EndRange | DateTime | Date and time
of the last data entry in a time series, in one the formats (month/day/year): "1/1/2010 11:00:00 PM" "1/1/2010 11:30 AM" "1/1/2010 11 am" "1/1/2000" "1/2000" | Spreadsheet | Minimum system value |
| EndTime | DateTime | Date and time to
end the visualizations, and return to the start time in the case of an auto
loop. This property is visible in the Lifetime dialog for a layer. Format (month/day/year): "1/1/2010 11:00:00 PM" "1/1/2010 11:30 AM" "1/1/2010 11 am" "1/1/2000" "1/2000" | All | Maximum system time. |
| GeometryColumn | Int | Column containing the geometry data. | Spreadsheet | -1 |
| Heading | Double | Heading angle of the model in radians. | 3D Model | 0 |
| HyperlinkColumn | Int | Column containing the hyperlink data. | Spreadsheet | -1 |
| HyperlinkFormat | String | Spreadsheet | "" | |
| FadeSpan | Time | The time it
takes to fade out the graphic. This property is visible in the Lifetime dialog for the layer and is shown in days in the dialog. When using the SDK use the format D.HH:MM:SS, so for one day use 1.00:00:00. | All | 0 |
| FadeType | Enum | One of: In, Out, Both, None. | All | None |
| FlipV | Boolean | True if the textures for the 3D model should be flipped. | 3D Model | False |
| LatColumn | Int | Column number for the Latitude data. | Spreadsheet | -1 |
| LngColumn | Int | Column number for the Longitude data. | Spreadsheet | -1 |
| MarkerColumn | Int | Column number for the marker data. | Spreadsheet | -1 |
| MarkerIndex | Int | Index number of marker graphic selected, or -1 if no marker has been selected. | Spreadsheet | -1 |
| MarkerMix | Enum | One of: Same_For_All, Group_by_Values. | Spreadsheet | Same_For_All |
| MarkerScale | Enum | One of:
Screen, World. If this is set to Screen the graphic will not change in size as the viewer zooms in and out. If it is set to World the graphic (Pushpin or Gaussian) will scale with the view. | Spreadsheet | World |
| Name | String | Name of the layer. | All | "New layer" |
| NameColumn | Int | Column containing the event name data. | Spreadsheet | -1 |
| Opacity | Float | Opacity of the layer graphics from 0.0 to 1.0. | All | 1 |
| Pitch | Double | Pitch angle of the model in radians. | 3d Model | 0 |
| PlotType | Enum | One of: Gaussian, Point, PushPin. | Spreadsheet | Gaussian |
| PointScaleType | Enum | One of: Linear, Power, Log, Constant, StellarMagnitude. | Spreadsheet | Power |
| RaUnits | Enum | When the longitude column
is being used for RA in astronomical data. One of: Hours, Degrees. | Spreadsheet | Hours |
| Roll | Double | Roll angle of the model in radians. | 3D Model | 0 |
| Scale | Vector3d | Scale of the model in x,
y and z dimensions. Format: 1,1,1 | 3D Model | 1,1,1 |
| ScaleFactor | Float | Scale factor to apply to the magnitude of the event. | Spreadsheet | 1 |
| ShowFarSide | Boolean | True if the data points on the invisible side of the body should be shown. | Spreadsheet | False |
| SizeColumn | Int | Column containing the size (magnitude) data. | Spreadsheet | -1 |
| Smooth | Boolean | True if the 3D Model should have its normals smoothed. | 3D Model | True |
| StartDateColumn | Int | Column containing the start date/time data. | Spreadsheet | -1 |
| StartTime | DateTime | Date and time to
start the visualizations. This
property is visible in the Lifetime dialog for the layer. Formats
(month/day/year): "1/1/2010 11:00:00 PM" "1/1/2010 11:30 AM" "1/1/2010 11 am" "1/1/2000" "1/2000" | All | Minimum system time |
| TimeSeries | Boolean | True if the layer should be treated as time series data. | Spreadsheet | False |
| Translate | Vector3d | Translation
(movement offset) of the model in x, y and z dimensions, in units of the
model size. Format: 1,1,1 | 3D Model | 0,0,0 |
| XAxisColumn | Int | Column number for X data. | Spreadsheet | -1 |
| YAxisColumn | Int | Column number for Y data. | Spreadsheet | -1 |
| ZAxisColumn | Int | Column number for Z data. | Spreadsheet | -1 |
| XAxisReverse | Boolean | True if the direction of the X axis is reversed. | Spreadsheet | False |
| YAxisReverse | Boolean | True if the direction of the Y axis is reversed. | Spreadsheet | False |
| ZAxisReverse | Boolean | True if the direction of the Z axis is reversed. | Spreadsheet | False |
If the call is successful the response will contain the following string:
<Status>Success</Status><Layer propertyName="propertyValue"</Layer></LayerApi>
Where propertyName is the property name requested, and propertyValue is the value returned. For example:
Get properties |
|
<LayerApi><Status>Success</Status><Layer AltType="Depth"</Layer></LayerApi> <LayerApi><Status>Success</Status><Layer AltColumn="3"</Layer></LayerApi> <LayerApi><Status>Success</Status><Layer Astronomical="False"</Layer></LayerApi> <LayerApi><Status>Success</Status><Layer BeginRange="1/9/2009 11:44:38 AM"</Layer></LayerApi> <LayerApi><Status>Success</Status><Layer EndRange="9/9/2009 11:13:52 PM"</Layer></LayerApi> <LayerApi><Status>Success</Status><Layer Decay="16"</Layer></LayerApi> <LayerApi><Status>Success</Status><Layer Name="EarthQuakes2009"</Layer></LayerApi> <LayerApi><Status>Success</Status><Layer FadeSpan="00:00:00"</Layer></LayerApi> <LayerApi><Status>Success</Status><Layer MarkerIndex="-1"</Layer></LayerApi> |
If the call is not successful the following string may be included in the response, or other errors may be returned:
<Status>Error - Invalid parameter</Status>
Get altitude units |
|
WebClient client = new WebClient(); string url = string.Format("http://{0}:5050/layerApi.aspx?cmd=getprop&id={1}&propname={2}", getIP().ToString(), layerId, "AltUnit"); string response = client.UploadString(url, ""); |
response |
| <?xml version="1.0" encoding="utf-8"?><LayerApi><Status>Success</Status><Layer AltUnit="Kilometers"</Layer></LayerApi> |
The getprops command is used to retrieve all the properties for a specified layer.
Refer to the table of properties listed for the getprop command.
Required Parameters | Description |
| &id | Specifies the id number of the layer. |
If the call is successful the response string will contain the following string:
<Status>Success</Status>
If the call is not successful the following string may be included in the response, or other errors may be returned:
<Status>Error - Invalid layer ID</Status>
The following example gets all the properties from any of the different types of layer. Note that the response string does not include newlines, these have been added for readability.
get all properties |
|
private void buttonGetProperties() { try { WebClient client = new WebClient(); string url = string.Format("http://{0}:5050/layerApi.aspx?cmd=getprops&id={1}", getIP().ToString(), layerId); string response = client.UploadString(url, ""); XmlDocument doc = new XmlDocument(); doc.LoadXml(response); XmlNode node = doc["LayerApi"]; if (node.InnerText.Contains("Success")) { XmlNode node2 = node["Layer"]; if (node2 != null) { string propName; string propValue; for (int i = 0; i < node2.Attributes.Count; i++) { propName = node2.Attributes[i].Name; propValue = node2.Attributes[i].Value; // Do something with the name/value pair } } else { // No properties returned } } else { throw new Exception(response); } } catch (Exception ex) { // Handle exception } } |
Spreadsheet |
|
<?xml version='1.0' encoding='UTF-8'?> <LayerApi> <Status>Success</Status> <Layer Class=\"SpreadSheetLayer\" TimeSeries=\"True\" BeginRange=\"1/9/2009 11:44:38 AM\" EndRange=\"9/9/2009 11:13:52 PM\" Decay=\"16\" CoordinatesType=\"Spherical\" LatColumn=\"1\" LngColumn=\"2\" GeometryColumn=\"-1\" XAxisColumn=\"-1\" YAxisColumn=\"-1\" ZAxisColumn=\"-1\" XAxisReverse=\"False\" YAxisReverse=\"False\" ZAxisReverse=\"False\" AltType=\"Depth\" RaUnits=\"Hours\" MarkerMix=\"Same_For_All\" MarkerColumn=\"-1\" ColorMapColumn=\"-1\" PlotType=\"Gaussian\" MarkerIndex=\"-1\" ShowFarSide=\"False\" MarkerScale=\"World\" AltUnit=\"Kilometers\" CartesianScale=\"Meters\" CartesianCustomScale=\"1\" AltColumn=\"3\" StartDateColumn=\"0\" EndDateColumn=\"-1\" SizeColumn=\"4\" NameColumn=\"0\" HyperlinkFormat=\"\" HyperlinkColumn=\"-1\" ScaleFactor=\"1\" PointScaleType=\"Power\" Opacity=\"1\" StartTime=\"1/1/0001 12:00:00 AM\" EndTime=\"12/31/9999 11:59:59 PM\" FadeSpan=\"00:00:00\" FadeType=\"None\" Name=\"EarthQuakes2009\" ColorValue=\"ARGBColor:255:255:0:0\" Enabled=\"True\" Astronomical=\"False\" /> </LayerApi> |
3D Model |
|
<?xml version='1.0' encoding='UTF-8'?> <LayerApi> <Status>Success</Status> <Layer Class=\"Object3dLayer\" FlipV=\"False\" Smooth=\"True\" Heading=\"0\" Pitch=\"0\" Roll=\"0\" Scale=\"1, 1, 1\" Translate=\"0, 0, 0\" Opacity=\"1\" StartTime=\"1/1/0001 12:00:00 AM\" EndTime=\"12/31/9999 11:59:59 PM\" FadeSpan=\"00:00:00\" FadeType=\"None\" Name=\"aurora\" ColorValue=\"ARGBColor:255:255:0:0\" Enabled=\"True\" Astronomical=\"False\" /> </LayerApi> |
Shapefile |
|
<?xml version='1.0' encoding='UTF-8'?> <LayerApi> <Status>Success</Status> <Layer Class=\"ShapeFileRenderer\" Opacity=\"1\" StartTime=\"1/1/0001 12:00:00 AM\" EndTime=\"12/31/9999 11:59:59 PM\" FadeSpan=\"00:00:00\" FadeType=\"None\" Name=\"state_bounds\" ColorValue=\"ARGBColor:255:255:0:0\" Enabled=\"True\" Astronomical=\"False\" /> </LayerApi> |
ImageSet |
|
<?xml version='1.0' encoding='UTF-8'?> <LayerApi> <Status>Success</Status> <Layer Class=\"ImageSetLayer\" Opacity=\"1\" StartTime=\"1/1/0001 12:00:00 AM\" EndTime=\"12/31/9999 11:59:59 PM\" FadeSpan=\"00:00:00\" FadeType=\"None\" Name=\"Bathymetry\" ColorValue=\"ARGBColor:255:255:0:0\" Enabled=\"True\" Astronomical=\"False\" /> </LayerApi> |
The group command specifies that a layer group should be added.
Layer groups are just an organizational aid when using the layer manager. The user will be able to collapse and expand groups in the Layer Manager, and have groups that are sub-sets of other groups.
Required Parameter | Description |
| &name | A unique name for the layer group. |
| &frame | The reference frame of the group. This
can be a layer group created with the group command, or one of: Earth, Moon, Mercury, Venus, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto, Io, Ganymede, Callisto, Europa, Sun, ISS. |
The following string will be included in the response if the call is successful:
<Status>Success</Status>
If the call is not successful the following string may be included in the response, or other errors may be returned:
<Status>Error - Invalid layer ID</Status>
|
private void createLayerGroup(string frame, string name) { try { WebClient client = new WebClient(); string url = string.Format("http://{0}:5050/layerApi.aspx?cmd=group&frame={1}&name={2}", getIP().ToString(), frame, name); string response = client.UploadString(url, ""); XmlDocument doc = new XmlDocument(); doc.LoadXml(response); XmlNode node = doc["LayerApi"]; string s = node.InnerText; // // Handle an error situation // if (s.Contains("Error")) { throw new Exception(s); } } catch (Exception ex) { } } |
The layerlist command returns the structure of the layers and layer group names (in an XML document format) that are currently in the layer manager.
Optional Parameter | Description |
Default |
| &layersonly | True indicates that only layers, and not reference frames or group names, should be returned. | False |
If the call is successful a string will be returned that is an XML document. Refer to the Example Code for the format and contents of the document.
If the call is not successful the following string may be included in the response, or other errors may be returned:
<Status>Error - Invalid layer ID</Status>
The following code will result in the response given below, though note that one layer (EarthQuakes2009) and one group (New Mercury Group) have been added to the layer manager prior to the layerlist call.
layerlist |
|
// // Recursive scanning of child nodes // private void scanNode(XmlNode node) { int i,n; // // First loop through the attributes of the node // for (i = 0; i < node.Attributes.Count; i++) { // Do something with the node.Attributes[i].Name and node.Attributes[i].Value } // // Next recurse the node tree // for (n = 0; n < node.ChildNodes.Count; n++) { scanNode(node.ChildNodes[n]) } } // // Get the current list of Reference Frames, groups and layers // private void getLayerlist(string layersonly) { try { WebClient client = new WebClient(); string url = string.Format("http://{0}:5050/layerApi.aspx?cmd=layerlist&layersonly={1}", getIP().ToString(), layersonly); string response = client.UploadString(url, ""); XmlDocument doc = new XmlDocument(); doc.LoadXml(response); XmlNode node = doc["LayerApi"]; if (node.InnerText.Contains("Success")) { XmlNode node2 = node["LayerList"]; if (node2 != null) { // Top level items returned = node2.ChildNodes.Count scanNode(node2); } else { // No items returned } } else { throw new Exception(response); } } catch (Exception ex) { // Handle exception } } |
response (layersonly = "false") |
|
<?xml version='1.0' encoding='UTF-8'?> <LayerApi> <Status>Success</Status> <LayerList> <ReferenceFrame Name=\"Sun\" Enabled=\"True\"> <ReferenceFrame Name=\"Mercury\" Enabled=\"True\"> <LayerGroup Name=\"New Mercury Group\" Enabled=\"True\" /> </ReferenceFrame> <ReferenceFrame Name=\"Venus\" Enabled=\"True\" /> <ReferenceFrame Name=\"Earth\" Enabled=\"True\"> <Layer Name=\"EarthQuakes2009\" ID=\"712cdef2-907f-4fc5-ae2c-c57488be4517\" Type="SpreadSheetLayer" Enabled=\"True\" /> <ReferenceFrame Name=\"Moon\" Enabled=\"True\" /> <ReferenceFrame Name=\"ISS\" Enabled=\"True\" /> </ReferenceFrame> <ReferenceFrame Name=\"Mars\" Enabled=\"True\" /> <ReferenceFrame Name=\"Jupiter\" Enabled=\"True\"> <ReferenceFrame Name=\"Io\" Enabled=\"True\" /> <ReferenceFrame Name=\"Europa\" Enabled=\"True\" /> <ReferenceFrame Name=\"Ganymede\" Enabled=\"True\" /> <ReferenceFrame Name=\"Callisto\" Enabled=\"True\" /> </ReferenceFrame> <ReferenceFrame Name=\"Saturn\" Enabled=\"True\" /> <ReferenceFrame Name=\"Uranus\" Enabled=\"True\" /> <ReferenceFrame Name=\"Neptune\" Enabled=\"True\" /> <ReferenceFrame Name=\"Pluto\" Enabled=\"True\" /> </ReferenceFrame> </LayerList> </LayerApi> |
response (layersonly = "true") |
|
<?xml version='1.0' encoding='UTF-8'?> <LayerApi> <Status>Success</Status> <LayerList> <Layer Name=\"EarthQuakes2009\" ID=\"712cdef2-907f-4fc5-ae2c-c57488be4517\" Type="SpreadSheetLayer" Enabled=\"True\" /> </LayerList> </LayerApi> |
The load command specifies a data file, and and some optional parameters, to apply to a new layer.
Files that can be loaded using this commend include spreadsheet data (comma or tab delimited), shape files (.shp), 3D model files (.3ds), and WTML files containing ImageSet references. In the latter case the first image set found in the file will be loaded. Refer to the WorldWide Telescope Data Files Reference for more details on WTML files.
If a spreadsheet of data is loaded, the load command will initiate an import wizard of WorldWide Telescope, in order to select the appropriate columns, timing data, and so on. An import wizard is not automatically invoked by the other data file types.
Note that parameter names are case-sensitive.
Required Parameter | Description | |
| &frame | The reference frame of the group.
This can be an existing layer group name, or one of: Earth, Moon, Mercury, Venus, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto, Io, Ganymede, Callisto, Europa, Sun, ISS. | |
| &filename | The full path of the file to load. | |
Optional Parameter |
Default | |
| &name | A friendly name for the layer. | "New Layer" |
| &color | ARBG hex value of the color to be used when rendering the events of the layer. | FFFFFFFF (white) |
| &startdate | With time series data, the date and
time to start the visualization for this layer. This could for example be slightly earlier
than the date of the first event in the actual data. For example:
"1/1/2000 12:30:30 AM". Formats (month/day/year): "1/1/2010 11:00:00 PM" "1/1/2010 11:30 AM" "1/1/2010 11 am" "1/1/2000" "1/2000" | The System minimum date value |
| &enddate | With time series data, the date and time to end the visualization for this layer. | The System maximum date value |
| &fadetype | Fades the data visualization. One of: In, Out, Both or None. | None |
| &faderange | Fade time in days. | Zero |
The following string will be included in the response string:
<LayerApi><NewLayerID>nnnn</NewLayerID></LayerApi>
Where nnnn is the layer id, which will be a GUID in string format.
If the call is not successful the following string may be included in the response, or other errors may be returned:
<Status>Error - Could not Load Layer</Status>
Note that the example code uses datetime, one of the general parameters, to initiate the visualization of the data immediately.
|
private void loadDatafile(string name, string frame, string filename, string datetime) { try { WebClient client = new WebClient(); string url = string.Format("http://{0}:5050/layerApi.aspx?cmd=load&frame={1}&filename={2}&name={3}&datetime={4}", getIP().ToString(), frame, filename, name, datetime); string response = client.UploadString(url, ""); XmlDocument doc = new XmlDocument(); doc.LoadXml(response); XmlNode node = doc["LayerApi"]; XmlNode child = node.ChildNodes[0]; layerId = child.InnerText; string s = node.InnerText; // // Handle an error situation // if (s.Contains("Error")) { throw new Exception(s); } } catch (Exception ex) { } } |
The mode command changes the view to one of Earth, Planet, Sky, Panorama, SolarSystem.
This command does not take any parameters.
The following string will be included in the response if the call is successful:
<Status>Success</Status>
Change mode |
|
WebClient client = new WebClient(); string url = string.Format("http://{0}:5050/layerApi.aspx?cmd=mode&lookat={1}", getIP().ToString(), "SolarSystem"); string response = client.UploadString(url, ""); |
The move command changes the view depending on the supplied parameter.
One move parameter must be supplied, &move=nnnn, where nnnn is one of the following:
Required Parameter | Description |
| ZoomIn | Zoom in on the current view. |
| ZoomOut | Zoom out of the current view. |
| Up | Move the current view up. |
| Down | Move the current view down. |
| Left | Move the current view left. |
| Right | Move the current view right. |
| Clockwise | Rotate the view clockwise 0.2 of one radian. |
| CounterClockwise | Rotate the view counterclockwise 0.2 of one radian. |
| TiltUp | Angle the view up 0.2 of one radian. |
| TiltDown | Angle the view down 0.2 of one radian. |
| Finder | Currently unimplemented. |
The following string will be included in the response if the call is successful:
<Status>Success</Status>
The following code will be included in the response if the move parameter is invalid:
<Status>Error - Invalid parameter</Status>
|
WebClient client = new WebClient(); string url = string.Format("http://{0}:5050/layerApi.aspx?cmd=move&move={1}", getIP().ToString(), "ZoomIn"); string response = client.UploadString(url, ""); |
The new command specifies that a new layer should be created.
The new command will request that an entirely new layer be created, with the following parameters (note that the parameter names are case-sensitive):
Required
|
Description | |
| &frame | The reference frame of the layer. This
can be one of: Earth, Moon, Mercury, Venus, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto, Io, Ganymede, Callisto, Europa, Sun, ISS. | |
Optional Parameters |
Default | |
| &name | A friendly name for the layer. | "New Layer" |
| &color | ARBG hex value of the color to be used when rendering the events of the layer. | FFFFFFFF (white) |
| &startdate | With time series data, the date
and time to start the visualization for this layer. This could for example be slightly
earlier than the date of the first event in the actual data. For
example:
"1/1/2000 12:30:30 AM". Formats (month/day/year): "1/1/2010 11:00:00 PM" "1/1/2010 11:30 AM" "1/1/2010 11 am" "1/1/2000" "1/2000" | The System minimum date value |
| &enddate | With time series data, the date and time to end the visualization for this layer. | The System maximum date value |
| &fadetype | Fades the data visualization. One of: In, Out, Both or None. | None |
| &faderange | Fade time in days. | Zero |
The new command is embedded in a formatted string (see the Example Code). This formatted string forms the first of two parameters to the WebClient UploadString method.
The second string parameter to UploadString should contain a comma or tab delimited string containing the heading names of the columns in the layer. The supported column names are listed in the following table. The names of the columns in the data file must contain the names listed here (so "Latitude" is acceptable for "Lat", or "dMag" acceptable for "Mag", for example).
| Column Heading | Description |
| Time | UTC time, for example: "1/1/2000 12:02:46 AM" |
| Lat | Latitude in decimal degrees. |
| Lon | Longitude in decimal degrees. |
| RA | Right ascension in decimal degrees. |
| Dec | Declination in decimal degrees. |
| Depth | Depth in kilometers. |
| Altitude | Altitude in meters. |
| Mag | Magnitude as a floating point number. |
| X | X co-ordinate, if a Rectangular co-ordinate system is being used. |
| Y | Y co-ordinate. |
| Z | Z co-ordinate. |
The following string will be included in the response string:
<LayerApi><NewLayerID>nnnn</NewLayerID></LayerApi>
Where nnnn is the layer id number, which will be a GUID in string format. If a GUID is not received, then the call was not successful.
Note that the example code uses datetime, one of the general parameters, to initiate the visualization of the data immediately.
|
// // Send a NEW command, extracting info from the data file and the UI // WebClient client = new WebClient(); string datetime = "1/1/2009 12:00:00 AM"; string name = "Earthquakes 2009"; string rate = "10000"; string frame = "Earth"; string color = "FFFF0000"; string url = string.Format("http://{0}:5050/layerApi.aspx?cmd=new&datetime={1}&timerate={2}&name={3}&frame={4}&color={5}", getIP().ToString(), datetime, rate, name, frame, color); // field string below is delimited by tabs, not spaces string response = client.UploadString(url, "TIME LAT LON DEPTH MAG"); XmlDocument doc = new XmlDocument(); doc.LoadXml(response); XmlNode node = doc["LayerApi"]; XmlNode child = node.ChildNodes[0]; layerId = child.InnerText; // // Handle an error situation // if (layerId.Length != 36) throw new Exception("Invalid Layer Id received"); // |
For an example of the use of this command in the sample application, see initWWTLayer.
The setprop command is used to specify a value for a single layer property.
Required Parameters | Description |
| &id | Specifies the id number of the layer. |
| &propname | Property name. Refer to the table of properties listed for the getprop command. |
| &propvalue | Property value in string form. |
If the call is successful, then the response will contain the string:
<Status>Success</Status>
If the call is not successful the following string may be included in the response, or other errors may be returned:
<Status>Error - Invalid parameter</Status>
Set Opacity property |
|
WebClient client = new WebClient(); string url = string.Format("http://{0}:5050/layerApi.aspx?cmd=setprop&id={1}&propname={2}&propvalue={3}", getIP().ToString(), layerId,"Opacity", "0.5"); string response = client.UploadString(url, ""); |
The setprops command is used to specify multiple properties for a layer.
Required Parameters | Description |
| &id | Specifies the id number of the layer. |
Note that the second string parameter to the UploadString method contains the xml encoding of the properties. The string should be a correctly formatted XML file, with xml, LayerApi and Layer entries. Each attribute to the Layer entry should be a property name/property value pair.
This method can be used to set a single property, though the setprop command is specifically designed for this.
Refer to the table of properties listed for the getprop command.
If the call is successful, then the response will contain the string:
<Status>Success</Status>
If the call is not successful the following string may be included in the response, or other errors may be returned:
<Status>Error - Invalid parameter</Status>
Set BeginRange and Decay properties |
|
string propertyXML = "<?xml version='1.0' encoding='UTF-8'?><LayerApi><Layer BeginRange=\"1/9/2008 11:44:38 AM\" Decay=\"5.5\" /> </LayerApi>"; WebClient client = new WebClient(); string url = string.Format("http://{0}:5050/layerApi.aspx?cmd=setprops&id={1}", getIP().ToString(), layerId); string response = client.UploadString(url, propertyXML); |
The state command requests some details of the current view.
This command does not take any parameters. The details returned vary slightly depending on the view mode, and include the current view mode, latitude (or declination) in decimal degrees, longitude (or right ascension) in decimal degrees, zoom factor (0 to 360), angle in radians, rotation in radians, current UTC time, time rate, reference frame, a view token, and zoom text.
If the call is successful the following string will be returned:
<LayerApi><Status>Success</Status><ViewState> state information </ViewState></LayerApi>
Get state |
|
private void getState() { try { WebClient client = new WebClient(); string url = string.Format("http://{0}:5050/layerApi.aspx?cmd=state", getIP().ToString()); string response = client.UploadString(url, ""); XmlDocument doc = new XmlDocument(); doc.LoadXml(response); XmlNode node = doc["LayerApi"]; if (node.InnerText.Contains("Success")) { XmlNode node2 = node["ViewState"]; if (node2 != null) { string propName; string propValue; for (int i = 0; i < node2.Attributes.Count; i++) { propName = node2.Attributes[i].Name; propValue = node2.Attributes[i].Value; // Do something with the name value pair } } else { // Success message was a false positive, no state was returned } } else { throw new Exception(response); } } catch (Exception ex) { // Handle the exception } } |
State information for each of the five modes: |
|
<ViewState lookat=\"Earth\" lat=\"86.1800140779305\" lng=\"4.56191579793961\" zoom=\"30.9237645312\" angle=\"-1.52\" rotation=\"0\" time=\"2/23/2011 7:03:31 PM\" timerate=\"1\" ReferenceFrame=\"Earth\" ViewToken=\"SD8834DFA\" zoomText=\"5085 km\"> </ViewState> <ViewState lookat=\"Planet\" lat=\"86.1800140779305\" lng=\"4.58610934632668\" zoom=\"360\" angle=\"-1.52\" rotation=\"0\" time=\"2/23/2011 7:04:19 PM\" timerate=\"1\" ReferenceFrame=\"Mars\" ViewToken=\"SD8834DFA\" zoomText=\"59200 km\"> </ViewState> <ViewState lookat=\"Sky\" ra=\"10.2626615902966\" dec=\"46.1799337621283\" zoom=\"30.9237645312\" rotation=\"0\" time=\"2/23/2011 7:04:51 PM\" timerate=\"1\" ReferenceFrame=\"Space\" ViewToken=\"SD8834DFA\" zoomText=\"05:09:14\"> </ViewState> <ViewState lookat=\"Panorama\" lat=\"-3.07957843596986\" lng=\"-39.9196238171819\" zoom=\"117.9648\" angle=\"-1.52\" rotation=\"0\" time=\"2/23/2011 7:05:35 PM\" timerate=\"1\" ReferenceFrame=\"Panorama\" ViewToken=\"SD8834DFA\" zoomText=\"19:39:39\"> </ViewState> <ViewState lookat=\"SolarSystem\" lat=\"2.25294244185011\" lng=\"262.382989924732\" zoom=\"0.000578857064151695\" angle=\"-1.52\" rotation=\"0\" time=\"2/23/2011 7:06:13 PM\" timerate=\"1\" ReferenceFrame=\"Sun\" ViewToken=\"SD8834DFA\" zoomText=\"38636 km\"> </ViewState> |
The uisettings command is used to change user interface settings, without altering the layer data. Note that the spelling errors in the names of the properties must be matched.
Setting Name |
Setting Type |
| AutoHideContext | True or False |
| AutoHideTabs | True or False |
| AutoRepeatTour | True or False |
| AutoRepeatTourAll | True or False |
| ConstellationBoundryColor | RGB color (default, "MidnightBlue") |
| ConstellationFigureColor | RGB color (default, "DarkRed") |
| ConstellationFiguresFile | String (a filename) |
| ConstellationSelectionColor | RGB color (default, "DarkGoldenrod") |
| ContextSearchFilter | String (default "Unfiltered") |
| DomeTilt | Double (default "0") |
| DomeTypeIndex | Integer (default, "0") |
| DomeView | True or False |
| EclipticColor | RGB color (default, "CornflowerBlue ") |
| FollowMouseOnZoom | True or False |
| FovCamera | Integer (default, "0") |
| FovColor | RGB color (default, "white") |
| FovEyepiece | Integer (default, "0") |
| FovTelescope | Integer (default, "0") |
| FullScreenTours | True or False |
| GridColor | RGB color (default, "64, 64, 64") |
| ImageQuality | Integer: 0 to 100 (default, 100) |
| LargeDomeTextures | True or False |
| LastLookAtMode | Integer (default, "2") |
| LineSmoothing | True or False |
| ListenMode | True or False |
| LocalHorizonMode | True or False |
| LocationAltitude | Double (default, "100") |
| LocationLat | Double (default, "47.64222") |
| LocationLng | Double (default, "-122.142") |
| LocationName | String (default, "Microsoft Research Building 99") |
| MasterController | True or False |
| ShowClouds | True or False |
| ShowConstellationBoundries | True or False |
| ShowConstellationFigures | True or False |
| ShowConstellationNames | True or False |
| ShowConstellationSelection | True or False |
| ShowCrosshairs | True or False |
| ShowDatasetNames | True or False |
| ShowEarthSky | True or False |
| ShowEcliptic | True or False |
| ShowElevationModel | True or False |
| ShowFieldOfView | True or False |
| ShowGrid | True or False |
| ShowSolarSystem | True or False |
| ShowTouchControls | True or False |
| ShowUTCTime | True or False |
| SolarSystemCosmos | True or False |
| SolarSystemLighting | True or False |
| SolarSystemMilkyWay | True or False |
| SolarSystemMinorOrbits | True or False |
| SolarSystemMinorPlanets | True or False |
| SolarSystemMultiRes | True or False |
| SolarSystemOrbitColor | RGB color (default, "64, 64, 64") |
| SolarSystemOrbits | True or False |
| SolarSystemOverlays | True or False |
| SolarSystemPlanets | True or False |
| SolarSystemScale | True or False |
| SolarSystemStars | True or False |
| StartUpLookAt | Integer (default, "4") |
This command does not perform any action other than that of changing of the user interface settings.
If the call is successful, then the response will contain the string:
<Status>Success</Status>
Fly to a location |
|
// // Sets the property "ShowConstellationFigures" to true. WebClient client = new WebClient(); string url = string.Format("http://{0}:5050/layerApi.aspx?cmd=uisettings&ShowConstellationFigures=True", getIP().ToString()); string response = client.UploadString(url, ""); |
The update command specifies that the data attached to this command should be added to the layer.
The update command will request that data for a layer be updated, with the following parameters (note that the parameter names are case-sensitive):
Required Parameter | Description |
|
| &id | Specifies the id number of the layer. | |
Optional Parameters |
Description |
Default |
| &hasheader | Set to true if the data has a header row. The header should be the first row of the data. | False |
| &name | A friendly name to rename the layer. | No change |
| &nopurge | The sending of an update command will delete events that occur before the start time of any events in the update and that have already decayed. Set this flag to true if the event data should not be deleted. | False |
| &purgeall | Purge (delete) all events. | False |
| &show | Set to true to show the layer, false to hide it. True and false are not case-sensitive. | True |
The second string parameter to UploadString should contain a comma or tab delimited string containing the data in a form that matches the heading names of the columns in the layer provided in the new command.
The following string will be included in the response if the call is successful:
<Status>Success</Status>
If the call is not successful the following string may be included in the response, or other errors may be returned:
<Status>Error - Invalid layer ID</Status>
|
// // Send an UPDATE command // WebClient client = new WebClient(); string url = string.Format("http://{0}:5050/layerApi.aspx?cmd=update&id={1}", getIP().ToString(), layerId); string response = client.UploadString(url, lineBuffer); XmlDocument doc = new XmlDocument(); doc.LoadXml(response); XmlNode node = doc["LayerApi"]; string s = node.InnerText; // // Handle an error situation // if (s.Contains("Error")) { throw new Exception(s); } // // Send an UPDATE command with a flyTo parameter // string lat, lon, zoom, rotation, angle; WebClient client = new WebClient(); string url = string.Format("http://{0}:5050/layerApi.aspx?cmd=update&id={1}&flyTo={2},{3},{4},{5},{6}&instant=True", getIP().ToString(), layerId, lat, lon, zoom, rotation, angle); string response = client.UploadString(url, lineBuffer); XmlDocument doc = new XmlDocument(); doc.LoadXml(response); XmlNode node = doc["LayerApi"]; string s = node.InnerText; // // Handle an error situation // if (s.Contains("Error")) { throw new Exception(s); } |
For an example of the use of this command in the sample application, see flushBufferToWWT.
The version command returns the version number of the running version of the LCAPI.
The version number should be used in an application to ensure that the LCAPI features used are supported by the version of the LCAPI running on the client computer.
The following string will be included in the response if the call is successful (the version number will be more recent than the one shown below) :
<LayerApi><Version><IP_ADDRESS></Version></LayerApi>
There are no specific errors returned if the call is not successful.
Refer to the getIP utility to see how to extract and check a version number.
The general parameters can be used with any of the commands.
Parameter |
Description |
| &datetime | Sets the viewing clock to the
given date and time, in UTC format, for example:
"1/1/2000 12:02:46 AM". This is
the date and time that can be set through the View
menu. Formats (month/day/year): "1/1/2010 11:00:00 PM" "1/1/2010 11:30 AM" "1/1/2010 11 am" "1/1/2000" "1/2000" |
| &timerate | The accelerated time to render the visualization, as a multiple of 10. |
| &flyto | Sets the position of the view
camera. Requires five floating point numbers separated by commas: latitude,
longitude, zoom level, rotation and angle.
Optionally there can be a sixth parameter containing the frame to change
the view to, which can be one of: |
| &instant | Used with the &flyto parameter, set this to true to specify that the camera should jump to the location, or false that the camera should smoothly pan and zoom to the location. |
| &autoloop | True sets the layer manager to auto loop. |
Fly to a location |
|
// // Extract the values from the text boxes of a dialog, assuming there are rich text boxes with the names shown below. // string flyString = richLat.Text + "," + richLong.Text + "," + richZoom.Text + "," + richRotation.Text + "," + richAngle.Text; WebClient client = new WebClient(); string url = string.Format("http://{0}:5050/layerApi.aspx?cmd=state&flyto={1}&instant={2}", getIP().ToString(), flyString, richInstant.Text); string response = client.UploadString(url, ""); |
The following utilities are not part of the API, but should be useful in building an application.
If the LCAPI application and WorldWide Telescope are running on the same computer, you can use the following utility to extract the IP address.
The getIP function extracts each IP address in turn, then calls the CheckForWWTWebServer function to check that WorldWide Telescope is both running at the given address and is recent enough that the LCAPI is supported.
Get IP address |
|
private IPAddress getIP() { IPAddress ipAddress = IPAddress.Loopback; // Find IPV4 Address foreach (IPAddress ipAdd in Dns.GetHostEntry(Dns.GetHostName()).AddressList) { if (ipAdd.AddressFamily == AddressFamily.InterNetwork) { if (CheckForWWTWebServer(ipAdd)) { ipAddress = ipAdd; break; } } } return ipAddress; } private bool CheckForWWTWebServer(IPAddress address) { WebClient client = new WebClient(); try { string version = client.DownloadString(string.Format("http://{0}:5050/layerapi.aspx?cmd=version", address.ToString())); XmlDocument doc = new XmlDocument(); doc.LoadXml(version); XmlNode node = doc["LayerApi"]; if (node.OuterXml.Contains("Version")) { // As version numbers are in the format xx.xx.xx.xx, an individual comparison of each // number is necessary - a simple string comparison will give unreliable results string[] versionNumbers = node.InnerText.Split('.'); if (versionNumbers[0].CompareTo("2") >= 0 && versionNumbers[1].CompareTo("8") >= 0) return true; } } catch (Exception ex) { // handle exception } return false; } |
With time series data care should be taken with the timings given in the data file. To convert local times to the recommended UTC time the following function could be used. Note that the local time is taken from the computer System time in the example below, so you may need to add some functionality to support local times that are not the same as your computer System time.
|
// // Convert a string time to the correct format // private string getUTCtime(string time) { DateTime d = DateTime.Parse(time); string s = d.ToUniversalTime().ToString(); return s; } |
The following sample application loads earthquake data from a CSV file, sends it in buffers of up to 100 events, and displays it as a time series in WorldWide Telescope.
Sample program |
|
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; // // Added References // using System.IO; using System.Net; using System.Net.Sockets; using System.Xml; // // Quakes is a sample of the WorldWide Telescope LCAPI // namespace Quakes { public partial class Quakes : Form { public Quakes() { InitializeComponent(); // // Set defaults // listBox1.SelectedItem = "1000000"; listBox2.SelectedItem = "Earth"; } private void buttonExit_Click(object sender, EventArgs e) { Dispose(true); } private void buttonBrowse_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { richFilename.Text = openFileDialog1.FileName; } } // // Add messages to the list box // private void addMessage(string m) { int i = richMessages.Items.Add(m); richMessages.SelectedIndex = i; } // // Go! // private void buttonGo_Click(object sender, EventArgs e) { string line; string w; richMessages.Items.Clear(); try { initWWTLayer(); StreamReader sr = new StreamReader(richFilename.Text); // // Ignore first line of data (the headings) // w = sr.ReadLine(); // // Read lines of data until there are none left // while ((w = sr.ReadLine()) != null) { line = parseLine(w,false); flushBufferToWWT(line); } sr.Close(); // // Flush buffer for last time - empty string indicates this is the last flush // flushBufferToWWT(""); // // Record the end // addMessage("Data transmission ended: " + totalEvents + " events"); } catch (Exception ex) { addMessage(ex.Message); } } // // Change the event color // private void buttonColor_Click(object sender, EventArgs e) { if (colorDialog.ShowDialog() == DialogResult.OK) { buttonColor.BackColor = colorDialog.Color; } } int timeSlot; // Data column number for time int latSlot; // Data column number for latitude int lonSlot; // Data column number for longitude int depSlot; // Data column number for depth int magSlot; // Data column number for magnitude string layerId; // string GUID for the WWT Layer string lineBuffer; // Buffer to hold events until they are sent int lineCountInBuffer; // Number of events in the buffer int totalEvents; // Count of total events transmitted DateTime lastTimeBufferFlushed; // Time of last transmission, used to check for time-out // // Locate the columns of the required data, they must be present but can be in any // order in the data file // private string initCSVData(string filename) { string w; // line of data from data file timeSlot = -1; latSlot = -1; lonSlot = -1; depSlot = -1; magSlot = -1; // // First line (line 0) of the data file must contain the column headings // StreamReader sr = new StreamReader(filename); w = sr.ReadLine(); string[] words = w.Split(new char[] { ',' }); for (int i = 0; i < words.Length; i++) { if (words[i].IndexOf("Time", StringComparison.OrdinalIgnoreCase) != -1) timeSlot = i; else if (words[i].IndexOf("Lat", StringComparison.OrdinalIgnoreCase) != -1) latSlot = i; else if (words[i].IndexOf("Lon", StringComparison.OrdinalIgnoreCase) != -1) lonSlot = i; else if (words[i].IndexOf("Depth", StringComparison.OrdinalIgnoreCase) != -1) depSlot = i; else if (words[i].IndexOf("Mag", StringComparison.OrdinalIgnoreCase) != -1) magSlot = i; } // // One of more heading is missing.... // if (timeSlot == -1 || latSlot == -1 || lonSlot == -1 || depSlot == -1 || magSlot == -1) throw new Exception("Source file does not contain one or more of: time, lat, lon, depth, mag"); // // Record a successful reading of the headings // addMessage("Time = " + timeSlot.ToString() + " Lat = " + latSlot.ToString() + " Lon = " + lonSlot.ToString() + " Depth = " + depSlot.ToString() + " Mag = " + magSlot.ToString()); // // Extract the start time from the data file by reading line 1 // w = sr.ReadLine(); string startDate = parseLine(w, true); sr.Close(); // // Record a successful reading of the start // addMessage("Start time = " + startDate); return startDate; } // // Convert a string time to the correct format // private string getUTCtime(string time) { DateTime d = DateTime.Parse(time); string s = d.ToUniversalTime().ToString(); return s; } // // Parses a line from the data file // private string parseLine(string w, bool timeOnly) { string[] words = w.Split(new char[] { ',' }); string line = ""; string time = getUTCtime(words[timeSlot]); string lat = words[latSlot]; string lon = words[lonSlot]; string depth = words[depSlot]; string mag = words[magSlot]; if (timeOnly) { return time; } line = time + "\t" + lat + "\t" + lon + "\t" + depth + "\t" + mag + "\t"; return line; } // // Create a new WWT layer // private void initWWTLayer() { // // Send a NEW command, extracting info from the data file and the UI // WebClient client = new WebClient(); string startDate = initCSVData(richFilename.Text); string name = Path.GetFileNameWithoutExtension(richFilename.Text); string rate = listBox1.SelectedItem.ToString(); string frame = listBox2.SelectedItem.ToString(); string color = buttonColor.BackColor.ToArgb().ToString("X8"); string url = string.Format("http://{0}:5050/layerApi.aspx?cmd=new&datetime={1}&timerate={2}&name={3}&frame={4}&color={5}", getIP().ToString(), startDate, rate, name, frame, color); // field string below is delimited by tabs, not spaces string response = client.UploadString(url, "TIME LAT LON DEPTH MAG"); XmlDocument doc = new XmlDocument(); doc.LoadXml(response); XmlNode node = doc["LayerApi"]; XmlNode child = node.ChildNodes[0]; layerId = child.InnerText; // // Handle an error situation // if (layerId.Length != 36) throw new Exception("Invalid Layer Id received"); // // Record a successful creation of a new layer // addMessage("New layer Id = " + layerId); // // Clear the buffer // lineBuffer = string.Empty; lineCountInBuffer = 0; totalEvents = 0; lastTimeBufferFlushed = DateTime.Now; } // // Utility to extract IP address // private IPAddress getIP() { IPAddress ipAddress = IPAddress.Loopback; // Find IPV4 Address foreach (IPAddress ipAdd in Dns.GetHostEntry(Dns.GetHostName()).AddressList) { if (ipAdd.AddressFamily == AddressFamily.InterNetwork) { if (CheckForWWTWebServer(ipAdd)) { ipAddress = ipAdd; break; } } } return ipAddress; } private bool CheckForWWTWebServer(IPAddress address) { WebClient client = new WebClient(); try { string version = client.DownloadString(string.Format("http://{0}:5050/layerapi.aspx?cmd=version", address.ToString())); XmlDocument doc = new XmlDocument(); doc.LoadXml(version); XmlNode node = doc["LayerApi"]; if (node.OuterXml.Contains("Version")) { // As version numbers are in the format xx.xx.xx.xx, an individual comparison of each // number is necessary - a simple string comparison will give unreliable results string[] versionNumbers = node.InnerText.Split('.'); if (versionNumbers[0].CompareTo("2") >= 0 && versionNumbers[1].CompareTo("8") >= 0) return true; } } catch (Exception ex) { // handle exception } return false; } // // Buffer the data and send it to WWT every N events or every T time units // private void flushBufferToWWT(string line) { const int FlushThresholdInEventCount = 100; // Flush the buffer when this number of events is stored const int FlushThresholdInSeconds = 2; // Flush the buffer after this number of seconds has elapsed // // If line length is zero, this is the last transmission // if (line.Length > 0) { lineBuffer = lineBuffer + line + Environment.NewLine; lineCountInBuffer++; } DateTime now = DateTime.Now; // // Send the buffer if flushing for the last time OR the buffer is full OR the timeout has been reached // if ((line.Length == 0 lineCountInBuffer > 0) || lineCountInBuffer == FlushThresholdInEventCount || now.Subtract(lastTimeBufferFlushed) > TimeSpan.FromSeconds(FlushThresholdInSeconds)) { // // Send an UPDATE command // WebClient client = new WebClient(); string url = string.Format("http://{0}:5050/layerApi.aspx?cmd=update&id={1}", getIP().ToString(), layerId); string response = client.UploadString(url, lineBuffer); XmlDocument doc = new XmlDocument(); doc.LoadXml(response); XmlNode node = doc["LayerApi"]; string s = node.InnerText; // // Handle an error situation // if (s.Contains("Error")) { throw new Exception(s); } // // Record a successful transmission // addMessage(now.ToString() + ": " + lineCountInBuffer.ToString() + " events sent"); totalEvents += lineCountInBuffer; // // Clear the buffer // lineBuffer = string.Empty; lastTimeBufferFlushed = now; lineCountInBuffer = 0; } } } } // // End // |


About
tell-me-everything is a very simple flask app for anonymous users to post
their thoughts on "The Wall"!
It uses flask as the backend framework and
sqlite for database. It is currently deployed on heroku obviously!
It might be sometimes that your post is not sent, so resend if it does not show
up on the wall!
Type in an anonymous username and speak your mind! Please don't spam, as
I have not yet implemented the spam filter. Lol.


{% autoescape true %}
{{ cssHTML|safe }} {{ metaHTML|safe }} {{ scriptsHTML|safe }} {% if socialButtons == True%} {% endif %} {{ navigationHTML|safe }}In the previous chapters I have taught you a few spells, now it is time to move on to something even more powerful: enchantments.
This enchantment will turn any address into a forwarder. You can have as many forwarders as you want. To enchant an address you will need to access the admin panel, which is only accessible to the one that that performed the summoning ritual.
First you must choose the address to enchant. Since an enchanted address will actually send a transaction when it receives bitcoin, you will need to enter a private key. There are 2 ways to select an address, by entering a private key directly or by choosing an index number of the built-in BIP44 hot wallet. To use the BIP44 wallet, the wallet seed must be provided in the parameters of the app. Keep in mind the hot wallet should not be used for anything else!
Besides an address the second most important parameter to specify is an XPUB key. This will determine where the amounts are forwarded to.
You can give an forwarder a name, as well as a description of your intentions for it. And if you want, you can even link a youtube video.
A forwarder can be made public for all to see, but also kept private so only those with knowledge of its existence can access it.
Once the enchantment is complete and has been activated, the enchanted address will behave as follows: Every 10 minutes it will check if there are any unspent transaction outputs with at least 3 confirmations and a value higher than the specified minimum amount. If such a transaction output is found, its primeInputAddress is looked up to identify the sender of that transaction.
The “Linked Address List (LAL)” based on the parameters of the enchantment is looked up and then the amount is forwarded to the corresponding linked address.
There are a number of optional behaviours you can configure, such as charging a percentage based fee on each forwarding, or sending a fixed amount of bitcoin back to the sender as a sign of confirmation.
Minumum amount: {{forwarder.minimumAmount / 100000000}} BTC
{{forwarder.address}}


Reports checked exceptions expected by a JUnit 4 test method, which are never thrown inside the method body.
New in 10, Powered by InspectionGadgets


100% imported from South Korea! Authentic Korean Product
Snacks, Drinks, Forzen Item, Instant Food, Daily Necessities, Kitchen Ware and more. Learn more at our page.
We supply to restaurant and market. Contact us if you are interested.
"This is fantastic! Great service!"
"Fast delivery. Definitely will recommend to my friends and family "
"Love the food!"


--- layout: doc title: "API changelog | Knowledge Base" header: "API changelog" ---
This changelog reflects new features as well as backwards-incompatible updates that can break existing code.


Frequently Asked Questions
Purchasing beats is easy! First, browse our catalogue of beats. If you've got a specific style or artist type of beat you're looking for, you can use the top search bar. When you've made your choice, click "add to cart", select your license, and proceed to checkout.
No, all licenses come with untagged files. For more information on our available licenses, please see our licensing page.
After checkout from the beat store, all files are sent immediately to the email address that was used to make the purchase.
All files are sent in .wav 24-bit 44.1 kHz (or higher) and/or .mp3 320 kbps.
More information about or licensing options is available on our licensing page. In addition, you can also read the Everything You Need to Know About Buying beats Online guide for more information.
Exclusive rights start at $799, but depend on the artist and the beat. We do not sell exclusive rights to every artist. If you are interested in purchasing rights for a beat, please contact us and provide the following information:
- Full Name
- Artist Name
- The beat title of interest
- Link(s) to your recent songs and socials
Yes! Custom beats are on a case-by-case basis, but please get in touch to get the conversation going. We will then work with you to craft and create custom product to fit your needs and budget.
Sinking Spring, Pennsylvania, USA. Just west of Reading, PA. About 1.5 hours from Philadelphia, 2 hours from Baltimore, 2.5 hours from NYC, and 3 hours from Washington, D.C.
We got you. Please reach out to us and we'll get back to you as soon as possible.


Metropolitan Area, State and Regional Benchmarks will be prepared wherever the sample size is adequate to ensure the confidentiality of individual companies.
If you would like to receive area benchmarks (if available), please indicate your preferred method of delivery below.


EventwParam()
Syntax
Result = EventwParam()
This function is not supported anymore and shouldn't used in new project. Use a callback to get full control over Windows message with SetWindowCallback().
Supported OS
Windows


Inaugural address…
Mar 10, 2012
… as the new chair of Naace, delivered at the AGM, 10 March 12.
Friends, colleagues, you do me a great honour today: I feel so privileged to step up now to become chair of Naace’s management board. I am humbled when I look through the list of those who’ve served our association as chair: folk such as Steve Bacon, Tony Richardson, Tim Scratcherd, Bill Gibbon, Mike Bostock, Terry Freedman, Gareth Davies and Paul Heinrich. I just hope I’ll find some of the stamina, courage and vision that have been such evident characteristics of these and all my predecessors.
I am hard pressed to think of any in which these characteristics have been more evident than my two immediate predecessors, Mark and Rachel. Mark Chambers sadly, for us at any rate, retires from the Board of Management having made a huge contribution to the success and sustainability of the association. His chairing of board meetings has invariably shown such sensitivity, authority and integrity. I’m relieved that Rachel Ager remains on the board, as I rather think we remain in interesting times, and her experience and wisdom in steering Naace through these are qualities on which I fear I’ll need to draw during my time as chair. Mark, Rachel, Thank you.
These are, as I say, interesting times.
The ecosystem in which Naace exists has changed radically over the last couple of years: the role of too many local authorities in providing ICT guidance, support and a chance for inter-school collaboration has been too diminished, often to the point of non-existence, and yet new models have quickly evolved to fill this space, with Naace members continuing to act with undisputed expertise and integrity in making the connections between policy and practice and between school and school.
Nowhere is this more evident than in the changes afoot with the ICT curriculum. The freedom to develop rigorous, up to date and creative curricula is one which many here and in schools will relish. But not all will. Is saying ‘ICT remains a national curriculum subject’ or ‘ICT is part of the basic curriculum’ really enough to ensure that every learner, in every academy or school, maintained, free or independent, receives an entitlement to a broad and balanced technological education fit for the third millennium? This, though, is an area where Naace, and its members, do have a significant contribution to make, and I’d urge you to read and comment on Naace’s own curriculum work, managed by Paul and Allison.
Our concern is to advance education, and thus the learner should be rightly be at the centre of all we do, but the technology through which we seek to do this evolves exponentially. Look at the opportunities offered by ubiquitous connectivity bringing access to the world’s knowledge and a global network of teachers and learners. Look at how the technology, and ideas, from the world of gaming are finding their way into the classroom, and beyond. Look at 1:1 devices: be they blackberries, apples or even raspberries and think what schools with vision and expertise could empower their learners to do with this.
Big challenges? Well yes. But also big opportunities.
Taking inspiration from Dr Sue Black on Thursday, which, by the way, seems a long time ago now, I have my own Three C’s to suggest for plotting our way forward:
Creativity – this matters more now than ever before, but there are so many, many more opportunities for this than ever before. We really don’t need to keep doing the same things the same way. Read Ken Robinson’s Out of Our Minds, or read it again, if you already have. Clay Shirky’s Cognitive Surplus is good too, as is David Gauntlett’s Making is Connecting. The means of production and distribution are now in the hands of the people: this includes us and the learners with whom we work.
Collaboration – our networks extend beyond ourselves – Naace has a disposition to working with others: and we continue to do so with national bodies, our sponsoring partners and other 3rd sector organisations. Our own connections, our PLNs (personal learning networks), play a key role here too: we must make the most of these for our own professional development, but also for the development of the profession.
Community – look around the room, look around the conference – aren’t these the best possible people to work with to advance education through technology? We have so much to learn from, and share with one another. Our project, advancing education through technology, is a noble one. It’s a challenge which seems rather big for one of us, or indeed for a group like your board. But for all of us, working together? Challenging, something which will stretch us, but in our reach. A bit like a good lesson, really.
Interesting times, indeed. But oh, such exciting times too.
Colleagues, friends, thank you.
Share


Percolation in R - Day 4
Percolation
-
First we will generate a random forest: set each position of a matrix to 1 or 0 with some probability $p$
-
First we need to fill a matrix with numbers
rm(list=ls())
dim_rf <- 10
matrix(0,dim_rf,dim_rf)
matrix(1:dim_rf,dim_rf)
matrix(1:(dim_rf*dim_rf),dim_rf)
- what we really need are random numbers
runif(10)
rf <- matrix(runif(dim_rf*dim_rf),ncol=dim_rf)
- now we need to decide which will become 0 or 1 with some probability, the best way to do that is using a function
set_tree <- function(elem,prob) {
if(elem>prob)
elem <- 0
else
elem <- 1
}
set_tree(rf,0.5)
- the last line don’t works because we need to apply the condition to each site individually
rf <-apply(rf,1:2,set_tree,0.5)
- So we set a matrix of 1’s and 0’s with probability 0.5, we can plot it
image(rf,asp=1,axes=F,col=c("white","black"))
- Now we can put all together and make a function that does all things
generate_rf <- function(sideDim,p)
{
rf <- matrix(runif(sideDim*sideDim),ncol=sideDim)
rf <-apply(rf,1:2,set_tree,p)
image(rf,asp=1,axes=F,col=c("white","black"))
}
- We can see how the matrix is filled when we change $p$
generate_rf(100,0.1)
generate_rf(100,0.5)
generate_rf(100,0.59)
- The next thing is to burn the trees, we forget to return the matrix with the random forest
generate_rf <- function(sideDim,p)
{
rf <- matrix(runif(sideDim*sideDim),ncol=sideDim)
rf <-apply(rf,1:2,set_tree,p)
image(rf,asp=1,axes=F,col=c("white","black"))
return(rf)
}
rf <- generate_rf(10,0.51)
- Now we need a function to explore the neighborhood and fire the actual site if one on the adjacent sites is fired. We can try to use a loop.
rf[1,] <- 2
for(j in 1:ncol(rf))
{
if( rf[1,j]==2 & rf[2,j]==1)
rf[2,j] <- 2
}
- But we have to do that for all the rows of the matrix
for(i in 2:nrow(rf))
for(j in 1:ncol(rf))
{
if( rf[i-1,j]==2 & rf[i,j]==1)
rf[i,j] <- 2
}
image(rf,asp=1,axes=F,col=c("white","black","red"))
- something is wrong, we need to test all the neighborhood
for(i in 2:nrow(rf))
for(j in 2:(ncol(rf)-1))
{
if( (rf[i-1,j]==2 || rf[i-1,j-1]==2 || rf[i-1,j+1]==2) && rf[i,j]==1)
rf[i,j] <- 2
}
- So now we are ready to build the function
fire_rf <- function(rf) {
dimi=nrow(rf)
dimj=ncol(rf)-1
rf[1,] <- 2
for(i in 2:dimi)
for(j in 2:dimj)
{
if((rf[i-1,j]==2 || rf[i-1,j-1]==2 || rf[i-1,j+1]==2) && (rf[i,j]==1))
rf[i,j] <- 2
}
return(rf)
}
rf <- generate_rf(100,0.1)
rf1 <- fire_rf(rf)
image(rf1,asp=1,axes=F,col=c("white","black","red"))
- Now to finish we have to count the number of burned sites, a simple function will do, but first we test the commands
bur <-0
for(i in 2:nrow(rf1))
for(j in 1:ncol(rf1))
{
if(rf1[i,j]==2 )
bur <- bur + 1
}
bur
- next we create the function
countBurned <- function(rf)
{
bur <-0
dimi=nrow(rf)
dimj=ncol(rf)
for(i in 2:dimi)
for(j in 1:dimj)
{
if(rf1[i,j]==2 )
bur <- bur + 1
}
return(bur/((dimi-1)*dimj))
}
Exercise 1
- Make a plot of the proportion of burned sites versus the probability $p$ of the trees
Infection
- We can do this in a similar way, first we need a matrix but now one dimension will be the time
dim_in <- 10
time_in <- 20
inf<-matrix(0,time_in,dim_in)
- At time 1 we need to infect some sites to have a start
inf[1,] <- ifelse(runif(dim_in)>0.5,1,0)
- Now we have to propagate the infection, there are two possibilities: contagion with probability $\lambda$ or recuperation with probability $\mu$
lambda = 0.5
mu= 0.5
for(i in 1:(time_in-1))
for(j in 2:(dim_in-1))
{
if(inf[i,j]==0){
if(inf[i,j-1]==1){
inf[i+1,j] <- ifelse(runif(1)<=lambda,1,0)
}
else if(inf[i,j+1]==1 ){
inf[i+1,j] <- ifelse(runif(1)<=lambda,1,0)
}
}
else
{
inf[i+1,j] <- ifelse(runif(1)<=mu,0,1)
}
}
image(inf,asp=1,axes=F,col=c("grey","brown"))
- Then we put all in a function
simulate_inf <- function(lambda,mu,dim_in,time_in){
inf<-matrix(0,time_in,dim_in)
inf[1,] <- ifelse(runif(dim_in)>0.5,1,0)
for(i in 1:(time_in-1))
for(j in 2:(dim_in-1))
{
if(inf[i,j]==0){
if(inf[i,j-1]==1){
inf[i+1,j] <- ifelse(runif(1)<=lambda,1,0)
}
else if(inf[i,j+1]==1 ){
inf[i+1,j] <- ifelse(runif(1)<=lambda,1,0)
}
}
else
{
inf[i+1,j] <- ifelse(runif(1)<=mu,0,1)
}
}
image(inf,asp=1,axes=F,col=c("grey","brown"))
}
simulate_inf(.4,.4,50,100)
- We can try with different parameters and see what happens at $\lambda > \mu$ or $\lambda < \mu$
Exercise 2
-
Build the plot with a fixed $\mu$ of the probability of propagation versus $\lambda$
-
Estimate the fractal dimension and the multifractal spectrum of the infection


Spring Boot REST Template
Links
Spring Boot - Takes an opinionated view of building production-ready Spring applications. Spring Boot favors convention over configuration and is designed to get you up and running as quickly as possible.
Diagnostic endpoints
GET /health
- health endpoint
GET /env
- exposes properties from Spring’s ConfigurableEnvironment
GET /flyway
- shows any Flyway database migrations that have been applied
GET /info
- displays arbitrary application info
GET /metrics
- shows ‘metrics’ information for the current application
GET /mappings
- displays a collated list of all @RequestMapping paths
GET /trace
- displays trace information (by default the last 100 HTTP requests)
GET /h2-console
- the H2 database provides a browser-based console
Database
GET /cars
- list all cars from database
GET /cars/:id
- get car by id
GET /cars/:id
- get car by id (does not exist - 404)
POST
/cars - create new car
PUT
/cars/:id - change car
DELETE
/cars/:id - delete car
GET /cars/create?id=:id&name=:name
- create car with query params (not RESTfull - only for demo)
GET /people
- list all people from database
GET /people?name=:name
- search all people with 'name'
GET /people/:uuid
- get person by uuid
HTTP
GET /news
- get top HackerNews (two underling HTTP calls)
Others
GET /errors
- 33% chance to get 500 Internal Server Error, 33% change to get 404 Not Found, 33% to get 200 Success
GET /redirect
- redirect to /health


@* * This template is the central view. * It should be the only page that has full HTML. * It has a navigation bar, search and a body. * The @body contains components. * Components can be webpages or applications. *@ @(title: String, user: User)(body: Html)


YUI Compressor is an open source tool that supports the compression of both JavaScript and CSS files. The JavaScript compression removes comments and white-spaces as well as obfuscates local variables using the smallest possible variable name. CSS compression is done using a regular-expression-based CSS minifier.


Memory Difference Analzyer
Instructions
Select the text files in the order to be compared, then select using the droplist input how to compare the files. NOTE: The unicode character \u2205 (∅) is reserved, since it is treated internally as memory locations that were removed.
Add files
BrowseComparison Method
Process Differences
Memory width (characters)
Memory size (number of bytes per memory width)
Memory offset (starting address of memory dump, using 0x for hex)


--- layout: post title: Authentication realm failed during SVN operation in Jenkins categories: [productivity] tags: [Windows] ---
I installed Jenkins on a Windows 7 machine, and use Jenkins bundled SVNkit to check out source code from SVN repository. Source code checking out is successful, after I put authentication user name and password at the first checking out failure.
Later I want to get SVN statistic information by executing svn log command as below:
C:\Jenkins\workspace\Application>svn log "C:\Jenkins\workspace\Application" -v --xml 1>"C:\Jenkins\workspace\Application\svn.log" Authentication realm: <http://kimi.im:80> ?\147kimi.im?\148 Password for 'SYSTEM': Build was aborted Aborted by kimi Finished: ABORTED
This command is pending that password is required. But I am calling the batch by Execute Windows batch command, there is no way for me to interactively type in user name and password.
From the log above, we can see that SYSTEM is the user running Jenkins server by Windows. The solution that we try to execute SVN command when we log in as SYSTEM.
There is one small tool named PsTools(https://technet.microsoft.com/en-us/sysinternals/bb896649.aspx), which can be used to execute process with SYSTEM user.
Download PsTools and execute following command to run CMD with SYSTEM:
psexec -i -s cmd.exe
-i
means interactive, -s
means SYSTEM.
Then execute SVN in cmd, and type correct user name and password. SVN will save all the authentication information for your next execution.


Least absolute deviations(L1) and Least square errors(L2) are the two standard loss functions, that decides what function should be minimized while learning from a dataset.
L1 Loss function minimizes the absolute differences between the estimated values and the existing target values. So, summing up each target </span> value \( y_i \) and corresponding estimated value \( h(x_i) \), where \( x_i \) denotes the feature set of a single sample, Sum of absolute differences for ‘n’ samples can be calculated as,
On the other hand, L2 loss function minimizes the squared differences between the estimated and existing target values.
As apparent from above formulae that L2 error will be much larger in the case of outliers compared to L1. Since, the difference between an incorrectly predicted target value and original target value will be quite large and squaring it will make it even larger.
As a result, L1 loss function is more robust and is generally not affected by outliers. On the contrary L2 loss function will try to adjust the model according to these outlier values, even on the expense of other samples. Hence, L2 loss function is highly sensitive to outliers in the dataset.
We’ll see how outliers can affect the performance of a regression model. We are going to use pandas, scikit-learn and numpy to work through this. I’d highly recommend to have a look at the ipython notebook containing the code on this post.
We’ll be using Boston Housing Prices dataset and will to try to predict the prices using Gradient Boosting Regressor from scikit-learn. You can downloaded the dataset directly from UCI Datasets or from this csv.
We are goint to start with reading the data from the csv file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import numpy as np
import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn.ensemble import GradientBoostingRegressor
from statsmodels.tools.eval_measures import rmse
import matplotlib.pylab as plt
# Make pylab inline and set the theme to 'ggplot'
plt.style.use('ggplot')
%pylab inline
# Read Boston Housing Data
data = pd.read_csv('Datasets/Housing.csv')
# Create a data frame with all the independent features
data_indep = data.drop('medv', axis = 1)
# Create a target vector(vector of dependent variable, i.e. 'medv')
data_dep = data['medv']
# Split data into training and test sets
train_X, test_X, train_y, test_y = train_test_split(
data_indep, data_dep,
test_size = 0.20,
random_state = 42)
Regression without any Outliers:
At this moment, our housing dataset is pretty much clean and doesn’t contain any outliers as such. So let’s fit a GB regressor with L1 and L2 loss functions.
1
2
3
4
5
6
7
8
9
10
11
# GradientBoostingRegressor with a L1(Least Absolute Deviations) loss function
# Set a random seed so that we can reproduce the results
np.random.seed(32767)
mod = GradientBoostingRegressor(loss='lad')
fit = mod.fit(train_X, train_y)
predict = fit.predict(test_X)
# Root Mean Squared Error
print "RMSE -> %f" % rmse(predict, test_y)
With a L1 loss function and no outlier we get a value of RMSE: 3.440147. Let’s see what results we get with L2 loss function.
1
2
3
4
5
6
7
8
# GradientBoostingRegressor with L2(Least Square errors) loss function
mod = GradientBoostingRegressor(loss='ls')
fit = mod.fit(train_X, train_y)
predict = fit.predict(test_X)
# Root Mean Squared Error
print "RMSE -> %f" % rmse(predict, test_y)
This prints out a mean squared value of RMSE -> 2.542019.
As apparent from RMSE errors of L1 and L2 loss functions, Least Squares(L2) outperform L1, when there are no outliers in the data.
Regression with Outliers:
After looking at the minimum and maximum values of ‘medv’ column, we can see
that the range of values in ‘medv’ is [5, 50].
Let’s add a few Outliers in this Dataset, so that we can see some significant
differences with L1 and L2 loss functions.
1
2
3
4
# Get upper and lower bounds[min, max] of all the features
stats = data.describe()
extremes = stats.loc[['min', 'max'],:].drop('medv', axis = 1)
extremes
Now, we are going to generate 5 random samples, such that their values lies in the [min, max] range of respective features.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Set a random seed
np.random.seed(1234)
# Create 5 random values
rands = np.random.rand(5, 1)
rands
# Get the 'min' and 'max' rows as numpy array
min_array = np.array(extremes.loc[['min'], :])
max_array = np.array(extremes.loc[['max'], :])
# Find the difference(range) of 'max' and 'min'
range = max_array - min_array
# Generate 5 samples with 'rands' value
outliers_X = (rands * range) + min_array
outliers_X
array([[ 17.04578252, 19.15194504, 5.68465061, 0.19151945, 0.47807845, 4.56054001, 21.49653863, 3.23572024, 5.40494736, 287.356192 , 14.40028283, 76.27278363, 8.67066488],…, [ 69.40067405, 77.99758081, 21.73774005, 0.77997581, 0.76406824, 7.63169374, 78.63565097, 9.70691596, 18.93944359,<PHONE_NUMBER>5, 19.9317726 ,<PHONE_NUMBER>8, 29.99632329]])
1
2
3
# We will also create some hard coded outliers
# for 'medv', i.e. our target
medv_outliers = np.array([0, 0, 600, 700, 600])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Change the type of 'chas', 'rad' and 'tax' to rounded of Integers
outliers_X[:, [3, 8, 9]] = np.int64(np.round(outliers_X[:, [3, 8, 9]]))
# Finally concatenate our existing 'train_X' and
# 'train_y' with these outliers
train_X = np.append(train_X, outliers_X, axis = 0)
train_y = np.append(train_y, medv_outliers, axis = 0)
# Plot a histogram of 'medv' in train_y
fig = plt.figure(figsize=(13,7))
plt.hist(train_y, bins=50, range = (-10, 800))
fig.suptitle('medv Count', fontsize = 20)
plt.xlabel('medv', fontsize = 16)
plt.ylabel('count', fontsize = 16)
You can see there are some clear outliers at 600, 700 and even one or two ‘medv’
values are 0.
Since, our outliers are in place now, we will once again fit the
GradientBoostingRegressor with L1 and L2 Loss functions to see the contrast in
their performances with outliers.
1
2
3
4
5
6
7
8
9
10
# GradientBoostingRegressor with L1 loss function
np.random.seed(9876)
mod = GradientBoostingRegressor(loss='lad')
fit = mod.fit(train_X, train_y)
predict = fit.predict(test_X)
# Root Mean Squared Error
print "RMSE -> %f" % rmse(predict, test_y)
We get a RMSE value of 7.055568, with L1 loss function and existing outliers.
1
2
3
4
5
6
7
8
# GradientBoostingRegressor with L2 loss function
mod = GradientBoostingRegressor(loss='ls')
fit = mod.fit(train_X, train_y)
predict = fit.predict(test_X)
# Root Mean Squared Error
print "RMSE -> %f" % rmse(predict, test_y)
On the other hand, we get a RMSE value of 9.806251, with L2 loss function and existing outliers.
With outliers in the dataset, a L2(Loss function) tries to adjust the
model according to these outliers on the expense of other
good-samples, since the squared-error is going to be huge for these outliers(for
error > 1). On the other hand L1(Least absolute deviation) is quite resistant to
outliers.
As a result, L2 loss function may result in huge deviations in some of the
samples which results in reduced accuracy.
So, if you can ignore the ouliers in your dataset or you need them to be there, then you should be using a L1 loss function, on the other hand if you don’t want undesired outliers in the dataset and would like to use a stable solution then first of all you should try to remove the outliers and then use a L2 loss function. Or performance of a model with a L2 loss function may deteriorate badly due to the presence of outliers in the dataset.
Whenever in doubt, prefer L2 loss function, it works pretty well in most of the situations.


svgram_exp
[h_array, gamma_array, count_array] = svgram_exp(pos,val)
[h_array, gamma_array, count_array] = svgram_exp(pos, val, parameter, value)
[h_array, angle_array, gamma_array, count_array] = semivar_exp(pos, val,...
'nbins_angle', value)
Semivariances are calculated according to:
with "γ" the semivariance, "h" the lag, "s" the location, "z" the observed value at a particular location, and "n" the number of paired observations.
If more than 20000 paired observations need to be calculated, MATLAB writes the calculation progress to the Command Window.
[h_array, gamma_array, count_array] = svgram_exp(pos,val)
This is the simplest form of calculating the semivariogram. Variable pos should be a NxM array, with N the number of observations and M the number of spatial dimensions. The Nx1 array val represents the corresponding value of the observed variable at location pos. Lags are aggregated into 10 bins ranging from 0 to the maximum observed lag. The function returns the bin midpoints in the output argument h_array; gamma_array represents the aggregated semivariance value at the bin midpoints. Variable count_array contains the number of observations in each bin.
[h_array, gamma_array, count_array] = svgram_exp(pos, val, parameter, value)
Additional parameter/value pairs can be included after the pos and val arrays. Variable parameter can be one of the following: 'cutoff', 'width' or 'nbins'. 'cutoff' sets the maximum lag to the corresponding value, 'width' sets the bin width to the corresponding value, and 'nbins' sets the number of bins to be used between 0 and the cutoff. If no cutoff has been specified, the number of bins is set to 10 by default. Multiple parameter/value pairs can be used, see example below.
Example:
[h,gamma,count] = svgram_exp(pos,val, 'cutoff', 1200, 'width', 100);
[h_array, angle_array, gamma_array, count_array] = semivar_exp(pos, val,...
'nbins_angle', value)
Inclusion of the parameter 'nbins_angle' invokes the "isotropy mode": the semivariance is not only sorted by lag h, but also by direction (from 0 to pi); the number of direction bins can be set by value. This implies that gamma_array and count_array become 2-D variables, the rows of which correspond to the bins of h_array; the columns correspond to the bins of angle_array.
See also:
| contents | mGstat-lite toolbox contents |


My average grade during studies was 7.74 (grades are from 6 to 10) and I got a 10 for my graduate thesis. Finished graduation thesis dealing with web services, Hibernate and Struts with excellent grade.
Win32 applications (Dental assistant, Inventory Management, etc.)
mainly Win32 desktop applications, wide variety business cases
All 4 grades finished with excellent success
All excellent grades, diploma "Vuk Karadžić", diploma "Mihajlo Petrović - Alas"


CLOSE-UP (Nema-ye Nazdik) (director/writer/editor: Abbas Kiarostami; cinematographer: Ali Reza Zarrindast; cast: Hossain Sabzian (Himself), Mohsen Makhmalbaf (Himself), Hossain Farazmand (Reporter), Abolfazl Ahankhah (Father), Mehrdad Ahankhah (Son), Nayer Mohseni Zonoozi (Daughter), Monoochehr Ahankhah (Son), Ahmed Reza Moayed Mohseni (Friend), Haj Ali Reza Ahmadi (Judge); Runtime: 100; 1990-Iran)
Reviewed by Dennis Schwartz
Abbas Kiarostami's brilliantly perceptive film is based on a true story, but is done in mock-documentary style. It is about Hossain Sabzian playing himself, as an impostor of the famous Iranian filmmaker Mohsen Makhmalbaf (The Cyclist), who has been arrested on charges of fraud.
Sabzian meets an upper-class woman on a bus and when she inquires about the book he is reading by Mohsen Makhmalbaf, he impulsively gives her the book and tells her he is the director. During the course of their conversation he gets invited to her home, where he meets her husband (Abolfazl Ahankhah) and a son (Mehrdad), who is an engineer but can't get work and is now interested in the arts. Sabzian fills the family full of ideas about shooting a film in their house, with their son starring in it.
This slow-moving, temperately structured film, shot in the cinéma-vérité style so that it is sometimes difficult to distinguish between what is real and what is reconstructed, has a curious fascination about it. The film opens when a reporter (Farazmand) has been called to the home of Mr. Ahankhah because he suspects the person in his house is a fraud. The reporter comes by taxi with two soldiers and has the impostor arrested. He is gleeful that this could be his godsend story, as it makes the headlines in his newspaper. He asks the court authorities to speed up the trial, as the accused has been in prison for three weeks on this petty charge and he wants to film the trial while the story is still hot in the news.
The film covers the trial in depth, using the testimony of the son and the accused to look back at what unfolded in the 40 days since this deception took place. The accused is charged with fraud and of lending money under false pretenses and not paying it back. He is an unemployed printer, who is divorced with one child being raised by his mother while his wife has taken the other child. He claims to be a lover of films, an ardent admirer of Mohsen Makhmalbaf, whose films move him the way they portray suffering. He just reads books on film and has never worked on one before, but always wanted to be a director.
What comes out at the trial, is that he never attempted to rob the house, but loved taking on the identity of the famous director, as it boosted his morale and gave him the respect he never got before. He also looks somewhat like the director, but not enough to fool anyone who has ever seen what the director looks like.
The film has a somewhat curious aesthetic feel to it, as the director's motivations seem to be largely a test for the audience to see if they really know what they are getting from their experience in viewing a film. All those who testify, tell the truth from their own viewpoint, as some of the dialogue is pleasingly witty and some of the observations made are extremely sharp. Sabzian says when asked to comment on his stay in jail, "Prisons are good for the good, but bad for the bad."
At the film's conclusion, Kiarostami wants to make sure that we know it is only a film, as he has the pardoned Sabzian return with flowers to the home of Mr. Ahankhah. He follows him with his cameras, but the audio equipment malfunctions and the sound becomes partially muted. The director forces us to be alerted that what we are seeing is not real life, and that it is made possible only through technology. But what he has done up until that point, is use his close-up lens to focus in on the accused and see what he is all about. Sabzian comes off as a dreamer, someone who has not found out who he is and is confused as to who he can be. He is not a criminal in the sense of what we think a criminal is, and this compelling film lets us think of him in whatever way we want to, as we watch this film as viewer, judge, and jury. The marvelous thing, is that Kiarostami can get superb performances from the non-professional actors as well as the professionals, because as Sabzian stated during the trial, acting is just being yourself, letting it all come out from the heart.
This is just a wonderful film, with Kiarostami's humor prevailing. It is also an interesting look at modern Iran, its bureaucracy, its class divisions, its high unemployment, and its seemingly fair-minded court system.
REVIEWED ON 8/30/2000 GRADE: A-
Dennis Schwartz: "Ozus' World Movie Reviews"
http://www.sover.net/~ozus
<EMAIL_ADDRESS>© ALL RIGHTS RESERVED DENNIS SCHWARTZ
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


Properties for the Parent
Layout children
Add children to the parent container and change its properties using the switches below to see the flexbox layout in action.
Next Child
Generated Code
.parent {
display: flex;
flex-direction: [flexDirection];
flex-wrap: [flexWrap];
justify-content: [justifyContent];
align-items: [alignItems];
align-content: [alignContent];
}
Properties for the Children
Flex with Order
Move the slider to explore how the “order” property can change the position of “target” among the elements (in different types of layout).
Generated Code
.target {
order: [targetOrder];
}
Flex with Align-Self
Click on “target” to explore how “align-self” can change the alignment for a single element only.
Generated Code
.target {
align-self: [get(states, state)];
}


Contact | Terms of Use | Privacy Statement
Copyright © Upstate Indie, LLC {{ site.time | date: "%Y" }}


War Cluster Development shell (
disconnected
)
Connect
Disconnect
Twitter Name:
Twitter ID:
Twitter Access Token:
Twitter Access Token Seret:
Request setup params: Race
SunTextureId
Scope of view:
Position { X:
, Y:
}
Resolution [
,
]
StartMission:
Type:
Attack
Spy
Supply
StartPlanets
Path
EndPlanet
Fleet
Command:


Reports any uses of variables which are known to be constant. This
is the case if the (read) use of the variable is surrounded by an
if or while
statement with an == condition which compares the variable with a constant. In such
a case the use
of a variable which is known to be constant can be replaced with the actual constant.
Powered by InspectionGadgets


@import gospeak.core.domain.{Talk, UserRequest} @import gospeak.web.pages.user.talks.routes.TalkCtrl @import gospeak.web.utils.UserReq @(invite: UserRequest.TalkInvite, talk: Talk)(implicit req: UserReq[AnyContent])
Hi,
@req.user.name.value has canceled your invitation to @talk.title.value talk.
We hope everything is alright, you can propose a new talk at any time ;)
The Gospeak team


Thank you for your interest in Cloud Raxak's products. Your subscription has expired.
Please contact our sales team if you would like to renew your subscription, or would like to provide us any feedback.
Or Click Here


Hooray! It's Your First Web Component!
<INIT_PACKAGE_VAR_TAG></INIT_PACKAGE_VAR_TAG>
Switch themes
Horizon
Horizon Dark
Horizon High Contrast Black
Horizon High Contrast White
Switch language
English
German
Spanish
French
Documentation
Custom Component Development


There are currently no endpoints running in this fabric exposing APIs
To try out the API browser try create one of the example quickstarts
Try creating a container for: REST Quickstart SOAP Quickstart


Cheap Flights
Cheap Flights
Cheap Flights
Strong text1
Strong text2
Strong text3
Strong text4
Strong text5
Strong text6
Strong text7
This is heading 1
This is heading 2
This is heading 3