Tuesday, August 17, 2010

RSS--Really Simple Syndication

RSS (most commonly expanded as Really Simple Syndication) is a family of web feed formats used to publish frequently updated works—such as blog entries, news headlines, audio, and video—in a standardized format.[2] An RSS document (which is called a "feed", "web feed",[3] or "channel") includes full or summarized text, plus metadata such as publishing dates and authorship. Web feeds benefit publishers by letting them syndicate content automatically. They benefit readers who want to subscribe to timely updates from favored websites or to aggregate feeds from many sites into one place. RSS feeds can be read using software called an "RSS reader", "feed reader", or "aggregator", which can be web-based, desktop-based, or mobile-device-based. A standardized XML file format allows the information to be published once and viewed by many different programs. The user subscribes to a feed by entering into the reader the feed's URI or by clicking an RSS icon in a web browser that initiates the subscription process. The RSS reader checks the user's subscribed feeds regularly for new work, downloads any updates that it finds, and provides a user interface to monitor and read the feeds.

RSS formats are specified using XML, a generic specification for the creation of data formats. Although RSS formats have evolved from as early as March 1999,[4] it was between 2005 and 2006 when RSS gained widespread use, and the ("Feed-icon.svg") icon was decided upon by several major Web browsers.[5]

History
Main article: History of web syndication technology

The RSS formats were preceded by several attempts at web syndication that did not achieve widespread popularity. The basic idea of restructuring information about websites goes back to as early as 1995, when Ramanathan V. Guha and others in Apple Computer's Advanced Technology Group developed the Meta Content Framework.[6] For a more detailed discussion of these early developments, see the history of web syndication technology.

RDF Site Summary, the first version of RSS, was created by Guha at Netscape in March 1999 for use on the My.Netscape.Com portal. This version became known as RSS 0.9.[4] In July 1999, Dan Libby of Netscape produced a new version, RSS 0.91,[2] which simplified the format by removing RDF elements and incorporating elements from Dave Winer's scriptingNews syndication format.[7] Libby also renamed RSS "Rich Site Summary" and outlined further development of the format in a "futures document".[8]

This would be Netscape's last participation in RSS development for eight years. As RSS was being embraced by web publishers who wanted their feeds to be used on My.Netscape.Com and other early RSS portals, Netscape dropped RSS support from My.Netscape.Com in April 2001 during new owner AOL's restructuring of the company, also removing documentation and tools that supported the format.[9]

Two entities emerged to fill the void, with neither Netscape's help nor approval: The RSS-DEV Working Group and Winer, whose UserLand Software had published some of the first publishing tools outside of Netscape that could read and write RSS.

Winer published a modified version of the RSS 0.91 specification on the UserLand website, covering how it was being used in his company's products, and claimed copyright to the document.[10] A few months later, UserLand filed a U.S. trademark registration for RSS, but failed to respond to a USPTO trademark examiner's request and the request was rejected in December 2001.[11]

The RSS-DEV Working Group, a project whose members included Guha and representatives of O'Reilly Media and Moreover, produced RSS 1.0 in December 2000.[12] This new version, which reclaimed the name RDF Site Summary from RSS 0.9, reintroduced support for RDF and added XML namespaces support, adopting elements from standard metadata vocabularies such as Dublin Core.

In December 2000, Winer released RSS 0.92[13] a minor set of changes aside from the introduction of the enclosure element, which permitted audio files to be carried in RSS feeds and helped spark podcasting. He also released drafts of RSS 0.93 and RSS 0.94 that were subsequently withdrawn.[14]

In September 2002, Winer released a major new version of the format, RSS 2.0, that redubbed its initials Really Simple Syndication. RSS 2.0 removed the type attribute added in the RSS 0.94 draft and added support for namespaces. To preserve backward compatibility with RSS 0.92, namespace support applies only to other content included within an RSS 2.0 feed, not the RSS 2.0 elements themselves.[15] (Although other standards such as Atom attempt to correct this limitation, RSS feeds are not aggregated with other content often enough to shift the popularity from RSS to other formats having full namespace support.)

Because neither Winer nor the RSS-DEV Working Group had Netscape's involvement, they could not make an official claim on the RSS name or format. This has fueled ongoing controversy in the syndication development community as to which entity was the proper publisher of RSS.

One product of that contentious debate was the creation of an alternative syndication format, Atom, that began in June 2003.[16] The Atom syndication format, whose creation was in part motivated by a desire to get a clean start free of the issues surrounding RSS, has been adopted as IETF Proposed Standard RFC 4287.

In July 2003, Winer and UserLand Software assigned the copyright of the RSS 2.0 specification to Harvard's Berkman Center for Internet & Society, where he had just begun a term as a visiting fellow.[17] At the same time, Winer launched the RSS Advisory Board with Brent Simmons and Jon Udell, a group whose purpose was to maintain and publish the specification and answer questions about the format.[18]

In December 2005, the Microsoft Internet Explorer team[19] and Outlook team[20] announced on their blogs that they were adopting the feed icon first used in the Mozilla Firefox browser (Feed-icon.svg). In February 2006, Opera Software followed suit.[21] This effectively made the orange square with white radio waves the industry standard for RSS and Atom feeds, replacing the large variety of icons and text that had been used previously to identify syndication data.

In January 2006, Rogers Cadenhead relaunched the RSS Advisory Board without Dave Winer's participation, with a stated desire to continue the development of the RSS format and resolve ambiguities. In June 2007, the board revised their version of the specification to confirm that namespaces may extend core elements with namespace attributes, as Microsoft has done in Internet Explorer 7. According to their view, a difference of interpretation left publishers unsure of whether this was permitted or forbidden.
Variants

There are several different versions of RSS, falling into two major branches (RDF and 2.*).

The RDF (or RSS 1.*) branch includes the following versions:

* RSS 0.90 was the original Netscape RSS version. This RSS was called RDF Site Summary, but was based on an early working draft of the RDF standard, and was not compatible with the final RDF Recommendation.
* RSS 1.0 is an open format by the RSS-DEV Working Group, again standing for RDF Site Summary. RSS 1.0 is an RDF format like RSS 0.90, but not fully compatible with it, since 1.0 is based on the final RDF 1.0 Recommendation.
* RSS 1.1 is also an open format and is intended to update and replace RSS 1.0. The specification is an independent draft not supported or endorsed in any way by the RSS-Dev Working Group or any other organization.

The RSS 2.* branch (initially UserLand, now Harvard) includes the following versions:

* RSS 0.91 is the simplified RSS version released by Netscape, and also the version number of the simplified version originally championed by Dave Winer from Userland Software. The Netscape version was now called Rich Site Summary; this was no longer an RDF format, but was relatively easy to use.
* RSS 0.92 through 0.94 are expansions of the RSS 0.91 format, which are mostly compatible with each other and with Winer's version of RSS 0.91, but are not compatible with RSS 0.90.
* RSS 2.0.1 has the internal version number 2.0. RSS 2.0.1 was proclaimed to be "frozen", but still updated shortly after release without changing the version number. RSS now stood for Really Simple Syndication. The major change in this version is an explicit extension mechanism using XML namespaces.[22]

For the most part, later versions in each branch are backward-compatible with earlier versions (aside from non-conformant RDF syntax in 0.90), and both versions include properly documented extension mechanisms using XML Namespaces, either directly (in the 2.* branch) or through RDF (in the 1.* branch). Most syndication software supports both branches. "The Myth of RSS Compatibility", an article written in 2004 by RSS critic and Atom advocate Mark Pilgrim, discusses RSS version compatibility issues in more detail.

The extension mechanisms make it possible for each branch to track innovations in the other. For example, the RSS 2.* branch was the first to support enclosures, making it the current leading choice for podcasting, and as of 2005[update] is the format supported for that use by iTunes and other podcasting software; however, an enclosure extension is now available for the RSS 1.* branch, mod_enclosure. Likewise, the RSS 2.* core specification does not support providing full-text in addition to a synopsis, but the RSS 1.* markup can be (and often is) used as an extension. There are also several common outside extension packages available, including a new proposal from Microsoft for use in Internet Explorer 7.

The most serious compatibility problem is with HTML markup. Userland's RSS reader—generally considered as the reference implementation—did not originally filter out HTML markup from feeds. As a result, publishers began placing HTML markup into the titles and descriptions of items in their RSS feeds. This behavior has become expected of readers, to the point of becoming a de facto standard, though there is still some inconsistency in how software handles this markup, particularly in titles. The RSS 2.0 specification was later updated to include examples of entity-encoded HTML; however, all prior plain text usages remain valid.

