The main method of a program.

In a module, the instructions defined outside any classes or methods (usually called the main of the module) is an implicit definition of this main method. Basically it means that the following program

print "Hello World"

is equivalent with

redef class Sys
   redef fun main do
      print "Hello World"
   end
end

Property definitions

core $ Sys :: main
	# The main method of a program.
	#
	# In a module, the instructions defined outside any classes or methods
	# (usually called the *main* of the module) is
	# an implicit definition of this `main` method.
	# Basically it means that the following program
	#
	# ~~~nit
	# print "Hello World"
	# ~~~
	#
	# is equivalent with
	#
	# ~~~nit
	# redef class Sys
	#    redef fun main do
	#       print "Hello World"
	#    end
	# end
	# ~~~
	fun main do end
lib/core/kernel.nit:261,2--281,16

app :: app_base $ Sys :: main
if "NIT_TESTING".environ == "true" then exit 0

test_bound_platform

app.setup
app.run
lib/app/app_base.nit:132,1--137,7

functional :: functional_gen $ Sys :: main
var fw = new FileWriter.open("functional_types.nit")
generate_functypes(20, fw)
lib/functional/functional_gen.nit:147,1--148,26

ai :: queens $ Sys :: main
var quiet = false

# The board size
var size = 8

# Basic argument parsing
if args.length > 0 and args.first == "-q" then
	args.shift
	quiet = true
end
if args.length > 0 then
	size = args.first.to_i
	if size <= 0 then
		print "usage: queens [-q] [size]\n -q for quiet"
		exit 1
	end
end

print "The {size}-queens problem"
var pb = new QueenProblem(size)
var s = pb.solve
var sols = 0
while s.is_running do
	if s.run != null then
		if not quiet then pb.print_state(s.state)
		sols += 1
	end
end
print "Found {sols} solutions"
lib/ai/examples/queens.nit:125,1--153,30

cocoa :: hello_cocoa $ Sys :: main
hello_world
lib/cocoa/examples/hello_cocoa.nit:29,1--11

dot :: clusters $ Sys :: main
var graph = new DotGraph("G", "digraph")

var cl0 = new DotGraph("cluster_0", "subgraph")
cl0["label"] = "process #1"
cl0["style"] = "filled"
cl0["color"] = "lightgrey"
cl0.nodes_attrs["style"] = "filled"
cl0.nodes_attrs["color"] = "white"

var a0 = cl0.add_node("a0")
var a1 = cl0.add_node("a1")
var a2 = cl0.add_node("a2")
var a3 = cl0.add_node("a3")
cl0.add_edge(a0, a1)
cl0.add_edge(a1, a2)
cl0.add_edge(a2, a3)

graph.add cl0

var cl1 = new DotGraph("cluster_1", "subgraph")
cl1["label"] = "process #2"
cl1["color"] = "blue"
cl1.nodes_attrs["style"] = "filled"

var b0 = cl1.add_node("b0")
var b1 = cl1.add_node("b1")
var b2 = cl1.add_node("b2")
var b3 = cl1.add_node("b3")
cl1.add_edge(b0, b1)
cl1.add_edge(b1, b2)
cl1.add_edge(b2, b3)

graph.add cl1

var start = graph.add_node("start")
start["shape"] = "Mdiamond"

var nend = graph.add_node("end")
nend["shape"] = "Msquare"

graph.add_edge(start, a0)
graph.add_edge(start, b0)
graph.add_edge(a1, b3)
graph.add_edge(b2, a3)
graph.add_edge(a3, a0)
graph.add_edge(a3, nend)
graph.add_edge(b3, nend)

if args.is_empty then
	print graph.to_dot
	# graph.show
else
	graph.to_dot.write_to_file args.first
end
lib/dot/examples/clusters.nit:20,1--73,3

dot :: hello $ Sys :: main
var graph = new DotGraph("G", "digraph")

var hello = graph.add_node("hello")
var world = graph.add_node("world")
graph.add_edge(hello, world)

if args.is_empty then
	print graph.to_dot
else
	graph.to_dot.write_to_file args.first
end
lib/dot/examples/hello.nit:20,1--30,3

dot :: undirected_clusters $ Sys :: main
var graph = new DotGraph("G", "graph")

var a = new DotNode("a")
var b = new DotNode("b")
var c = new DotNode("c")
var d = new DotNode("d")
var e = new DotNode("e")
var f = new DotNode("f")
var g = new DotNode("g")

var clA = new DotGraph("clusterA", "subgraph")
clA.add_edge(a, b).directed = false
graph.add clA

var clB = new DotGraph("clusterB", "subgraph")
clB.add_edge(c, d).directed = false
clA.add clB

var clC = new DotGraph("clusterC", "subgraph")
clC.add_edge(e, g).directed = false
graph.add clC

graph.add_edge(e, d).directed = false
graph.add_edge(f, g).directed = false

if args.is_empty then
	print graph.to_dot
else
	graph.to_dot.write_to_file args.first
end
lib/dot/examples/undirected_clusters.nit:20,1--49,3

html :: html_page $ Sys :: main
var page = new NitHomepage
page.write_to stdout
page.write_to_file("nit.html")
lib/html/examples/html_page.nit:105,1--107,30

curl :: curl_http $ Sys :: main
if args.length < 2 then
	print_usage
	exit 1
end

var url = args[1]
var request = new CurlHTTPRequest(url)
request.verbose = false # Set to `true` to debug

