Pointer
class Pointer extends Bounds
a pointer object, representing a single finger on a touch enabled device.
Summary
Properties from Pointer
| number |
|
| number |
|
| number |
|
| number |
|
| number |
|
| number |
|
| number |
|
| PointerEvent | TouchEvent | MouseEvent |
|
| number |
|
| number |
|
| number |
|
| number |
|
| number |
|
| number |
|
| number |
|
| number |
|
| boolean |
|
| boolean |
|
| number |
|
| boolean |
|
| number |
|
| number |
|
| number |
|
| number |
|
| number |
|
| number |
|
| number |
|
| string |
|
Properties inherited from Bounds
Methods inherited from Bounds
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
reset the bound |
|
| Bounds |
|
| boolean |
|
| boolean |
|
| boolean |
|
|
|
|
|
|
|
| Polygon |
|
|
|
|
|
|
Public Properties
button: number = 0
number
the button property indicates which button was pressed on the mouse to trigger the event.
clientX: number = 0
number
the horizontal coordinate within the application's client area at which the event occurred
clientY: number = 0
number
the vertical coordinate within the application's client area at which the event occurred
deltaMode: number = 0
number
an unsigned long representing the unit of the delta values scroll amount
deltaX: number = 0
number
a double representing the horizontal scroll amount in the Wheel Event deltaMode unit.
deltaY: number = 0
number
a double representing the vertical scroll amount in the Wheel Event deltaMode unit.
deltaZ: number = 0
number
a double representing the scroll amount in the z-axis, in the Wheel Event deltaMode unit.
event: PointerEvent | TouchEvent | MouseEvent
PointerEvent | TouchEvent | MouseEvent
the originating Event Object
gameLocalX: number = 0
number
Event X coordinate relative to the holding container
gameLocalY: number = 0
number
Event Y coordinate relative to the holding container
gameScreenX: number = 0
number
Event X coordinate relative to the viewport
gameScreenY: number = 0
number
Event Y coordinate relative to the viewport
gameX: number = 0
number
Event normalized X coordinate within the game canvas itself
gameY: number = 0
number
Event normalized Y coordinate within the game canvas itself
isNormalized: boolean = false
boolean
true if not originally a pointer event
isPrimary: boolean = false
boolean
indicates whether or not the pointer device that created the event is the primary pointer.
movementX: number = 0
number
the difference in the X coordinate of the pointer since the previous move event
movementY: number = 0
number
the difference in the Y coordinate of the pointer since the previous move event
pageX: number = 0
number
the horizontal coordinate at which the event occurred, relative to the left edge of the entire document.
pageY: number = 0
number
the vertical coordinate at which the event occurred, relative to the left edge of the entire document.
pointerId: number
number
The unique identifier of the contact for a touch, mouse or pen
type: string
string
a string containing the event's type.


---
layout: home
---
I'm {{ site.author }}, a Software Engineer at Zipcar.
Some of my interests include:
BJJ, Photography, and more recently playing with data.
You can contact me by email: First Name @ this domain
{% include social.html %}


Preparation time
less than 30 mins
Cooking time
30 mins to 1 hour
Serves
Serves 4
Dietary
Oozy, melty and just the right kind of smelly, cheese lovers will find this dish of reblochon baked in the box hard to beat. Turn up la décadence with a topping of buttery brioche crumbs with thyme and blue cheese beignets on the side.
For the baked reblechon cheese, preheat the oven to 180C/350F/Gas 4.
Leave the cheese in the boxes and score around the top about 5mm/¼in in and cut off the top layer of skin.
Drizzle the oil over the cheeses and place in the oven for 15-20 minutes, or until oozy in the middle.
In the meantime, heat a large frying pan and, once hot, add the butter. Add the breadcrumbs and thyme to the pan and cook until golden-brown and toasted. Top the cheese with the breadcrumbs.
For the deep-fried blue cheese beignets and seasonal vegetables, preheat a deep-fat fryer to 190C/375F. (CAUTION: hot oil can be dangerous. Do not leave unattended.) Place 125ml/4fl oz water and the butter into a saucepan and bring to a rolling boil for a minute.
Remove the pan from the heat and add the flour, beating well until the mixture is smooth and comes away from the sides of the pan.
Return to the heat for a minute or two to cook the flour out.
Remove from the heat again and add the eggs, one at a time, beating well between the addition of each egg.
Add the crumbled Stilton and mix well. Season with salt and freshly ground black pepper.
Drop teaspoonfuls of the batter into the deep-fat fryer and fry for 2-3 minutes, or until golden-brown and crisp (you may need to do this in batches).
Remove the beignets from the oil with a slotted spoon and set aside to drain on a plate lined with kitchen paper. Season with a little salt.
Meanwhile heat a large saucepan of boiling water and cook the vegetables to your liking. Drain.
To serve, place the baked cheeses on a large serving plate and place the beignets and vegetables alongside.


Employee Management System
HOME
List
Employee ID
1
First Name
Jack
Last Name
B
E-mail
B
Department
B
Start Date
2017-03-12
Salary
25,000