As of January 2007[update], tracking data from www.syndic8.com indicates that the three main versions of RSS in current use are 0.91, 1.0, and 2.0. Of these, RSS 0.91 accounts for 13 percent of worldwide RSS usage and RSS 2.0 for 67 percent, while RSS 1.0 has a 17 percent share.[23] These figures, however, do not include usage of the rival web feed format Atom. As of August 2008[update], the syndic8.com website is indexing 546,069 total feeds, of which 86,496 were some dialect of Atom and 438,102 were some dialect of RSS.[24]
Modules

The primary objective of all RSS modules is to extend the basic XML schema established for more robust syndication of content. This inherently allows for more diverse, yet standardized, transactions without modifying the core RSS specification.

To accomplish this extension, a tightly controlled vocabulary (in the RSS world, "module"; in the XML world, "schema") is declared through an XML namespace to give names to concepts and relationships between those concepts.

Some RSS 2.0 modules with established namespaces are:

* Ecommerce RSS 2.0 Module
* Media RSS 2.0 Module
* OpenSearch RSS 2.0 Module

Ruby (programming language)

Ruby is a dynamic, reflective, general purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto. It was influenced primarily by Perl, Smalltalk, Eiffel, and Lisp.

Ruby supports multiple programming paradigms, including functional, object oriented, imperative and reflective. It also has a dynamic type system and automatic memory management; it is therefore similar in varying respects to Python, Perl, Lisp, Dylan, Pike, and CLU.

The standard 1.8.7 implementation is written in C, as a single-pass interpreted language. There is currently no specification of the Ruby language, so the original implementation is considered to be the de facto reference. As of 2010[update], there are a number of complete or upcoming alternative implementations of the Ruby language, including YARV, JRuby, Rubinius, IronRuby, MacRuby and HotRuby, each of which takes a different approach, with IronRuby, JRuby and MacRuby providing just-in-time compilation and MacRuby also providing ahead-of-time compilation. The official 1.9 branch uses YARV, as will 2.0 (development), and will eventually supersede the slower Ruby MRI.


History
Yukihiro Matsumoto, the creator of Ruby.

Ruby was conceived on February 24, 1993 by Yukihiro Matsumoto who wished to create a new language that balanced functional programming with imperative programming.[1] Matsumoto has stated, "I wanted a scripting language that was more powerful than Perl, and more object-oriented than Python. That's why I decided to design my own language".[2]
[edit] Etymology of the name "Ruby"

The name "Ruby" was decided on during an online chat session between Matsumoto and Keiju Ishitsuka on February 24, 1993, before any code had been written for the language.[3] Initially two names were proposed: "Coral" and "Ruby", with the latter being chosen by Matsumoto in a later email to Ishitsuka.[4] Matsumoto has later stated that a factor in choosing the name "Ruby" was because it was the birthstone of one of his colleagues.[5]
[edit] First publication

The first public release of Ruby 0.95 was announced on Japanese domestic newsgroups on December 21, 1995.[6][7] Subsequently three more versions of Ruby were released in two days.[3] The release coincided with the launch of the Japanese language ruby-list mailing list which was the first mailing list for the new language.

Already present at this stage of development were many of the features familiar in later releases of Ruby, including object-oriented design, classes with inheritance, mixins, iterators, closures, exception handling, and garbage collection.[8]
[edit] Ruby 1.0

Ruby reached version 1.0 on December 25, 1996.[3]

Following the release of Ruby 1.3 in 1999 the first English language mailing list ruby-talk began,[2] which signalled a growing interest in the language outside of Japan. In September 2000, the first English language book Programming Ruby was printed, which was later freely released to the public further widening the adoption of Ruby amongst English speakers.
[edit] Ruby on Rails

Around 2005, interest in the Ruby language surged in tandem with Ruby on Rails, a popular web application framework written in Ruby. Rails is frequently credited with making Ruby "famous" and the association is so strong that the two are sometimes conflated by programmers who are new to Ruby.[9]
[edit] Ruby 1.9.1

The latest stable version of the reference implementation is 1.9.1.

Ruby 1.9.1 introduces many significant changes over version 1.8.6. Some examples are:

* Block local variables (variables that are local to the block in which they are declared)
* An additional lambda syntax (fun = ->(a,b) { puts a + b })
* Per-string character encodings are supported

[edit] Philosophy

Matsumoto has said that Ruby is designed for programmer productivity and fun, following the principles of good user interface design.[10] He stresses that systems design needs to emphasize human, rather than computer, needs:[11]
“ Often people, especially computer engineers, focus on the machines. They think, "By doing this, the machine will run faster. By doing this, the machine will run more effectively. By doing this, the machine will something something something." They are focusing on machines. But in fact we need to focus on humans, on how humans care about doing programming or operating the application of the machines. We are the masters. They are the slaves. ”

Ruby is said to follow the principle of least astonishment (POLA), meaning that the language should behave in such a way as to minimize confusion for experienced users. Matsumoto has said his primary design goal was to make a language which he himself enjoyed using, by minimizing programmer work and possible confusion. He has said that he had not applied the principle of least surprise to the design of Ruby,[11] but nevertheless the phrase has come to be closely associated with the Ruby programming language. The phrase has itself been a source of surprise, as novice users may take it to mean that Ruby's behaviors try to closely match behaviors familiar from other languages. In a May 2005 discussion on the comp.lang.ruby newsgroup, Matsumoto attempted to distance Ruby from POLA, explaining that because any design choice will be surprising to someone, he uses a personal standard in evaluating surprise. If that personal standard remains consistent there will be few surprises for those familiar with the standard.[12]

Matsumoto defined it this way in an interview:[11]
“ Everyone has an individual background. Someone may come from Python, someone else may come from Perl, and they may be surprised by different aspects of the language. Then they come up to me and say, 'I was surprised by this feature of the language, so Ruby violates the principle of least surprise.' Wait. Wait. The principle of least surprise is not for you only. The principle of least surprise means principle of least my surprise [sic]. And it means the principle of least surprise after you learn Ruby very well. For example, I was a C++ programmer before I started designing Ruby. I programmed in C++ exclusively for two or three years. And after two years of C++ programming, it still surprises me. ”
[edit] Features

* Thoroughly object-oriented with inheritance, mixins and metaclasses [13]
* Dynamic typing and Duck typing
* Everything is an expression (even statements) and everything is executed imperatively (even declarations)
* Succinct and flexible syntax [14] that minimizes syntactic noise and serves as a foundation for domain specific languages [15]
* Dynamic reflection and alteration of objects to facilitate metaprogramming[16]
* Lexical closures, Iterators and generators, with a unique block syntax [17]
* Literal notation for arrays, hashes, regular expressions and symbols
* Embedding code in strings (interpolation)
* Default arguments
* Four levels of variable scope (global, class, instance, and local) denoted by sigils and capitalization
* Automatic garbage collection
* First-class continuations
* Strict boolean coercion rules (everything is true except false and nil)
* Exception handling
* Operator overloading
* Built-in support for rational numbers, complex numbers and arbitrary-precision arithmetic
* Custom dispatch behavior (through method_missing and const_missing)
* Native threads and cooperative fibers
* Initial support for Unicode and multiple character encodings (still buggy as of version 1.9)[18]
* Native plug-in API in C
* Interactive Ruby Shell (a REPL)
* Centralized package management through RubyGems
* Implemented on all major platforms
* Large standard library

[edit] Semantics

Ruby is object-oriented: every data type is an object, including classes and types that many other languages designate as primitives (such as integers, booleans, and "nil"). Every function is a method. Named values (variables) always designate references to objects, not the objects themselves. Ruby supports inheritance with dynamic dispatch, mixins and singleton methods (belonging to, and defined for, a single instance rather than being defined on the class). Though Ruby does not support multiple inheritance, classes can import modules as mixins. Procedural syntax is supported, but all methods defined outside of the scope of a particular object are actually methods of the Object class. Since this class is parent to every other class, the changes become visible to all classes and objects.

Ruby has been described as a multi-paradigm programming language: it allows procedural programming (defining functions/variables outside classes makes them part of the root, 'self' Object), with object orientation (everything is an object) or functional programming (it has anonymous functions, closures, and continuations; statements all have values, and functions return the last evaluation). It has support for introspection, reflection and metaprogramming, as well as support for interpreter-based[19] threads. Ruby features dynamic typing, and supports parametric polymorphism.