if args[0] == "GET" then
	# HTTP Get Request
	var response = request.execute

	if response isa CurlResponseSuccess then
		print "Status code: {response.status_code}"
		print "Body: {response.body_str}"
	else if response isa CurlResponseFailed then
		print "Error code: {response.error_code}"
		print "Error msg: {response.error_msg}"
	end

else if args[0] == "POST" then
	# HTTP Post Request
	var my_http_fetcher = new MyHttpFetcher
	request.delegate = my_http_fetcher

	var post_data = new HeaderMap
	post_data["Bugs Bunny"] = "Daffy Duck"
	post_data["Batman"] = "Robin likes special characters @#ùà!è§'(\"é&://,;<>∞~*"
	post_data["Batman"] = "Yes you can set multiple identical keys, but APACHE will consider only one, the last one"
	request.data = post_data
	var response = request.execute

	print "Our body from the callback: {my_http_fetcher.fetched_body}"

	if response isa CurlResponseSuccess then
		print "*** Answer ***"
		print "Status code: {response.status_code}"
		print "Body should be empty, because we decided to manage callbacks: {response.body_str.length}"
	else if response isa CurlResponseFailed then
		print "Error code: {response.error_code}"
		print "Error msg: {response.error_msg}"
	end

else if args[0] == "GET_FILE" then
	# HTTP Get to file Request
	var headers = new HeaderMap
	headers["Accept"] = "Moo"
	request.headers = headers
	var response = request.download_to_file(null)

	if response isa CurlFileResponseSuccess then
		print "*** Answer ***"
		print "Status code: {response.status_code}"
		print "Size downloaded: {response.size_download}"
	else if response isa CurlResponseFailed then
		print "Error code: {response.error_code}"
		print "Error msg: {response.error_msg}"
	end

else
	print_usage
	exit 1
end
lib/curl/examples/curl_http.nit:41,1--104,3

cocoa :: cocoa_message_box $ Sys :: main
if "NIT_TESTING".environ != "true" then dialog
lib/cocoa/examples/cocoa_message_box.nit:32,1--46

markdown :: nitmd $ Sys :: main
var opt_to = new OptionString("Specify output format (html, md, man)", "-t", "--to")

var usage = new Buffer
usage.append "Usage: nitmd [-t format] <file.md>\n"
usage.append "Translate Markdown documents to other formats."

var config = new Config
config.add_option(opt_to)
config.tool_description = usage.write_to_string

config.parse_options(args)
if config.args.length != 1 then
	config.usage
	exit 1
end

var file = config.args.first
if not file.file_exists then
	print "'{file}' not found"
	exit 1
end

var ifs = new FileReader.open(file)
var md = ifs.read_all
ifs.close

var processor = new MarkdownProcessor
var to = opt_to.value
if to == null or to == "html" then
	# Noop
else if to == "md" then
	processor.decorator = new MdDecorator
else if to == "man" then
	processor.decorator = new ManDecorator
else
	print "Unknown output format: {to}"
	exit 1
end
print processor.process(md)
lib/markdown/nitmd.nit:24,1--62,27

bcm2835 :: input $ Sys :: main
assert bcm2835_init else print "Failed to init"

var out = new RPiPin.p1_11
out.fsel = new FunctionSelect.outp
out.write(false)

var inp = new RPiPin.p1_22
inp.fsel = new FunctionSelect.inpt
inp.pud = new PUDControl.down

var last_in = false
loop
	var lev = inp.lev
	if lev != last_in then
		last_in = lev
		if lev then print "button pressed"
	end

	out.write(true)
	100.bcm2835_delay
	out.write(false)
	100.bcm2835_delay
end
lib/bcm2835/examples/input.nit:21,1--43,3

gettext :: langannot $ Sys :: main
var t = new X
print t.foo

print "This String is a test"

print """Multiline string

example


of the language annotation capacities
"""

var s = "example"

print "This superstring {s} rocks"

print "This superstring %1 rocks".format(s)
lib/gettext/examples/langannot.nit:28,1--45,43

libevent :: libevent_example $ Sys :: main
if "NIT_TESTING".environ == "true" then exit 0

# Setup libevent system
var event_base = new NativeEventBase
var factory = new MyFactory(event_base)

# Open a TCP socket for listening
factory.bind_tcp("localhost", 8888)

# Open a UNIX domain socket for listening
factory.bind_unix("/tmp/my.sck")

# Launch event loop
event_base.dispatch

event_base.free
lib/libevent/libevent_example.nit:42,1--57,15

pthreads :: threaded_example $ Sys :: main
print "main"
foo
bar(10, "parameterized and threaded")
sys.nanosleep(5,0)
var x  = baz(2, 3)
print "main, waiting for baz"
var y = x.join
print("baz result : " + y.to_s)
lib/pthreads/examples/threaded_example.nit:41,1--48,31

pthreads :: concurrent_array_and_barrier $ Sys :: main
var n_threads = 20

# This `ConcurrentArray` has its own `Mutex`
var array = new ConcurrentArray[String]

# Use an explicit `Barrier`
var barrier = new Barrier(n_threads)

# Create all our threads
var threads = new Array[Thread]
for t in n_threads.times do
	var thread = new MyThread(array, barrier, t)
	threads.add thread
	thread.start
end

# Wait for the threads to complete
for thread in threads do
	print "Thread {thread.join or else "null"} is done"
end

print "{array.length} strings inserted"
lib/pthreads/examples/concurrent_array_and_barrier.nit:51,1--72,39

socket :: socket_client $ Sys :: main
if args.length < 2 then
	print "Usage : socket_client <host> <port>"
	exit 1
end

var address = args[0]
var port = args[1].to_i

