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
# 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
var fw = new FileWriter.open("functional_types.nit")
generate_functypes(20, fw)
lib/functional/functional_gen.nit:147,1--148,26
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
hello_world
lib/cocoa/examples/hello_cocoa.nit:29,1--11
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
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
var page = new NitHomepage
page.write_to stdout
page.write_to_file("nit.html")
lib/html/examples/html_page.nit:105,1--107,30
var f = new TmplComposers
f.add_composer("Johann Sebastian", "Bach", 1685, 1750)
f.add_composer("George Frideric", "Handel", 1685, 1759)
f.add_composer("Wolfgang Amadeus", "Mozart", 1756, 1791)
f.write_to(stdout)
lib/template/examples/tmpl_composer.nit:83,1--87,18
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
nslog "Hello using to_nsstring".to_nsstring
nslog new NSString.hello
var msg_box = new NSAlert
msg_box.message_text = "From Nit".to_nsstring
if "NIT_TESTING".environ != "true" then msg_box.run_modal
lib/cocoa/examples/cocoa_extern_types.nit:38,1--43,57
var configs = false
if not args.is_empty then
if args.first == "--configs" then
configs = true
args.shift
end
end
if args.is_empty then
print """
Usage: puzzle [--configs] initial...
--configs: search and time solutions with various configurations of solvers.
initial: an initial configuration (letters for the tiles, and dot for the hole). eg:
8-puzzle:
goal (0): abcdefgh.
easy (4): abce.fdgh
medium (10): eabf.cdgh
hard (20): feacbh.dg
harder (31): hfgbedc.a
15-puzzle:
goal (0): abcdefghijklmno.
easy (30): bacdefghijlkmno.
medium (40): fg.jacoheldnibmk
hard (55): kleg.mondcafjhbi
harder (61): lomgkcend.afjhbi
24-puzzle:
goal (0): abcdefghijklmnopqrstuvwx.
easy (55): giabcjekmdhrtflqsownpuv.x
medium (75): giabcjekmdrtwulhs.vnqofpx
hard (79): giabcjekmdrtw.uhsvnlqofpx
harder (80): giabcjekmdrt.wuhsvnlqofpx
"""
exit 0
end
for arg in args do
var pb = new PuzzleProblem(arg)
print "Initial: {arg}"
pb.print_state(pb.initial_state)
if configs then
pb.run_configs(1000000)
continue
end
var s = pb.astar
s.memorize = true
var r = s.run
if r == null then
print "No solution."
break
end
print "Solved, after looking at {r.steps} positions"
pb.print_plan(r.plan)
end
lib/ai/examples/puzzle.nit:229,1--291,3
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
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
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
print "Data home: {xdg_basedir.data_home}"
print "Config home: {xdg_basedir.config_home}"
print "Cache home: {xdg_basedir.cache_home}"
print "Data dirs: {xdg_basedir.data_dirs.join(", ")}"
print "Searchable data dirs: {xdg_basedir.searchable_data_dirs.join(", ")}"
print "Config dirs: {xdg_basedir.config_dirs.join(", ")}"
print "Searchable config dirs: {xdg_basedir.searchable_config_dirs.join(", ")}"
lib/xdg_basedir/show_basedir.nit:22,1--28,79
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
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
if args.is_empty then
print "Usage : socket_server <port>"
return
end
var socket = new TCPServer(args[0].to_i)
socket.listen 1
print "[PORT] : {socket.port.to_s}"
var clients = new Array[TCPStream]
var max = socket
loop
var fs = new SocketObserver.with_sets(true, true, true)
fs.read_set.add socket
for c in clients do fs.read_set.add c
printn "."
if fs.select(max, 4, 0) == 0 then
print "Error occured in select {sys.errno.strerror}"
break
end
if fs.read_set.has(socket) then
var ns = socket.accept
print "Accepting {ns.address} ... "
print "[Message from {ns.address}] : {ns.read_line}"
ns.write "Hello client.\n"
print "[Message from {ns.address}] : {ns.read_line}"
ns.write "Bye client.\n"
print "Closing {ns.address} ..."
ns.close
end
end
lib/socket/examples/socket_server.nit:22,1--55,3
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
if args.has("-h") then
print "Usage: nit msgpack::msgpack_to_json [source_file.msgpack]"
print "Convert MessagePack format to JSON. Read from stdin if no source_file is given."
exit 0
end
var reader = if args.length >= 1 then
new FileReader.open(args.first)
else stdin
while reader.last_error == null and not reader.eof do
var deserialized = reader.read_msgpack
if deserialized != null then
print deserialized.serialize_to_json(plain=true, pretty=true)
else
print "null"
end
end
lib/msgpack/msgpack_to_json.nit:21,1--39,3
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
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
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
var server = new HTCPCServer(1227)
server.run
lib/nitcorn/examples/src/htcpcp_server.nit:101,1--103,10
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
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
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
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
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
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
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
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
var server = new ServerThread
server.start
0.1.sleep
# Launch 4 parallel requests to the async method
for i in 4.times do
var client = new ClientParallelThread(i)
client.start
0.1.sleep
end
# Successes
system "curl -s '{iface}/rest_path/foo?s=s&i=12&b=true'"
system "curl -s '{iface}/rest_path/foo?s=s&i=-4&b=false'"
system "curl -s '{iface}/rest_path/foo' --data 's=s&i=12&b=true'"
system "curl -s '{iface}/rest_path/api_name?s=s'"
system "curl -s '{iface}/rest_path/alt_name?s=s'"
system "curl -s '{iface}/rest_path/api_name?i=4&b=false'"
system """curl -s '{{{iface}}}/rest_path/complex_args?array=["a","b"]&data={"str":"asdf"}' -g"""
system """curl -s '{{{iface}}}/rest_path/complex_args?array=["a","b"]&data={"__class":"MyOtherData","str":"asdf","i":1234}' -g"""
# Errors falling back to `answer`
system "curl -s '{iface}/rest_path/non_existent_service'"
system "curl -s '{iface}/rest_path/foo'" # Missing args
system "curl -s '{iface}/rest_path/foo?b=WrongDataType'"
system "curl -s '{iface}/rest_path/bar?s=s'" # Renamed
system "curl -s '{iface}/rest_path/api_name' --data s=DoesNotAcceptPOST"
system """curl -s '{{{iface}}}/rest_path/complex_args?array=["a","b"]&data={"str":"as' -g""" # Truncated JSON
2.5.sleep
exit 0
lib/nitcorn/examples/src/test_restful_annot.nit:73,1--105,6
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
var app = new App
app.use("/", new MyTemplateHandler)
app.use("/string", new MyTemplateStringHandler)
app.use("/file", new MyTemplateFileHandler)
app.use("/pug", new MyTemplatePugHandler)
app.use("/pug_file", new MyTemplatePugFileHandler)
app.listen("localhost", 3000)
lib/popcorn/examples/templates/example_templates.nit:109,1--115,29
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
var loader = new Loader
loader.config.parse_options(args)
# TODO TMP
loader.jobs.clear
loader.repos.clear
loader.branches.clear
loader.commits.clear
loader.issues.clear
loader.pulls.clear
loader.issue_comments.clear
loader.issue_events.clear
if loader.config.help then
loader.config.usage
exit 0
end
if loader.config.opt_show_wallet.value then
loader.show_wallet
end
var args = loader.config.args
if loader.config.opt_show_jobs.value or args.is_empty then
loader.show_jobs
end
if args.is_empty then return
if loader.config.opt_clear.value then
loader.remove args.first
else
loader.start args.first
var repo = loader.config.wallet.api.get_repo(args.first)
if repo == null then return
print "Loaded"
print "* {if loader.repos.find_by_id(args.first) != null then 1 else 0} repos"
print "* {loader.branches.find_by_repo(repo).length} branches"
print "* {loader.commits.find_by_repo(repo).length} commits"
print "* {loader.issues.find_by_repo(repo).length} issues"
print "* {loader.pulls.find_by_repo(repo).length} pulls"
print "* {loader.issue_comments.find_by_repo(repo).length} comments"
print "* {loader.issue_events.find_by_repo(repo).length} events"
end
lib/github/loader.nit:554,1--598,3