According to the Ruby FAQ,[20] "If you like Perl, you will like Ruby and be right at home with its syntax. If you like Smalltalk, you will like Ruby and be right at home with its semantics. If you like Python, you may or may not be put off by the huge difference in design philosophy between Python and Ruby/Perl."
[edit] Syntax

The syntax of Ruby is broadly similar to Perl and Python. Class and method definitions are signaled by keywords. In contrast to Perl, variables are not obligatorily prefixed with a sigil. When used, the sigil changes the semantics of scope of the variable. The most striking difference from C and Perl is that keywords are typically used to define logical code blocks, without braces (i.e., pair of { and }). For practical purposes there is no distinction between expressions and statements[21]. Line breaks are significant and taken as the end of a statement; a semicolon may be equivalently used. Unlike Python, indentation is not significant.

One of the differences of Ruby compared to Python and Perl is that Ruby keeps all of its instance variables completely private to the class and only exposes them through accessor methods (attr_writer, attr_reader, etc.). Unlike the "getter" and "setter" methods of other languages like C++ or Java, accessor methods in Ruby are created with a single line of code via metaprogramming. As invocation of these methods does not require the use of parentheses, it is trivial to change an instance variable into a full function, without modifying a single line of code or having to do any refactoring achieving similar functionality to C# and VB.NET property members. Python's property descriptors are similar, but come with a tradeoff in the development process. If one begins in Python by using a publicly exposed instance variable and later changes the implementation to use a private instance variable exposed through a property descriptor, code internal to the class may need to be adjusted to use the private variable rather than the public property. Ruby removes this design decision by forcing all instance variables to be private, but also provides a simple way to declare set and get methods. This is in keeping with the idea that in Ruby, one never directly accesses the internal members of a class from outside of it. Rather one passes a message to the class and receives a response.

See the examples section for samples of code demonstrating Ruby syntax.
[edit] Deviations from behaviour elsewhere

Some features which differ notably from languages such as C or Perl:

* The language syntax is sensitive to the capitalization of identifiers, in most cases treating capitalized variables as constants.
* The sigils $ and @ do not indicate variable data type as in Perl, but rather function as scope resolution operators.
* To denote a floating point without a decimal component, one must follow with a zero digit (99.0) or an explicit conversion (99.to_f). It is insufficient to append a dot (99.) since numbers are susceptible to method syntax.
* Boolean evaluation of non-boolean data is strict: 0, "" and [] are all evaluated to true. In C, the expression 0 ? 1 : 0 evaluates to 0 (i.e. false). In Ruby, however, it yields 1, as all numbers evaluate to true; only nil and false evaluate to false. A corollary to this rule is that Ruby methods by convention — for example, regular-expression searches — return numbers, strings, lists, or other non-false values on success, but nil on failure. This convention is also used in Smalltalk, where only the special objects true and false can be used in a boolean expression.
* Versions prior to 1.9 use plain integers to represent single characters, much like C. This may cause surprises when slicing strings: "abc"[0] yields 97 (the ASCII code of the first character in the string); to obtain "a" use "abc"[0,1] (a substring of length 1) or "abc"[0].chr.
* The notation statement until expression, unlike other languages' equivalent statements (e.g. do { statement } while (!(expression)); in C/C++/...), actually never runs the statement if the expression is already true. This is because statement until expression is actually syntactic sugar over until expression; statement; end, the equivalent of which in C/C++ is while (!(expression)) { statement; }, just like statement if expression is an equivalent to if (expression) { statement; }. However, the notation begin statement end until expression in Ruby will in fact run the statement once even if the expression is already true, acting similar to the "do-while" of other languages.
* Because constants are references to objects, changing what a constant refers to generates a warning, but modifying the object itself does not. For example, Greeting << " world!" if Greeting == "Hello" does not generate an error or warning. This is similar to final variables in Java or a const pointer to a non-const object in C++, but Ruby provides the functionality to "freeze" an object, unlike Java.

Some features which differ notably from other languages:

* The usual operators for conditional expressions, and and or, do not follow the normal rules of precedence: and does not bind tighter than or. Ruby also has expression operators || and && which work as expected.

A list of so-called gotchas may be found in Hal Fulton's book The Ruby Way, 2nd ed (ISBN 0-672-32884-4), Section 1.5. A similar list in the 1st edition pertained to an older version of Ruby (version 1.6), some problems of which have been fixed in the meantime. retry, for example, now works with while, until, and for, as well as iterators.
[edit] Interaction
See also: Interactive Ruby Shell

The Ruby official distribution also includes "irb", an interactive command-line interpreter which can be used to test code quickly. The following code fragment represents a sample session using irb:

$ irb
irb(main):001:0> puts "Hello, World"
Hello, World
=> nil
irb(main):002:0> 1+2
=> 3

[edit] Examples

The following examples can be run in a Ruby shell such as Interactive Ruby Shell or saved in a file and run from the command line by typing ruby .

Classic Hello world example:

puts "Hello World!"

Some basic Ruby code:

# Everything, including a literal, is an object, so this works:
-199.abs # 199
"ruby is cool".length # 12
"Your mother is nice.".index("u") # 2
"Nice Day Isn't It?".downcase.split("").uniq.sort.join # " '?acdeinsty"

Conversions:

puts "What's your favorite number?"
number = gets.chomp
output_number = number.to_i + 1
puts output_number.to_s + ' is a bigger and better favorite number.'

[edit] Strings

There are a variety of methods for defining strings in Ruby.

The following assignments are equivalent and support String interpolation:

a = "\nThis is a double-quoted string\n"
a = %Q{\nThis is a double-quoted string\n}
a = %{\nThis is a double-quoted string\n}
a = %/\nThis is a double-quoted string\n/
a = <<-BLOCK

This is a double-quoted string
BLOCK

The following assignments are equivalent and produce raw strings:

a = 'This is a single-quoted string'
a = %q{This is a single-quoted string}

[edit] Collections

Constructing and using an array:

a = [1, 'hi', 3.14, 1, 2, [4, 5]]

puts a[2] # 3.14
puts a.[](2) # 3.14
puts a.reverse # [[4, 5], 2, 1, 3.14, 'hi', 1]
puts a.flatten.uniq # [1, 'hi', 3.14, 2, 4, 5]

Constructing and using an associative array (called hashes in Ruby):

hash = { :water => 'wet', :fire => 'hot' }
puts hash[:fire] # Prints: hot

hash.each_pair do |key, value| # Or: hash.each do |key, value|
puts "#{key} is #{value}"
end

# Prints: water is wet
# fire is hot

hash.delete :water # Deletes :water => 'wet'
hash.delete_if {|key,value| value=='hot'} # Deletes :fire => 'hot'

[edit] Blocks and iterators

The two syntaxes for creating a code block:

{ puts "Hello, World!" } # Note the { braces }
#or
do puts "Hello, World!" end

When a code block is created it is always attached to a method as an optional block argument.

Parameter-passing a block to be a closure:

# In an object instance variable (denoted with '@'), remember a block.
def remember(&a_block)
@block = a_block
end

# Invoke the above method, giving it a block which takes a name.
remember {|name| puts "Hello, #{name}!"}

# When the time is right (for the object) -- call the closure!
@block.call("Jon")
# => "Hello, Jon!"

Creating an anonymous function:

proc {|arg| print arg}
Proc.new {|arg| print arg}
lambda {|arg| print arg}

Returning closures from a method:

def create_set_and_get(initial_value=0) # Note the default value of 0
closure_value = initial_value
return Proc.new {|x| closure_value = x}, Proc.new { closure_value }
end

setter, getter = create_set_and_get # ie. returns two values
setter.call(21)
getter.call # => 21

#You can also use a parameter variable as a binding for the closure.
#So the above can be rewritten as...

def create_set_and_get(closure_value=0)
proc {|x| closure_value = x } , proc { closure_value }
end

Yielding the flow of program control to a block which was provided at calling time:

def use_hello
yield "hello"
end

# Invoke the above method, passing it a block.
use_hello {|string| puts string} # => 'hello'

Iterating over enumerations and arrays using blocks:

array = [1, 'hi', 3.14]
array.each {|item| puts item }
# => 1
# => 'hi'
# => 3.14

array.each_index {|index| puts "#{index}: #{array[index]}" }
# => 0: 1
# => 1: 'hi'
# => 2: 3.14

(3..6).each {|num| puts num }
# => 3
# => 4
# => 5
# => 6

A method such as inject() can accept both a parameter and a block. Inject iterates over each member of a list, performing some function on it while retaining an aggregate. This is analogous to the foldl function in functional programming languages. For example:

[1,3,5].inject(10) {|sum, element| sum + element} # => 19

On the first pass, the block receives 10 (the argument to inject) as sum, and 1 (the first element of the array) as element; this returns 11. 11 then becomes sum on the next pass, which is added to 3 to get 14. 14 is then added to 5, to finally return 19.

Blocks work with many built-in methods:

File.open('file.txt', 'w') do |file| # 'w' denotes "write mode".
file.puts 'Wrote some text.'
end # File is automatically closed here

File.readlines('file.txt').each do |line|
puts line
end
# => Wrote some text.

Using an enumeration and a block to square the numbers 1 to 10:

(1..10).collect {|x| x*x} # => [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

[edit] Classes

The following code defines a class named Person. In addition to 'initialize', the usual constructor to create new objects, it has two methods: one to override the <=> comparison operator (so Array#sort can sort by age) and the other to override the to_s method (so Kernel#puts can format its output). Here, "attr_reader" is an example of metaprogramming in Ruby: "attr_accessor" defines getter and setter methods of instance variables, "attr_reader" only getter methods. Also, the last evaluated statement in a method is its return value, allowing the omission of an explicit 'return'.

class Person
attr_reader :name, :age
def initialize(name, age)
@name, @age = name, age
end
def <=>(person) # Comparison operator for sorting
@age <=> person.age
end
def to_s
"#@name (#@age)"
end
end

group = [
Person.new("Bob", 33),
Person.new("Chris", 16),
Person.new("Ash", 23)
]

puts group.sort.reverse

The above prints three names in reverse age order:

Bob (33)
Ash (23)
Chris (16)

[edit] Open classes

In Ruby, classes are never closed: you can always add methods to an existing class. This applies to the classes you write as well as the standard, built-in classes. All you have to do is open up a class definition for an existing class, and the new contents you specify will be added to whatever's there. A simple example of adding a new method to the standard library's Time class:

# re-open Ruby's Time class
class Time
def yesterday
self - 86400
end
end

today = Time.now # => Thu Aug 14 16:51:50 +1200 2008
yesterday = today.yesterday # => Wed Aug 13 16:51:50 +1200 2008

Adding methods to previously defined classes is often called monkey-patching. This practice, however, can lead to possible collisions of behavior and subsequent unexpected results, and is a concern for code scalability if performed recklessly.
[edit] Exceptions

An exception is raised with a raise call:

raise

An optional message can be added to the exception:

raise "This is a message"

You can also specify which type of exception you want to raise:

raise ArgumentError, "Illegal arguments!"

Alternatively, you can pass an exception instance to the raise method:

raise ArgumentError.new("Illegal arguments!")

This last construct is useful when you need to raise a custom exception class featuring a constructor which takes more than one argument:

class ParseError < Exception
def initialize input, line, pos
super "Could not parse '#{input}' at line #{line}, position #{pos}"
end
end

raise ParseError.new("Foo", 3, 9)

Exceptions are handled by the rescue clause. Such a clause can catch exceptions which inherit from StandardError. Also supported for use with exceptions are else and ensure

begin
# Do something
rescue
# Handle exception
else
# Do this if no exception was raised
ensure
# Do this whether or not an exception was raised
end

It is a common mistake to attempt to catch all exceptions with a simple rescue clause. To catch all exceptions one must write:

begin
# Do something
rescue Exception # don't write just rescue -- that only catches StandardError, a subclass of Exception
# Handle exception
end

Or catch particular exceptions:

begin
# ...
rescue RuntimeError
# handling
end

It is also possible to specify that the exception object be made available to the handler clause:

begin
# ...
rescue RuntimeError => e
# handling, possibly involving e, such as "print e.to_s"
end

Alternatively, the most recent exception is stored in the magic global $!.

You can also catch several exceptions:

begin
# ...
rescue RuntimeError, Timeout::Error => e
# handling, possibly involving e
end

[edit] Metaprogramming

Ruby code can programmatically modify, at runtime, aspects of its own structure that would be fixed in more rigid languages, such as class and method definitions. This sort of metaprogramming can be used to write more concise code and effectively extend the language.

For example, the following Ruby code generates new methods for the built-in String class, based on a list of colors. The methods wrap the contents of the string with an HTML tag styled with the respective color.

COLORS = { :black => "000",
:red => "f00",
:green => "0f0",
:yellow => "ff0",
:blue => "00f",
:magenta => "f0f",
:cyan => "0ff",
:white => "fff" }

class String
COLORS.each do |color,code|
define_method "in_#{color}" do
"#{self}"
end
end
end

The generated methods could then be used like so:

"Hello, World!".in_blue

=> "Hello, World!"

To implement the equivalent in many other languages, the programmer would have to write each method (in_black, in_red, in_green, etc.) by hand.

Some other possible uses for Ruby metaprogramming include:

* intercepting and modifying method calls
* implementing new inheritance models
* dynamically generating classes from parameters
* automatic object serialization
* interactive help and debugging

[edit] More examples

More sample Ruby code is available as algorithms in the following articles:

* Exponentiating by squaring
* Trabb Pardo-Knuth algorithm

[edit] Implementations
See also: Ruby MRI#Operating systems

The newest version of Ruby, the recently released version 1.9, has a single working implementation written in C that utilizes a Ruby-specific virtual machine.

Ruby version 1.8 has two main implementations: The official Ruby interpreter often referred to as the Matz's Ruby Interpreter or MRI, which is the most widely used, and JRuby, a Java-based implementation that runs on the Java Virtual Machine.

There are other less-known or upcoming implementations such as Cardinal (an implementation for the Parrot virtual machine), IronRuby (alpha version available since July 24, 2008),[22] MacRuby (0.6 experimental), MagLev, Rubinius, Ruby.NET, XRuby and HotRuby (runs Ruby source code on a web browser and Flash).

The maturity of Ruby implementations tends to be measured by their ability to run the Ruby on Rails (Rails) framework, because it is a complex framework to implement, and it uses many Ruby-specific features. The point when a particular implementation achieves this goal is called The Rails singularity. As of May 2010, only the reference implementation (MRI) and JRuby are able to run Rails unmodified in a production environment. Rubinius recently released 1.0 and can run Rails,[23] but may not be being used for production sites yet.[24] IronRuby[25][26] is starting to be able to run Rails test cases, but is still far from being production-ready.

Ruby is available on many operating systems such as Linux, Mac OS X, Microsoft Windows, Windows CE and most flavors of Unix.

Ruby 1.9 has recently been ported onto Symbian OS 9.x.[27]
[edit] Repositories and libraries

The Ruby Application Archive (RAA), as well as RubyForge, serve as repositories for a wide range of Ruby applications and libraries, containing more than seven thousand items. Although the number of applications available does not match the volume of material available in the Perl or Python community, there are a wide range of tools and utilities which serve to foster further development in the language.

RubyGems has become the standard package manager for Ruby libraries. It is very similar in purpose to Perl's CPAN, although its usage is more like apt-get.

Recently, many new and existing libraries have found a home on GitHub, which is focused on Git and used to have native support for RubyGems packaging.[28]

Go (programming language)

Go is a compiled, garbage-collected, concurrent programming language developed by Google Inc.[3]

The initial design of Go was started in September 2007 by Robert Griesemer, Rob Pike, and Ken Thompson,[1] building on previous work related to the Inferno operating system.[4] Go was officially announced in November 2009, with implementations released for the Linux and Mac OS X platforms.[5] At the time of its launch, Go was not considered to be ready for adoption in production environments.[6] In May 2010, Rob Pike stated publicly that Go is being used "for real stuff" at Google.[7]

Description

The syntax of Go is close to that of C except for the type declarations; other syntactical differences are the missing parentheses around for and if expressions. It is designed for exceptionally fast compilation times, even on modest hardware.[8] The language requires garbage collection. Certain concurrency-related structural conventions of Go (channels and alternative channel inputs) are borrowed from Tony Hoare's CSP. Unlike previous concurrent programming languages such as occam or Limbo, Go does not provide any in-built notion of safe or verifiable concurrency.[9] Today, Go does not have any kind of built-in generics implementation, but one may be added in the future.[10]

Features not included in Go are type inheritance, generic programming, assertions, method overloading, and pointer arithmetic.[1] Of these, the Go authors express an openness to generic programming, explicitly argue against assertions and pointer arithmetic, while defending the choice to omit type inheritance as giving a more useful language.[1] Initially, the language did not include exception handling, but this was added in March 2010.[11][12] Maps (also known as hashes or dictionaries) are an intrinsic part of the language, as are strings.

Visibility of functions outside of their defining file is defined implicitly according to the capitalization of their identifier, in contrast to C, where an explicit static keyword is used.[13]
[edit] Implementations

There are currently two Go compilers. 6g (and its supporting tools, collectively known as gc) are in C, using yacc/Bison for the parser. Gccgo is a Go compiler with a C++ front-end with a recursive descent parser coupled to the standard GCC backend.[14] Both compilers only work on Unix-like systems, although a Windows version for non-production use is available;[15] it is maintained by a developer named Hector Chu[16] separate from the Go language team.[17] There is also a Go version available for Cygwin.[18] Recently, Windows ports based on mingw are being deployed and updated.[19]
[edit] Examples

The following is a Hello world program in Go:

package main

import "fmt"

func main() {
fmt.Println("Hello, World")
}

Go's automatic semicolon insertion feature requires that opening braces not be placed on their own lines, and this is thus the preferred brace style; the examples shown comply with this style.[20]

Example illustrating how to write a program like the Unix echo command in Go:[21]

package main

import (
"os"
"flag" // command line option parser
)

var omitNewline = flag.Bool("n", false, "don't print final newline")

const (
Space = " "
Newline = "\n"
)

func main() {
flag.Parse() // Scans the arg list and sets up flags
var s string = ""
for i := 0; i < flag.NArg(); i++ {
if i > 0 {
s += Space
}
s += flag.Arg(i)
}
if !*omitNewline {
s += Newline
}
os.Stdout.WriteString(s)
}

[edit] Reception

Go's initial release led to much discussion.

Michele Simionato wrote in an article for artima.com: "Here I just wanted to point out the design choices about interfaces and inheritance. Such ideas are not new and it is a shame that no popular language has followed such particular route in the design space. I hope Go will become popular; if not, I hope such ideas will finally enter in a popular language, we are already 10 or 20 years too late :-("[22]

Dave Astels at Engine Yard wrote: "Go is extremely easy to dive into. There are a minimal number of fundamental language concepts and the syntax is clean and designed to be clear and unambiguous. Go is still experimental and still a little rough around the edges."[23]

Blogger Michael Hoisie wrote: "Overall I think go will find a good niche - a high performance language that's suitable for most system tasks. It has a great initial library, and it seems to have attracted a large community already (the irc chat room currently has over 500 users)."[24]

Ars Technica interviewed Rob Pike, one of the authors of Go, and asked why a new language was needed. He replied that "it wasn't enough to just add features to existing programming languages, because sometimes you can get more in the long run by taking things away. They wanted to start from scratch and rethink everything." They did not want however "to deviate too much from what developers already knew because they wanted to avoid alienating Go's target audience."[6]
[edit] Naming dispute

On the day of the general release of the language, Francis McCabe, developer of the Go! programming language, requested a name change of Google's language to prevent confusion with his language. While McCabe has not trademarked the name, commenters on McCabe's posting have called for Google to adopt a new one. As of 16 December 2009 (2009 -12-16)[update], Google has not commented on the issue, although they let InformationWeek know that they were aware of it.[25]
[edit] Concurrency

Go provides goroutines, small lightweight threads; the name alludes to coroutines. Goroutines are created with the "go" statement from anonymous or normal functions.

Goroutines are executed in parallel with other goroutines, including their caller. They do not necessarily run in separate threads, but a group of goroutines are multiplexed onto multiple threads — execution control is moved between them by blocking them when sending or receiving messages over channels.
[edit] Popularity

Go entered the TIOBE Programming Community Index[26] at fifteenth place in its first year, surpassing established languages like Pascal. But as of June 2010[update], it has dropped out of the top 20. As of 1 August 2010 (2010 -08-01)[update], it is in the 20th place.

Django (web framework)

Django (pronounced /ˈdʒæŋɡoʊ/ JANG-goh[1]) is an open source web application framework, written in Python, which follows the model-view-controller architectural pattern.[2] It was originally developed to manage several news-oriented sites for The World Company[3] of Lawrence, Kansas, and was released publicly under a BSD license in July 2005; the framework was named after gypsy jazz guitarist Django Reinhardt.[4] In June 2008 it was announced that a newly formed Django Software Foundation will take care of Django in the future. [5]

Django's primary goal is to ease the creation of complex, database-driven websites. Django emphasizes reusability and "pluggability" of components, rapid development, and the principle of DRY (Don't Repeat Yourself). Python is used throughout, even for settings, files, and data models.