# Open a conection with the server
var s = new TCPStream.connect(address, port)
printn "Connecting to {s.host}:{s.port} at {s.address}... "
print if s.connected then "Connected" else "Connection failed"

if s.connected then
	# Communicate
	s.write "Hello server!\n"
	print s.read_line
	s.write "Bye server!\n"
	print s.read_line

	s.close
end
lib/socket/examples/socket_client.nit:22,1--43,3

socket :: socket_simple_server $ Sys :: main
if args.is_empty then
	print "Usage : socket_simple_server <port>"
	exit 1
end

var port = args[0].to_i

# Open the listening socket
var socket = new TCPServer(port)
socket.listen 4
socket.blocking = false

print "Listening on port {socket.port}"

# Loop until a single client connects
var client: nullable TCPStream = null
while client == null do
	printn "."
	sys.nanosleep(0, 200000)

	client = socket.accept
end
print " Connected"

# Communicate
print client.read_line
client.write "Hello client!\n"
print client.read_line
client.write "Bye client!\n"

client.close
lib/socket/examples/socket_simple_server.nit:20,1--50,12

privileges :: drop_privileges $ Sys :: main
var opts = new OptionContext
var opt_ug = new OptionUserAndGroup.for_dropping_privileges
opt_ug.mandatory = true
opts.add_option(opt_ug)

# parse and check command line options
opts.parse(args)
if not opts.errors.is_empty then
	print opts.errors.join("\n")
	print "Usage: drop_privileges [options]"
	opts.usage
	exit 1
end

# original user
print "before {sys.uid}:{sys.gid}"

# make the switch
var user_group = opt_ug.value
assert user_group != null
user_group.drop_privileges

# final user
print "after {sys.uid}:{sys.egid}"
lib/privileges/examples/drop_privileges.nit:23,1--46,34

pthreads :: jointask_example $ Sys :: main
var tp = new ThreadPool
var t0 = new StringTask(10, "First, long task", 0)
var tasks = new Array[StringTask]
for i in 5.times do
	tasks.add(new StringTask(1, "Small task", i + 1))
end
tp.execute(t0)
for t in tasks do tp.execute(t)
for t in tasks do
	t.join
	print t.value
end
t0.join
print t0.value
lib/pthreads/examples/jointask_example.nit:39,1--52,14

pthreads :: threadpool_example $ Sys :: main
var tp = new ThreadPool
for i in 100.times do
	var t = new HWTask(2.rand, i)
	tp.execute(t)
end

nanosleep(20,10)
lib/pthreads/examples/threadpool_example.nit:36,1--42,16

sdl2 :: minimal $ Sys :: main
sys.sdl.initialize((new SDLInitFlags).video)
check_error "init"

# Init `sdl2::image`
sdl.img.initialize((new SDLImgInitFlags).png)
check_error "img_init"

# Create a window
var window = new SDLWindow("Window title!".to_cstring, 800, 600, (new SDLWindowFlags).opengl)
check_error "window"

# Create a render, the suffested one
var renderer = new SDLRenderer(window, -1, (new SDLRendererFlags).accelerated)
check_error "renderer"

# Load an image
var surface = new SDLSurface.load("assets/fighter.png".to_cstring)
check_error "surface"
assert not surface.address_is_null

# Alternative code to load a BMP image without `sdl2::image`
#
# var surface = new SDLSurface.load_bmp("assets/fighter.bmp".to_cstring)

# Set the window icon
window.icon = surface
check_error "icon"

# Get a texture out of that surface
var texture = new SDLTexture.from_surface(renderer, surface)
check_error "texture"

# Allocate memory for reusable objects
var event = new SDLEventBuffer.malloc
var src = new SDLRect.nil
var dst = new SDLRect(0, 0, 128, 128)

# Set the colors we will be using
var white = new SDLColor(255, 255, 255, 255)
var green = new SDLColor(  0, 255,   0, 255)
var spacy = new SDLColor( 25,  25,  50, 255)

loop
	# Loop over events until we get a quit event
	while event.poll_event do
		var higher_event = event.to_event
		if higher_event isa SDLQuitEvent then
			break label out
		else if higher_event isa SDLMouseButtonDownEvent then
			# Update `dst` to be centered on the latest click
			dst.x = higher_event.x - dst.w/2
			dst.y = higher_event.y - dst.h/2
		end
	end

	# Clear the screen with a spacy color
	renderer.draw_color = spacy
	renderer.clear

	# Draw the target box for the following `copy`
	renderer.draw_color = green
	renderer.draw_rect dst

	# Copy a texture to the screen
	renderer.draw_color = white
	renderer.copy(texture, src, dst)

	# Copy the back buffer to the screen
	renderer.present

	check_error "present"

	33.delay
end label out

# Free all resources
event.free
src.free
dst.free

texture.free
surface.free

window.destroy
sdl.img.quit
sys.sdl.quit
lib/sdl2/examples/minimal/src/minimal.nit:35,1--120,12

crapto :: repeating_key_xor_solve $ Sys :: main
if args.length != 1 then
	print "Usage: repeating_key_xor_solve <cipher_file>"
	exit 1
end

# Read the cipher from the file
var cipher_bytes = args[0].to_path.read_all_bytes.decode_base64

# Create a RepeatingKeyXorCipher object to manipulate your ciphertext
var xorcipher = new RepeatingKeyXorCipher
xorcipher.ciphertext = cipher_bytes

# Try to find the best candidate key
xorcipher.find_key

# Decrypt the cipher according to the found key
xorcipher.decrypt

# Check the resulting plaintext out...
print xorcipher.plaintext
lib/crapto/examples/repeating_key_xor_solve.nit:21,1--40,25