Ruleset Naming Rules
Language -
Description
The Naming Ruleset contains a collection of rules about names - too long, too short, and so forth.
Rule ShortVariable::
TOC
Description
Detects when a field, local, or parameter has a very short name.
- Message
- Avoid variables with short names like {0}
- Class
- net.sourceforge.pmd.rules.XPathRule
- Reference
- -
- ExternalInfoUrl
- http://pmd.sourceforge.net/rules/naming.html#ShortVariable
- TypeResolution
- -
- Priority
- 3
Example
Example code snippet of this rule.
public class Something {
private int q = 15; // VIOLATION - Field
public static void main( String as[] ) { // VIOLATION - Formal
int r = 20 + q; // VIOLATION - Local
for (int i = 0; i < 10; i++) { // Not a Violation (inside FOR)
r += q;
}
}
}
Properties
Following properties are defined:
- Name
- xpath
- Description
- -
- Value
-
//VariableDeclaratorId[string-length(@Image) < 3]
[not(ancestor::ForInit)]
[not((ancestor::FormalParameter) and (ancestor::TryStatement))]
TOC
Rule LongVariable::
TOC
Description
Detects when a field, formal or local variable is declared with a long name.
- Message
- Avoid excessively long variable names like {0}
- Class
- net.sourceforge.pmd.rules.XPathRule
- Reference
- -
- ExternalInfoUrl
- http://pmd.sourceforge.net/rules/naming.html#LongVariable
- TypeResolution
- -
- Priority
- 3
Example
Example code snippet of this rule.
public class Something {
int reallyLongIntName = -3; // VIOLATION - Field
public static void main( String argumentsList[] ) { // VIOLATION - Formal
int otherReallyLongName = -5; // VIOLATION - Local
for (int interestingIntIndex = 0; // VIOLATION - For
interestingIntIndex < 10;
interestingIntIndex ++ ) {
}
}
Properties
Following properties are defined:
- Name
- minimum
- Description
- The variable length reporting threshold
- Value
-
17
- Name
- xpath
- Description
- -
- Value
-
//VariableDeclaratorId[string-length(@Image) > $minimum]
TOC
Rule ShortMethodName::
TOC
Description
Detects when very short method names are used.
- Message
- Avoid using short method names
- Class
- net.sourceforge.pmd.rules.XPathRule
- Reference
- -
- ExternalInfoUrl
- http://pmd.sourceforge.net/rules/naming.html#ShortMethodName
- TypeResolution
- -
- Priority
- 3
Example
Example code snippet of this rule.
public class ShortMethod {
public void a( int i ) { // Violation
}
}
Properties
Following properties are defined:
- Name
- xpath
- Description
- -
- Value
-
//MethodDeclarator[string-length(@Image) < 3]
TOC
Rule VariableNamingConventions::
TOC
Description
A variable naming conventions rule - customize this to your liking. Currently, it
checks for final variables that should be fully capitalized and non-final variables
that should not include underscores.
- Message
- {0} variable {1} should begin with {2}
- Class
- net.sourceforge.pmd.rules.VariableNamingConventions
- Reference
- -
- ExternalInfoUrl
- http://pmd.sourceforge.net/rules/naming.html#VariableNamingConventions
- TypeResolution
- -
- Priority
- 1
Example
Example code snippet of this rule.
public class Foo {
public static final int MY_NUM = 0;
public String myTest = "";
DataModule dmTest = new DataModule();
}
Properties
Following properties are defined:
- Name
- staticPrefix
- Description
- A prefix for static variables
- Value
-
- Name
- staticSuffix
- Description
- A suffix for static variables
- Value
-
- Name
- memberPrefix
- Description
- A prefix for member variables
- Value
-
- Name
- memberSuffix
- Description
- A suffix for member variables
- Value
-
TOC
Rule MethodNamingConventions::
TOC
Description
Method names should always begin with a lower case character, and should not contain underscores.
- Message
- Method name does not begin with a lower case character.
- Class
- net.sourceforge.pmd.rules.MethodNamingConventions
- Reference
- -
- ExternalInfoUrl
- http://pmd.sourceforge.net/rules/naming.html#MethodNamingConventions
- TypeResolution
- -
- Priority
- 1
Example
Example code snippet of this rule.
public class Foo {
public void fooStuff() {
}
}
TOC
Rule ClassNamingConventions::
TOC
Description
Class names should always begin with an upper case character.
- Message
- Class names should begin with an uppercase character
- Class
- net.sourceforge.pmd.rules.ClassNamingConventions
- Reference
- -
- ExternalInfoUrl
- http://pmd.sourceforge.net/rules/naming.html#ClassNamingConventions
- TypeResolution
- -
- Priority
- 1
Example
Example code snippet of this rule.
public class Foo {}
TOC
Rule AbstractNaming::
TOC
Description
Abstract classes should be named 'AbstractXXX'.
- Message
- Abstract classes should be named 'AbstractXXX'
- Class
- net.sourceforge.pmd.rules.XPathRule
- Reference
- -
- ExternalInfoUrl
- http://pmd.sourceforge.net/rules/naming.html#AbstractNaming
- TypeResolution
- -
- Priority
- 3
Example
Example code snippet of this rule.
public abstract class Foo { // should be AbstractFoo
}
Properties
Following properties are defined:
- Name
- xpath
- Description
- -
- Value
-
//ClassOrInterfaceDeclaration
[@Abstract='true' and @Interface='false']
[not (starts-with(@Image,'Abstract'))]
TOC
Rule AvoidDollarSigns::
TOC
Description
Avoid using dollar signs in variable/method/class/interface names.
- Message
- Avoid using dollar signs in variable/method/class/interface names
- Class
- net.sourceforge.pmd.rules.naming.AvoidDollarSigns
- Reference
- -
- ExternalInfoUrl
- http://pmd.sourceforge.net/rules/naming.html#AvoidDollarSigns
- TypeResolution
- -
- Priority
- 3
Example
Example code snippet of this rule.
public class Fo$o { // yikes!
}
TOC
Rule MethodWithSameNameAsEnclosingClass::
TOC
Description
Non-constructor methods should not have the same name as the enclosing class.
- Message
- Classes should not have non-constructor methods with the same name as the class
- Class
- net.sourceforge.pmd.rules.MethodWithSameNameAsEnclosingClass
- Reference
- -
- ExternalInfoUrl
- http://pmd.sourceforge.net/rules/naming.html#MethodWithSameNameAsEnclosingClass
- TypeResolution
- -
- Priority
- 3
Example
Example code snippet of this rule.
public class MyClass {
// this is bad because it is a method
public void MyClass() {}
// this is OK because it is a constructor
public MyClass() {}
}
TOC
Rule SuspiciousHashcodeMethodName::
TOC
Description
The method name and return type are suspiciously close to hashCode(), which
may mean you are intending to override the hashCode() method.
- Message
- The method name and return type are suspiciously close to hashCode()
- Class
- net.sourceforge.pmd.rules.naming.SuspiciousHashcodeMethodName
- Reference
- -
- ExternalInfoUrl
- http://pmd.sourceforge.net/rules/naming.html#SuspiciousHashcodeMethodName
- TypeResolution
- -
- Priority
- 3
Example
Example code snippet of this rule.
public class Foo {
public int hashcode() {
// oops, this probably was supposed to be hashCode
}
}
TOC
Rule SuspiciousConstantFieldName::
TOC
Description
A field name is all in uppercase characters, which in Sun's Java naming
conventions indicate a constant. However, the field is not final.
- Message
- The field name indicates a constant but its modifiers do not
- Class
- net.sourceforge.pmd.rules.XPathRule
- Reference
- -
- ExternalInfoUrl
- http://pmd.sourceforge.net/rules/naming.html#SuspiciousConstantFieldName
- TypeResolution
- -
- Priority
- 3
Example
Example code snippet of this rule.
public class Foo {
// this is bad, since someone could accidentally
// do PI = 2.71828; which is actualy e
// final double PI = 3.16; is ok
double PI = 3.16;
}
Properties
Following properties are defined:
- Name
- xpath
- Description
- -
- Value
-
//ClassOrInterfaceDeclaration[@Interface='false']
/ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/FieldDeclaration
[@Final='false']
[VariableDeclarator/VariableDeclaratorId[upper-case(@Image)=@Image]]
TOC
Rule SuspiciousEqualsMethodName::
TOC
Description
The method name and parameter number are suspiciously close to
equals(Object), which may mean you are intending to override the equals(Object)
method.
- Message
- The method name and parameter number are suspiciously close to equals(Object)
- Class
- net.sourceforge.pmd.rules.XPathRule
- Reference
- -
- ExternalInfoUrl
- http://pmd.sourceforge.net/rules/naming.html#SuspiciousEqualsMethodName
- TypeResolution
- -
- Priority
- 2
Example
Example code snippet of this rule.
public class Foo {
public int equals(Object o) {
// oops, this probably was supposed to be boolean equals
}
public boolean equals(String s) {
// oops, this probably was supposed to be equals(Object)
}
}
Properties
Following properties are defined:
- Name
- xpath
- Description
- -
- Value
-
//MethodDeclarator[
(
@Image = 'equals'
and count(FormalParameters/*) = 1
and not (FormalParameters/FormalParameter/Type/ReferenceType/ClassOrInterfaceType
[@Image = 'Object' or @Image = 'java.lang.Object'])
)
or
@Image='equal'
and count(FormalParameters/*) = 1
and (FormalParameters/FormalParameter/Type/ReferenceType/ClassOrInterfaceType
[@Image = 'Object' or @Image = 'java.lang.Object'])
]
TOC
Rule AvoidFieldNameMatchingTypeName::
TOC
Description
It is somewhat confusing to have a field name matching the declaring class name.
This probably means that type and or field names could be more precise.
- Message
- It is somewhat confusing to have a field name matching the declaring class name
- Class
- net.sourceforge.pmd.rules.AvoidFieldNameMatchingTypeName
- Reference
- -
- ExternalInfoUrl
- http://pmd.sourceforge.net/rules/naming.html#AvoidFieldNameMatchingTypeName
- TypeResolution
- -
- Priority
- 3
Example
Example code snippet of this rule.
public class Foo extends Bar {
// There's probably a better name for foo
int foo;
}
TOC
Rule AvoidFieldNameMatchingMethodName::
TOC
Description
It is somewhat confusing to have a field name with the same name as a method.
While this is totally legal, having information (field) and actions (method) is
not clear naming.
- Message
- It is somewhat confusing to have a field name with the same name as a method
- Class
- net.sourceforge.pmd.rules.AvoidFieldNameMatchingMethodName
- Reference
- -
- ExternalInfoUrl
- http://pmd.sourceforge.net/rules/naming.html#AvoidFieldNameMatchingMethodName
- TypeResolution
- -
- Priority
- 3
Example
Example code snippet of this rule.
public class Foo {
Object bar;
// bar is data or an action or both?
void bar() {
}
}
TOC
Rule AvoidNonConstructorMethodsWithClassName::
TOC
Description
It is very easy to confuse methods with classname with constructors. It is preferrable
to name these non-constructor methods in a different way.
- Message
- Method {0} is not a constructor but it can be confused with one
- Class
- net.sourceforge.pmd.rules.AvoidNonConstructorMethodsWithClassName
- Reference
- -
- ExternalInfoUrl
- http://pmd.sourceforge.net/rules/naming.html#AvoidNonConstructorMethodsWithClassName
- TypeResolution
- -
- Priority
- 3
Example
Example code snippet of this rule.
public class Foo {
public void Foo() {
// not a constructor, just a poorly named method
}
}
TOC
Rule NoPackage::
TOC
Description
Detects when a class or interface does not have a package definition.
- Message
- All classes and interfaces must belong to a named package
- Class
- net.sourceforge.pmd.rules.XPathRule
- Reference
- -
- ExternalInfoUrl
- http://pmd.sourceforge.net/rules/naming.html#NoPackage
- TypeResolution
- -
- Priority
- 3
Example
Example code snippet of this rule.
// no package declaration
public class ClassInDefaultPackage {
}
Properties
Following properties are defined:
- Name
- xpath
- Description
- -
- Value
-
//ClassOrInterfaceDeclaration[count(preceding::PackageDeclaration) = 0]
TOC
Rule PackageCase::
TOC
Description
Detects when a package definition contains upper case characters.
- Message
- Package name contains upper case characters
- Class
- net.sourceforge.pmd.rules.XPathRule
- Reference
- -
- ExternalInfoUrl
- http://pmd.sourceforge.net/rules/naming.html#PackageCase
- TypeResolution
- -
- Priority
- 3
Example
Example code snippet of this rule.
package com.MyCompany; // <- should be lower case name
public class SomeClass {
}
Properties
Following properties are defined:
- Name
- xpath
- Description
- -
- Value
-
//PackageDeclaration/Name[lower-case(@Image)!=@Image]
TOC
Rule MisleadingVariableName::
TOC
Description
Detects when a non-field has a name starting with 'm_'. This usually
indicates a field and thus is confusing.
- Message
- Avoid naming non-fields with the prefix 'm_'
- Class
- net.sourceforge.pmd.rules.XPathRule
- Reference
- -
- ExternalInfoUrl
- http://pmd.sourceforge.net/rules/naming.html#MisleadingVariableName
- TypeResolution
- -
- Priority
- 3
Example
Example code snippet of this rule.
public class Foo {
private int m_foo; // OK
public void bar(String m_baz) { // Bad
int m_boz = 42; // Bad
}
}
Properties
Following properties are defined:
- Name
- xpath
- Description
- -
- Value
-
//VariableDeclaratorId
[starts-with(@Image, 'm_')]
[not (../../../FieldDeclaration)]
TOC


--- layout: page title: "Experience" description: "My research and work experience" header-img: "img/post-bg-exp.jpg" ---
I'm a research engineer with over ten years experience in the field of computer vision.
In 2009 I received my bachelor degree in Software Engineering. In the same year, I completed my undergraduate thesis on "Virtual Campus", where basic image processing and 3D modelling tools were used to build this virtual reality system: Virtual Campus
I started my PhD study from 2010 and received the degree from University of New South Wales in late 2013, where my research has been focused on using computer vision and photogrammetry technologies for 3D mapping and visual navigation: Vision-based Navigation
I joined High Resolution Plant Phenomics Centre (HRPPC), Agriculture Flagship, CSIRO in 2014. As a software engineer (research) in their R&D team, I was mainly responsible for developing software to process, analysis and understand visual information collected from various plant phenotyping platforms, including helicopter&UAV, field robotics and controlled environment imaging platforms, etc. I participated in several projects and here I listed two main projects I led and published: Stereo Reconstruction of Small Plants and Plant Height Estimation from Aerial Platforms.
Currently I returned to UNSW as a postdoctoral research associate. My current research project is using deep learning based video analysis to build intelligent surveillance systems, focusing on pedestrian detection, tracking and human action recognition.


Note that by design anyone can read these cookies, so you shouldn't store sensitive data in them. Also note that the cookie server works by setting so-called third-party cookies, so a browser set to block those won't be able to use this tool.
To use this protocol, just load
the cookie-service.js script. You can
then call CookieService.setCookie("cookiename", data)
to
store some data in the cookie, and
CookieService.getCookie("cookiename", callback)
to
specify that the function callback should be invoked with the current
cookie data as its sole argument. Note that since asynchronous
messaging is used, a callback must be used to receive the value of a cookie.
How does it work? The cookie is associated with this cookie-server.html page. cookie-server.html loads cookie-server.js which implements the cookie server. It listens for window.postMessage events asking it to get/set the cookie value; it does so by accessing the cookie and using window.postMessage to return the result if necessary.
Below is a small inspection screen for testing the library. Type to change the clipboard cookie; or click "refresh" to update/paste from the clipboard after changing the clipboard elsewhere:


adv = advantages - state_values
// Update averaged advantage norm.
policy.ma_adv_norm.add_(
1e-6 * (torch.mean(torch.pow(adv, 2.0)) - policy.ma_adv_norm))
// //xponentially weighted advantages.
exp_advs = torch.exp(policy.config["beta"] *
(adv / (1e-8 + torch.pow(policy.ma_adv_norm, 0.5))))
// Advantage estimation.
adv = advantages - state_values
adv_squared = torch.mean(torch.pow(adv, 2.0))
// Value loss.
policy.v_loss = 0.5 * adv_squared


{% extends 'base.html' %} {% block styles %} {% endblock %} {% block content %}
Food packing can be one of the most difficult parts of trip planning. Backcountry meal planner was created to simplify the process and provide information about meals and ingredients. It uses a meal based system to calculate food quantities, so you don’t end up carrying extra weight or run out of food. It is designed for fast and light solo trips as well as large group expeditions. Nutrition data is available for each meal, so food can be planned based on calories. Dietary info such as vegetarian, vegan, and gluten-free is also available for each meal, to simplify meal planning for group expeditions.


Example: Node Types
Used shared configuration per node type.
See the
Node Type Tutorial
for details.
Skin:
Fancytree project home
Link to this page
Example Browser
View source code


The operations of set_union, set_intersection, and set_difference were all described in Section 8.2.7 when we discussed the set container class. However, the algorithms that implement these operations are generic, and applicable to any ordered data structure. The algorithms assume the input ranges are ordered collections that represent multisets; that is, elements can be repeated. However, if the inputs represent sets, then the result will always be a set. Unlike the std::merge() algorithm, none of the set algorithms produce repeated elements in the output that are not present in the input sets.
The set operations all have the same format. The two input sets are specified by pairs of input iterators. The output set is specified by an input iterator, and the end of this range is returned as the result value. An optional comparison operator is the final argument. In all cases it is required that the output sequence not overlap in any manner with either of the input sequences.
namespace std { OutputIterator set_union (InputIterator first1, InputIterator last1, InputIterator first2, InputIterator last2, OutputIterator result [, Compare ] ); }
The example program illustrates the use of the four set algorithms, std::set_union(), std::set_intersection(), std::set_difference(), and std::set_symmetric_difference(). It also shows a call on std::merge() in order to contrast the merge and the set union operations. The algorithm std::includes() is slightly different. Again the two input sets are specified by pairs of input iterators, and the comparison operator is an optional fifth argument. The return value for the algorithm is true if the first set is entirely included in the second, and false otherwise.
void set_example() // illustrates the use of the generic set algorithms // see alg7.cpp for complete source code { std::ostream_iterator<int> intOut(cout, " "); // make a couple of ordered lists std::list<int> listOne, listTwo; std::generate_n(std::inserter(listOne, listOne.begin()), 5, iotaGen(1)); std::generate_n(std::inserter(listTwo, listTwo.begin()), 5, iotaGen(3)); // now do the set operations // union - 1 2 3 4 5 6 7 std::set_union(listOne.begin(), listOne.end(), listTwo.begin(), listTwo.end(), intOut); std::cout << std::endl; // merge - 1 2 3 3 4 4 5 5 6 7 std::merge(listOne.begin(), listOne.end(), listTwo.begin(), listTwo.end(), intOut); std::cout << std::endl; // intersection - 3 4 5 std::set_intersection(listOne.begin(), listOne.end(), listTwo.begin(), listTwo.end(), intOut); std::cout << std::endl; // difference - 1 2 std::set_difference(listOne.begin(), listOne.end(), listTwo.begin(), listTwo.end(), intOut); std::cout << std::endl; // symmetric difference - 1 2 6 7 std::set_symmetric_difference(listOne.begin(), listOne.end(), listTwo.begin(), listTwo.end(), intOut); std::cout << std::endl; if (std::includes(listOne.begin(), listOne.end(), listTwo.begin(), listTwo.end())) std::cout << "set is subset" << std::endl; else std::cout << "set is not subset" << std::endl; }


Fetching data from IRIS servers...
Seismokraft is a web-based seismic sonification application currently under development.
track the progress of Seismokraft


--- layout: post title: Ode to Eddie Izzard ---
I have to agree with Cyrus on that one… I fell in love with this comedian a few weeks ago, with the sexy show…
And notice how when he dresses up as a woman, he’s neither man nor woman, can’t call it a drag queen or a proper transvestite either… He’s redefining it by wearing heels.
(This post has been done off line and its delivery may be delayed.)


(Chapter written by Jérôme Vouillon, Didier Rémy and Jacques Garrigue)
This chapter gives an overview of the object-oriented features of Objective Caml. Note that the relation between object, class and type in Objective Caml is very different from that in main stream object-oriented languages like Java or C++, so that you should not assume that similar keywords mean the same thing.
3.1 Classes and objects
3.2 Immediate objects
3.3 Reference to self
3.4 Initializers
3.5 Virtual methods
3.6 Private methods
3.7 Class interfaces
3.8 Inheritance
3.9 Multiple inheritance
3.10 Parameterized classes
3.11 Polymorphic methods
3.12 Using coercions
3.13 Functional objects
3.14 Cloning objects
3.15 Recursive classes
3.16 Binary methods
3.17 Friends
The class point below defines one instance variable x and two methods get_x and move. The initial value of the instance variable is 0. The variable x is declared mutable, so the method move can change its value.
#class point = object val mutable x = 0 method get_x = x method move d = x <- x + d end;; class point : object val mutable x : int method get_x : int method move : int -> unit end
We now create a new point p, instance of the point class.
#let p = new point;; val p : point = <obj>
Note that the type of p is point. This is an abbreviation automatically defined by the class definition above. It stands for the object type <get_x : int; move : int -> unit>, listing the methods of class point along with their types.
We now invoke some methods to p:
#p#get_x;; - : int = 0 #p#move 3;; - : unit = () #p#get_x;; - : int = 3
The evaluation of the body of a class only takes place at object creation time. Therefore, in the following example, the instance variable x is initialized to different values for two different objects.
#let x0 = ref 0;; val x0 : int ref = {contents = 0} #class point = object val mutable x = incr x0; !x0 method get_x = x method move d = x <- x + d end;; class point : object val mutable x : int method get_x : int method move : int -> unit end #new point#get_x;; - : int = 1 #new point#get_x;; - : int = 2
The class point can also be abstracted over the initial values of the x coordinate.
#class point = fun x_init -> object val mutable x = x_init method get_x = x method move d = x <- x + d end;; class point : int -> object val mutable x : int method get_x : int method move : int -> unit end
Like in function definitions, the definition above can be abbreviated as:
#class point x_init = object val mutable x = x_init method get_x = x method move d = x <- x + d end;; class point : int -> object val mutable x : int method get_x : int method move : int -> unit end
An instance of the class point is now a function that expects an initial parameter to create a point object:
#new point;; - : int -> point = <fun> #let p = new point 7;; val p : point = <obj>
The parameter x_init is, of course, visible in the whole body of the definition, including methods. For instance, the method get_offset in the class below returns the position of the object relative to its initial position.
#class point x_init = object val mutable x = x_init method get_x = x method get_offset = x - x_init method move d = x <- x + d end;; class point : int -> object val mutable x : int method get_offset : int method get_x : int method move : int -> unit end
Expressions can be evaluated and bound before defining the object body of the class. This is useful to enforce invariants. For instance, points can be automatically adjusted to the nearest point on a grid, as follows:
#class adjusted_point x_init = let origin = (x_init / 10) * 10 in object val mutable x = origin method get_x = x method get_offset = x - origin method move d = x <- x + d end;; class adjusted_point : int -> object val mutable x : int method get_offset : int method get_x : int method move : int -> unit end
(One could also raise an exception if the x_init coordinate is not on the grid.) In fact, the same effect could here be obtained by calling the definition of class point with the value of the origin.
#class adjusted_point x_init = point ((x_init / 10) * 10);; class adjusted_point : int -> point
An alternative solution would have been to define the adjustment in a special allocation function:
#let new_adjusted_point x_init = new point ((x_init / 10) * 10);; val new_adjusted_point : int -> point = <fun>
However, the former pattern is generally more appropriate, since the code for adjustment is part of the definition of the class and will be inherited.
This ability provides class constructors as can be found in other languages. Several constructors can be defined this way to build objects of the same class but with different initialization patterns; an alternative is to use initializers, as decribed below in section 3.4.
There is another, more direct way to create an object: create it without going through a class.
The syntax is exactly the same as for class expressions, but the result is a single object rather than a class. All the constructs described in the rest of this section also apply to immediate objects.
#let p = object val mutable x = 0 method get_x = x method move d = x <- x + d end;; val p : < get_x : int; move : int -> unit > = <obj> #p#get_x;; - : int = 0 #p#move 3;; - : unit = () #p#get_x;; - : int = 3
Unlike classes, which cannot be defined inside an expression, immediate objects can appear anywhere, using variables from their environment.
#let minmax x y = if x < y then object method min = x method max = y end else object method min = y method max = x end;; val minmax : ’a -> ’a -> < max : ’a; min : ’a > = <fun>
Immediate objects have two weaknesses compared to classes: their types are not abbreviated, and you cannot inherit from them. But these two weaknesses can be advantages in some situations, as we will see in sections 3.3 and 3.10.
A method or an initializer can send messages to self (that is, the current object). For that, self must be explicitly bound, here to the variable s (s could be any identifier, even though we will often choose the name self.)
#class printable_point x_init = object (s) val mutable x = x_init method get_x = x method move d = x <- x + d method print = print_int s#get_x end;; class printable_point : int -> object val mutable x : int method get_x : int method move : int -> unit method print : unit end #let p = new printable_point 7;; val p : printable_point = <obj> #p#print;; 7- : unit = ()
Dynamically, the variable s is bound at the invocation of a method. In particular, when the class printable_point is inherited, the variable s will be correctly bound to the object of the subclass.
A common problem with self is that, as its type may be extended in subclasses, you cannot fix it in advance. Here is a simple example.
#let ints = ref [];; val ints : ’_a list ref = {contents = []} #class my_int = object (self) method n = 1 method register = ints := self :: !ints end;; Error: This expression has type < n : int; register : ’a; .. > but an expression was expected of type ’b Self type cannot escape its class
You can ignore the first two lines of the error message. What matters is the last one: putting self into an external reference would make it impossible to extend it afterwards. We will see in section 3.12 a workaround to this problem. Note however that, since immediate objects are not extensible, the problem does not occur with them.
#let my_int = object (self) method n = 1 method register = ints := self :: !ints end;; val my_int : < n : int; register : unit > = <obj>
Let-bindings within class definitions are evaluated before the object is constructed. It is also possible to evaluate an expression immediately after the object has been built. Such code is written as an anonymous hidden method called an initializer. Therefore, it can access self and the instance variables.
#class printable_point x_init = let origin = (x_init / 10) * 10 in object (self) val mutable x = origin method get_x = x method move d = x <- x + d method print = print_int self#get_x initializer print_string "new point at "; self#print; print_newline() end;; class printable_point : int -> object val mutable x : int method get_x : int method move : int -> unit method print : unit end #let p = new printable_point 17;; new point at 10 val p : printable_point = <obj>
Initializers cannot be overridden. On the contrary, all initializers are evaluated sequentially. Initializers are particularly useful to enforce invariants. Another example can be seen in section 5.1.
It is possible to declare a method without actually defining it, using the keyword virtual. This method will be provided later in subclasses. A class containing virtual methods must be flagged virtual, and cannot be instantiated (that is, no object of this class can be created). It still defines type abbreviations (treating virtual methods as other methods.)
#class virtual abstract_point x_init = object (self) method virtual get_x : int method get_offset = self#get_x - x_init method virtual move : int -> unit end;; class virtual abstract_point : int -> object method get_offset : int method virtual get_x : int method virtual move : int -> unit end #class point x_init = object inherit abstract_point x_init val mutable x = x_init method get_x = x method move d = x <- x + d end;; class point : int -> object val mutable x : int method get_offset : int method get_x : int method move : int -> unit end
Instance variables can also be declared as virtual, with the same effect as with methods.
#class virtual abstract_point2 = object val mutable virtual x : int method move d = x <- x + d end;; class virtual abstract_point2 : object val mutable virtual x : int method move : int -> unit end #class point2 x_init = object inherit abstract_point2 val mutable x = x_init method get_offset = x - x_init end;; class point2 : int -> object val mutable x : int method get_offset : int method move : int -> unit end
Private methods are methods that do not appear in object interfaces. They can only be invoked from other methods of the same object.
#class restricted_point x_init = object (self) val mutable x = x_init method get_x = x method private move d = x <- x + d method bump = self#move 1 end;; class restricted_point : int -> object val mutable x : int method bump : unit method get_x : int method private move : int -> unit end #let p = new restricted_point 0;; val p : restricted_point = <obj> #p#move 10;; Error: This expression has type restricted_point It has no method move #p#bump;; - : unit = ()
Note that this is not the same thing as private and protected methods in Java or C++, which can be called from other objects of the same class. This is a direct consequence of the independence between types and classes in Objective Caml: two unrelated classes may produce objects of the same type, and there is no way at the type level to ensure that an object comes from a specific class. However a possible encoding of friend methods is given in section 3.17.
Private methods are inherited (they are by default visible in subclasses), unless they are hidden by signature matching, as described below.
Private methods can be made public in a subclass.
#class point_again x = object (self) inherit restricted_point x method virtual move : _ end;; class point_again : int -> object val mutable x : int method bump : unit method get_x : int method move : int -> unit end
The annotation virtual here is only used to mention a method without providing its definition. Since we didn’t add the private annotation, this makes the method public, keeping the original definition.
An alternative definition is
#class point_again x = object (self : < move : _; ..> ) inherit restricted_point x end;; class point_again : int -> object val mutable x : int method bump : unit method get_x : int method move : int -> unit end
The constraint on self’s type is requiring a public move method, and this is sufficient to override private.
One could think that a private method should remain private in a subclass. However, since the method is visible in a subclass, it is always possible to pick its code and define a method of the same name that runs that code, so yet another (heavier) solution would be:
#class point_again x = object inherit restricted_point x as super method move = super#move end;; class point_again : int -> object val mutable x : int method bump : unit method get_x : int method move : int -> unit end
Of course, private methods can also be virtual. Then, the keywords must appear in this order method private virtual.
Class interfaces are inferred from class definitions. They may also be defined directly and used to restrict the type of a class. Like class declarations, they also define a new type abbreviation.
#class type restricted_point_type = object method get_x : int method bump : unit end;; class type restricted_point_type = object method bump : unit method get_x : int end #fun (x : restricted_point_type) -> x;; - : restricted_point_type -> restricted_point_type = <fun>
In addition to program documentation, class interfaces can be used to constrain the type of a class. Both concrete instance variables and concrete private methods can be hidden by a class type constraint. Public methods and virtual members, however, cannot.
#class restricted_point’ x = (restricted_point x : restricted_point_type);; class restricted_point’ : int -> restricted_point_type
Or, equivalently:
#class restricted_point’ = (restricted_point : int -> restricted_point_type);; class restricted_point’ : int -> restricted_point_type
The interface of a class can also be specified in a module signature, and used to restrict the inferred signature of a module.
#module type POINT = sig class restricted_point’ : int -> object method get_x : int method bump : unit end end;; module type POINT = sig class restricted_point’ : int -> object method bump : unit method get_x : int end end #module Point : POINT = struct class restricted_point’ = restricted_point end;; module Point : POINT
We illustrate inheritance by defining a class of colored points that inherits from the class of points. This class has all instance variables and all methods of class point, plus a new instance variable c and a new method color.
#class colored_point x (c : string) = object inherit point x val c = c method color = c end;; class colored_point : int -> string -> object val c : string val mutable x : int method color : string method get_offset : int method get_x : int method move : int -> unit end #let p’ = new colored_point 5 "red";; val p’ : colored_point = <obj> #p’#get_x, p’#color;; - : int * string = (5, "red")
A point and a colored point have incompatible types, since a point has no method color. However, the function get_x below is a generic function applying method get_x to any object p that has this method (and possibly some others, which are represented by an ellipsis in the type). Thus, it applies to both points and colored points.
#let get_succ_x p = p#get_x + 1;; val get_succ_x : < get_x : int; .. > -> int = <fun> #get_succ_x p + get_succ_x p’;; - : int = 8
Methods need not be declared previously, as shown by the example:
#let set_x p = p#set_x;; val set_x : < set_x : ’a; .. > -> ’a = <fun> #let incr p = set_x p (get_succ_x p);; val incr : < get_x : int; set_x : int -> ’a; .. > -> ’a = <fun>
Multiple inheritance is allowed. Only the last definition of a method is kept: the redefinition in a subclass of a method that was visible in the parent class overrides the definition in the parent class. Previous definitions of a method can be reused by binding the related ancestor. Below, super is bound to the ancestor printable_point. The name super is a pseudo value identifier that can only be used to invoke a super-class method, as in super#print.
#class printable_colored_point y c = object (self) val c = c method color = c inherit printable_point y as super method print = print_string "("; super#print; print_string ", "; print_string (self#color); print_string ")" end;; class printable_colored_point : int -> string -> object val c : string val mutable x : int method color : string method get_x : int method move : int -> unit method print : unit end #let p’ = new printable_colored_point 17 "red";; new point at (10, red) val p’ : printable_colored_point = <obj> #p’#print;; (10, red)- : unit = ()
A private method that has been hidden in the parent class is no longer visible, and is thus not overridden. Since initializers are treated as private methods, all initializers along the class hierarchy are evaluated, in the order they are introduced.
Reference cells can be implemented as objects. The naive definition fails to typecheck:
#class ref x_init = object val mutable x = x_init method get = x method set y = x <- y end;; Error: Some type variables are unbound in this type: class ref : ’a -> object val mutable x : ’a method get : ’a method set : ’a -> unit end The method get has type ’a where ’a is unbound
The reason is that at least one of the methods has a polymorphic type (here, the type of the value stored in the reference cell), thus either the class should be parametric, or the method type should be constrained to a monomorphic type. A monomorphic instance of the class could be defined by:
#class ref (x_init:int) = object val mutable x = x_init method get = x method set y = x <- y end;; class ref : int -> object val mutable x : int method get : int method set : int -> unit end
Note that since immediate objects do not define a class type, they have no such restriction.
#let new_ref x_init = object val mutable x = x_init method get = x method set y = x <- y end;; val new_ref : ’a -> < get : ’a; set : ’a -> unit > = <fun>
On the other hand, a class for polymorphic references must explicitly list the type parameters in its declaration. Class type parameters are always listed between [ and ]. The type parameters must also be bound somewhere in the class body by a type constraint.
#class [’a] ref x_init = object val mutable x = (x_init : ’a) method get = x method set y = x <- y end;; class [’a] ref : ’a -> object val mutable x : ’a method get : ’a method set : ’a -> unit end #let r = new ref 1 in r#set 2; (r#get);; - : int = 2
The type parameter in the declaration may actually be constrained in the body of the class definition. In the class type, the actual value of the type parameter is displayed in the constraint clause.
#class [’a] ref_succ (x_init:’a) = object val mutable x = x_init + 1 method get = x method set y = x <- y end;; class [’a] ref_succ : ’a -> object constraint ’a = int val mutable x : int method get : int method set : int -> unit end
Let us consider a more complex example: define a circle, whose center may be any kind of point. We put an additional type constraint in method move, since no free variables must remain unaccounted for by the class type parameters.
#class [’a] circle (c : ’a) = object val mutable center = c method center = center method set_center c = center <- c method move = (center#move : int -> unit) end;; class [’a] circle : ’a -> object constraint ’a = < move : int -> unit; .. > val mutable center : ’a method center : ’a method move : int -> unit method set_center : ’a -> unit end
An alternate definition of circle, using a constraint clause in the class definition, is shown below. The type #point used below in the constraint clause is an abbreviation produced by the definition of class point. This abbreviation unifies with the type of any object belonging to a subclass of class point. It actually expands to < get_x : int; move : int -> unit; .. >. This leads to the following alternate definition of circle, which has slightly stronger constraints on its argument, as we now expect center to have a method get_x.
#class [’a] circle (c : ’a) = object constraint ’a = #point val mutable center = c method center = center method set_center c = center <- c method move = center#move end;; class [’a] circle : ’a -> object constraint ’a = #point val mutable center : ’a method center : ’a method move : int -> unit method set_center : ’a -> unit end
The class colored_circle is a specialized version of class circle that requires the type of the center to unify with #colored_point, and adds a method color. Note that when specializing a parameterized class, the instance of type parameter must always be explicitly given. It is again written between [ and ].
#class [’a] colored_circle c = object constraint ’a = #colored_point inherit [’a] circle c method color = center#color end;; class [’a] colored_circle : ’a -> object constraint ’a = #colored_point val mutable center : ’a method center : ’a method color : string method move : int -> unit method set_center : ’a -> unit end
While parameterized classes may be polymorphic in their contents, they are not enough to allow polymorphism of method use.
A classical example is defining an iterator.
#List.fold_left;; - : (’a -> ’b -> ’a) -> ’a -> ’b list -> ’a = <fun> #class [’a] intlist (l : int list) = object method empty = (l = []) method fold f (accu : ’a) = List.fold_left f accu l end;; class [’a] intlist : int list -> object method empty : bool method fold : (’a -> int -> ’a) -> ’a -> ’a end
At first look, we seem to have a polymorphic iterator, however this does not work in practice.
#let l = new intlist [1; 2; 3];; val l : ’_a intlist = <obj> #l#fold (fun x y -> x+y) 0;; - : int = 6 #l;; - : int intlist = <obj> #l#fold (fun s x -> s ^ string_of_int x ^ " ") "";; Error: This expression has type int but an expression was expected of type string
Our iterator works, as shows its first use for summation. However, since objects themselves are not polymorphic (only their constructors are), using the fold method fixes its type for this individual object. Our next attempt to use it as a string iterator fails.
The problem here is that quantification was wrongly located: this is not the class we want to be polymorphic, but the fold method. This can be achieved by giving an explicitly polymorphic type in the method definition.
#class intlist (l : int list) = object method empty = (l = []) method fold : ’a. (’a -> int -> ’a) -> ’a -> ’a = fun f accu -> List.fold_left f accu l end;; class intlist : int list -> object method empty : bool method fold : (’a -> int -> ’a) -> ’a -> ’a end #let l = new intlist [1; 2; 3];; val l : intlist = <obj> #l#fold (fun x y -> x+y) 0;; - : int = 6 #l#fold (fun s x -> s ^ string_of_int x ^ " ") "";; - : string = "1 2 3 "
As you can see in the class type shown by the compiler, while polymorphic method types must be fully explicit in class definitions (appearing immediately after the method name), quantified type variables can be left implicit in class descriptions. Why require types to be explicit? The problem is that (int -> int -> int) -> int -> int would also be a valid type for fold, and it happens to be incompatible with the polymorphic type we gave (automatic instantiation only works for toplevel types variables, not for inner quantifiers, where it becomes an undecidable problem.) So the compiler cannot choose between those two types, and must be helped.
However, the type can be completely omitted in the class definition if it is already known, through inheritance or type constraints on self. Here is an example of method overriding.
#class intlist_rev l = object inherit intlist l method fold f accu = List.fold_left f accu (List.rev l) end;;
The following idiom separates description and definition.
#class type [’a] iterator = object method fold : (’b -> ’a -> ’b) -> ’b -> ’b end;; class intlist l = object (self : int #iterator) method empty = (l = []) method fold f accu = List.fold_left f accu l end;;
Note here the (self : int #iterator) idiom, which ensures that this object implements the interface iterator.
Polymorphic methods are called in exactly the same way as normal methods, but you should be aware of some limitations of type inference. Namely, a polymorphic method can only be called if its type is known at the call site. Otherwise, the method will be assumed to be monomorphic, and given an incompatible type.
#let sum lst = lst#fold (fun x y -> x+y) 0;; val sum : < fold : (int -> int -> int) -> int -> ’a; .. > -> ’a = <fun> #sum l;; Error: This expression has type intlist but an expression was expected of type < fold : (int -> int -> int) -> int -> ’a; .. > Types for method fold are incompatible
The workaround is easy: you should put a type constraint on the parameter.
#let sum (lst : _ #iterator) = lst#fold (fun x y -> x+y) 0;; val sum : int #iterator -> int = <fun>
Of course the constraint may also be an explicit method type. Only occurences of quantified variables are required.
#let sum lst = (lst : < fold : ’a. (’a -> _ -> ’a) -> ’a -> ’a; .. >)#fold (+) 0;; val sum : < fold : ’a. (’a -> int -> ’a) -> ’a -> ’a; .. > -> int = <fun>
Another use of polymorphic methods is to allow some form of implicit subtyping in method arguments. We have already seen in section 3.8 how some functions may be polymorphic in the class of their argument. This can be extended to methods.
#class type point0 = object method get_x : int end;; class type point0 = object method get_x : int end #class distance_point x = object inherit point x method distance : ’a. (#point0 as ’a) -> int = fun other -> abs (other#get_x - x) end;; class distance_point : int -> object val mutable x : int method distance : #point0 -> int method get_offset : int method get_x : int method move : int -> unit end #let p = new distance_point 3 in (p#distance (new point 8), p#distance (new colored_point 1 "blue"));; - : int * int = (5, 2)
Note here the special syntax (#point0 as ’a) we have to use to quantify the extensible part of #point0. As for the variable binder, it can be omitted in class specifications. If you want polymorphism inside object field it must be quantified independently.
#class multi_poly = object method m1 : ’a. (< n1 : ’b. ’b -> ’b; .. > as ’a) -> _ = fun o -> o#n1 true, o#n1 "hello" method m2 : ’a ’b. (< n2 : ’b -> bool; .. > as ’a) -> ’b -> _ = fun o x -> o#n2 x end;; class multi_poly : object method m1 : < n1 : ’a. ’a -> ’a; .. > -> bool * string method m2 : < n2 : ’b -> bool; .. > -> ’b -> bool end
In method m1, o must be an object with at least a method n1, itself polymorphic. In method m2, the argument of n2 and x must have the same type, which is quantified at the same level as ’a.
Subtyping is never implicit. There are, however, two ways to perform subtyping. The most general construction is fully explicit: both the domain and the codomain of the type coercion must be given.
We have seen that points and colored points have incompatible types. For instance, they cannot be mixed in the same list. However, a colored point can be coerced to a point, hiding its color method:
#let colored_point_to_point cp = (cp : colored_point :> point);; val colored_point_to_point : colored_point -> point = <fun> #let p = new point 3 and q = new colored_point 4 "blue";; val p : point = <obj> val q : colored_point = <obj> #let l = [p; (colored_point_to_point q)];; val l : point list = [<obj>; <obj>]
An object of type t can be seen as an object of type t’ only if t is a subtype of t’. For instance, a point cannot be seen as a colored point.
#(p : point :> colored_point);; Error: Type point = < get_offset : int; get_x : int; move : int -> unit > is not a subtype of colored_point = < color : string; get_offset : int; get_x : int; move : int -> unit >
Indeed, narrowing coercions without runtime checks would be unsafe. Runtime type checks might raise exceptions, and they would require the presence of type information at runtime, which is not the case in the Objective Caml system. For these reasons, there is no such operation available in the language.
Be aware that subtyping and inheritance are not related. Inheritance is a syntactic relation between classes while subtyping is a semantic relation between types. For instance, the class of colored points could have been defined directly, without inheriting from the class of points; the type of colored points would remain unchanged and thus still be a subtype of points.
The domain of a coercion can often be omitted. For instance, one can define:
#let to_point cp = (cp :> point);; val to_point : #point -> point = <fun>
In this case, the function colored_point_to_point is an instance of the function to_point. This is not always true, however. The fully explicit coercion is more precise and is sometimes unavoidable. Consider, for example, the following class:
#class c0 = object method m = {< >} method n = 0 end;; class c0 : object (’a) method m : ’a method n : int end
The object type c0 is an abbreviation for <m : ’a; n : int> as ’a. Consider now the type declaration:
#class type c1 = object method m : c1 end;; class type c1 = object method m : c1 end
The object type c1 is an abbreviation for the type <m : ’a> as ’a. The coercion from an object of type c0 to an object of type c1 is correct:
#fun (x:c0) -> (x : c0 :> c1);; - : c0 -> c1 = <fun>
However, the domain of the coercion cannot be omitted here:
#fun (x:c0) -> (x :> c1);; - : c0 -> c1 = <fun>
The solution is to use the explicit form. Sometimes, a change in the class-type definition can also solve the problem
#class type c2 = object (’a) method m : ’a end;; class type c2 = object (’a) method m : ’a end #fun (x:c0) -> (x :> c2);; - : c0 -> c2 = <fun>
While class types c1 and c2 are different, both object types c1 and c2 expand to the same object type (same method names and types). Yet, when the domain of a coercion is left implicit and its co-domain is an abbreviation of a known class type, then the class type, rather than the object type, is used to derive the coercion function. This allows to leave the domain implicit in most cases when coercing form a subclass to its superclass. The type of a coercion can always be seen as below:
#let to_c1 x = (x :> c1);; val to_c1 : < m : #c1; .. > -> c1 = <fun> #let to_c2 x = (x :> c2);; val to_c2 : #c2 -> c2 = <fun>
Note the difference between the two coercions: in the second case, the type #c2 = < m : ’a; .. > as ’a is polymorphically recursive (according to the explicit recursion in the class type of c2); hence the success of applying this coercion to an object of class c0. On the other hand, in the first case, c1 was only expanded and unrolled twice to obtain < m : < m : c1; .. >; .. > (remember #c1 = < m : c1; .. >), without introducing recursion. You may also note that the type of to_c2 is #c2 -> c2 while the type of to_c1 is more general than #c1 -> c1. This is not always true, since there are class types for which some instances of #c are not subtypes of c, as explained in section 3.16. Yet, for parameterless classes the coercion (_ :> c) is always more general than (_ : #c :> c).
A common problem may occur when one tries to define a coercion to a class c while defining class c. The problem is due to the type abbreviation not being completely defined yet, and so its subtypes are not clearly known. Then, a coercion (_ :> c) or (_ : #c :> c) is taken to be the identity function, as in
#function x -> (x :> ’a);; - : ’a -> ’a = <fun>
As a consequence, if the coercion is applied to self, as in the following example, the type of self is unified with the closed type c (a closed object type is an object type without ellipsis). This would constrain the type of self be closed and is thus rejected. Indeed, the type of self cannot be closed: this would prevent any further extension of the class. Therefore, a type error is generated when the unification of this type with another type would result in a closed object type.
#class c = object method m = 1 end and d = object (self) inherit c method n = 2 method as_c = (self :> c) end;; Error: This expression cannot be coerced to type c = < m : int >; it has type < as_c : c; m : int; n : int; .. > but is here used with type c Self type cannot be unified with a closed object type
However, the most common instance of this problem, coercing self to its current class, is detected as a special case by the type checker, and properly typed.
#class c = object (self) method m = (self :> c) end;; class c : object method m : c end
This allows the following idiom, keeping a list of all objects belonging to a class or its subclasses:
#let all_c = ref [];; val all_c : ’_a list ref = {contents = []} #class c (m : int) = object (self) method m = m initializer all_c := (self :> c) :: !all_c end;; class c : int -> object method m : int end
This idiom can in turn be used to retrieve an object whose type has been weakened:
#let rec lookup_obj obj = function [] -> raise Not_found | obj’ :: l -> if (obj :> < >) = (obj’ :> < >) then obj’ else lookup_obj obj l ;; val lookup_obj : < .. > -> (< .. > as ’a) list -> ’a = <fun> #let lookup_c obj = lookup_obj obj !all_c;; val lookup_c : < .. > -> < m : int > = <fun>
The type < m : int > we see here is just the expansion of c, due to the use of a reference; we have succeeded in getting back an object of type c.
The previous coercion problem can often be avoided by first
defining the abbreviation, using a class type:
#class type c’ = object method m : int end;; class type c’ = object method m : int end #class c : c’ = object method m = 1 end and d = object (self) inherit c method n = 2 method as_c = (self :> c’) end;; class c : c’ and d : object method as_c : c’ method m : int method n : int end
It is also possible to use a virtual class. Inheriting from this class simultaneously allows to enforce all methods of c to have the same type as the methods of c’.
#class virtual c’ = object method virtual m : int end;; class virtual c’ : object method virtual m : int end #class c = object (self) inherit c’ method m = 1 end;; class c : object method m : int end
One could think of defining the type abbreviation directly:
#type c’ = <m : int>;;
However, the abbreviation #c’ cannot be defined directly in a similar way. It can only be defined by a class or a class-type definition. This is because # sharp abbreviations carry an implicit anonymous variable .. that cannot be explicitly named. The closer you get to it is:
#type ’a c’_class = ’a constraint ’a = < m : int; .. >;;
with an extra type variable capturing the open object type.
It is possible to write a version of class point without assignments on the instance variables. The construct {< ... >} returns a copy of “self” (that is, the current object), possibly changing the value of some instance variables.
#class functional_point y = object val x = y method get_x = x method move d = {< x = x + d >} end;; class functional_point : int -> object (’a) val x : int method get_x : int method move : int -> ’a end #let p = new functional_point 7;; val p : functional_point = <obj> #p#get_x;; - : int = 7 #(p#move 3)#get_x;; - : int = 10 #p#get_x;; - : int = 7
Note that the type abbreviation functional_point is recursive, which can be seen in the class type of functional_point: the type of self is ’a and ’a appears inside the type of the method move.
The above definition of functional_point is not equivalent to the following:
#class bad_functional_point y = object val x = y method get_x = x method move d = new bad_functional_point (x+d) end;; class bad_functional_point : int -> object val x : int method get_x : int method move : int -> bad_functional_point end
While objects of either class will behave the same, objects of their subclasses will be different. In a subclass of the latter, the method move will keep returning an object of the parent class. On the contrary, in a subclass of the former, the method move will return an object of the subclass.
Functional update is often used in conjunction with binary methods as illustrated in section 5.2.1.
Objects can also be cloned, whether they are functional or imperative. The library function Oo.copy makes a shallow copy of an object. That is, it returns an object that is equal to the previous one. The instance variables have been copied but their contents are shared. Assigning a new value to an instance variable of the copy (using a method call) will not affect instance variables of the original, and conversely. A deeper assignment (for example if the instance variable if a reference cell) will of course affect both the original and the copy.
The type of Oo.copy is the following:
#Oo.copy;; - : (< .. > as ’a) -> ’a = <fun>
The keyword as in that type binds the type variable ’a to the object type < .. >. Therefore, Oo.copy takes an object with any methods (represented by the ellipsis), and returns an object of the same type. The type of Oo.copy is different from type < .. > -> < .. > as each ellipsis represents a different set of methods. Ellipsis actually behaves as a type variable.
#let p = new point 5;; val p : point = <obj> #let q = Oo.copy p;; val q : point = <obj> #q#move 7; (p#get_x, q#get_x);; - : int * int = (5, 12)
In fact, Oo.copy p will behave as p#copy assuming that a public method copy with body {< >} has been defined in the class of p.
Objects can be compared using the generic comparison functions = and <>. Two objects are equal if and only if they are physically equal. In particular, an object and its copy are not equal.
#let q = Oo.copy p;; val q : point = <obj> #p = q, p = p;; - : bool * bool = (false, true)
Other generic comparissons such as (<, <=,...) can also be used on objects. The relation < defines an unspecified but strict ordering on objets. The ordering relationship between two objects is fixed once for all after the two objects have been created and it is not affected by mutation of fields.
Cloning and override have a non empty intersection. They are interchangeable when used within an object and without overriding any field:
#class copy = object method copy = {< >} end;; class copy : object (’a) method copy : ’a end #class copy = object (self) method copy = Oo.copy self end;; class copy : object (’a) method copy : ’a end
Only the override can be used to actually override fields, and only the Oo.copy primitive can be used externally.
Cloning can also be used to provide facilities for saving and restoring the state of objects.
#class backup = object (self : ’mytype) val mutable copy = None method save = copy <- Some {< copy = None >} method restore = match copy with Some x -> x | None -> self end;; class backup : object (’a) val mutable copy : ’a option method restore : ’a method save : unit end
The above definition will only backup one level. The backup facility can be added to any class using multiple inheritance.
#class [’a] backup_ref x = object inherit [’a] ref x inherit backup end;; class [’a] backup_ref : ’a -> object (’b) val mutable copy : ’b option val mutable x : ’a method get : ’a method restore : ’b method save : unit method set : ’a -> unit end #let rec get p n = if n = 0 then p # get else get (p # restore) (n-1);; val get : (< get : ’b; restore : ’a; .. > as ’a) -> int -> ’b = <fun> #let p = new backup_ref 0 in p # save; p # set 1; p # save; p # set 2; [get p 0; get p 1; get p 2; get p 3; get p 4];; - : int list = [2; 1; 1; 1; 1]
A variant of backup could retain all copies. (We then add a method clear to manually erase all copies.)
#class backup = object (self : ’mytype) val mutable copy = None method save = copy <- Some {< >} method restore = match copy with Some x -> x | None -> self method clear = copy <- None end;; class backup : object (’a) val mutable copy : ’a option method clear : unit method restore : ’a method save : unit end
#class [’a] backup_ref x = object inherit [’a] ref x inherit backup end;; class [’a] backup_ref : ’a -> object (’b) val mutable copy : ’b option val mutable x : ’a method clear : unit method get : ’a method restore : ’b method save : unit method set : ’a -> unit end #let p = new backup_ref 0 in p # save; p # set 1; p # save; p # set 2; [get p 0; get p 1; get p 2; get p 3; get p 4];; - : int list = [2; 1; 0; 0; 0]
Recursive classes can be used to define objects whose types are mutually recursive.
#class window = object val mutable top_widget = (None : widget option) method top_widget = top_widget end and widget (w : window) = object val window = w method window = window end;; class window : object val mutable top_widget : widget option method top_widget : widget option end and widget : window -> object val window : window method window : window end
Although their types are mutually recursive, the classes widget and window are themselves independent.
A binary method is a method which takes an argument of the same type as self. The class comparable below is a template for classes with a binary method leq of type ’a -> bool where the type variable ’a is bound to the type of self. Therefore, #comparable expands to < leq : ’a -> bool; .. > as ’a. We see here that the binder as also allows to write recursive types.
#class virtual comparable = object (_ : ’a) method virtual leq : ’a -> bool end;; class virtual comparable : object (’a) method virtual leq : ’a -> bool end
We then define a subclass money of comparable. The class money simply wraps floats as comparable objects. We will extend it below with more operations. There is a type constraint on the class parameter x as the primitive <= is a polymorphic comparison function in Objective Caml. The inherit clause ensures that the type of objects of this class is an instance of #comparable.
#class money (x : float) = object inherit comparable val repr = x method value = repr method leq p = repr <= p#value end;; class money : float -> object (’a) val repr : float method leq : ’a -> bool method value : float end
Note that the type money1 is not a subtype of type comparable, as the self type appears in contravariant position in the type of method leq. Indeed, an object m of class money has a method leq that expects an argument of type money since it accesses its value method. Considering m of type comparable would allow to call method leq on m with an argument that does not have a method value, which would be an error.
Similarly, the type money2 below is not a subtype of type money.
#class money2 x = object inherit money x method times k = {< repr = k *. repr >} end;; class money2 : float -> object (’a) val repr : float method leq : ’a -> bool method times : float -> ’a method value : float end
It is however possible to define functions that manipulate objects of type either money or money2: the function min will return the minimum of any two objects whose type unifies with #comparable. The type of min is not the same as #comparable -> #comparable -> #comparable, as the abbreviation #comparable hides a type variable (an ellipsis). Each occurrence of this abbreviation generates a new variable.
#let min (x : #comparable) y = if x#leq y then x else y;; val min : (#comparable as ’a) -> ’a -> ’a = <fun>
This function can be applied to objects of type money or money2.
#(min (new money 1.3) (new money 3.1))#value;; - : float = 1.3 #(min (new money2 5.0) (new money2 3.14))#value;; - : float = 3.14
More examples of binary methods can be found in sections 5.2.1 and 5.2.3.
Notice the use of functional update for method times. Writing new money2 (k *. repr) instead of {< repr = k *. repr >} would not behave well with inheritance: in a subclass money3 of money2 the times method would return an object of class money2 but not of class money3 as would be expected.
The class money could naturally carry another binary method. Here is a direct definition:
#class money x = object (self : ’a) val repr = x method value = repr method print = print_float repr method times k = {< repr = k *. x >} method leq (p : ’a) = repr <= p#value method plus (p : ’a) = {< repr = x +. p#value >} end;; class money : float -> object (’a) val repr : float method leq : ’a -> bool method plus : ’a -> ’a method print : unit method times : float -> ’a method value : float end
The above class money reveals a problem that often occurs with binary methods. In order to interact with other objects of the same class, the representation of money objects must be revealed, using a method such as value. If we remove all binary methods (here plus and leq), the representation can easily be hidden inside objects by removing the method value as well. However, this is not possible as long as some binary requires access to the representation on object of the same class but different from self.
#class safe_money x = object (self : ’a) val repr = x method print = print_float repr method times k = {< repr = k *. x >} end;; class safe_money : float -> object (’a) val repr : float method print : unit method times : float -> ’a end
Here, the representation of the object is known only to a particular object. To make it available to other objects of the same class, we are forced to make it available to the whole world. However we can easily restrict the visibility of the representation using the module system.
#module type MONEY = sig type t class c : float -> object (’a) val repr : t method value : t method print : unit method times : float -> ’a method leq : ’a -> bool method plus : ’a -> ’a end end;; module Euro : MONEY = struct type t = float class c x = object (self : ’a) val repr = x method value = repr method print = print_float repr method times k = {< repr = k *. x >} method leq (p : ’a) = repr <= p#value method plus (p : ’a) = {< repr = x +. p#value >} end end;;
Another example of friend functions may be found in section 5.2.3. These examples occur when a group of objects (here objects of the same class) and functions should see each others internal representation, while their representation should be hidden from the outside. The solution is always to define all friends in the same module, give access to the representation and use a signature constraint to make the representation abstract outside of the module.


My Favorite Places
This is a site about my
favorite places
Places I've been
Agra
, India
Solomon Islands
Edinburgh
, Scotland
Places I want to visit
Montenegro
Costa Rica
Tokyo
, Japan
Fictitious places I want to visit
Hogwarts
Middle Earth:
Lothlorien
Rivendell
Mordor
USS Enterprise NCC-1701-D


|
µEvLoop
A fast and lightweight event loop aimed at embedded platforms in C99.
|
A container for the system pools. More...
Data Fields | |
| uel_event_t | event_pool_buffer [UEL_SYSPOOLS_EVENT_POOL_SIZE] |
| The buffer used to store events in the event pool. | |
| void * | event_pool_queue_buffer [UEL_SYSPOOLS_EVENT_POOL_SIZE] |
| The buffer used to store event pointers in the event pool queue. | |
| uel_objpool_t | event_pool |
| The event pool object. Contains all the events used by the core. | |
| uel_llist_node_t | llist_node_pool_buffer [UEL_SYSPOOLS_LLIST_NODE_POOL_SIZE] |
| The buffer used to store llist nodes in the llist node pool. | |
| void * | llist_node_pool_queue_buffer [UEL_SYSPOOLS_LLIST_NODE_POOL_SIZE] |
| The budder used to store llist node pointers in the llist node pool queue. | |
| uel_objpool_t | llist_node_pool |
| The llist node pool object. Contains all llist nodes used by the core. | |
A container for the system pools.
The syspools object is meant as a container for the internal system pools. It is a safe interface to the pools, acquiring and releasing objects on demand.


The Requirements for Silver document is the next phase in the development of the next major upgrade to accessibility guidelines that will be the successor to Web Content Accessibility Guidelines (WCAG) 2 series. The Silver Task Force of the Accessibility Guidelines Working Group and the W3C Silver Community group have partnered to incubate the needs, requirements, and structure for the new accessibility guidance. To date, the group has:
The Requirements for Silver is published as a joint effort of the Silver Task Force of the Accessibility Guidelines Working Group and of the W3C Silver Community Group. It is a work in progress, and comments are welcome as Github Issues or by email.
People with disabilities can face problems using online content and applications. Disabilities can be permanent, temporary, or situational limitations.
We need guidelines to:
The research done in 2017-2018 by the Silver Task Force, the Silver Community Group, and the research partners was used to identify the key problem statements related to the current accessibility guidelines (WCAG 2.x, ATAG 2.0 and UAAG 2.0). See the Silver Research Summary slides for more detailed information. These problem statements were used to identify the opportunities for Silver to address that will improve accessibility guidance.
The Web Content Accessibility Guidelines (WCAG) 2.0 were designed to be technology neutral, and has stayed relevant for over 10 years. The Authoring Tool Accessibility Guidelines (ATAG) 2.0 has been implemented in the open source authoring tool communities (chiefly Wordpress and Drupal) with little known uptake in commercial authoring tools. UAAG 2.0 offers useful guidance to user agent developers and has been implemented on an individual success criterion basis. There is no known user agent that has implemented all of UAAG 2.0.
During the year of Silver research, a recurring theme was the popularity and quality of the guidance in WCAG 2.0. Most of the opportunities identified in the research were improvements in the structure and presentation accessibility guidance to improve usability, to support more disability needs, and to improve maintenance.
Silver builds on the WCAG 2.0 Requirements of 2006. The WCAG 2.0 requirements are:
Silver wishes to advance the WCAG 2.0 Requirements of:
The Silver research has identified some issues with "requirements may be applied across technologies" and is not yet ready to include that requirement. Silver is also not ready to address "Ensure that the revision is 'backwards and forward compatible'" and wishes to develop prototypes and receive user feedback.
The WCAG 2.1 Requirements are very specific to WCAG 2.1 and will not be advanced by Silver.
The Problem Statements describe areas identified during the Silver research in 2017-2018 that need to be addressed in the new guidelines. Each problem statement also has an opportunity section that is the basis for the Silver Requirements.
There are several areas for exploration in how conformance can work. These opportunities may or may not be incorporated. Then need to work together, and that interplay will be governed by the design principles
The Silver Design Principles are based on the requirements of WCAG 2.0 and build on those requirements to meet needs identified in the Silver research.
Accessibility guidelines should:
The development process for the guidelines should
Previous W3C Accessibility Guidelines described how to make web pages accessible to people with disabilities. These guidelines provided a flexible framework that has kept the guidelines relevant for 10 years. Changing technology and changing needs of people with disabilities has shown areas where they could be improved. The requirements are drawn from the research performed by Silver to improve the guidelines, and the suggestions from the Silver Design Sprint.
The Silver Requirements are high level and will be expanded and refined as Silver members move through the prototyping process. These requirements will be refined in Q3 of 2018 at the end of the prototyping process and in 2019 after public input from the First Public Working Draft.
Different guidance has potential for different measurement. For example, it may describe "minimal" and "better" methods of conforming to a requirement or allow user testing and usability testing as a method of conformance.
Create a structure for guidelines that can better meet the needs of people with disabilities in unanticipated technologies and interactions. The structure is flexible and forgiving of unanticipated needs.
Make the guidelines available in different accessible and usable ways so the guidance can be customized for different audiences.
Technology neutral is a requirement of WCAG 2.0 and it has enabled 2.0 to stay relevant as technology has changed. The Silver research indicates that it has also introduced challenges to users understanding, applying, and evaluating the guidance partially because it forces a level of abstraction that can be confusing to users. Silver is pursuing other solutions at this time and will relook at this requirement in a future version of this document.
It is likely that a layer of guidance will be written to be technology neutral, with additional guidance that is technology-specific. The guidelines may include criteria that cannot be met using some technologies. See the Flavors of Silver prototype for one idea of how it could work.
The following people participated in the Design Sprint of 2018 held in San Diego, California prior to the CSUN AT 2018 conference. We thank them for the generous gift of time that they donated to the Silver project.
These researchers selected a Silver research question, did the research, and graciously allowed us to use the results.


Most important heading here
Less important heading here
Some additional information here
Google Chrome is a free, open-source web browser developed by Google, released in 2008.
Some additional information here
Google Chrome is a free, open-source web browser developed by Google, released in 2008.
| Savings |
|---|
- by Refsnes Data. All Rights Reserved.
All content and graphics on this web site are the property of the company Refsnes Data.


[[duration(status.started)]][[startTime(status.started)]]
Completed [[status.count]] out of [[status.total]] jobs.
So far, we've encountered [[status.errors]] errors.
Migration completed.


GREAT EXPECTATIONS 1998 A film review by Timothy Voon Copyright 1998 Timothy Voon 1 :-) for a merry ending, but Dickens it ain't
Cast: Ethan Hawke, Gwyneth Paltrow, Anne Bancroft, Robert DeNiro, Chris Cooper, Hank Azaria, Raquel Beaudene, Jeremy Kissner Director: Alfonso Cuaron Producer: Art Linson Screenplay: Mitch Glazer based on the novel by Charles Dickens
When one thinks of GREAT EXPECTATIONS, one thinks of Pip not Finn; Miss Havisham who incinerates herself in her wedding dress, not a remorseful Ms Dinsmoor who regrets what she has done; a vindictive, cold Estella who is unable to love and mostly an unhappy ending.
The original story may have been a miserable tale about an orphan and a bratty girl, but that's how Dickens wanted it. Recreating Dickens 90's style is a dangerous thing. Can we safely say that this is still Dickens?
Although the jist of the story is much the same, there are elements which make this story subtly different. Minor annoyances like how Finn's sister sleeps around then leaves them. A seductive Estella who eventually mellows into a human being and the implication that Finn and Estella fall in love in the end, may be enough to make Dickens turn in his grave. It is as ludicrous as rewriting ROMEO AND JULIET so they live happily ever after, then still calling it Shakespeare!
If this story were not so closely tied with Dickens, then perhaps it would not be receiving such harsh criticism. Ethan Hawke is a charismatic actor and good in his role as Finn, although better in GATTACA. The seductive Estella, played by Gwyneth Paltrow, works the camera with looks that could kill. Anne Bancroft is delightful as the eccentric Ms Dinsmoor, reminiscent of Gloria Swanson in SUNSET BOULEVARD. Whilst Robert De Niro's puts in a heartfelt performance as the escaped convict who brings fortune to the young Finn.
Playing around with classical literature is a dangerous thing, especially if you're going to change the ending.
Timothy Voon e-mail<EMAIL_ADDRESS>Movie Archives http://us.imdb.com/M/reviews_by?Tim+Voon Hugues Bouclier's Movies in Melbourne http://www.labyrinth.net.au/~bouclier/week/movies.html
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


For inline code, wrap your code in the code tag. Be sure to escape HTML angle brackets.
code

For example,
 should be wrapped as inline.


Welcome to Andre's Restaurant
Come in to Andre's restaurant, an authentic Brampton restaurant for a truly authentic dining experience! Here, we present our dishes with excellent flavours and finest ingredients.
Our menus take you on a tour of different countries with a range of regional dishes. Whether You are in mood for a party or a quick bite. Andre's Restaurant is perfect place for you. We invite you to pur restaurant to taste our diverse menu.
About Us
Our restaurant is known for diversity in menu.Our main motive is to provide best services and delicious and unique dishes to our customers than at any other restaurant they ever visit. Want to know about us..
about usCuisine
The menu is the heart and soul of the restaurant. All the dishes served at restaurants are freshly cooked or baked as tasty and healthy food keeps our customer and our restaurant growing. Check our diverse menu..
CuisineSpecial Events
we strive to make your most important moments special and memorable. Join us for one of our special events.Host a private event with us, and we will work with you to customize the event to fit your needs.
View Events


Excel to D3.js Graph
Menu
About
Use the form below to upload a CSV or Excel file for parsing
Upload CSV/Excel
File
Generate D3.js Graph
send


A bit of an improvement over css, allows you to organize css in a better format in my opinion. Feel free to either use css or Sass its up to you after all.


This demo demonstrates the render speed of ng-staticize. Switch tabs to view the render speed of using ng-staticize or not.
If you are using Chrome, you can use Angular watchers to view the watcher's change.


The R Script associated with this page is available here. Download this file and open it (or copy-paste into a new script) with RStudio if you want to follow along.
Raster data in R can be loaded in a relatively straight forward way using the raster package. There are other ways of loading raster data, including implementations in sp, where raster data can be formatted as ‘SpatialPixelsDataFrame()’.
The raster package is still the most widely used package though, although it is increasingly being replaced by an approach that is based on a tidy concept (separating raw data from metadata and spatial information). More on this later
First, lets load the raster package and some first prepared data. If the loading below does not work, download the tif here or from the repository
library(raster)
# The data to load is from Jung et al. (2020), https://www.nature.com/articles/s41597-020-00599-8
# I have prepared a subset for the Alpes to load in here.
# These contain the fraction (multiplied with 1000) of a grid cell containing forest or arti at 1km.
# We now load the forest layer from this object
ras <- raster('ht_004_clipped.tif',layer = 1)
class(ras)
## [1] "RasterLayer"
## attr(,"package")
## [1] "raster"
# Note that the range of values is loaded by default to the minimum and maximum possible
# Reset like this
ras <- setMinMax(ras)
# -> range of values 1 - 1000
# Plot the raster data
plot(ras, col = topo.colors(100))
Here we loaded in the first band of the data as Raster object, but there are others (more about this below).
Can you load in and plot the second band (artifical landscapes)?
ras_crop <- raster('ht_004_clipped.tif',layer = 2)
plot(ras, col = rev(heat.colors(100)))
There are multiple functions to assess the metadata associated with a raster
# Plot the extent
extent(ras)
## class : Extent
## xmin : 7.377105
## xmax : 16.67129
## ymin : 43.44738
## ymax : 48.96765
# How many rows and columns are there? How many cells
nrow(ras)
## [1] 557
ncol(ras)
## [1] 937
ncell(ras)
## [1] 521909
# We can also define a custom function to work with raster data information
# This one here converts the extent to a WKT bounding box object
bbox2wkt <- function(bbox=NULL){
if(!is.null(bbox)) bbox <- c(bbox[1], bbox[3], bbox[2], bbox[4]) else stop('Provide a an extent object')
stopifnot(length(bbox)==4) #check for 4 digits
paste('POLYGON((',
sprintf('%s %s',bbox[1],bbox[2]), ',', sprintf('%s %s',bbox[3],bbox[2]), ',',
sprintf('%s %s',bbox[3],bbox[4]), ',', sprintf('%s %s',bbox[1],bbox[4]), ',',
sprintf('%s %s',bbox[1],bbox[2]),
'))', sep="")
}
# Print the extent in WKT format
bbox2wkt(extent(ras))
## [1] "POLYGON((7.377105383 43.447384894,16.671291018 43.447384894,16.671291018 48.967647157,7.377105383 48.967647157,7.377105383 43.447384894))"
Now we want to know what the mean fraction of forest across the scene is? To do so you first need to convert the units to fractions (0-1) and then calculate a mean using the function ‘cellStats()’. Check the help to see how to use this function via ?cellStats
# Calculate fractions
ras_frac <- ras / 1000
cellStats(x = ras_frac,stat = 'mean')
## [1] 0.4230384
# On average grid cells with some level of forest area
In essence raster files are just large matrices, thus it is relatively straight forward to convert the raster object to other common r data formats
# One can access all raster data like this
ras[] # Careful, large file!
# or all coordinates
coordinates(ras)
# Convert to matrix
mat <- as.matrix(ras)
# Or to data.frame. Here we set the option xy to TRUE, which saves the coordinates of each cell as well
df <- as.data.frame(ras,xy = TRUE)
Similarly the raster data can be manipulated by accessing the raw data
# For instance, suppose we want to set all cells with values lower than 500 (50%) to NA (No data)
# CAREFUL: This overwrites the original data in R!
ras[ras < 500] <- NA
# Plot
plot(ras)
Finally we going to write the output as new raster
# What is the data type of the raster?
dataType(ras)
## [1] "INT2U"
# The output data type decides how you can save the raster most space efficiently.
# If you have for instance an integer raster, then it is a waste of space saving it with floating point precision.
# Here is a list of all output formats your system supports via the gdal library
knitr::kable(writeFormats() )
| name | long_name |
|---|---|
| raster | R-raster |
| SAGA | SAGA GIS |
| IDRISI | IDRISI |
| IDRISIold | IDRISI (img/doc) |
| BIL | Band by Line |
| BSQ | Band Sequential |
| BIP | Band by Pixel |
| ascii | Arc ASCII |
| CDF | NetCDF |
| ADRG | ARC Digitized Raster Graphics |
| BMP | MS Windows Device Independent Bitmap |
| BT | VTP .bt (Binary Terrain) 1.3 Format |
| BYN | Natural Resources Canada’s Geoid |
| CTable2 | CTable2 Datum Grid Shift |
| EHdr | ESRI .hdr Labelled |
| ELAS | ELAS |
| ENVI | ENVI .hdr Labelled |
| ERS | ERMapper .ers Labelled |
| FITS | Flexible Image Transport System |
| GPKG | GeoPackage |
| GS7BG | Golden Software 7 Binary Grid (.grd) |
| GSBG | Golden Software Binary Grid (.grd) |
| GTiff | GeoTIFF |
| GTX | NOAA Vertical Datum .GTX |
| HDF4Image | HDF4 Dataset |
| HFA | Erdas Imagine Images (.img) |
| IDA | Image Data and Analysis |
| ILWIS | ILWIS Raster Map |
| INGR | Intergraph Raster |
| ISCE | ISCE raster |
| ISIS2 | USGS Astrogeology ISIS cube (Version 2) |
| ISIS3 | USGS Astrogeology ISIS cube (Version 3) |
| KRO | KOLOR Raw |
| LAN | Erdas .LAN/.GIS |
| Leveller | Leveller heightfield |
| MBTiles | MBTiles |
| MRF | Meta Raster Format |
| netCDF | Network Common Data Format |
| NGW | NextGIS Web |
| NITF | National Imagery Transmission Format |
| NTv2 | NTv2 Datum Grid Shift |
| NWT_GRD | Northwood Numeric Grid Format .grd/.tab |
| PAux | PCI .aux Labelled |
| PCIDSK | PCIDSK Database File |
| PCRaster | PCRaster Raster File |
| Geospatial PDF | |
| PDS4 | NASA Planetary Data System 4 |
| PNM | Portable Pixmap Format (netpbm) |
| RMF | Raster Matrix Format |
| ROI_PAC | ROI_PAC raster |
| RRASTER | R Raster |
| RST | Idrisi Raster A.1 |
| SAGA | SAGA GIS Binary Grid (.sdat, .sg-grd-z) |
| SGI | SGI Image File Format 1.0 |
| Terragen | Terragen heightfield |
Can you save the ras object as new file ? The function is called ‘writeRaster’
writeRaster(ras, 'ht_004_clipped.tif',
# This bit is extra. Here we specify that the output should be compressed
options=c("COMPRESS=DEFLATE"))
Above we have overwritten the original data object. You might have also noticed that the provided raster file contains two bands, one forest and one for artifical landscapes Let’s load it back again, but this time as multidimensional raster stack
library(raster)
ras <- stack('ht_004_clipped.tif')
# Notice the difference in class
class(ras)
## [1] "RasterStack"
## attr(,"package")
## [1] "raster"
# When plotted, by default all layers are shown
plot(ras)
However quite often these stacks are provided in formats that require other wrapper packages. I have saved the above file also in NetCDF (Network Common Data Form) format (https://en.wikipedia.org/wiki/NetCDF), which is a self-describing data format that supports for instance metadata.
Generally these data are a convenient format to store spatial-temporal information or other spatial data with more than two axes (for instance depth or height in addition to coordinates). The file can be found here.
library(ncdf4)
# When the ncdf4 package is installed, nc files should be loadable directly with raster
# (might spit out a few warnings though)
ras <- raster('ht_004_clipped.nc')
## Warning in .varName(nc, varname, warn = warn): varname used is: Band1
## If that is not correct, you can set it to one of: Band1, Band2
## Warning in .getCRSfromGridMap4(atts): cannot process these parts of the CRS:
## long_name=CRS definition
## spatial_ref=GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AXIS["Latitude",NORTH],AXIS["Longitude",EAST],AUTHORITY["EPSG","4326"]]
## GeoTransform=7.377105383 0.00991908819103522 0 48.967647157 0 -0.009910704242369837
## Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO"): Discarded
## datum unknown in CRS definition
## Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO"): Discarded
## datum unknown in CRS definition
# Another way to open these files are the functions from the ncdf4 package
ras <- nc_open('ht_004_clipped.nc')
# This format looks a bit different
# Notice how there are variables, dimensions and global attributes
ras
## File ht_004_clipped.nc (NC_FORMAT_CLASSIC):
##
## 3 variables (excluding dimension variables):
## float Band1[lon,lat]
## long_name: GDAL Band Number 1
## _FillValue: 0
## grid_mapping: crs
## float Band2[lon,lat]
## long_name: GDAL Band Number 2
## _FillValue: 0
## grid_mapping: crs
## char crs[]
## grid_mapping_name: latitude_longitude
## long_name: CRS definition
## longitude_of_prime_meridian: 0
## semi_major_axis: 6378137
## inverse_flattening:<PHONE_NUMBER>63
## spatial_ref: GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AXIS["Latitude",NORTH],AXIS["Longitude",EAST],AUTHORITY["EPSG","4326"]]
## GeoTransform: 7.377105383 0.00991908819103522 0 48.967647157 0 -0.009910704242369837
##
## 2 dimensions:
## lon Size:937
## standard_name: longitude
## long_name: longitude
## units: degrees_east
## lat Size:557
## standard_name: latitude
## long_name: latitude
## units: degrees_north
##
## 3 global attributes:
## Conventions: CF-1.5
## GDAL: GDAL 3.0.4, released 2020/01/28
## history: Mo Okt 12 14:45:47 2020: GDAL Create( /mnt/hdrive/Talks/20201022_ESMTrainingSession/CDAT_Materials/SpatialDataAnalysis_withR/ht_004_clipped.nc, ... )
What we going to do now is to save an attribute directly to the file, that specifies the type of data contained in the file.
# Description
desc <- 'This file contains data on forested and artifical habitats'
# Reopen the file in write mode
ras <- nc_open('ht_004_clipped.nc',write = TRUE)
# We are writing a global attribute with the description of the file
ncatt_put(nc = ras,varid = 0 ,attname = 'description',attval = desc)
# And close
nc_close(ras)
# Now load again to check that the description is there
ras <- nc_open('ht_004_clipped.nc')
ras
More data manipulation functions with this format can be found in the help files (?ncdf4).
The raster package can be slow, especially if your files are large. Splitting them up in tiles is usually a good idea for processing. There is an upcoming replacement package called terra that aims to implement most raster packages functions in faster, more efficient code.
Another new package of loading and analysing multidimensional data is the stars package. This new package specifically aims at processing multidimensional rasters and works with netCDF files too.
library(stars)
## Loading required package: abind
## Loading required package: sf
## Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 7.0.0
# Load in the ncdf or tif file
ras <- read_stars('ht_004_clipped.tif')
ras
## stars object with 3 dimensions and 1 attribute
## attribute(s), summary of first 1e+05 cells:
## ht_004_clipped.tif
## Min. : 1.0
## 1st Qu.: 48.0
## Median : 119.0
## Mean : 203.0
## 3rd Qu.: 272.5
## Max. :1000.0
## NA's :24513
## dimension(s):
## from to offset delta refsys point values
## x 1 937 7.37711 0.00991909 WGS 84 FALSE NULL [x]
## y 1 557 48.9676 -0.0099107 WGS 84 FALSE NULL [y]
## band 1 2 NA NA NA NA NULL
plot(ras,
downsample = TRUE # Show only as many colours as fit in the pixel size of the image
)
Another very useful feature of stars is that it allows to read in lazy object. This is particularly useful for very large files. The object can be created and investigated even without loading all data into memory. Only if any calculation requires the data stored within the stars object, it is loaded into memory.
ras <- read_stars('ht_004_clipped.tif',proxy = TRUE)
# There are also ways to load in for instance only a specific area (bbox) or range of the data into R.
If you are familiar with the methods of the tidyverse family of packages: Stars objects interact with a number of functions from these package. For instance, here is how I would select the top 100 cell values (e.g. those from left to right) from the stars object for band 1 (Forest) and plot it
suppressPackageStartupMessages(library(tidyverse))
# Take the raster object and 'pipe' into slice for the y-coordinate (Latitude)
ras %>% slice(y, 1:100) %>%
# Filter to band 1
filter(band == 1) %>%
# Plot the output of the chain
plot()
# Note that nothing is saved as part of this processing chain, although one obviously could save the output in a new object.
# Equally one access the attributes and dimensions of any stars object
# The first arguement to any stars object is the attribute (could be time), the next the dimensions
# For instance if I want to plot the first 20 values (upper left corner), here is how
plot(ras[,1:10,1:20])
See here for a number of functions provided by the stars package. Some of which we will explore later on. (Can you find the function that lets you write a stars file?)
# All functions of the stars package
methods(class = "stars")
## [1] [ [<- $<- adrop
## [5] aggregate aperm as_tibble as.data.frame
## [9] c coerce contour cut
## [13] dim dimnames dimnames<- droplevels
## [17] filter image initialize is.na
## [21] Math merge mutate Ops
## [25] plot predict print pull
## [29] select show slice slotsFromS3
## [33] split st_apply st_area st_as_sf
## [37] st_as_sfc st_as_stars st_bbox st_coordinates
## [41] st_crop st_crs st_crs<- st_dimensions
## [45] st_dimensions<- st_extract st_geometry st_interpolate_aw
## [49] st_intersects st_join st_mosaic st_normalize
## [53] st_redimension st_sample st_transform_proj st_transform
## [57] write_stars
## see '?methods' for accessing help and source code
Final exercise: Remember the outline of Laxenburg park that was saved in the vector exercise? Take the artifical dataset loaded via stars and clip it to the bounding box of the Laxenburg park!
ras <- read_stars('ht_004_clipped.tif',proxy = TRUE)
laxpol <- read_sf('Laxenburg.gpkg')
bb = st_bbox(laxpol)
plot( ras[bb] )
# There are many different ways of doing this. One could equally process this in a chain using 'pipes'
laxpol %>%
st_bbox() %>%
ras[.] %>%
plot()
Another big field of application for stars is the analysis of multi-temporal raster stacks or data-cubes. Custom-written function can then be easily applied to entire stacks of rasters, e.g. stars::st_apply()
. We don’t explore this as part of this tutorial, but have a look at the stars website for some example code.
(source: https://r-spatial.github.io/stars/ )


{% extends "global/Page.html" %} {% load otree static %} {% block title %}
In the next screen you will be informed of your earnings. After that, please remain seated until you are called
to receive your payment.
To conclude, please press the button indicating your gender:


Select Dataset:
Blue Marble
CMU Carnival 2010
Early Universe
Ocean Chlorophyll
Plant Growth
Sun (304A)
Weather Radar


@@include('./html/header.html')
@@include('./html/sections/hero.html')
@@include('./html/sections/category-grid.html')
@@include('./html/sections/popular.html')
@@include('./html/sections/why-us.html')
@@include('./html/sections/sales.html')
@@include('./html/sections/about.html')
@@include('./html/footer.html')