Django also provides an optional administrative CRUD (create, read, update and delete) interface that is generated dynamically through introspection and configured via admin models.




Components
Screenshot of the Django admin interface for modifying a user.

The core Django framework consists of an object-relational mapper which mediates between data models (defined as Python classes) and a relational database; a regular-expression-based URL dispatcher; a view system for processing requests; and a templating system.

Also included in the core framework are:

* A lightweight, standalone web server for development and testing.
* A form serialization and validation system which can translate between HTML forms and values suitable for storage in the database.
* A caching framework which can use any of several cache methods.
* Support for middleware classes which can intervene at various stages of request processing and carry out custom functions.
* An internal dispatcher system which allows components of an application to communicate events to each other via pre-defined signals.
* An internationalization system, including translations of Django's own components into a variety of languages.
* A serialization system which can produce and read XML and/or JSON representations of Django model instances.
* A system for extending the capabilities of the template engine.
* An interface to Python's built-in unit test framework.

[edit] Bundled applications

The main Django distribution also bundles a number of applications in its "contrib" package, including:

* An extensible authentication system.
* The dynamic administrative interface.
* Tools for generating RSS and Atom syndication feeds.
* A flexible commenting system.
* A sites framework that allows one Django installation to run multiple websites, each with their own content and applications
* Tools for generating Google Sitemaps.
* Tools for preventing cross-site request forgery.
* Template libraries which enable the use of lightweight markup languages such as Textile and Markdown.
* A framework for creating GIS applications.

[edit] Applications built on Django

* The Pinax framework provides reusable applications aimed at Django-based social networking websites.
* RapidSMS is a framework for SMS applications built on Django.
* Pootle is an online translation management tool.
* Review Board is a web-based code review tool.

[edit] Server arrangements

Django can be run in conjunction with Apache using mod_python or mod_wsgi. Django also includes the ability to launch a FastCGI server, enabling use behind any web server which supports FastCGI. It should also be possible to use other WSGI-compliant web servers. Django officially supports four database backends: PostgreSQL, MySQL, SQLite and Oracle. MS SQL backend can be used with django-mssql but only in Microsoft operating systems, similarly external backends exist for IBM DB2 and SQL Anywhere.

Django may also be run in conjunction with Jython on any Java EE application server such as GlassFish or JBoss. In this case django-jython must be installed in order to provide JDBC drivers for database connectivity, which also provides functionality to compile Django in to a .war suitable for deployment.

Versions of Django prior to 1.0 had multithreading issues [6] and it would be recommended that those versions of Django only be used in a single threaded server configuration, such as with Apache prefork MPM using mod_python or embedded mode of mod_wsgi. Although Django 1.0 is principally believed to now be thread safe, some minor threading issues are still occasionally being found; it may be prudent to continue to use a single threaded server configuration and/or stay current with Django releases and notices about the multithreading issues. [6]

Google App Engine includes Django 0.96.1[7] as one of the bundled frameworks.
[edit] Django books

* July 2009: Apress published the second edition of the book The Definitive Guide to Django, for version 1.1, released under the GNU Free Document License (the first edition of the book was published in December 2007.)[8]
* June 2009: Apress published the second edition of the book Practical Django Projects by James Bennett (the first edition was released in June 2008.)[9]
* March 2009: Packt Publishing published Django 1.0 Website Development by Ayman Hourieh [10]
* December 2008: Packt Publishing published Django 1.0 Template Development by Scott Newman [11]
* December 2008: Apress also published the book Pro Django by Marty Alchin.[12]
* November 2008: Addison-Wesley published Python Web Development with Django by Jeff Forcier, Wesley Chun, and Paul Bissex. [13]
* April 2008: Packt Publishing published Learning Website Development with Django by Ayman Hourieh [14]

Brain–computer interface

A brain–computer interface (BCI), sometimes called a direct neural interface or a brain–machine interface, is a direct communication pathway between a brain and an external device. BCIs are often aimed at assisting, augmenting or repairing human cognitive or sensory-motor functions.