websocket :: websocket_server $ Sys :: main
var sock = new WebsocketServer.with_infos(8088, 1)

var msg: String

if sock.listener.closed then
	print sys.errno.strerror
end

var cli: WebsocketConnection

while not sock.closed do
	cli = sock.accept
	while cli.connected do
		if sys.stdin.poll_in then
			msg = gets
			printn "Sending message : {msg}"
			if msg == "disconnect" then cli.close
			cli.write(msg)
		end
		if cli.can_read(10) then
			msg = ""
			while cli.can_read(0) do msg += cli.read(100)
			if msg != "" then print msg
		end
	end
end
lib/websocket/examples/websocket_server.nit:22,1--47,3

vsm :: example_vsm $ Sys :: main
var config = new Config
config.tool_description = "usage: example_vsm <files>"
config.parse_options(args)

if args.length < 1 then
	config.usage
	exit 1
end

var index = new FileIndex
index.whitelist_exts = config.opt_white_exts.value
index.blacklist_exts = config.opt_black_exts.value

print "Building index..."
index.index_files(args, true)
print "Indexed {index.documents.length} documents"

loop
	print "\nEnter query:"
	printn "> "
	var input = sys.stdin.read_line
	var matches = index.match_string(input)
	printn ""
	for match in matches do
		print match
	end
end
lib/vsm/examples/example_vsm.nit:39,1--65,3

markdown2 :: nitmd $ Sys :: main
var opt_to = new OptionString("Specify output format (html, md, man, latex)", "-t", "--to")

var usage = new Buffer
usage.append "Usage: nitmd [-t format] [file.md]\n"
usage.append "Translate Markdown documents to other formats.\n\n"
usage.append "If no argument, read the Markdown input from `stdin`."

var config = new Config
config.add_option(opt_to)
config.tool_description = usage.write_to_string

config.parse_options(args)
if config.args.length > 1 then
	config.usage
	exit 1
end

var md
if config.args.is_empty then
	md = sys.stdin.read_all
else
	var file = config.args.first
	if not file.file_exists then
		print "'{file}' not found"
		exit 1
	end
	md = file.to_path.read_all
end

# Parse the input
var parser = new MdParser
var node = parser.parse(md)

var renderer: MdRenderer
var to = opt_to.value
if to == null or to == "html" then
	renderer = new HtmlRenderer
else if to == "md" then
	renderer = new MarkdownRenderer
else if to == "man" then
	renderer = new ManRenderer
else if to == "latex" then
	renderer = new LatexRenderer
else
	print "Unknown output format: {to}"
	exit 1
	return
end
printn renderer.render(node)
lib/markdown2/nitmd.nit:25,1--73,28

actors :: chameneosredux $ Sys :: main
var n = if args.is_empty then 600 else args[0].to_i

print_all_colors
print ""

work(n, 3)
work(n, 10)
lib/actors/examples/chameneos-redux/chameneosredux.nit:148,1--154,11

actors :: fannkuchredux $ Sys :: main
n = if args.is_empty then 7 else args[0].to_i

fact = new Array[Int].with_capacity(n+1)
fact[0] = 1
for i in [1..n] do fact.add(fact[i-1] * i)