Research on BCIs began in the 1970s at the University of California Los Angeles (UCLA) under a grant from the National Science Foundation, followed by a contract from DARPA.[1][2] The papers published after this research also mark the first appearance of the expression brain–computer interface in scientific literature.

The field of BCI has since blossomed spectacularly, mostly toward neuroprosthetics applications that aim at restoring damaged hearing, sight and movement. Thanks to the remarkable cortical plasticity of the brain, signals from implanted prostheses can, after adaptation, be handled by the brain like natural sensor or effector channels.[3] Following years of animal experimentation, the first neuroprosthetic devices implanted in humans appeared in the mid-nineties.


BCI versus neuroprosthetics
Main article: Neuroprosthetics

Neuroprosthetics is an area of neuroscience concerned with neural prostheses—using artificial devices to replace the function of impaired nervous systems or sensory organs. The most widely used neuroprosthetic device is the cochlear implant, which, as of 2006, has been implanted in approximately 100,000 people worldwide.[4] There are also several neuroprosthetic devices that aim to restore vision, including retinal implants.

The differences between BCIs and neuroprosthetics are mostly in the ways the terms are used: neuroprosthetics typically connect the nervous system to a device, whereas BCIs usually connect the brain (or nervous system) with a computer system. Practical neuroprosthetics can be linked to any part of the nervous system—for example, peripheral nerves—while the term "BCI" usually designates a narrower class of systems which interface with the central nervous system.

The terms are sometimes used interchangeably, and for good reason. Neuroprosthetics and BCIs seek to achieve the same aims, such as restoring sight, hearing, movement, ability to communicate, and even cognitive function. Both use similar experimental methods and surgical techniques.
[edit] Animal BCI research
Rats implanted with BCIs in Theodore Berger's experiments

Several laboratories have managed to record signals from monkey and rat cerebral cortices in order to operate BCIs to carry out movement. Monkeys have navigated computer cursors on screen and commanded robotic arms to perform simple tasks simply by thinking about the task and without any motor output.[5] In May 2008 photographs that showed a monkey operating a robotic arm with its mind at the Pittsburgh University Medical Center were published in a number of well known science journals and magazines.[6] Other research on cats has decoded visual signals.
[edit] Early work
Monkey operating a robotic arm with brain–computer interfacing

The operant conditioning studies of Fetz and colleagues first showed that monkeys could learn to control the deflection of a biofeedback meter arm with neural activity .[7] Such work in the 1970s established that monkeys could quickly learn to voluntarily control the firing rates of individual and multiple neurons in the primary motor cortex if they were rewarded for generating appropriate patterns of neural activity.[8]

Studies that developed algorithms to reconstruct movements from motor cortex neurons, which control movement, date back to the 1970s. In the 1980s, Apostolos Georgopoulos at Johns Hopkins University found a mathematical relationship between the electrical responses of single motor-cortex neurons in rhesus macaque monkeys and the direction that monkeys moved their arms (based on a cosine function). He also found that dispersed groups of neurons in different areas of the brain collectively controlled motor commands but was only able to record the firings of neurons in one area at a time because of technical limitations imposed by his equipment.[9]

There has been rapid development in BCIs since the mid-1990s.[10] Several groups have been able to capture complex brain motor centre signals using recordings from neural ensembles (groups of neurons) and use these to control external devices, including research groups led by Richard Andersen, John Donoghue, Phillip Kennedy, Miguel Nicolelis, and Andrew Schwartz.
[edit] Prominent research successes

Phillip Kennedy and colleagues built the first intracortical brain–computer interface by implanting neurotrophic-cone electrodes into monkeys.
Yang Dan and colleagues' recordings of cat vision using a BCI implanted in the lateral geniculate nucleus (top row: original image; bottom row: recording)

In 1999, researchers led by Yang Dan at University of California, Berkeley decoded neuronal firings to reproduce images seen by cats. The team used an array of electrodes embedded in the thalamus (which integrates all of the brain’s sensory input) of sharp-eyed cats. Researchers targeted 177 brain cells in the thalamus lateral geniculate nucleus area, which decodes signals from the retina. The cats were shown eight short movies, and their neuron firings were recorded. Using mathematical filters, the researchers decoded the signals to generate movies of what the cats saw and were able to reconstruct recognizable scenes and moving objects.[11] Similar results in humans have been since then achieved by researchers in Japan (see below).

Miguel Nicolelis has been a prominent proponent of using multiple electrodes spread over a greater area of the brain to obtain neuronal signals to drive a BCI. Such neural ensembles are said to reduce the variability in output produced by single electrodes, which could make it difficult to operate a BCI.

After conducting initial studies in rats during the 1990s, Nicolelis and his colleagues developed BCIs that decoded brain activity in owl monkeys and used the devices to reproduce monkey movements in robotic arms. Monkeys have advanced reaching and grasping abilities and good hand manipulation skills, making them ideal test subjects for this kind of work.

By 2000, the group succeeded in building a BCI that reproduced owl monkey movements while the monkey operated a joystick or reached for food.[12] The BCI operated in real time and could also control a separate robot remotely over Internet protocol. But the monkeys could not see the arm moving and did not receive any feedback, a so-called open-loop BCI.
Diagram of the BCI developed by Miguel Nicolelis and colleagues for use on Rhesus monkeys

Later experiments by Nicolelis using rhesus monkeys, succeeded in closing the feedback loop and reproduced monkey reaching and grasping movements in a robot arm. With their deeply cleft and furrowed brains, rhesus monkeys are considered to be better models for human neurophysiology than owl monkeys. The monkeys were trained to reach and grasp objects on a computer screen by manipulating a joystick while corresponding movements by a robot arm were hidden.[13][14] The monkeys were later shown the robot directly and learned to control it by viewing its movements. The BCI used velocity predictions to control reaching movements and simultaneously predicted hand gripping force.

Other labs that develop BCIs and algorithms that decode neuron signals include John Donoghue from Brown University, Andrew Schwartz from the University of Pittsburgh and Richard Andersen from Caltech. These researchers were able to produce working BCIs even though they recorded signals from far fewer neurons than Nicolelis (15–30 neurons versus 50–200 neurons).

Donoghue's group reported training rhesus monkeys to use a BCI to track visual targets on a computer screen with or without assistance of a joystick (closed-loop BCI).[15] Schwartz's group created a BCI for three-dimensional tracking in virtual reality and also reproduced BCI control in a robotic arm.[16] The group created headlines when they demonstrated that a monkey could feed itself pieces of zucchini using a robotic arm controlled by the animal's own brain signals.[17][18]

Andersen's group used recordings of premovement activity from the posterior parietal cortex in their BCI, including signals created when experimental animals anticipated receiving a reward.[19]

In addition to predicting kinematic and kinetic parameters of limb movements, BCIs that predict electromyographic or electrical activity of muscles are being developed.[20] Such BCIs could be used to restore mobility in paralyzed limbs by electrically stimulating muscles.

Miguel Nicolelis et al. showed that activity of large neural ensembles can predict arm position. This work made possible creation of brain–machine interfaces — electronic devices that read arm movement intentions and translate them into movements of artificial actuators. Carmena et al.[13] programmed the neural coding in a brain–machine interface allowed a monkey to control reaching and grasping movements by a robotic arm, and Lebedev et al.[14] argued that brain networks reorganize to create a new representation of the robotic appendage in addition to the representation of the animal's own limbs.

The biggest impediment of BCI technology at present is the lack of a sensor modality that provides safe, accurate, and robust access to brain signals. It is conceivable or even likely that such a sensor will be developed within the next twenty years. The use of such a sensor should greatly expand the range of communication functions that can be provided using a BCI.

Development and implementation of a Brain–Computer Interface (BCI) system is complex and time consuming. In response to this problem, Dr. Gerwin Schalk has been developing a general-purpose system for BCI research, called BCI2000. BCI2000 has been in development since 2000 in a project led by the Brain–Computer Interface R&D Program at the Wadsworth Center of the New York State Department of Health in Albany, New York, USA.

A new 'wireless' approach uses light-gated ion channels such as Channelrhodopsin to control the activity of genetically defined subsets of neurons in vivo. In the context of a simple learning task, illumination of transfected cells in the somatosensory cortex influenced the decision making process of freely moving mice.[21]
[edit] Human BCI research
[edit] Invasive BCIs