chunk_sz = (fact[n] + n_chunks - 1) / n_chunks
n_tasks = (fact[n] + chunk_sz - 1) / chunk_sz
max_flips = new Array[Int].with_capacity(n_tasks)
for i in [0..n_tasks[ do max_flips.add(0)
chk_sums = new Array[Int].with_capacity(n_tasks)
for i in [0..n_tasks[ do chk_sums.add(0)

var actors = new Array[FannkuchRedux].with_capacity(nb_actors)
for i in [0..nb_actors[ do
	var a = new FannkuchRedux
	actors.add(a)
	a.async.run
end

for i in [0..nb_actors[ do
	actors[i].async.terminate
	actors[i].async.wait_termination
end

var res = 0
for i in max_flips do res = res.max(i)

var chk = 0
for i in chk_sums do
	chk += i
end

print_result(n, res, chk)
lib/actors/examples/fannkuchredux/fannkuchredux.nit:151,1--184,25

actors :: mandelbrot $ Sys :: main
n = if args.is_empty then 200 else args[0].to_i

sys.crb = new Array[Float].with_capacity(n)
sys.cib = new Array[Float].with_capacity(n)
sys.inv_n = 2.0 / n.to_f
for i in [0..n[ do
	sys.cib[i] = i.to_f * inv_n - 1.0
	sys.crb[i] = i.to_f * inv_n - 1.5
end
sys.data = new Array[Array[Int]].with_capacity(n)
for i in [0..n[ do sys.data[i] = new Array[Int].filled_with(0, (n) / 8)

# Parallel Approach
var actors = new Array[Worker]
for i in [0..nb_threads[ do
	var a = new Worker
	actors.add(a)
	a.async.work
end

for a in actors do
	a.async.terminate
	a.async.wait_termination
end

var filename = "WRITE".environ
if filename == "" then filename = "out"
var output = new FileWriter.open(filename)
output.write_bytes("P4\n{n} {n}\n".to_bytes)
for i in [0..n[ do
	var length = data[i].length
	for j in [0..length[ do output.write_byte(data[i][j])
end
output.close
lib/actors/examples/mandelbrot/mandelbrot.nit:83,1--116,12

actors :: simple $ Sys :: main
var a = new A

# Make an asynchronous call
a.async.foo

# Make a synchronous call
a.foo

# Make an asynchronous call
# Which return a `Future[Int]` instead of `Int`
var r = a.async.bar(5)

# Retrieve the value of the future
print r.join

# Make a Synchronous call
print a.bar(5)
lib/actors/examples/simple/simple.nit:34,1--50,14

actors :: thread_ring $ Sys :: main
var first = new ThreadRing(1)
var current = new ThreadRing(2)
first.next = current
for i in [3..nb_actors] do
	var t = new ThreadRing(i)
	current.next = t
	current = t
end
current.next = first
var n = if args.is_empty then 1000 else args[0].to_i
first.send_token(n)
lib/actors/examples/thread-ring/thread_ring.nit:46,1--56,19

serialization :: custom_serialization $ Sys :: main
var a = new A("a", 1)
var b = new B("b", a)

a.ser_json
a.ser_json2
b.ser_json
b.ser_json2
lib/serialization/examples/custom_serialization.nit:149,1--155,11

glesv2 :: opengles2_hello_triangle $ Sys :: main
if "NIT_TESTING".environ == "true" then exit(0)

var window_width = 800
var window_height = 600

#
## SDL2
#
assert sdl.initialize((new SDLInitFlags).video) else
	print sdl.error
end

var sdl_window = new SDLWindow("Title".to_cstring, window_width, window_height, (new SDLWindowFlags).opengl)
assert not sdl_window.address_is_null else print sdl.error

var sdl_wm_info = sdl_window.wm_info
var native_window = sdl_wm_info.window_handle
var native_display = sdl_wm_info.display_handle
assert not native_display.address_is_null else print "Failed to get handle to native display"

#
## EGL
#
var egl_display = new EGLDisplay(native_display)
assert egl_display.is_valid else print "EGL display is not valid"

egl_display.initialize
assert egl_display.is_valid else print egl_display.error

print "EGL version: {egl_display.version}"
print "EGL vendor: {egl_display.vendor}"
print "EGL extensions: \n* {egl_display.extensions.join("\n* ")}"
print "EGL client APIs: {egl_display.client_apis.join(", ")}"

var config_chooser = new EGLConfigChooser
#config_chooser.surface_type_egl
config_chooser.blue_size = 8
config_chooser.green_size = 8
config_chooser.red_size = 8
#config_chooser.alpha_size = 8
#config_chooser.depth_size = 8
#config_chooser.stencil_size = 8
#config_chooser.sample_buffers = 1
config_chooser.close

var configs = config_chooser.choose(egl_display)
assert configs != null else print "choosing config failed: {egl_display.error}"
assert not configs.is_empty else print "no EGL config"

print "{configs.length} EGL configs available"
for config in configs do
	var attribs = config.attribs(egl_display)
	print "* caveats: {attribs.caveat}"
	print "  conformant to: {attribs.conformant}"
	print "  size of RGBA: {attribs.red_size} {attribs.green_size} {attribs.blue_size} {attribs.alpha_size}"
	print "  buffer, depth, stencil: {attribs.buffer_size} {attribs.depth_size} {attribs.stencil_size}"
end

var config = configs.first

var surface = egl_display.create_window_surface(config, native_window, [0])
assert surface.is_ok else print egl_display.error

var context = egl_display.create_context(config)
assert context.is_ok else print egl_display.error

var make_current_res = egl_display.make_current(surface, surface, context)
assert make_current_res else print egl_display.error

var width = surface.attribs(egl_display).width
var height = surface.attribs(egl_display).height
print "Width: {width}"
print "Height: {height}"

assert egl_bind_opengl_es_api else print "eglBingAPI failed: {egl_display.error}"

#
## GLESv2
#

print "Can compile shaders? {gl.shader_compiler}"
assert_no_gl_error

assert gl.shader_compiler else print "Cannot compile shaders"

# gl program
print glGetError.to_s
var program = new GLProgram
if not glIsProgram(program) then
	print "Program is not ok: {glGetError.to_s}\nLog:"
	print glGetProgramInfoLog(program)
	abort
end
assert_no_gl_error

# vertex shader
var vertex_shader = new GLVertexShader
assert glIsShader(vertex_shader) else print "Vertex shader is not ok: {glGetError}"
glShaderSource(vertex_shader, """
attribute vec4 vPosition;
void main()
{
  gl_Position = vPosition;
}
""".to_cstring)
glCompileShader vertex_shader
assert vertex_shader.is_compiled else print "Vertex shader compilation failed with: {glGetShaderInfoLog(vertex_shader)} {glGetProgramInfoLog(program)}"
assert_no_gl_error

# fragment shader
var fragment_shader = new GLFragmentShader
assert glIsShader(fragment_shader) else print "Fragment shader is not ok: {glGetError}"
glShaderSource(fragment_shader, """
precision mediump float;
void main()
{
	gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
""".to_cstring)
glCompileShader(fragment_shader)
assert fragment_shader.is_compiled else print "Fragment shader compilation failed with: {glGetShaderInfoLog(fragment_shader)}"
assert_no_gl_error

glAttachShader(program, vertex_shader)
glAttachShader(program, fragment_shader)
program.bind_attrib_location(0, "vPosition")
glLinkProgram program
assert program.is_linked else print "Linking failed: {glGetProgramInfoLog(program)}"
assert_no_gl_error

# prepare
glViewport(0, 0, width, height)
glClearColor(0.5, 0.0, 0.5, 1.0)

# draw!
var vertices = [0.0, 0.5, 0.0, -0.5, -0.5, 0.0, 0.5, -0.5, 0.0]
var vertex_array = new VertexArray(0, 3, vertices)
vertex_array.attrib_pointer

var clock = new Clock

var n_frames = 1000
for i in [0..n_frames[ do
	printn "."
	assert_no_gl_error

	glClear gl_COLOR_BUFFER_BIT
	glUseProgram program
	vertex_array.enable
	glDrawArrays(gl_TRIANGLES, 0, 3)
	egl_display.swap_buffers(surface)
end

print "FPS: {n_frames.to_f/clock.lapse.to_f}"

# delete
glDeleteProgram program
glDeleteShader vertex_shader
glDeleteShader fragment_shader

#
## EGL
#
# close
egl_display.make_current(new EGLSurface.none, new EGLSurface.none, new EGLContext.none)
egl_display.destroy_context context
egl_display.destroy_surface surface

#
## SDL2
#
# close
sdl.quit
lib/glesv2/examples/opengles2_hello_triangle.nit:29,1--201,8

dom :: checker $ Sys :: main
if args.length != 1 then
	print_error "Usage: checker xml_file"
	exit 2
end

var path = args.first
if not path.file_exists then
	print_error "Path '{path}' does not exist"
	exit 3
end

# Read file
var content = path.to_path.read_all

# Parse XML
var xml = content.to_xml

# Check for errors
if xml isa XMLError then
	print_error "XML file at '{path}' is invalid:"
	print_error xml.message
	var loc = xml.location
	if loc != null then print_error loc
	exit 1
else
	print "XML file at '{path}' is valid"
end
lib/dom/examples/checker.nit:17,1--43,3

actors :: simple_simulation $ Sys :: main
var nb_steps = 0
var nb_agents = 0
if args.is_empty or args.length != 2 then
	nb_steps = 10
	nb_agents = 10
else
	nb_steps = args[0].to_i
	nb_agents = args[1].to_i
end

var agents = new Array[Agent]
for i in [0..nb_agents[ do agents.add(new Agent)
for a in agents do for b in agents do if a != b then a.others.add(b)
clock_agent = new ClockAgent(nb_steps, agents)
clock_agent.async.do_step
lib/actors/examples/agent_simulation/simple_simulation.nit:43,1--57,25

gamnit :: texture_atlas_parser $ Sys :: main
var opts = new OptionContext
var opt_name = new OptionString("Name of the module to generate", "--name", "-n")
var opt_dir = new OptionString("Folder where to write the generated module", "--dir")
opts.add_option(opt_name, opt_dir)
opts.parse
var rest = opts.rest

if opts.errors.not_empty then
	print_error opts.errors
	exit 1
end

if rest.is_empty then
	print_error "Error: Expected the path to the XML file as argument"
	exit 2
end

# Prepare to read XML file and gather the attributes
var xml_file = rest.first
var attributes = new Array[String]

# Insert the first attribute, to load the root texture
var png_file = "images" / xml_file.basename("xml") + "png"
attributes.add """
	var root_texture = new TextureAsset("{{{png_file}}}")"""

# Read XML file
var content = xml_file.to_path.read_all
var xml = content.to_xml
if xml isa XMLError then
	print_error "RSS Parse Error: {xml.message}:{xml.location or else "null"}"
	exit 3
end

var items = xml["TextureAtlas"].first.children
for item in items do if item isa XMLOnelinerTag then
	var x = null
	var y = null
	var width = null
	var height = null
	var name = null
	for attr in item.attributes do if attr isa XMLStringAttr then
		if attr.name == "x" then
			x = attr.value.to_i
		else if attr.name == "y" then
			y = attr.value.to_i
		else if attr.name == "width" then
			width = attr.value.to_i
		else if attr.name == "height" then
			height = attr.value.to_i
		else if attr.name == "name" then
			name = attr.value
		end
	end

	if x != null and y != null and width != null and height != null and name != null then
		name = name.strip_extension(".png").to_snake_case

			var coords = "{x}, {y}, {width}, {height}"
			attributes.add """
	var {{{name}}}: Texture = root_texture.subtexture({{{coords}}})"""
	else
		print_error "Error on {item}"
	end
end

var module_name = opt_name.value
if module_name == null then module_name = "spritesheet"
var class_name = module_name.capitalized.to_camel_case

# Generate Nit code
var nit_module = new NitModule(module_name)
nit_module.header = """
# This file is generated by texture_atlas_parser
"""

nit_module.content.add """
import gamnit::display
import gamnit::textures

class {{{class_name}}}
"""

for a in attributes do nit_module.content.add a

nit_module.content.add """
end"""

var dir = opt_dir.value
if dir != null then
	var out_path = dir / module_name + ".nit"
	nit_module.write_to_file out_path
else
	printn nit_module.write_to_string
end
lib/gamnit/texture_atlas_parser.nit:23,1--117,3

markdown2 :: commonmark_gen $ Sys :: main
if args.length != 2 then
	print "Usage: commonmark_gen <tests.json> <output_dir>"
	exit 1
end

var gen = new TestGenerator(args.first, args.last)
gen.gen_tests
lib/markdown2/tests/commonmark_gen.nit:245,1--251,13

curl :: curl_rest $ Sys :: main
var url = "http://example.com"

# POST REQUEST
var my_request = new CurlHTTPRequest(url, method="POST")
var person = new Person("Jean",12)
my_request.body = person.serialize_to_json
my_request.execute
lib/curl/examples/curl_rest.nit:31,1--37,18

nlp :: nlp_index $ Sys :: main
var config = new Config
config.tool_description = "usage: example_index <files>"
config.parse_options(args)

if args.length < 1 then
	config.usage
	exit 1
end

var host = config.opt_server.value
if host == null then host = "http://localhost:9000"
var lang = config.opt_lang.value
if lang == null then lang = "en"

var cli = new NLPClient(host)
cli.language = lang

var bl = config.opt_black_exts.value
if bl.is_empty then bl = ["CD", "SYM", "-RRB-", "-LRB-", "''", "``", ".", "#", ":", ",", "$", ""]

var index = new NLPFileIndex(cli)
index.whitelist_exts = config.opt_white_exts.value
index.blacklist_exts = bl

print "Building index..."
index.index_files(args, true)

print "Indexed {index.documents.length} documents"

loop
	print "\nEnter query:"
	printn "> "
	var input = sys.stdin.read_line
	var matches = index.match_string(input)

	for match in matches do
		print match
	end
end
lib/nlp/examples/nlp_index.nit:43,1--81,3

nlp :: nlp_server $ Sys :: main
var config = new Config
config.parse_options(args)

var cp = config.opt_java_cp.value
if cp == null then cp = "stanfordnlp/*"

var srv = new NLPServer(cp, config.opt_port.value)
srv.start
lib/nlp/examples/nlp_server.nit:30,1--37,9

mpi :: mpi_simple $ Sys :: main
var mpi = new MPI

var data = new CIntArray(2)
if comm_world.size == 1 then
	print "not enough nodes, got only 1"
	mpi.finalize
	exit 1
end

print "stdout: processor '{mpi.processor_name}' {comm_world.rank}/{comm_world.size}"

if comm_world.rank == 0.rank then
	# send - ints
	data[0] = 123
	data[1] = 456
	mpi.send_from(data, 0, 2, 1.rank, 0.tag, comm_world)

	# send - simple string
	mpi.send_all("Hello", 1.rank, 0.tag, comm_world)
	mpi.send_from(" World", 0, 6, 1.rank, 0.tag, comm_world)
	mpi.send_from("+-!0?", 2, 2, 1.rank, 0.tag, comm_world)
else if comm_world.rank == 1.rank then

	# recv - ints
	mpi.recv_into(data, 0, 2, 0.rank, 0.tag, comm_world)
	print "received data: {data[0]} {data[1]}"

	# recv - simple string
	var buf = new FlatBuffer.with_capacity(5)
	mpi.recv_fill(buf, 0.rank, 0.tag, comm_world)
	print "received string: {buf}"

	mpi.recv_into(buf, 5, 6, 0.rank, 0.tag, comm_world)
	print "received string: {buf}"

	mpi.recv_into(buf, 3, 2, 0.rank, 0.tag, comm_world)
	print "received string: {buf}"
end

# Passing complex objects and inverse sender/receiver
if comm_world.rank == 0.rank then
	var errors = 0
	var processors_per_host = new HashMap[String, Int]

	# recv - serializable
	for p in [1 .. comm_world.size[ do
		var a = mpi.recv(new Rank.any, 0.tag, comm_world)
		print "received serialized: {a or else "<null>"}"

		if a != null and a isa ProcessorInfo then
			if not processors_per_host.keys.has(a.name) then
				processors_per_host[a.name] = 1
			else processors_per_host[a.name] += 1
		else errors += 1
	end

	print "errors: {errors}"
	print "processors: {processors_per_host.join(", ", ": ")}"
else
	# send - serializable
	srand_from comm_world.rank.to_i
	var a = new ProcessorInfo(mpi)
	mpi.send(a, 0.rank, 0.tag, comm_world)
end

mpi.finalize
lib/mpi/examples/src/mpi_simple.nit:41,1--106,12

nitcorn :: nitcorn_reverse_proxy $ Sys :: main
var vh = new VirtualHost("localhost:8080")

# Create the interface to represent your proxy target
var proxy_interface = new Interface("localhost", 31337)

# Add your action as usual
vh.routes.add new Route("/", new ProxyAction(proxy_interface))

# Let it be (serve)
var factory = new HttpFactory.and_libevent
factory.config.virtual_hosts.add vh
factory.run
lib/nitcorn/examples/src/nitcorn_reverse_proxy.nit:23,1--34,11

nitcorn :: htcpcp_server $ Sys :: main
var server = new HTCPCServer(1227)

server.run
lib/nitcorn/examples/src/htcpcp_server.nit:101,1--103,10

nitcorn :: nitcorn_hello_world $ Sys :: main
var vh = new VirtualHost("localhost:8080")

# Serve index.html with our custom handler
vh.routes.add new Route("/index.html", new StaticAction)
vh.routes.add new Route("/hello/:name", new ParamAction)

# Serve everything else with a standard `FileServer` with a root at "www/hello_world/"
vh.routes.add new Route(null, new FileServer("www/hello_world/"))

var factory = new HttpFactory.and_libevent
factory.config.virtual_hosts.add vh
factory.run
lib/nitcorn/examples/src/nitcorn_hello_world.nit:71,1--82,11

nitcorn :: simple_file_server $ Sys :: main
var opts = new OptionContext
var opt_drop = new OptionUserAndGroup.for_dropping_privileges
var opt_port = new OptionInt("Server port", 80, "--port", "-p")
var opt_help = new OptionBool("Print this message", "--help", "-h")
opts.add_option(opt_drop, opt_port, opt_help)
opts.parse args

# Check options errors and help
if not opts.errors.is_empty or opt_help.value then
	print opts.errors.join("\n")
	print "Usage: file_server [Options]"
	opts.usage
	exit 1
end

# Serve everything with a standard FilesHandler
var vh = new VirtualHost("localhost:{opt_port.value}")
vh.routes.add new Route(null, new FileServer("www/hello_world/"))
var factory = new HttpFactory.and_libevent
factory.config.virtual_hosts.add vh

# Drop to a low-privileged user
var user_group = opt_drop.value
if user_group != null then user_group.drop_privileges

factory.run
lib/nitcorn/examples/src/simple_file_server.nit:27,1--52,11

android :: nit_activity $ Sys :: main
app.setup
lib/android/nit_activity.nit:325,1--9

popcorn :: example_post_handler $ Sys :: main
var app = new App
app.use("/", new PostHandler)
app.listen("localhost", 3000)
lib/popcorn/examples/handlers/example_post_handler.nit:36,1--38,29

popcorn :: example_query_string $ Sys :: main
var app = new App
app.use("/", new QueryStringHandler)
app.listen("localhost", 3000)
lib/popcorn/examples/handlers/example_query_string.nit:36,1--38,29

popcorn :: example_hello $ Sys :: main
var app = new App
app.use("/", new HelloHandler)
app.listen("localhost", 3000)
lib/popcorn/examples/hello_world/example_hello.nit:27,1--29,29

popcorn :: example_advanced_logger $ Sys :: main
var app = new App
app.use_before("/*", new RequestTimeHandler)
app.use("/", new AnotherHandler)
app.use_after("/*", new AdvancedLoggerHandler)
app.listen("localhost", 3000)
lib/popcorn/examples/middlewares/example_advanced_logger.nit:52,1--56,29

popcorn :: example_html_error_handler $ Sys :: main
var app = new App
app.use("/*", new HtmlErrorHandler)
app.listen("localhost", 3000)
lib/popcorn/examples/middlewares/example_html_error_handler.nit:51,1--53,29

popcorn :: example_simple_error_handler $ Sys :: main
var app = new App
app.use("/", new SomeHandler)
app.use("/*", new SimpleErrorHandler)
app.listen("localhost", 3000)
lib/popcorn/examples/middlewares/example_simple_error_handler.nit:36,1--39,29

popcorn :: example_simple_logger $ Sys :: main
var app = new App
app.use_before("/*", new SimpleLoggerHandler)
app.use("/", new MyOtherHandler)
app.listen("localhost", 3000)
lib/popcorn/examples/middlewares/example_simple_logger.nit:34,1--37,29

popcorn :: example_glob_route $ Sys :: main
var app = new App
app.use("/user/:user/item/:item/*", new UserItem)
app.listen("localhost", 3000)
lib/popcorn/examples/routing/example_glob_route.nit:35,1--37,29

popcorn :: example_param_route $ Sys :: main
var app = new App
app.use("/:user", new UserHome)
app.listen("localhost", 3000)
lib/popcorn/examples/routing/example_param_route.nit:34,1--36,29

popcorn :: example_router $ Sys :: main
var user_router = new Router
user_router.use("/*", new UserLogger)
user_router.use("/", new UserHomepage)
user_router.use("/profile", new UserProfile)

var app = new App
app.use("/", new AppHome)
app.use("/user", user_router)
app.listen("localhost", 3000)
lib/popcorn/examples/routing/example_router.nit:45,1--53,29

popcorn :: example_session $ Sys :: main
var app = new App
app.use("/*", new SessionInit)
app.use("/", new AppLogin)
app.listen("localhost", 3000)
lib/popcorn/examples/sessions/example_session.nit:42,1--45,29

popcorn :: example_static $ Sys :: main
var app = new App
app.use("/", new StaticHandler("public/"))
app.listen("localhost", 3000)
lib/popcorn/examples/static_files/example_static.nit:21,1--23,29

popcorn :: example_static_default $ Sys :: main
var app = new App
app.use("/", new StaticHandler("public/", "default.html"))
app.listen("localhost", 3000)
lib/popcorn/examples/static_files/example_static_default.nit:21,1--23,29

popcorn :: example_static_multiple $ Sys :: main
var app = new App
app.use("/", new StaticHandler("public/"))
app.use("/", new StaticHandler("files/"))
app.use("/static", new StaticHandler("public/"))
app.use("/static", new StaticHandler("files/"))
app.listen("localhost", 3000)
lib/popcorn/examples/static_files/example_static_multiple.nit:21,1--26,29

nitcorn :: restful_annot $ Sys :: main
var vh = new VirtualHost("localhost:8080")

# Set `rest_path` as the root for an instance of `MyAction`, so:
# * `MyClass::foo` is available as `localhost:8080/rest_path/foo?s=s&i=12&b=true`,
# * `MyClass::bar` is available as both `localhost:8080/rest_path/api_name?s=s`
#   and `localhost:8080/rest_path/alt_name?...`.
# * `MyClass::async_service` is available as `localhost:8080/rest_path/async_service?str=str`
# * `MyClass::complex_args` is available as
#   `localhost:8080/rest_path/complex_args?array=["a","b"]&data={"str":"asdf"}`
vh.routes.add new Route("rest_path", new MyAction)

var factory = new HttpFactory.and_libevent
factory.config.virtual_hosts.add vh
factory.run
lib/nitcorn/examples/src/restful_annot.nit:122,1--135,11

popcorn :: example_angular $ Sys :: main
var app = new App
app.use("/counter", new CounterAPI)
app.use("/*", new StaticHandler("www/", "index.html"))
app.listen("localhost", 3000)
lib/popcorn/examples/angular/example_angular.nit:45,1--48,29

popcorn :: example_mongodb $ Sys :: main
var mongo = new MongoClient("mongodb://mongo:27017/")
var db = mongo.database("mongo_example")

var app = new App
app.use("/", new UserList(db))
app.listen("localhost", 3000)
lib/popcorn/examples/mongodb/example_mongodb.nit:63,1--68,29