Invasive BCI research has targeted repairing damaged sight and providing new functionality to persons with paralysis. Invasive BCIs are implanted directly into the grey matter of the brain during neurosurgery. As they rest in the grey matter, invasive devices produce the highest quality signals of BCI devices but are prone to scar-tissue build-up, causing the signal to become weaker or even lost as the body reacts to a foreign object in the brain.
Jens Naumann, a man with acquired blindness, being interviewed about his vision BCI on CBS's The Early Show

In vision science, direct brain implants have been used to treat non-congenital (acquired) blindness. One of the first scientists to come up with a working brain interface to restore sight was private researcher William Dobelle.

Dobelle's first prototype was implanted into "Jerry", a man blinded in adulthood, in 1978. A single-array BCI containing 68 electrodes was implanted onto Jerry’s visual cortex and succeeded in producing phosphenes, the sensation of seeing light. The system included cameras mounted on glasses to send signals to the implant. Initially, the implant allowed Jerry to see shades of grey in a limited field of vision at a low frame-rate. This also required him to be hooked up to a two-ton mainframe, but shrinking electronics and faster computers made his artificial eye more portable and now enable him to perform simple tasks unassisted.[22]
Dummy unit illustrating the design of a BrainGate interface

In 2002, Jens Naumann, also blinded in adulthood, became the first in a series of 16 paying patients to receive Dobelle’s second generation implant, marking one of the earliest commercial uses of BCIs. The second generation device used a more sophisticated implant enabling better mapping of phosphenes into coherent vision. Phosphenes are spread out across the visual field in what researchers call the starry-night effect. Immediately after his implant, Jens was able to use his imperfectly restored vision to drive slowly around the parking area of the research institute.

BCIs focusing on motor neuroprosthetics aim to either restore movement in individuals with paralysis or provide devices to assist them, such as interfaces with computers or robot arms.

Researchers at Emory University in Atlanta led by Philip Kennedy and Roy Bakay were first to install a brain implant in a human that produced signals of high enough quality to simulate movement. Their patient, Johnny Ray (1944–2002), suffered from ‘locked-in syndrome’ after suffering a brain-stem stroke in 1997. Ray’s implant was installed in 1998 and he lived long enough to start working with the implant, eventually learning to control a computer cursor; he died in 2002 of a brain aneurysm.[23]

Tetraplegic Matt Nagle became the first person to control an artificial hand using a BCI in 2005 as part of the first nine-month human trial of Cyberkinetics Neurotechnology’s BrainGate chip-implant. Implanted in Nagle’s right precentral gyrus (area of the motor cortex for arm movement), the 96-electrode BrainGate implant allowed Nagle to control a robotic arm by thinking about moving his hand as well as a computer cursor, lights and TV.[24] One year later, professor Jonathan Wolpaw received the prize of the Altran Foundation for Innovation to develop a Brain Computer Interface with electrodes located on the surface of the skull, instead of directly in the brain.
[edit] Partially-invasive BCIs

Partially invasive BCI devices are implanted inside the skull but rest outside the brain rather than within the grey matter. They produce better resolution signals than non-invasive BCIs where the bone tissue of the cranium deflects and deforms signals and have a lower risk of forming scar-tissue in the brain than fully-invasive BCIs.

Electrocorticography (ECoG) measures the electrical activity of the brain taken from beneath the skull in a similar way to non-invasive electroencephalography (see below), but the electrodes are embedded in a thin plastic pad that is placed above the cortex, beneath the dura mater.[25] ECoG technologies were first trialed in humans in 2004 by Eric Leuthardt and Daniel Moran from Washington University in St Louis. In a later trial, the researchers enabled a teenage boy to play Space Invaders using his ECoG implant.[26] This research indicates that control is rapid, requires minimal training, and may be an ideal tradeoff with regards to signal fidelity and level of invasiveness.

(Note: These electrodes were not implanted in the patients for BCI experiments. The patient was suffering from severe epilepsy and had the electrodes temporarily implanted to help his physicians localize seizure foci; the researchers simply took advantage of this.)

Light Reactive Imaging BCI devices are still in the realm of theory. These would involve implanting a laser inside the skull. The laser would be trained on a single neuron and the neuron's reflectance measured by a separate sensor. When the neuron fires, the laser light pattern and wavelengths it reflects would change slightly. This would allow researchers to monitor single neurons but require less contact with tissue and reduce the risk of scar-tissue build-up.

This signal can be either subdural or epidural, but is not taken from within the brain parenchyma itself. It has not been studied extensively until recently due to the limited access of subjects. Currently, the only manner to acquire the signal for study is through the use of patients requiring invasive monitoring for localization and resection of an epileptogenic focus.

ECoG is a very promising intermediate BCI modality because it has higher spatial resolution, better signal-to-noise ratio, wider frequency range, and lesser training requirements than scalp-recorded EEG, and at the same time has lower technical difficulty, lower clinical risk, and probably superior long-term stability than intracortical single-neuron recording. This feature profile and recent evidence of the high level of control with minimal training requirements shows potential for real world application for people with motor disabilities.
[edit] Non-invasive BCIs

As well as invasive experiments, there have also been experiments in humans using non-invasive neuroimaging technologies as interfaces. Signals recorded in this way have been used to power muscle implants and restore partial movement in an experimental volunteer. Although they are easy to wear, non-invasive implants produce poor signal resolution because the skull dampens signals, dispersing and blurring the electromagnetic waves created by the neurons. Although the waves can still be detected it is more difficult to determine the area of the brain that created them or the actions of individual neurons.
[edit] EEG
Main article: Electroencephalography
Recordings of brainwaves produced by an electroencephalogram

Electroencephalography (EEG) is the most studied potential non-invasive interface, mainly due to its fine temporal resolution, ease of use, portability and low set-up cost. But as well as the technology's susceptibility to noise, another substantial barrier to using EEG as a brain–computer interface is the extensive training required before users can work the technology. For example, in experiments beginning in the mid-1990s, Niels Birbaumer of the University of Tübingen in Germany trained severely paralysed people to self-regulate the slow cortical potentials in their EEG to such an extent that these signals could be used as a binary signal to control a computer cursor.[27] (Birbaumer had earlier trained epileptics to prevent impending fits by controlling this low voltage wave.) The experiment saw ten patients trained to move a computer cursor by controlling their brainwaves. The process was slow, requiring more than an hour for patients to write 100 characters with the cursor, while training often took many months.

Another research parameter is the type of waves measured. Birbaumer's later research with Jonathan Wolpaw at New York State University has focused on developing technology that would allow users to choose the brain signals they found easiest to operate a BCI, including mu and beta rhythms.

A further parameter is the method of feedback used and this is shown in studies of P300 signals. Patterns of P300 waves are generated involuntarily (stimulus-feedback) when people see something they recognize and may allow BCIs to decode categories of thoughts without training patients first. By contrast, the biofeedback methods described above require learning to control brainwaves so the resulting brain activity can be detected.

Lawrence Farwell and Emanuel Donchin developed an EEG-based brain–computer interface in the 1980s.[28] Their "mental prosthesis" used the P300 brainwave response to allow subjects, including one paralyzed Locked-In syndrome patient, to communicate words, letters, and simple commands to a computer and thereby to speak through a speech synthesizer driven by the computer. A number of similar devices have been developed since then. In 2000, for example, research by Jessica Bayliss at the University of Rochester showed that volunteers wearing virtual reality helmets could control elements in a virtual world using their P300 EEG readings, including turning lights on and off and bringing a mock-up car to a stop.[29]

In the early 90s Babak Taheri, at UC DAVIS demonstrated the first single and also multichannel dry active electrode arrays using micro-machining. The single channel dry EEG electrode construction and results were published in 1994.[30] The arrayed electrode was also demonstrated to perform well compared to silver silver chloride electrodes. The device consisted of four sites of sensors with integrated electronics to reduce noise by impedance matching. The advantages of such electrodes are: (1) no electrolyte used, (2) no skin preparation, (3) significantly reduced sensor size, and (4) compatibility with EEG monitoring systems. The active electrode array is an integrated system made of an array of capacitive sensors with local integrated circuitry housed in a package with batteries to power the circuitry. This level of integration was required to achieve the functional performance obtained by the electrode. The electrode was tested on an electrical test bench and on human subjects in four modalities of EEG activity, namely: (1) spontaneous EEG, (2) sensory event-related potentials, (3) brain stem potentials, and (4) cognitive event-related potentials. The performance of the dry electrode compared favorably with that of the standard wet Ag/AgCl electrodes in terms of skin preparation, no gel requirements (dry), and higher signal-to-noise ratio.[31]

In 1999, researchers at Case Western Reserve University led by Hunter Peckham, used 64-electrode EEG skullcap to return limited hand movements to quadriplegic Jim Jatich. As Jatich concentrated on simple but opposite concepts like up and down, his beta-rhythm EEG output was analysed using software to identify patterns in the noise. A basic pattern was identified and used to control a switch: Above average activity was set to on, below average off. As well as enabling Jatich to control a computer cursor the signals were also used to drive the nerve controllers embedded in his hands, restoring some movement.[32]

Electronic neural networks have been deployed which shift the learning phase from the user to the computer. Experiments by scientists at the Fraunhofer Society in 2004 using neural networks led to noticeable improvements within 30 minutes of training.[33]

Experiments by Eduardo Miranda aim to use EEG recordings of mental activity associated with music to allow the disabled to express themselves musically through an encephalophone.[34]

The Emotiv company plans to produce a commercial video game controller (known as the Epoc) in December 21, 2009, which uses electromagnetic sensors.[35]
[edit] MEG and MRI
Main articles: Magnetoencephalography and Magnetic resonance imaging
ATR Labs' reconstruction of human vision using fMRI (top row: original image; bottom row: reconstruction from mean of combined readings)

Magnetoencephalography (MEG) and functional magnetic resonance imaging (fMRI) have both been used successfully as non-invasive BCIs.[36] In a widely reported experiment, fMRI allowed two users being scanned to play Pong in real-time by altering their haemodynamic response or brain blood flow through biofeedback techniques.[37]

fMRI measurements of haemodynamic responses in real time have also been used to control robot arms with a seven second delay between thought and movement.[38]

More recently, research developed in the Advanced Telecommunications Research (ATR) Computational Neuroscience Laboratories in Kyoto, Japan allowed the scientists to reconstruct images directly from the brain and display them on a computer. The article announcing these achievements was the cover story of the journal Neuron of 10 December 2008,[39] While the early results are limited to black and white images of 10x10 squares (pixels), according to the researchers further development of the technology may make it possible to achieve color images, and even view or record dreams.[40][41]
[edit] Commercialization and companies

John Donoghue and fellow researchers founded Cyberkinetics. The company markets its electrode arrays under the BrainGate product name and has set the development of practical BCIs for humans as its major goal. The BrainGate is based on the Utah Array developed by Dick Normann.

Philip Kennedy founded Neural Signals in 1987 to develop BCIs that would allow paralysed patients to communicate with the outside world and control external devices. As well as an invasive BCI, the company also sells an implant to restore speech. Neural Signals' Brain Communicator BCI device uses glass cones containing microelectrodes coated with proteins to encourage the electrodes to bind to neurons.

Although 16 paying patients were treated using William Dobelle's vision BCI, new implants ceased within a year of Dobelle's death in 2004. A company controlled by Dobelle, Avery Biomedical Devices, and Stony Brook University are continuing development of the implant, which has not yet received Food and Drug Administration approval in the United States for human implantation.[42]

Ambient, at a TI developers conference in early 2008, demoed a product they have in development call The Audeo. The Audeo is being developed to create a human–computer interface for communication without the need of physical motor control or speech production. Using signal processing, unpronounced speech representing the thought of the mind can be translated from intercepted neurological signals.[43]

Mindball is a product developed and commercialized by Interactive Productline in which players compete to control a ball's movement across a table by becoming more relaxed and focused.[44] Interactive Productline is a Swedish company whose objective is to develop and sell easy understandable EEG products that train the ability to relax and focus.[45]

An Austrian company, Guger Technologies,[46] g.tec, has been offering Brain Computer Interface systems since 1999. The company provides base BCI models as development platforms for the research community to build upon, including the P300 Speller, Motor Imagery, and mu-rhythm. They commercialized a Steady State Visual Evoked Potiential BCI solution in 2008 with 4 degrees of machine control.

A Spanish company, Starlab, has entered this market in 2009 with a wireless 4-channel system called ENOBIO. Designed for research purposes the system provides a platform for application development.[47]

There are three main consumer-devices commercial-competitors in this area (expected launch date mentioned in brackets) which are going to launch such devices primarily for gaming- and PC-users:

* Neural Impulse Actuator (April, 2008)
* Emotiv Systems (December, 2009)
* NeuroSky (MindSet – June, 2009; Uncle Milton Force Trainer – Fall 2009, Mattel MindFlex – Summer, 2009)

[edit] Synthetic telepathy

Research is ongoing into synthetic or computer-mediated telepathy which would allow user-to-user communication through analysis of neural signals.[48] The research aims to detect and analyze the word-specific neural signals, using EEG, which occur before speech is vocalized, and to see if the patterns are generalizable.[48] As of 2009[update], the research is focused on military uses[48] but it could also find medical applications enabling communication with people suffering a loss of Motor coordination.[49]
[edit] Cell-culture BCIs
Main article: Cultured neuronal networks

Researchers have built devices to interface with neural cells and entire neural networks in cultures outside animals. As well as furthering research on animal implantable devices, experiments on cultured neural tissue have focused on building problem-solving networks, constructing basic computers and manipulating robotic devices. Research into techniques for stimulating and recording from individual neurons grown on semiconductor chips is sometimes referred to as neuroelectronics or neurochips.[50]
World first: Neurochip developed by Caltech researchers Jerome Pine and Michael Maher

Development of the first working neurochip was claimed by a Caltech team led by Jerome Pine and Michael Maher in 1997.[51] The Caltech chip had room for 16 neurons.

In 2003, a team led by Theodore Berger at the University of Southern California started work on a neurochip designed to function as an artificial or prosthetic hippocampus. The neurochip was designed to function in rat brains and is intended as a prototype for the eventual development of higher-brain prosthesis. The hippocampus was chosen because it is thought to be the most ordered and structured part of the brain and is the most studied area. Its function is to encode experiences for storage as long-term memories elsewhere in the brain.[52]

Thomas DeMarse at the University of Florida used a culture of 25,000 neurons taken from a rat's brain to fly a F-22 fighter jet aircraft simulator.[53] After collection, the cortical neurons were cultured in a petri dish and rapidly began to reconnect themselves to form a living neural network. The cells were arranged over a grid of 60 electrodes and used to control the pitch and yaw functions of the simulator. The study's focus was on understanding how the human brain performs and learns computational tasks at a cellular level.
[edit] Ethical considerations

There has not been a vigorous debate about the ethical implications of BCIs, even though there are several commercially available systems such as brain pacemakers used to treat neurological conditions, and could theoretically be used to modify other behaviours.

Jens Clausen from the Institute for Ethics and History of Medicine considers the important topics in the neuroethical debate to be:[54][55][56] 1) obtaining informed consent from people who have difficulty communicating, 2) risk/benefit analysis 3) shared responsibility of BCI teams (e.g. how to ensure that responsible group decisions can be made), 4) the consequences of BCI technology for the quality of life of patients and their families, 5) side-effects (e.g. neurofeedback of sensorimotor rhythm training is reported to affect sleep quality) 6) personal responsibility and its possible constraints (e.g. who is responsible for erroneous actions with a neuroprosthesis), 7) issues concerning personality and personhood and its possible alteration, 8) therapeutic applications and their possible exceedance, 9) questions of research ethics that arise when progressing from animal experimentation to application in human subjects, 10) mind-reading and privacy, 11) mind-control, 12) selective enhancement and social stratification and 13) communication to the media.

Emory University neuroscience professor Michael Crutcher has expressed concern about BCIs, specifically ear and eye implants: "If only the rich can afford it, it puts everyone else at a disadvantage."[57] Clausen concluded in 2009 that “BCIs pose ethical challenges, but these are conceptually similar to those that bioethicists have addressed for other realms of therapy”[58]. Moreover, he suggests that bioethics is well-prepared to deal with the issues that arise with BCI technologies. Haselager and colleagues [59] pointed out that expectations of BCI efficacy and value play a great role in ethical analysis and the way BCI scientists should approach media. Furthermore, standard protocols can be implemented to ensure ethically sound informed-consent procedures with locked-in patients.

Researchers are well aware that sound ethical guidelines, appropriately moderated enthusiasm in media coverage and education about BCI systems will be of utmost importance for the societal acceptence of this technology. Thus, recently more effort is made inside the BCI community to initiate the development of ethical guidelines for BCI research, development and dissemination.[citation needed]
[edit] Theme in fiction
See also: Category:Brain-computer interfacing in fiction

The prospect of BCIs and brain implants of all kinds have been important themes in science fiction. See brain implants in fiction and philosophy for a review of this literature.