task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Nim | Nim | import os, strutils
echo "Enter how long I should sleep (in milliseconds):"
var timed = stdin.readLine.parseInt()
echo "Sleeping..."
sleep timed
echo "Awake!" |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #JavaFX_Script | JavaFX Script | import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
Stage {
scene: Scene {
width: 300 height: 200
content: VBox {
var clicks: Integer;
spacing: 10
content: [
Label {
def varText = bind if (clicks == 0) then "no clicks yet" else "{clicks} clicks"
text : bind "There have been {varText}"
}
Button {
text: "click me"
onMouseClicked: function(e) { clicks++; }
}
]
}
}
} |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #JavaScript | JavaScript |
<html>
<head>
<title>Simple Window Application</title>
</head>
<body>
<br>        
<script type="text/javascript">
var box = document.createElement('input')
box.style.position = 'absolute'; // position it
box.style.left = '10px';
box.style.top = '60px';
document.body.appendChild(box).style.border="3px solid white";
document.body.appendChild(box).value = "There have been no clicks yet";
document.body.appendChild(box).style['width'] = '220px';
var clicks = 0;
function count_clicks() {
document.body.appendChild(box).remove()
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<button type="button" onclick="count_clicks()"> Click me</button>
<pre><p> Clicks: <a id="clicks">0</a> </p></pre>
</body>
</html>
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #NS-HUBASIC | NS-HUBASIC | 10 PRINT "I'LL TELL YOU WHEN I BECOME AWAKE AGAIN..."
20 PAUSE 100
30 PRINT "NOW I'M AWAKE AGAIN." |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Objeck | Objeck |
bundle Default {
class Test {
function : Main(args : System.String[]) ~ Nil {
if(args->Size() = 1) {
"Sleeping..."->PrintLine();
Thread->Sleep(args[0]->ToInt());
"Awake!"->PrintLine();
};
}
}
}
|
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Julia | Julia | using Gtk.ShortNames
function clickwindow()
clicks = 0
win = Window("Click Counter", 300, 100) |> (Frame() |> (vbox = Box(:v)))
lab = Label("There have been no clicks yet.")
but = Button("click me")
push!(vbox, lab)
push!(vbox, but)
set_gtk_property!(vbox, :expand, lab, true)
set_gtk_property!(vbox, :spacing, 20)
callback(w) = (clicks += 1; set_gtk_property!(lab, :label, "There have been $clicks button clicks."))
id = signal_connect(callback, but, :clicked)
Gtk.showall(win)
c = Condition()
endit(w) = notify(c)
signal_connect(endit, win, :destroy)
wait(c)
end
clickwindow()
|
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Kotlin | Kotlin | // version 1.0.6
import java.awt.BorderLayout
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import javax.swing.*
class Clicks : JFrame(), ActionListener {
private var clicks = 0
private val label: JLabel
private val clicker: JButton
private var text: String
init {
text = "There have been no clicks yet"
label = JLabel(text)
clicker = JButton("click me")
clicker.addActionListener(this) // listen to the button
layout = BorderLayout() // handles placement of components
add(label, BorderLayout.CENTER) // add the label to the biggest section
add(clicker, BorderLayout.SOUTH) // put the button underneath it
setSize(300, 200) // stretch out the window
defaultCloseOperation = EXIT_ON_CLOSE // stop the program on "X"
isVisible = true // show it
}
override fun actionPerformed(arg0: ActionEvent) {
if (arg0.source == clicker) { // if they clicked the button
if (clicks == 0) text = "There has been " + (++clicks) + " click"
else text = "There have been " + (++clicks) + " clicks"
label.text = text // change the text
}
}
}
fun main(args: Array<String>) {
Clicks() // call the constructor where all the magic happens
} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Objective-C | Objective-C | #import <Foundation/Foundation.h>
int main()
{
@autoreleasepool {
NSTimeInterval sleeptime;
printf("wait time in seconds: ");
scanf("%f", &sleeptime);
NSLog(@"sleeping...");
[NSThread sleepForTimeInterval: sleeptime];
NSLog(@"awakening...");
}
return 0;
} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #OCaml | OCaml | #load "unix.cma";;
let seconds = read_int ();;
print_endline "Sleeping...";;
Unix.sleep seconds;; (* number is integer in seconds *)
print_endline "Awake!";; |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Lambdatalk | Lambdatalk |
1) the label: {div {@ id="label"} There have been no clicks yet }
2) the button: {input {@ type="button" value="click me" onclick="CLICKAPP.inc()" }}
3) the script: {script °° code °°} where code is a single function:
var CLICKAPP = (function() {
var counter = 0;
var inc = function() {
counter++;
getId('label').innerHTML =
'There are ' + counter + ' clicks now';
};
return {inc:inc}
})();
|
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #11l | 11l | V sqrt3_2 = sqrt(3) / 2
F sierpinski_arrowhead_next(points)
V result = [(0.0, 0.0)] * (3 * (points.len - 1) + 1)
V j = 0
L(i) 0 .< points.len - 1
V (x0, y0) = points[i]
V (x1, y1) = points[i + 1]
V dx = x1 - x0
result[j] = (x0, y0)
I y0 == y1
V d = abs(dx * :sqrt3_2 / 2)
result[j + 1] = (x0 + dx / 4, y0 - d)
result[j + 2] = (x1 - dx / 4, y0 - d)
E I y1 < y0
result[j + 1] = (x1, y0)
result[j + 2] = (x1 + dx / 2, (y0 + y1) / 2)
E
result[j + 1] = (x0 - dx / 2, (y0 + y1) / 2)
result[j + 2] = (x0, y1)
j += 3
result[j] = points.last
R result
V size = 600
V iterations = 8
V outfile = File(‘sierpinski_arrowhead.svg’, ‘w’)
outfile.write(‘<svg xmlns='http://www.w3.org/2000/svg' width='’size‘' height='’size"'>\n")
outfile.write("<rect width='100%' height='100%' fill='white'/>\n")
outfile.write(‘<path stroke-width='1' stroke='black' fill='none' d='’)
V margin = 20.0
V side = size - 2 * margin
V x = margin
V y = 0.5 * size + 0.5 * sqrt3_2 * side
V points = [(x, y), (x + side, y)]
L 0 .< iterations
points = sierpinski_arrowhead_next(points)
L(point) points
outfile.write(I L.index == 0 {‘M’} E ‘L’)
outfile.write(point.x‘,’point.y"\n")
outfile.write("'/>\n</svg>\n") |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Oforth | Oforth | : sleepMilli(n) "Sleeping..." . n sleep "Awake!" println ; |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #ooRexx | ooRexx | Say time()
Call sysSleep 10 -- wait 10 seconds
Say time() |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Liberty_BASIC | Liberty BASIC | nomainwin
button #demo.btn, "Click Me", [btnClick], UL, 20, 50
statictext #demo.num, "There have been no clicks yet.", 20, 100, 240, 30
open "Rosetta Task: Simple windowed application" for window as #demo
#demo "trapclose [quit]"
nClicks = 0
wait
[quit]
close #demo
end
[btnClick]
nClicks = nClicks + 1
#demo.num "The button has been clicked ";nClicks;" times."
wait |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #Ada | Ada | with Ada.Command_Line;
with Ada.Numerics.Generic_Elementary_Functions;
with Ada.Text_IO;
with PDF_Out;
procedure Arrowhead_Curve is
package Real_Math is
new Ada.Numerics.Generic_Elementary_Functions (PDF_Out.Real);
use Real_Math, PDF_Out, Ada.Command_Line, Ada.Text_IO;
subtype Angle_Deg is Real;
type Order_Type is range 0 .. 7;
Purple : constant Color_Type := (0.7, 0.0, 0.5);
Length : constant Real := 340.0;
Corner : constant Point := (120.0, 480.0);
Order : Order_Type;
Current : Point := (0.0, 0.0);
Direction : Angle_Deg := Angle_Deg'(0.0);
Doc : PDF_Out_File;
procedure Curve (Order : Order_Type; Length : Real; Angle : Angle_Deg) is
begin
if Order = 0 then
Current := Current + Length * Point'(Cos (Direction, 360.0),
Sin (Direction, 360.0));
Doc.Line (Corner + Current);
else
Curve (Order - 1, Length / 2.0, -Angle); Direction := Direction + Angle;
Curve (Order - 1, Length / 2.0, Angle); Direction := Direction + Angle;
Curve (Order - 1, Length / 2.0, -Angle);
end if;
end Curve;
begin
if Argument_Count /= 1 then
Put_Line ("arrowhead_curve <order>");
Put_Line (" <order> 0 .. 7");
Put_Line ("open sierpinski-arrowhead-curve.pdf to view ouput");
return;
end if;
Order := Order_Type'Value (Argument (1));
Doc.Create ("sierpinski-arrowhead-curve.pdf");
Doc.Page_Setup (A4_Portrait);
Doc.Margins (Margins_Type'(Left => Cm_2_5,
others => One_cm));
Doc.Stroking_Color (Purple);
Doc.Line_Width (2.0);
Doc.Move (Corner);
if Order mod 2 = 0 then
Direction := 0.0;
Curve (Order, Length, 60.0);
else
Direction := 60.0;
Curve (Order, Length, -60.0);
end if;
Doc.Finish_Path (Close_Path => False,
Rendering => Stroke,
Rule => Nonzero_Winding_Number);
Doc.Close;
end Arrowhead_Curve; |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Oz | Oz | declare
class TextFile from Open.file Open.text end
StdIn = {New TextFile init(name:stdin)}
WaitTime = {String.toInt {StdIn getS($)}}
in
{System.showInfo "Sleeping..."}
{Delay WaitTime} %% in milliseconds
{System.showInfo "Awake!"} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #PARI.2FGP | PARI/GP | sleep(ms)={
print("Sleeping...");
while((ms-=gettime()) > 0,);
print("Awake!")
};
sleep(input()) |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Lingo | Lingo | on startMovie
-- window settings
_movie.stage.title = "Hello World!"
_movie.stage.titlebarOptions.visible = TRUE
_movie.stage.rect = rect(0,0,320, 240)
_movie.centerStage = 1
-- create a label (called "field" in Director)
m = new(#field)
m.name = "label"
m.rect = rect(0,0,320,0)
m.text = "There have been no clicks yet"
m.alignment = "center"
-- create sprite, assign field
_movie.puppetSprite(1, TRUE)
sprite(1).member = m
sprite(1).loc = point(0,80)
-- create a button
m = new(#button)
m.rect = rect(0,0,220,0)
m.text = "click me"
m.alignment = "center"
-- create sprite, assign button
_movie.puppetSprite(2, TRUE)
sprite(2).member = m
sprite(2).loc = point(50,105)
-- create new script at runtime, assign it to button sprite
m = new(#script)
m.scriptType = #score
m.scriptText = "on mouseDown"&RETURN&\
" m=member(""E&"label""E&")"&RETURN&\
" m.text=string(integer(m.text)+1)"&RETURN&\
"end"
sprite(2).scriptInstanceList.add(m.script.new())
-- force immediate update
_movie.updateStage()
-- show the window
_movie.stage.visible = 1
end |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #LiveCode | LiveCode | global count
on openCard
put empty into count
put "There have been no clicks yet" into field "clicks"
end openCard
on mouseUp
add 1 to count
put count into field "clicks"
end mouseUp |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #ALGOL_W | ALGOL W | begin % draw sierpinski arrowhead curves using ascii art %
integer CANVAS_WIDTH;
CANVAS_WIDTH := 200;
begin
% the ascii art canvas and related items %
string(1) array canvas ( 1 :: CANVAS_WIDTH, 1 :: CANVAS_WIDTH );
integer heading, asciiX, asciiY, width, maxX, maxY, minX, minY;
% draw a line using ascii art - the length is ignored and the heading determines the %
% character to use %
% the position is updated %
procedure drawLine( real value length ) ;
begin
% stores the min and max coordinates %
procedure updateCoordinateRange ;
begin
if asciiX > maxX then maxX := asciiX;
if asciiY > maxY then maxY := asciiY;
if asciiX < minX then minX := asciiX;
if asciiY < minY then minY := asciiY
end updateCoordinateRange ;
if heading = 0 then begin
updateCoordinateRange;
canvas( asciiX, asciiY ) := "_";
asciiX := asciiX + 1
end
else if heading = 60 then begin
updateCoordinateRange;
canvas( asciiX, asciiY ) := "/";
asciiY := asciiY - 1;
asciiX := asciiX + 1
end
else if heading = 120 then begin
asciiX := asciiX - 1;
updateCoordinateRange;
canvas( asciiX, asciiY ) := "\";
asciiY := asciiY - 1
end
else if heading = 180 then begin
asciiX := asciiX - 1;
updateCoordinateRange;
canvas( asciiX, asciiY ) := "_"
end
else if heading = 240 then begin
asciiX := asciiX - 1;
asciiY := asciiY + 1;
updateCoordinateRange;
canvas( asciiX, asciiY ) := "/"
end
else if heading = 300 then begin
asciiY := asciiY + 1;
updateCoordinateRange;
canvas( asciiX, asciiY ) := "\";
asciiX := asciiX + 1
end if_various_headings
end drawLine ;
% changes the heading by the specified angle ( in degrees ) - angle must be +/- 60 %
procedure turn( integer value angle ) ;
if angle > 0
then heading := ( heading + angle ) rem 360
else begin
heading := heading + angle;
if heading < 0 then heading := heading + 360
end tuen ;
% initialises the ascii art canvas %
procedure initArt ;
begin
heading := 0;
asciiX := CANVAS_WIDTH div 2;
asciiY := asciiX;
maxX := asciiX;
maxY := asciiY;
minX := asciiX;
minY := asciiY;
for x := 1 until CANVAS_WIDTH do for y := 1 until CANVAS_WIDTH do canvas( x, y ) := " "
end initArt ;
% shows the used parts of the canvas %
procedure drawArt ;
begin
for y := minY until maxY do begin
write();
for x := minX until maxX do writeon( canvas( x, y ) )
end for_y ;
write()
end drawIArt ;
% draws a sierpinski arrowhead curve of the specified order and line length %
procedure sierpinskiArrowheadCurve( integer value order; real value length ) ;
begin
% recursively draws a segment of the sierpinski arrowhead curve %
procedure curve( integer value order; real value length; integer value angle ) ;
if 0 = order then drawline( length )
else begin
curve( order - 1, length / 2, - angle );
turn( angle );
curve( order - 1, length / 2, angle );
turn( angle );
curve( order - 1, length / 2, - angle )
end curve ;
if not odd( order ) then begin % order is even, we can just draw the curve. %
curve( order, length, +60 );
end
else begin % order is odd %
turn( +60 );
curve( order, length, -60 )
end if_not_odd_order__
end sierpinskiArrowheadCurve ;
% draw curves %
i_w := 1; s_w := 0; % set output formatting %
for order := 5 do begin
write( "Sierpinski arrowhead curve of order ", order );
write( "=====================================" );
write();
initArt;
sierpinskiArrowheadCurve( order, 1 );
drawArt
end for_order
end
end. |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #AutoHotkey | AutoHotkey | order := 7
theta := 0
curve := []
curve.curveW := 1000
curve.curveH := 1000
curve.iy := 1
curve.cx := curve.curveW/2
curve.cy := curve.curveH
curve.ch := curve.cx/2
arrowhead(order, curve, theta, Arr :=[])
xmin := xmax := ymin := ymax := 0
for i, point in Arr
{
xmin := A_Index = 1 ? point.x : xmin < point.x ? xmin : point.x
xmax := point.x > xmax ? point.x : xmax
ymin := A_Index = 1 ? point.y : ymin < point.y ? ymin : point.y
ymax := point.y > ymax ? point.y : ymax
}
arrowheadX := A_ScreenWidth/2 - (xmax-xmin)/2 , arrowheadY := A_ScreenHeight/2 - (ymax-ymin)/2
for i, point in Arr
points .= point.x - xmin + arrowheadX "," point.y - ymin + arrowheadY "|"
points := Trim(points, "|")
gdip1()
Gdip_DrawLines(G, pPen, Points)
UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height)
return
; ---------------------------------------------------------------
arrowhead(order, curve, theta, Arr) {
length := curve.cx
if (order&1 = 0)
curve(order, length, theta, 60, Arr)
else
{
theta := turn(theta, 60)
theta := curve(order, length, theta, -60, Arr)
}
drawLine(length, theta, Arr)
}
; ---------------------------------------------------------------
drawLine(length, theta, Arr) {
global curve
Arr[Arr.count()+1, "x"] := curve.cx-curve.curveW/2+curve.ch
Arr[Arr.count(), "y"] := (curve.curveH-curve.cy)*curve.iy+2*curve.ch
pi := 3.141592653589793
curve.cx := curve.cx + length * Cos(theta*pi/180)
curve.cy := curve.cy + length * Sin(theta*pi/180)
}
; ---------------------------------------------------------------
turn(theta, angle) {
return theta := Mod(theta+angle, 360)
}
; ---------------------------------------------------------------
curve(order, length, theta, angle, Arr) {
if (order = 0)
drawLine(length, theta, Arr)
else
{
theta := curve(order-1, length/2, theta, -angle, Arr)
theta := turn(theta, angle)
theta := curve(order-1, length/2, theta, angle, Arr)
theta := turn(theta, angle)
theta := curve(order-1, length/2, theta, -angle, Arr)
}
return theta
}
; ---------------------------------------------------------------
gdip1(){
global
If !pToken := Gdip_Startup()
{
MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system
ExitApp
}
OnExit, Exit
Width := A_ScreenWidth, Height := A_ScreenHeight
Gui, 1: -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop
Gui, 1: Show, NA
hwnd1 := WinExist()
hbm := CreateDIBSection(Width, Height)
hdc := CreateCompatibleDC()
obm := SelectObject(hdc, hbm)
G := Gdip_GraphicsFromHDC(hdc)
Gdip_SetSmoothingMode(G, 4)
pPen := Gdip_CreatePen(0xFFFF0000, 2)
}
; ---------------------------------------------------------------
gdip2(){
global
Gdip_DeleteBrush(pBrush)
Gdip_DeletePen(pPen)
SelectObject(hdc, obm)
DeleteObject(hbm)
DeleteDC(hdc)
Gdip_DeleteGraphics(G)
}
; ---------------------------------------------------------------
Exit:
gdip2()
Gdip_Shutdown(pToken)
ExitApp
Return |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Pascal | Pascal | <@ SAYLIT>Number of seconds: </@><@ GETVAR>secs</@>
<@ SAYLIT>Sleeping</@>
<@ ACTPAUVAR>secs</@>
<@ SAYLIT>Awake</@> |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Peloton | Peloton | <@ SAYLIT>Number of seconds: </@><@ GETVAR>secs</@>
<@ SAYLIT>Sleeping</@>
<@ ACTPAUVAR>secs</@>
<@ SAYLIT>Awake</@> |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Logo | Logo | to clickwindow
windowCreate "root "clickWin [Click that button!!!] 0 0 100 100 []
Make "i 0
staticCreate "clickWin "clickSt [There have been no clicks yet] 0 0 100 20
buttonCreate "clickWin "clickBtn [click me] 10 20 80 20 ~
[Make "i :i+1 ~
ifelse :i=1 [staticUpdate "clickSt (list "clicked :i "time)] ~
[staticUpdate "clickSt (list "clicked :i "times)]]
end |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Lua | Lua | require"iuplua"
l = iup.label{title="There have been no clicks yet."}
b = iup.button{title="Click me!"}
clicks = 0
function b:button_cb()
clicks = clicks + 1
l.title = "There have been " .. clicks/2 .. " clicks so far." --yes, this is correct.
end
dlg = iup.dialog{iup.vbox{l, b}, title="Simple Windowed Application"}
dlg:show()
if (not iup.MainLoopLevel or iup.MainLoopLevel()==0) then
iup.MainLoop()
end |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #C | C | // See https://en.wikipedia.org/wiki/Sierpi%C5%84ski_curve#Arrowhead_curve
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
// Structure to keep track of current position and orientation
typedef struct cursor_tag {
double x;
double y;
int angle;
} cursor_t;
void turn(cursor_t* cursor, int angle) {
cursor->angle = (cursor->angle + angle) % 360;
}
void draw_line(FILE* out, cursor_t* cursor, double length) {
double theta = (M_PI * cursor->angle)/180.0;
cursor->x += length * cos(theta);
cursor->y += length * sin(theta);
fprintf(out, "L%g,%g\n", cursor->x, cursor->y);
}
void curve(FILE* out, int order, double length, cursor_t* cursor, int angle) {
if (order == 0) {
draw_line(out, cursor, length);
} else {
curve(out, order - 1, length/2, cursor, -angle);
turn(cursor, angle);
curve(out, order - 1, length/2, cursor, angle);
turn(cursor, angle);
curve(out, order - 1, length/2, cursor, -angle);
}
}
void write_sierpinski_arrowhead(FILE* out, int size, int order) {
const double margin = 20.0;
const double side = size - 2.0 * margin;
cursor_t cursor;
cursor.angle = 0;
cursor.x = margin;
cursor.y = 0.5 * size + 0.25 * sqrt(3) * side;
if ((order & 1) != 0)
turn(&cursor, -60);
fprintf(out, "<svg xmlns='http://www.w3.org/2000/svg' width='%d' height='%d'>\n",
size, size);
fprintf(out, "<rect width='100%%' height='100%%' fill='white'/>\n");
fprintf(out, "<path stroke-width='1' stroke='black' fill='none' d='");
fprintf(out, "M%g,%g\n", cursor.x, cursor.y);
curve(out, order, side, &cursor, 60);
fprintf(out, "'/>\n</svg>\n");
}
int main(int argc, char** argv) {
const char* filename = "sierpinski_arrowhead.svg";
if (argc == 2)
filename = argv[1];
FILE* out = fopen(filename, "w");
if (!out) {
perror(filename);
return EXIT_FAILURE;
}
write_sierpinski_arrowhead(out, 600, 8);
fclose(out);
return EXIT_SUCCESS;
} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Perl | Perl | $seconds = <>;
print "Sleeping...\n";
sleep $seconds; # number is in seconds
print "Awake!\n"; |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Phix | Phix | without js -- (prompt_number, sleep)
atom a = prompt_number("wait for duration (in seconds, 0..20):", {0,20})
puts(1,"Sleeping...\n")
sleep(a)
puts(1,"Awake!\n")
|
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Declare Form1 Form
Declare Label1 Button Form Form1
Declare Button1 Button Form Form1
Method Label1,"move", 2000, 2000, 4000, 600
Method Button1,"move", 2000, 3000, 4000, 600
With Label1, "Caption" as caption$, "Locked", true, "Caption" as cap
With Button1, "Caption", "click me", "Default", True ' make this the default control
caption$="There have been no clicks yet"
m=0
Function Button1.Click {
m++
cap=m
}
Method Form1, "Show",1
Declare Form1 Nothing
}
Checkit
|
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | DynamicModule[{n = 0},
CreateDialog[{Dynamic@
TextCell@If[n == 0, "There have been no clicks yet", n],
Button["click me", n++]}]] |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #C.2B.2B | C++ | #include <fstream>
#include <iostream>
#include <vector>
constexpr double sqrt3_2 = 0.86602540378444; // sqrt(3)/2
struct point {
double x;
double y;
};
std::vector<point> sierpinski_arrowhead_next(const std::vector<point>& points) {
size_t size = points.size();
std::vector<point> output(3*(size - 1) + 1);
double x0, y0, x1, y1;
size_t j = 0;
for (size_t i = 0; i + 1 < size; ++i, j += 3) {
x0 = points[i].x;
y0 = points[i].y;
x1 = points[i + 1].x;
y1 = points[i + 1].y;
double dx = x1 - x0;
output[j] = {x0, y0};
if (y0 == y1) {
double d = dx * sqrt3_2/2;
if (d < 0) d = -d;
output[j + 1] = {x0 + dx/4, y0 - d};
output[j + 2] = {x1 - dx/4, y0 - d};
} else if (y1 < y0) {
output[j + 1] = {x1, y0};
output[j + 2] = {x1 + dx/2, (y0 + y1)/2};
} else {
output[j + 1] = {x0 - dx/2, (y0 + y1)/2};
output[j + 2] = {x0, y1};
}
}
output[j] = {x1, y1};
return output;
}
void write_sierpinski_arrowhead(std::ostream& out, int size, int iterations) {
out << "<svg xmlns='http://www.w3.org/2000/svg' width='"
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='white'/>\n";
out << "<path stroke-width='1' stroke='black' fill='none' d='";
const double margin = 20.0;
const double side = size - 2.0 * margin;
const double x = margin;
const double y = 0.5 * size + 0.5 * sqrt3_2 * side;
std::vector<point> points{{x, y}, {x + side, y}};
for (int i = 0; i < iterations; ++i)
points = sierpinski_arrowhead_next(points);
for (size_t i = 0, n = points.size(); i < n; ++i)
out << (i == 0 ? "M" : "L") << points[i].x << ',' << points[i].y << '\n';
out << "'/>\n</svg>\n";
}
int main() {
std::ofstream out("sierpinski_arrowhead.svg");
if (!out) {
std::cerr << "Cannot open output file\n";
return EXIT_FAILURE;
}
write_sierpinski_arrowhead(out, 600, 8);
return EXIT_SUCCESS;
} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #PHP | PHP | $seconds = 42;
echo "Sleeping...\n";
sleep($seconds); # number is integer in seconds
echo "Awake!\n"; |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #PicoLisp | PicoLisp | (prinl "Sleeping..." )
(wait 2000) # Wait for 2 seconds
(prinl "Awake!") |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #MAXScript | MAXScript | rollout buttonClick "Button Click"
(
label l "There have been no clicks yet"
button clickMe "Click me"
local clickCount = 0
on clickMe pressed do
(
clickCount += 1
l.text = ("Number of clicks: " + clickCount as string)
)
)
createDialog buttonClick |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #Factor | Factor | USING: accessors L-system ui ;
: arrowhead ( L-system -- L-system )
L-parser-dialect >>commands
[ 60 >>angle ] >>turtle-values
"XF" >>axiom
{
{ "X" "YF+XF+Y" }
{ "Y" "XF-YF-X" }
} >>rules ;
[ <L-system> arrowhead "Arrowhead" open-window ] with-ui |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #Forth | Forth | ( ASCII output with use of ANSI terminal control )
: draw-line ( direction -- )
case
0 of .\" _" endof ( horizontal right: _ )
1 of .\" \e[B\\" endof ( down right: CUD \ )
2 of .\" \e[D\e[B/\e[D" endof ( down left: CUB CUD / CUB )
3 of .\" \e[D_\e[D" endof ( horizontal left: CUB _ CUB )
4 of .\" \e[D\\\e[A\e[D" endof ( up left: CUB \ CUU CUB )
5 of .\" /\e[A" endof ( up right: / CUU )
endcase ( cursor is up-right of the last point )
;
: turn+ 1+ 6 mod ;
: turn- 1- 6 mod ;
defer curve
: A-rule ( order direction -- ) turn+ 2dup 'B curve turn- 2dup 'A curve turn- 'B curve ;
: B-rule ( order direction -- ) turn- 2dup 'A curve turn+ 2dup 'B curve turn+ 'A curve ;
:noname ( order direction type -- )
2 pick 0 = if drop draw-line drop exit then \ draw line when order is 0
rot 1- rot rot
'A = if A-rule else B-rule then
; is curve
: arrowhead ( order -- )
page
s" Sierpinski arrowhead curve of order " type dup . cr
s" =====================================" type cr
0 'A curve
;
5 arrowhead |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Pike | Pike | int main() {
int seconds = (int)Stdio.stdin->gets();
write("Sleeping...\n");
sleep(seconds);
write("Awake!\n");
return 0;
} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Pixilang | Pixilang | fputs("Sleeping...\n")
sleep(1000)
fputs("Awake!\n") |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Modula-3 | Modula-3 | MODULE Click EXPORTS Main;
IMPORT Fmt, TextVBT, ButtonVBT, VBT, Axis, HVSplit, TrestleComm, Trestle;
VAR label := TextVBT.New("There have been no clicks yet.");
button := ButtonVBT.New(TextVBT.New("Click me!"), Clicked);
main := HVSplit.Cons(Axis.T.Ver, label, button, adjustable := FALSE);
count := 0;
PROCEDURE Clicked(<*UNUSED*>button: ButtonVBT.T; <*UNUSED*>READONLY cd: VBT.MouseRec) =
BEGIN
INC(count);
TextVBT.Put(label, "Button pressed: " & Fmt.Int(count));
END Clicked;
<*FATAL TrestleComm.Failure*>
BEGIN
Trestle.Install(main);
Trestle.AwaitDelete(main);
END Click. |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #Go | Go | package main
import (
"github.com/fogleman/gg"
"math"
)
var (
width = 770.0
height = 770.0
dc = gg.NewContext(int(width), int(height))
iy = 1.0
theta = 0
)
var cx, cy, h float64
func arrowhead(order int, length float64) {
// if order is even, we can just draw the curve
if order&1 == 0 {
curve(order, length, 60)
} else {
turn(60)
curve(order, length, -60)
}
drawLine(length) // needed to make base symmetric
}
func drawLine(length float64) {
dc.LineTo(cx-width/2+h, (height-cy)*iy+2*h)
rads := gg.Radians(float64(theta))
cx += length * math.Cos(rads)
cy += length * math.Sin(rads)
}
func turn(angle int) {
theta = (theta + angle) % 360
}
func curve(order int, length float64, angle int) {
if order == 0 {
drawLine(length)
} else {
curve(order-1, length/2, -angle)
turn(angle)
curve(order-1, length/2, angle)
turn(angle)
curve(order-1, length/2, -angle)
}
}
func main() {
dc.SetRGB(0, 0, 0) // black background
dc.Clear()
order := 6
if order&1 == 0 {
iy = -1 // apex will point upwards
}
cx, cy = width/2, height
h = cx / 2
arrowhead(order, cx)
dc.SetRGB255(255, 0, 255) // magenta curve
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG("sierpinski_arrowhead_curve.png")
} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #PL.2FI | PL/I |
put ('sleeping');
delay (2000); /* wait for 2 seconds (=2000 milliseconds). */
put ('awake');
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Plain_English | Plain English | To run:
Start up.
Demonstrate waiting.
Wait for the escape key.
Shut down.
To demonstrate waiting:
Write "How many milliseconds should I wait? " to the console without advancing.
Read some milliseconds from the console.
Write "Sleeping..." to the console.
Wait for the milliseconds.
Write "Awake!" to the console. |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Nanoquery | Nanoquery | import Nanoquery.Util.Windows
// define the necessary objects
$w = new("Window")
$b = new("Button")
$l = new("Label")
$b.setParent($w)
$l.setParent($w)
// define the amount of clicks
$clicks = 0
// a function to update the label
def updateLabel($caller, $event)
global $clicks
global $l
$clicks = $clicks+1
$l.setText(str($clicks))
global $clicks = $clicks
end
// prepare the components to be displayed
$w.setSize(200,200)
$b.setText("click me")
$b.setPosition(0,100)
$l.setText("There have been no clicks yet")
// set the button's event handler to the function updateLabel
$b.setHandler($updateLabel)
// show the window
$w.show() |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Nim | Nim | import gtk2
nim_init()
var
win = windowNew WINDOW_TOPLEVEL
button = buttonNew "Click me"
label = labelNew "There have been no clicks yet"
vbox = vboxNew(true, 1)
counter = 0
proc clickedMe(o: var PButton, l: PLabel) =
inc counter
l.setText "You clicked me " & $counter & " times"
win.setTitle "Click me"
vbox.add label
vbox.add button
win.add vbox
discard win.signal_connect("delete-event", SignalFunc mainQuit, nil)
discard button.signal_connect("clicked", SignalFunc clickedMe, label)
win.showAll()
main() |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #jq | jq | include "turtle" {search: "."};
# Compute the curve using a Lindenmayer system of rules
def rules:
{X: "Yf+Xf+Y", Y: "Xf-Yf-X", "": "X"};
def sierpinski($count):
rules as $rules
| def repeat($count):
if $count == 0 then .
else ascii_downcase | gsub("x"; $rules["X"]) | gsub("y"; $rules["Y"])
| repeat($count-1)
end;
$rules[""] | repeat($count) ;
def interpret($x):
if $x == "+" then turtleRotate(60)
elif $x == "-" then turtleRotate(-60)
elif $x == "f" then turtleForward(3)
else .
end;
def sierpinski_curve($n):
sierpinski($n)
| split("")
| reduce .[] as $action (
turtle([0,-350]) | turtleDown | turtleRotate(60);
interpret($action) ) ;
# viewBox = <min-x> <min-y> <width> <height>
# Input: {svg, minx, miny, maxx, maxy}
def svg:
"<svg viewBox='\(.minx|floor) \(.miny - 4 |floor) \(.maxx - .minx|ceil) \(6 + .maxy - .miny|ceil)'",
" preserveAspectRatio='xMinYmin meet'",
" xmlns='http://www.w3.org/2000/svg' >",
path("none"; "red"; 1),
"</svg>";
sierpinski_curve(8)
| svg
|
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #Julia | Julia | using Lindenmayer # https://github.com/cormullion/Lindenmayer.jl
scurve = LSystem(Dict("F" => "G+F+Gt", "G"=>"F-G-F"), "G")
drawLSystem(scurve,
forward = 3,
turn = 60,
startingy = -350,
iterations = 8,
startingorientation = π/3,
filename = "sierpinski_arrowhead_curve.png",
showpreview = true
)
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #PowerShell | PowerShell | $d = [int] (Read-Host Duration in seconds)
Write-Host Sleeping ...
Start-Sleep $d
Write-Host Awake! |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Prolog | Prolog | rosetta_sleep(Time) :-
writeln('Sleeping...'),
sleep(Time),
writeln('Awake!').
|
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Objective-C | Objective-C | #include <Foundation/Foundation.h>
#include <AppKit/AppKit.h>
@interface ClickMe : NSWindow
{
NSButton *_button;
NSTextField *_text;
int _counter;
}
- (void)applicationDidFinishLaunching: (NSNotification *)notification;
- (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSNotification *)notification;
- (void)advanceCounter: (id)sender;
@end |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #11l | 11l | F sierpinski(n)
V d = [String(‘*’)]
L(i) 0 .< n
V sp = ‘ ’ * (2 ^ i)
d = d.map(x -> @sp‘’x‘’@sp) [+] d.map(x -> x‘ ’x)
R d
print(sierpinski(4).join("\n")) |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #Lambdatalk | Lambdatalk |
{def sierp
{def sierp.r
{lambda {:order :length :angle}
{if {= :order 0}
then M:length
else {sierp.r {- :order 1} {/ :length 2} {- :angle}}
T:angle
{sierp.r {- :order 1} {/ :length 2} :angle}
T:angle
{sierp.r {- :order 1} {/ :length 2} {- :angle}}
}}}
{lambda {:order :length}
{if {= {% :order 2} 0}
then {sierp.r :order :length 60}
else T60
{sierp.r :order :length -60}
}}}
the output can be seen in http://lambdaway.free.fr/lambdawalks/?view=sierpinsky
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #PureBasic | PureBasic | If OpenConsole()
Print("Enter a time(milliseconds) to sleep: ")
x.i = Val(Input())
PrintN("Sleeping...")
Delay(x) ;in milliseconds
PrintN("Awake!")
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Python | Python | import time
seconds = float(raw_input())
print "Sleeping..."
time.sleep(seconds) # number is in seconds ... but accepts fractions
print "Awake!" |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #OCaml | OCaml | #directory "+labltk"
#load "labltk.cma"
let () =
let top = Tk.openTk() in
Wm.title_set top "Tk-OCaml Example";
let label = Label.create ~text:"There have been no clicks yet" top in
let b =
Button.create
~text:"click me"
~command:(fun () -> Tk.closeTk (); exit 0)
top
in
Tk.pack [Tk.coe label; Tk.coe b];
Tk.mainLoop ();
;; |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #8080_Assembly | 8080 Assembly | argmt: equ 5Dh ; Command line argument
puts: equ 9 ; CP/M syscall to print a string
putch: equ 2 ; CP/M syscall to print a character
org 100h
mvi b,4 ; Default order is 4
mvi e,' ' ; Keep space in E since we're saving it anyway
lda argmt ; Argument given?
cmp e ; If not, use default
jz start
sui '0' ; Make sure given N makes sense
cpi 3 ; <3?
jc start
cpi 8 ; >=8?
jnc start
mov b,a
start: mvi a,1 ; Find size (2 ** order)
shift: rlc
dcr b
jnz shift
mov b,a ; B = size
mov c,a ; C = current line
line: mov d,c ; D = column
indent: mov a,e ; Indent line
call chout
dcr d
jnz indent
column: mov a,c ; line + col <= size?
add d
dcr a
cmp b
jnc cdone
mov a,c ; (line - 1) & col == 0?
dcr a
ana d
mov a,e ; space if not, star if so
jnz print
mvi a,'*'
print: call chout
mov a,e
call chout
inr d
jmp column
cdone: push b ; done, print newline
push d
lxi d,nl
mvi c,puts
call 5
pop d
pop b
dcr c ; next line
jnz line
ret
chout: push b ; save BC and DE
push d
mov e,a ; print character
mvi c,putch
call 5
pop d ; restore BC and DE
pop b
ret
nl: db 13,10,'$' |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[DoStep]
DoStep[Line[{x_, y_}]] := Module[{diff, perp, pts},
diff = y - x;
perp = Cross[diff] Sqrt[3]/2;
pts = {x, x + diff/4 + perp/2, x + 3 diff/4 + perp/2, y};
{Line[pts[[{2, 1}]]], Line[pts[[{2, 3}]]], Line[pts[[{4, 3}]]]}
]
lns = {Line[{{0.0, 0.0}, {1.0, 0.0}}]};
lns = Nest[Catenate[DoStep /@ #] &, lns, 5];
Graphics[lns] |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #Nim | Nim | import math
const Sqrt3_2 = sqrt(3.0) / 2.0
type Point = tuple[x, y: float]
func sierpinskiArrowheadNext(points: seq[Point]): seq[Point] =
result.setLen(3 * (points.len - 1) + 1)
var j = 0
for i in 0..<points.high:
let (x0, y0) = points[i]
let (x1, y1) = points[i + 1]
let dx = x1 - x0
result[j] = (x0, y0)
if y0 == y1:
let d = abs(dx * Sqrt3_2 / 2)
result[j + 1] = (x0 + dx / 4, y0 - d)
result[j + 2] = (x1 - dx / 4, y0 - d)
elif y1 < y0:
result[j + 1] = (x1, y0)
result[j + 2] = (x1 + dx / 2, (y0 + y1) / 2)
else:
result[j + 1] = (x0 - dx / 2, (y0 + y1) / 2)
result[j + 2] = (x0, y1)
inc j, 3
result[j] = points[^1]
proc writeSierpinskiArrowhead(outfile: File; size, iterations: int) =
outfile.write "<svg xmlns='http://www.w3.org/2000/svg' width='", size, "' height='", size, "'>\n"
outfile.write "<rect width='100%' height='100%' fill='white'/>\n"
outfile.write "<path stroke-width='1' stroke='black' fill='none' d='"
const Margin = 20.0
let side = size.toFloat - 2 * Margin
let x = Margin
let y = 0.5 * size.toFloat + 0.5 * Sqrt3_2 * side
var points = @[(x: x, y: y), (x: x + side, y: y)]
for _ in 1..iterations:
points = sierpinskiArrowheadNext(points)
for i, point in points:
outfile.write if i == 0: 'M' else: 'L', point.x, ',', point.y, '\n'
outfile.write "'/>\n</svg>\n"
let outfile = open("sierpinski_arrowhead.svg", fmWrite)
outfile.writeSierpinskiArrowhead(600, 8)
outfile.close() |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #R | R |
sleep <- function(time=1)
{
message("Sleeping...")
flush.console()
Sys.sleep(time)
message("Awake!")
}
sleep()
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Racket | Racket |
#lang racket
(displayln "Enter a time (in seconds): ")
(define time (read))
(when (number? time)
(displayln "Sleeping...")
(sleep time)
(displayln "Awake!"))
|
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #ooRexx | ooRexx | /* REXX ***************************************************************************************
* 18.06.2014 Walter Pachl shortened from Rony Flatscher's bsf4oorexx (see sourceforge) samples
* Look there for ShowCount.rxj
* bsf4oorexx lets the ooRexx program use Java classes
**********************************************************************************************/
userData=.directory~new -- a directory which will be passed to Rexx with the event
-- create a framed Java window, set a title text
win=.bsf~new("java.awt.Frame", "Show Count")
-- Create a Java RexxProxy for controlling the closing of the application
rexxCloseEH =.RexxCloseAppEventHandler~new -- Rexx event handler
-- Create Java RexxProxy for the Rexx event handler
rpCloseEH=BsfCreateRexxProxy(rexxCloseEH,,"java.awt.event.WindowListener" )
win~addWindowListener(rpCloseEH) -- add RexxProxy event handler
-- create a Java push button
but=.bsf~new("java.awt.Button","Press me!")
-- Create a RexxProxy for the button Rexx event handler
rp=BsfCreateRexxProxy(.RexxShowCountEventHandler~new,userData,"java.awt.event.ActionListener")
but~addActionListener(rp) -- add RexxProxy event handler
lab=.bsf~new("java.awt.Label") -- create a Java label,set it to show the text centered
userData~label=lab -- save label object for later use in event handler
lab~setAlignment(lab~center) -- set alignment to center
lab~setText("Button was not yet pressed") -- assign initial text to the label
win ~~add("Center",lab) ~~add("South",but) -- add the label and the button to the frame
win ~~pack -- now calculate all widget dimensions
call enlargeWidth win,but,120 -- enlarge the width of the frame and the button
win ~~setVisible(.true) ~~toFront -- make frame visible and move it to the front
userData~i=0 -- set counter to 0
rexxCloseEH~waitForExit -- wait until we are allowed to end the program
-- if Java was loaded by Rexx,then terminate Java's RexxEngine to inhibit callbacks from Java
call BSF.terminateRexxEngine
::requires BSF.CLS -- get Java support
/* enlarge the width of the frame and of the button without using a layout manager */
::routine enlargeWidth
use arg win,but,addToWidth
winDim=win~getSize -- get frame's dimension
winDim~width+=addToWidth -- increase width
win~setSize(winDim) -- set frame's dimension
/* ------------------------------------------------------------------------ */
/* Rexx event handler to set "close app" indicator */
::class RexxCloseAppEventHandler
::method init -- constructor
expose closeApp
closeApp = .false -- if set to .true, then it is safe to close the app
::attribute closeApp -- indicates whether app should be closed
::method unknown -- intercept unhandled events,do nothing
::method windowClosing -- event method (from WindowListener)
expose closeApp
closeApp=.true -- indicate that the app should close
::method waitForExit -- method blocks until attribute is set to .true
expose closeApp
guard on when closeApp=.true
/* ------------------------------------------------------------------------ */
/* Rexx event handler to process tab changes */
::class RexxShowCountEventHandler
::method actionPerformed
use arg eventObject,slotDir
call showCount slotDir~userData
/* ------------------------------------------------------------------------ */
::routine ShowCount -- increment counter and show text
use arg userData
userData~i+=1 -- increment counter in directory object
Select -- construct text part
When userData~i=1 Then how_often='once'
When userData~i=2 Then how_often='twice'
When userData~i=3 Then how_often='three times'
Otherwise how_often=userData~i 'times'
End
userData~label~setText("Button was pressed" how_often) -- display text |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #8086_Assembly | 8086 Assembly | putch: equ 2 ; MS-DOS syscall to print character
puts: equ 9 ; MS-DOS syscall to print string
argmt: equ 5Dh ; MS-DOS still has FCB in same place as CP/M
cpu 8086
org 100h
section .text
mov cx,4 ; Default order is 4
mov al,[argmt]
sub al,'3' ; Argument is there and makes sense? (3 - 7)
cmp al,7-3
ja start ; If not, use default
add al,3 ; If so, use it
mov cl,al
start: mov bl,1 ; Let BL be the size (2 ** order)
shl bl,cl
mov bh,bl ; Let BH be the current line
line: mov cl,bh ; Let CL be the column
mov dl,' ' ; Indent line with spaces
mov ah,putch
indent: int 21h
loop indent
column: mov al,cl ; line + column <= size?
add al,bh
cmp al,bl
ja .done ; then column is done
mov al,bh ; (line - 1) & column == 0?
dec al
test al,cl
jnz .print ; space if not, star if so
mov dl,'*'
.print: int 21h
mov dl,' '
int 21h
inc cx ; next column
jmp column
.done: mov dx,nl ; done, print newline
mov ah,puts
int 21h
dec bh ; next line
jnz line
ret
nl: db 13,10,'$' |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #Perl | Perl | use strict;
use warnings;
use SVG;
use List::Util qw(max min);
use constant pi => 2 * atan2(1, 0);
my %rules = (
X => 'YF+XF+Y',
Y => 'XF-YF-X'
);
my $S = 'Y';
$S =~ s/([XY])/$rules{$1}/eg for 1..7;
my (@X, @Y);
my ($x, $y) = (0, 0);
my $theta = 0;
my $r = 6;
for (split //, $S) {
if (/F/) {
push @X, sprintf "%.0f", $x;
push @Y, sprintf "%.0f", $y;
$x += $r * cos($theta);
$y += $r * sin($theta);
}
elsif (/\+/) { $theta += pi/3; }
elsif (/\-/) { $theta -= pi/3; }
}
my ($xrng, $yrng) = ( max(@X) - min(@X), max(@Y) - min(@Y));
my ($xt, $yt) = (-min(@X) + 10, -min(@Y) + 10);
my $svg = SVG->new(width=>$xrng+20, height=>$yrng+20);
my $points = $svg->get_path(x=>\@X, y=>\@Y, -type=>'polyline');
$svg->rect(width=>"100%", height=>"100%", style=>{'fill'=>'black'});
$svg->polyline(%$points, style=>{'stroke'=>'orange', 'stroke-width'=>1}, transform=>"translate($xt,$yt)");
open my $fh, '>', 'sierpinski-arrowhead-curve.svg';
print $fh $svg->xmlify(-namespace=>'svg');
close $fh; |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Raku | Raku | my $sec = prompt("Sleep for how many microfortnights? ") * 1.2096;
say "Sleeping...";
sleep $sec;
say "Awake!"; |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #RapidQ | RapidQ |
input "Enter the number of seconds to sleep: ";s
sleep s
print "I'm awake I think..."
input "Press enter to quit";a$
|
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Oz | Oz | functor
import
Application
QTk at 'x-oz://system/wp/QTk.ozf'
define
Count = {NewCell 0}
Label
GUI = td(action:proc {$} {Application.exit 0} end %% exit on close
label(text:"There have been no clicks yet." handle:Label)
button(text:"Click Me"
action:proc {$}
Count := @Count + 1
{Label set(text:"Number of clicks: "#@Count#".")}
end
))
Window = {QTk.build GUI}
{Window show}
end
|
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #ACL2 | ACL2 | (defun pascal-row (prev)
(if (endp (rest prev))
(list 1)
(cons (+ (first prev) (second prev))
(pascal-row (rest prev)))))
(defun pascal-triangle-r (rows prev)
(if (zp rows)
nil
(let ((curr (cons 1 (pascal-row prev))))
(cons curr (pascal-triangle-r (1- rows) curr)))))
(defun pascal-triangle (rows)
(cons (list 1)
(pascal-triangle-r rows (list 1))))
(defun print-odds-row (row)
(if (endp row)
(cw "~%")
(prog2$ (cw (if (oddp (first row)) "[]" " "))
(print-odds-row (rest row)))))
(defun print-spaces (n)
(if (zp n)
nil
(prog2$ (cw " ")
(print-spaces (1- n)))))
(defun print-odds (triangle height)
(if (endp triangle)
nil
(progn$ (print-spaces height)
(print-odds-row (first triangle))
(print-odds (rest triangle) (1- height)))))
(defun print-sierpenski (levels)
(let ((height (1- (expt 2 levels))))
(print-odds (pascal-triangle height)
height))) |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #Phix | Phix | --
-- demo\rosetta\Sierpinski_arrowhead_curve.exw
-- ===========================================
--
-- Draws curves lo to hi (simultaneously), initially {6,6}, max {10,10}, min {1,1}
-- Press +/- to change hi, shift +/- to change lo.
-- ("=_" are also mapped to "+-", for the non-numpad +/-)
--
with javascript_semantics
include pGUI.e
Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas
integer width, height,
lo = 6, hi = 6
atom cx, cy, h, theta
integer iy = +1
procedure draw_line(atom l)
cdCanvasVertex(cddbuffer, cx-width/2+h, (height-cy)*iy+2*h)
cx += l*cos(theta*CD_DEG2RAD)
cy += l*sin(theta*CD_DEG2RAD)
end procedure
procedure turn(integer angle)
theta = mod(theta+angle,360)
end procedure
procedure curve(integer order, atom l, integer angle)
if order=0 then
draw_line(l)
else
curve(order-1, l/2, -angle)
turn(angle)
curve(order-1, l/2, angle)
turn(angle)
curve(order-1, l/2, -angle)
end if
end procedure
procedure sierpinski_arrowhead_curve(integer order, atom l)
-- If order is even we can just draw the curve.
if and_bits(order,1)=0 then
curve(order, l, +60)
else -- order is odd
turn( +60)
curve(order, l, -60)
end if
draw_line(l)
end procedure
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/)
{width, height} = IupGetIntInt(canvas, "DRAWSIZE")
cdCanvasActivate(cddbuffer)
for order=lo to hi do
cx = width/2
cy = height
h = cx/2
theta = 0
iy = iff(and_bits(order,1)?-1:+1)
cdCanvasBegin(cddbuffer, CD_OPEN_LINES)
sierpinski_arrowhead_curve(order, cx)
cdCanvasEnd(cddbuffer)
end for
cdCanvasFlush(cddbuffer)
return IUP_DEFAULT
end function
function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
cdCanvasSetBackground(cddbuffer, CD_WHITE)
cdCanvasSetForeground(cddbuffer, CD_BLUE)
return IUP_DEFAULT
end function
function key_cb(Ihandle /*ih*/, atom c)
if c=K_ESC then return IUP_CLOSE end if
if find(c,"+=-_") then
bool bShift = IupGetInt(NULL,"SHIFTKEY")
if c='+' or c='=' then
if bShift then
lo = min(lo+1,hi)
else
hi = min(10,hi+1)
end if
elsif c='-' or c='_' then
if bShift then
lo = max(1,lo-1)
else
hi = max(lo,hi-1)
end if
end if
IupSetStrAttribute(dlg, "TITLE", "Sierpinski arrowhead curve (%d..%d)",{lo,hi})
cdCanvasClear(cddbuffer)
IupUpdate(canvas)
end if
return IUP_DEFAULT
end function
procedure main()
IupOpen()
canvas = IupCanvas(NULL)
IupSetAttribute(canvas, "RASTERSIZE", "770x770")
IupSetCallback(canvas, "MAP_CB", Icallback("map_cb"))
IupSetCallback(canvas, "ACTION", Icallback("redraw_cb"))
dlg = IupDialog(canvas)
IupSetAttribute(dlg, "TITLE", "Sierpinski arrowhead curve (6..6)")
IupSetCallback(dlg, "K_ANY", Icallback("key_cb"))
IupMap(dlg)
IupShowXY(dlg,IUP_CENTER,IUP_CENTER)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
end procedure
main()
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #REBOL | REBOL | rebol [
Title: "Sleep Main Thread"
URL: http://rosettacode.org/wiki/Sleep_the_Main_Thread
]
naptime: to-integer ask "Please enter sleep time in seconds: "
print "Sleeping..."
wait naptime
print "Awake!" |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Pascal | Pascal | Program SimpleWindowApplication;
uses
SysUtils,
glib2,
Gtk2;
const
clickme = 'Click Me';
MAXLEN = 64;
var
counter: integer = 0;
procedure clickedme(o: PGtkButton; d: pointer); cdecl;
var
nt: Pchar;
l: PGtkLabel;
begin
l := Gtk_LABEL(d);
inc(counter);
nt := Pchar('You clicked me ' + inttostr(counter) + ' times');
Gtk_label_set_text(l, nt);
end;
var
win: PGtkWindow;
button: PGtkButton;
Mylabel: PGtkLabel;
vbox: PGtkVBox;
begin
Gtk_init(@argc, @argv);
win := PGtkWindow(Gtk_window_new(Gtk_WINDOW_TOPLEVEL));
Gtk_window_set_title(win, clickme);
button := PGtkButton(Gtk_button_new_with_label(clickme));
Mylabel := PGtkLabel(Gtk_label_new('There have been no clicks yet'));
Gtk_label_set_single_line_mode(Mylabel, TRUE);
vbox := PGtkVBox(Gtk_vbox_new(TRUE, 1));
Gtk_container_add(Gtk_CONTAINER(vbox), Gtk_WIDGET(Mylabel));
Gtk_container_add(Gtk_CONTAINER(vbox), Gtk_WIDGET(button));
Gtk_container_add(Gtk_CONTAINER(win), Gtk_WIDGET(vbox));
g_signal_connect(G_OBJECT(win), 'delete-event', TGCallBack(@Gtk_main_quit), NULL);
g_signal_connect(G_OBJECT(button), 'clicked', TGCallBack(@clickedme), Mylabel);
Gtk_widget_show_all(Gtk_WIDGET(win));
Gtk_main();
end. |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #Action.21 | Action! | PROC Main()
BYTE x,y,size=[16]
Graphics(0)
PutE() PutE()
y=size-1
DO
FOR x=1 TO y+2
DO Put(' ) OD
FOR x=0 TO size-y-1
DO
IF (x&y)=0 THEN
Print("* ")
ELSE
Print(" ")
FI
OD
PutE()
IF y=0 THEN
EXIT
FI
y==-1
OD |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #8086_Assembly | 8086 Assembly | ;;; Display a Sierpinski triangle on a CGA screen
;;; (order 7 is the maximum that fits in 200 lines)
mode: equ 0Fh ; INT 10H call to get current video mode
puts: equ 9h ; MS-DOS call to print string
cgaseg: equ 0B800h ; Location of CGA video memory
cpu 8086
bits 16
org 100h
section .text
cmp [80h],byte 2 ; Argument length should be 2 (space + digit)
jne eusage
mov al,[82h] ; Get digit
sub al,'0'+2 ; 2->0, 7->5
cmp al,5 ; Then it must be <=5
jbe argok
eusage: mov dx,usage ; Print usage string
estop: mov ah,puts
int 21h
ret ; And stop
argok: add al,2 ; Add 2, setting AL to the order
mov [order],al ; Store the order
mov ah,mode ; Get the current video mode
int 10h
cmp al,7 ; If MDA, we don't have graphics support
mov dx,errcga
je estop
mov [vmode],al ; Otherwise, store the old mode
mov ax,4 ; and switch to mode 4 (320x200 graphics)
int 10h
mov ch,1 ; Size = 2^order
mov cl,[order]
shl ch,cl
xor dh,dh ; Start at coords (0,0)
mov bp,cgaseg ; Point ES at the CGA memory
mkscr: mov es,bp
xor di,di ; Start at the beginning
mkline: xor dl,dl ; Start at coords (0,Y)
mkbyte: xor al,al ; A byte has 4 pixels in it
mov cl,4
mkpx: shl al,1 ; Make room for next pixel
shl al,1
test dl,dh ; X & Y == 0?
jnz nextpx
or al,3 ; X & Y == 0, set pixel on
nextpx: inc dl ; Increment X coordinate
dec cl ; More pixels in this byte?
jnz mkpx ; If so, add them in
stosb ; Otherwise, write it out to CGA memory
cmp dl,ch ; And if the line is not done yet,
jb mkbyte ; do the next byte on this line.
shr dl,1 ; Move ahead to start of next line
shr dl,1
mov ax,80 ; 80 bytes per line
sub al,dl
add di,ax
add dh,2 ; Memory is interlaced so we're 2 lines further
cmp dh,ch ; If we're not done yet,
jb mkline ; Do the next line.
add bp,200h ; Move ahead 8k to the area for the odd lines
cmp bp,0BA00h ; Unless we were already there
mov dh,1 ; We'll have to start at line 1
jbe mkscr
xor ah,ah ; Wait for a keypress to get back to DOS
int 16h
xor ah,ah ; Then, restore the old video mode,
mov al,[vmode]
int 10h
ret ; And exit to DOS
section .data
usage: db 'SIERPCGA [2..7] - display Sierpinski triangle of order N$'
errcga: db 'Need at least CGA.$'
section .bss
order: resb 1 ; Order of Sierpinski triangle
vmode: resb 1 ; Store old video mode (to restore later) |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #Processing | Processing | final PVector t = new PVector(20, 30, 60);
void setup() {
size(450, 400);
noLoop();
background(0, 0, 200);
stroke(-1);
sc(7, 400, -60, t);
}
PVector sc(int o, float l, final int a, final PVector s) {
if (o > 0) {
sc(--o, l *= .5, -a, s).z += a;
sc(o, l, a, s).z += a;
sc(o, l, -a, s);
} else line(s.x, s.y,
s.x += cos(radians(s.z)) * l,
s.y += sin(radians(s.z)) * l);
return s;
} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Red | Red |
str-time: to integer! ask "Enter wait time " ;get user input , convert to integer
print "waiting"
wait str-time ;Seconds
print "awake" |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Retro | Retro | : sleep ( n- )
[ time [ time over - 1 > ] until drop ] times ;
: test
"\nTime to sleep (in seconds): " puts getToken toNumber
"\nSleeping..." sleep
"\nAwake!\n" ; |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Perl | Perl | use Tk;
$main = MainWindow->new;
$l = $main->Label('-text' => 'There have been no clicks yet.')->pack;
$count = 0;
$main->Button(
-text => ' Click Me ',
-command => sub { $l->configure(-text => 'Number of clicks: '.(++$count).'.'); },
)->pack;
MainLoop(); |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #Ada | Ada | with Ada.Text_Io; use Ada.Text_Io;
with Ada.Strings.Fixed;
with Interfaces; use Interfaces;
procedure Sieteri_Triangles is
subtype Practical_Order is Unsigned_32 range 0..4;
function Pow(X : Unsigned_32; N : Unsigned_32) return Unsigned_32 is
begin
if N = 0 then
return 1;
else
return X * Pow(X, N - 1);
end if;
end Pow;
procedure Print(Item : Unsigned_32) is
use Ada.Strings.Fixed;
package Ord_Io is new Ada.Text_Io.Modular_Io(Unsigned_32);
use Ord_Io;
Temp : String(1..36) := (others => ' ');
First : Positive;
Last : Positive;
begin
Put(To => Temp, Item => Item, Base => 2);
First := Index(Temp, "#") + 1;
Last := Index(Temp(First..Temp'Last), "#") - 1;
for I in reverse First..Last loop
if Temp(I) = '0' then
Put(' ');
else
Put(Temp(I));
end if;
end loop;
New_Line;
end Print;
procedure Sierpinski (N : Practical_Order) is
Size : Unsigned_32 := Pow(2, N);
V : Unsigned_32 := Pow(2, Size);
begin
for I in 0..Size - 1 loop
Print(V);
V := Shift_Left(V, 1) xor Shift_Right(V,1);
end loop;
end Sierpinski;
begin
for N in Practical_Order loop
Sierpinski(N);
end loop;
end Sieteri_Triangles; |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Action.21 | Action! | PROC Draw(INT x0 BYTE y0,depth)
BYTE i,x,y,size
size=1 LSH depth
FOR y=0 TO size-1
DO
FOR x=0 TO size-1
DO
IF (x&y)=0 THEN
Plot(x0+x,y0+y)
FI
OD
OD
RETURN
PROC Main()
BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6
Graphics(8+16)
Color=1
COLOR1=$0C
COLOR2=$02
Draw(96,32,7)
DO UNTIL CH#$FF OD
CH=$FF
RETURN |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #ActionScript | ActionScript |
package {
import flash.display.GraphicsPathCommand;
import flash.display.Sprite;
/**
* A Sierpinski triangle.
*/
public class SierpinskiTriangle extends Sprite {
/**
* Creates a new SierpinskiTriangle object.
*
* @param n The order of the Sierpinski triangle.
* @param c1 The background colour.
* @param c2 The foreground colour.
* @param width The width of the triangle.
* @param height The height of the triangle.
*/
public function SierpinskiTriangle(n:uint, c1:uint, c2:uint, width:Number, height:Number):void {
_init(n, c1, c2, width, height);
}
/**
* Generates the triangle.
*
* @param n The order of the Sierpinski triangle.
* @param c1 The background colour.
* @param c2 The foreground colour.
* @param width The width of the triangle.
* @param height The height of the triangle.
* @private
*/
private function _init(n:uint, c1:uint, c2:uint, width:Number, height:Number):void {
if ( n <= 0 )
return;
// Draw the outer triangle.
graphics.beginFill(c1);
graphics.moveTo(width / 2, 0);
graphics.lineTo(0, height);
graphics.lineTo(width, height);
graphics.lineTo(width / 2, 0);
// Draw the inner triangle.
graphics.beginFill(c2);
graphics.moveTo(width / 4, height / 2);
graphics.lineTo(width * 3 / 4, height / 2);
graphics.lineTo(width / 2, height);
graphics.lineTo(width / 4, height / 2);
if ( n == 1 )
return;
// Recursively generate three Sierpinski triangles of half the size and order n - 1 and position them appropriately.
var sub1:SierpinskiTriangle = new SierpinskiTriangle(n - 1, c1, c2, width / 2, height / 2);
var sub2:SierpinskiTriangle = new SierpinskiTriangle(n - 1, c1, c2, width / 2, height / 2);
var sub3:SierpinskiTriangle = new SierpinskiTriangle(n - 1, c1, c2, width / 2, height / 2);
sub1.x = width / 4;
sub1.y = 0;
sub2.x = 0;
sub2.y = height / 2;
sub3.x = width / 2;
sub3.y = height / 2;
addChild(sub1);
addChild(sub2);
addChild(sub3);
}
}
}
|
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #Python | Python |
import matplotlib.pyplot as plt
import math
def nextPoint(x, y, angle):
a = math.pi * angle / 180
x2 = (int)(round(x + (1 * math.cos(a))))
y2 = (int)(round(y + (1 * math.sin(a))))
return x2, y2
def expand(axiom, rules, level):
for l in range(0, level):
a2 = ""
for c in axiom:
if c in rules:
a2 += rules[c]
else:
a2 += c
axiom = a2
return axiom
def draw_lsystem(axiom, rules, angle, iterations):
xp = [1]
yp = [1]
direction = 0
for c in expand(axiom, rules, iterations):
if c == "F":
xn, yn = nextPoint(xp[-1], yp[-1], direction)
xp.append(xn)
yp.append(yn)
elif c == "-":
direction = direction - angle
if direction < 0:
direction = 360 + direction
elif c == "+":
direction = (direction + angle) % 360
plt.plot(xp, yp)
plt.show()
if __name__ == '__main__':
# Sierpinski Arrowhead Curve L-System Definition
s_axiom = "XF"
s_rules = {"X": "YF+XF+Y",
"Y": "XF-YF-X"}
s_angle = 60
draw_lsystem(s_axiom, s_rules, s_angle, 7)
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #REXX | REXX | /*REXX program sleeps X seconds (the number of seconds is supplied via the argument).*/
parse arg secs . /*obtain optional argument from the CL.*/
if secs=='' | secs=="," then secs=0 /*Not specified? Then assume 0 (zero).*/
say 'Sleeping' secs "seconds." /*inform the invoker what's happening. */
call delay secs /*Snooze. Hopefully, just a short nap.*/
say 'Awake!' /*and now inform invoker we're running.*/
/*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Ring | Ring |
load "guilib.ring"
for n = 1 to 10
Sleep(3)
see "" + n + " "
next
see nl
func Sleep x
nTime = x * 1000
oTest = new qTest
oTest.qsleep(nTime)
|
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Phix | Phix | -- demo\rosetta\Simple_window.exw
with javascript_semantics
include pGUI.e
Ihandle dlg, lbl, btn, vbox
integer clicks = 0
function click_cb(Ihandle /*btn*/)
clicks += 1
IupSetStrAttribute(lbl,"TITLE","clicked %d times",{clicks})
return IUP_DEFAULT;
end function
IupOpen()
lbl = IupLabel("There have been no clicks yet")
btn = IupButton("Click me", Icallback("click_cb"))
vbox = IupVbox({lbl, IupHbox({IupFill(),btn,IupFill()})})
dlg = IupDialog(vbox,"MARGIN=10x10, GAP=10, RASTERSIZE=400x0")
IupSetAttribute(dlg, "TITLE", "Simple windowed application")
IupShow(dlg)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
|
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #ALGOL_68 | ALGOL 68 | PROC sierpinski = (INT n)[]STRING: (
FLEX[0]STRING d := "*";
FOR i TO n DO
[UPB d * 2]STRING next;
STRING sp := " " * (2 ** (i-1));
FOR x TO UPB d DO
STRING dx = d[x];
next[x] := sp+dx+sp;
next[UPB d+x] := dx+" "+dx
OD;
d := next
OD;
d
);
printf(($gl$,sierpinski(4))) |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #Asymptote | Asymptote | path subtriangle(path p, real node) {
return
point(p, node) --
point(p, node + 1/2) --
point(p, node - 1/2) --
cycle;
}
void sierpinski(path p, int order) {
if (order == 0)
fill(p);
else {
sierpinski(subtriangle(p, 0), order - 1);
sierpinski(subtriangle(p, 1), order - 1);
sierpinski(subtriangle(p, 2), order - 1);
}
}
sierpinski((0, 0) -- (5 inch, 1 inch) -- (2 inch, 6 inch) -- cycle, 10); |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #Prolog | Prolog | main:-
write_sierpinski_arrowhead('sierpinski_arrowhead.svg', 600, 8).
write_sierpinski_arrowhead(File, Size, Order):-
open(File, write, Stream),
format(Stream,
"<svg xmlns='http://www.w3.org/2000/svg' width='~d' height='~d'>\n",
[Size, Size]),
write(Stream, "<rect width='100%' height='100%' fill='white'/>\n"),
write(Stream, "<path stroke-width='1' stroke='black' fill='none' d='"),
Margin = 20.0,
Side is Size - 2.0 * Margin,
X = Margin,
Y is 0.5 * Size + 0.25 * sqrt(3) * Side,
Cursor = cursor(X, Y, 0),
(Order mod 2 == 1 -> turn(Cursor, -60, Cursor1) ; Cursor1 = Cursor),
format(Stream, "M~g,~g", [X, Y]),
curve(Stream, Order, Side, Cursor1, _, 60),
write(Stream, "'/>\n</svg>\n"),
close(Stream).
turn(cursor(X, Y, A), Angle, cursor(X, Y, A1)):-
A1 is (A + Angle) mod 360.
draw_line(Stream, cursor(X, Y, A), Length, cursor(X1, Y1, A)):-
Theta is (pi * A)/180.0,
X1 is X + Length * cos(Theta),
Y1 is Y + Length * sin(Theta),
format(Stream, "L~g,~g", [X1, Y1]).
curve(Stream, 0, Length, Cursor, Cursor1, _):-
!,
draw_line(Stream, Cursor, Length, Cursor1).
curve(Stream, Order, Length, Cursor, Cursor1, Angle):-
Order1 is Order - 1,
Angle1 is -Angle,
Length2 is Length/2.0,
curve(Stream, Order1, Length2, Cursor, Cursor2, Angle1),
turn(Cursor2, Angle, Cursor3),
curve(Stream, Order1, Length2, Cursor3, Cursor4, Angle),
turn(Cursor4, Angle, Cursor5),
curve(Stream, Order1, Length2, Cursor5, Cursor1, Angle1). |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Ruby | Ruby | seconds = gets.to_f
puts "Sleeping..."
sleep(seconds) # number is in seconds ... but accepts fractions
# Minimum resolution is system dependent.
puts "Awake!" |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Rust | Rust | use std::{io, time, thread};
fn main() {
println!("How long should we sleep in milliseconds?");
let mut sleep_string = String::new();
io::stdin().read_line(&mut sleep_string)
.expect("Failed to read line");
let sleep_timer: u64 = sleep_string.trim()
.parse()
.expect("Not an integer");
let sleep_duration = time::Duration::from_millis(sleep_timer);
println!("Sleeping...");
thread::sleep(sleep_duration);
println!("Awake!");
} |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #PicoLisp | PicoLisp | #!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(load "@ext.l" "@lib/http.l" "@lib/xhtml.l" "@lib/form.l")
(zero *Count)
(de start ()
(app)
(action
(html 0 "Clicks" NIL NIL
(form NIL
(gui '(+Init +TextField) "There have been no clicks yet")
(----)
(gui '(+JS +Button) "click me"
'(set> (field -1)
(pack "Clicked " (inc '*Count) " times") ) ) ) ) ) )
(server 8080 "!start")
(wait) |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Pike | Pike | GTK2.Widget mainwindow,clickcnt,clicker;
int clicks;
void click()
{
clickcnt->set_text("Clicks: "+(++clicks));
}
int main()
{
GTK2.setup_gtk();
mainwindow=GTK2.Window(GTK2.WindowToplevel);
mainwindow->set_title("Click counter");
mainwindow->add(GTK2.Vbox(0,10)
->add(clickcnt=GTK2.Label("There have been no clicks yet"))
->add(clicker=GTK2.Button("Click me"))
)->show_all();
mainwindow->signal_connect("delete_event",lambda() {exit(0);});
clicker->signal_connect("clicked",click);
return -1;
}
|
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #ALGOL_W | ALGOL W | begin
integer SIZE;
SIZE := 16;
for y := SIZE - 1 step - 1 until 0 do begin
integer x;
for i := 0 until y - 1 do writeon( " " );
x := 0;
while x + y < SIZE do begin
writeon( if number( bitstring( x ) and bitstring( y ) ) not = 0 then " " else "* " );
x := x + 1
end while_x_plus_y_lt_SIZE ;
write();
end for_y
end. |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #ATS | ATS | // patscc -O2 -flto -D_GNU_SOURCE -DATS_MEMALLOC_LIBC sierpinski.dats -o sierpinski -latslib -lSDL2
#include "share/atspre_staload.hats"
typedef point = (int, int)
extern fun midpoint(A: point, B: point): point = "mac#"
extern fun sierpinski_draw(n: int, A: point, B: point, C: point): void = "mac#"
extern fun triangle_remove(A: point, B: point, C: point): void = "mac#"
extern fun sdl_drawline(x1: int, y1: int, x2: int, y2: int): void = "ext#sdl_drawline"
extern fun line(A: point, B: point): void
extern fun ats_tredraw(): void = "mac#ats_tredraw"
implement midpoint(A, B) = (xmid, ymid) where {
val xmid = (A.0 + B.0) / 2
val ymid = (A.1 + B.1) / 2
}
implement triangle_remove(A, B, C) = (
line(A, B);
line(B, C);
line(C, A);
)
implement sierpinski_draw(n, A, B, C) =
if n > 0 then
let
val AB = midpoint(A, B)
val BC = midpoint(B, C)
val CA = midpoint(C, A)
in
triangle_remove(AB, BC, CA);
sierpinski_draw(n-1, A, AB, CA);
sierpinski_draw(n-1, B, BC, AB);
sierpinski_draw(n-1, C, CA, BC);
end
implement line(A, B) = sdl_drawline(A.0, A.1, B.0, B.1)
extern fun SDL_Init(): void = "ext#sdl_init"
extern fun SDL_Quit(): void = "ext#sdl_quit"
extern fun SDL_Loop(): void = "ext#sdl_loop"
implement ats_tredraw() = sierpinski_draw(7, (320, 0), (0, 480), (640, 480))
implement main0() = (
SDL_Init();
SDL_Loop();
SDL_Quit();
)
%{
#include <SDL2/SDL.h>
#include <unistd.h>
extern void ats_tredraw();
SDL_Window *sdlwin;
SDL_Renderer *sdlren;
void sdl_init() {
if (SDL_Init(SDL_INIT_VIDEO)) {
exit(1);
}
if ((sdlwin = SDL_CreateWindow("sierpinski triangles", 100, 100, 640, 480, SDL_WINDOW_SHOWN)) == NULL) {
SDL_Quit();
exit(2);
}
if ((sdlren = SDL_CreateRenderer(sdlwin, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC)) == NULL) {
SDL_DestroyWindow(sdlwin);
SDL_Quit();
exit(3);
}
}
void sdl_clear() {
SDL_SetRenderDrawColor(sdlren, 0, 0, 0, SDL_ALPHA_OPAQUE);
SDL_RenderClear(sdlren);
SDL_SetRenderDrawColor(sdlren, 255, 255, 255, SDL_ALPHA_OPAQUE);
}
void sdl_loop() {
SDL_Event event;
while (1) {
sdl_clear();
ats_tredraw();
SDL_RenderPresent(sdlren);
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
return;
}
}
}
}
void sdl_quit() {
SDL_DestroyRenderer(sdlren);
SDL_DestroyWindow(sdlwin);
SDL_Quit();
}
void sdl_drawline(int x1, int y1, int x2, int y2) {
SDL_RenderDrawLine(sdlren, x1, y1, x2, y2);
}
%} |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #AutoHotkey | AutoHotkey | #NoEnv
#SingleInstance, Force
SetBatchLines, -1
; Parameters
Width := 512, Height := Width/2*3**0.5, n := 8 ; iterations = 8
; Uncomment if Gdip.ahk is not in your standard library
#Include ..\lib\Gdip.ahkl
If !pToken := Gdip_Startup() ; Start gdi+
{
MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system
ExitApp
}
; I've added a simple new function here, just to ensure if anyone is having any problems then to make sure they are using the correct library version
if (Gdip_LibraryVersion() < 1.30)
{
MsgBox, 48, Version error!, Please download the latest version of the gdi+ library
ExitApp
}
OnExit, Exit
; Create a layered window (+E0x80000 : must be used for UpdateLayeredWindow to work!) that is always on top (+AlwaysOnTop), has no taskbar entry or caption
Gui, -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop
Gui, Show
hwnd1 := WinExist()
OnMessage(0x201, "WM_LBUTTONDOWN")
, hbm := CreateDIBSection(Width, Height)
, hdc := CreateCompatibleDC()
, obm := SelectObject(hdc, hbm)
, G := Gdip_GraphicsFromHDC(hdc)
, Gdip_SetSmoothingMode(G, 4)
; Sierpinski triangle by subtracting triangles
, pBrushBlack := Gdip_BrushCreateSolid(0xff000000)
, rectangle := 0 "," 0 "|" 0 "," Height "|" Width "," Height "|" Width "," 0
, Gdip_FillPolygon(G, pBrushBlack, rectangle, FillMode=0)
, pBrushBlue := Gdip_BrushCreateSolid(0xff0000ff)
, triangle := Width/2 "," 0 "|" 0 "," Height "|" Width "," Height
, Gdip_FillPolygon(G, pBrushBlue, triangle, FillMode=0)
, Gdip_DeleteBrush(pBrushBlue)
, UpdateLayeredWindow(hwnd1, hdc, (A_ScreenWidth-Width)/2, (A_ScreenHeight-Height)/2, Width, Height)
, k:=2, x:=0, y:=0, i:=1
Loop, % n
{
Sleep 0.5*1000
While x*y<Width*Height
{
triangle := x "," y "|" x+Width/2/k "," y+Height/k "|" x+Width/k "," y
, Gdip_FillPolygon(G, pBrushBlack, triangle, FillMode=0)
, x += Width/k
, (x >= Width) ? (x := i*Width/2/k, y += Height/k, i:=!i) : ""
}
UpdateLayeredWindow(hwnd1, hdc, (A_ScreenWidth-Width)/2, (A_ScreenHeight-Height)/2, Width, Height)
, k*=2, x:=0, y:=0, i:=1
}
Gdip_DeleteBrush(pBrushBlack)
, UpdateLayeredWindow(hwnd1, hdc, (A_ScreenWidth-Width)/2, (A_ScreenHeight-Height)/2, Width, Height)
Sleep, 1*1000
; Bonus: Sierpinski triangle by random dots
Gdip_GraphicsClear(G, 0xff000000)
, pBrushBlue := Gdip_BrushCreateSolid(0xff0000ff)
, x1:=Width/2, y1:=0, x2:=0, y2:=Height, x3:=Width, y3:=Height
, x:= Width/2, y:=Height/2 ; I'm to lazy to pick a random point.
Loop, % n
{
Loop, % 10*10**(A_Index/2)
{
Random, rand, 1, 3
x := abs(x+x%rand%)/2
, y := abs(y+y%rand%)/2
, Gdip_FillEllipse(G, pBrushBlue, x, y, 1, 1)
}
UpdateLayeredWindow(hwnd1, hdc, (A_ScreenWidth-Width)/2, (A_ScreenHeight-Height)/2, Width, Height)
Sleep, 0.5*1000
}
SelectObject(hdc, obm)
, DeleteObject(hbm)
, DeleteDC(hdc)
, Gdip_DeleteGraphics(G)
Return
Exit:
Gdip_Shutdown(pToken)
ExitApp
WM_LBUTTONDOWN()
{
If (A_Gui = 1)
PostMessage, 0xA1, 2
} |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #Quackery | Quackery | [ $ "turtleduck.qky" loadfile ] now!
[ stack ] is switch.arg ( --> [ )
[ switch.arg put ] is switch ( x --> )
[ switch.arg release ] is otherwise ( --> )
[ switch.arg share
!= iff ]else[ done
otherwise ]'[ do ]done[ ] is case ( x --> )
[ $ "" swap witheach
[ nested quackery join ] ] is expand ( $ --> $ )
[ $ "L" ] is L ( $ --> $ )
[ $ "R" ] is R ( $ --> $ )
[ $ "BLALB" ] is A ( $ --> $ )
[ $ "ARBRA" ] is B ( $ --> $ )
$ "A"
6 times expand
turtle
witheach
[ switch
[ char L case [ -1 6 turn ]
char R case [ 1 6 turn ]
otherwise [ 4 1 walk ] ] ] |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #Raku | Raku | use SVG;
role Lindenmayer {
has %.rules;
method succ {
self.comb.map( { %!rules{$^c} // $c } ).join but Lindenmayer(%!rules)
}
}
my $arrow = 'X' but Lindenmayer( { X => 'YF+XF+Y', Y => 'XF-YF-X' } );
$arrow++ xx 7;
my $w = 800;
my $h = ($w * 3**.5 / 2).round(1);
my $scale = 6;
my @points = (400, 15);
my $dir = pi/3;
for $arrow.comb {
state ($x, $y) = @points[0,1];
state $d = $dir;
when 'F' { @points.append: ($x += $scale * $d.cos).round(1), ($y += $scale * $d.sin).round(1) }
when '+' { $d += $dir }
when '-' { $d -= $dir }
default { }
}
my $out = './sierpinski-arrowhead-curve-perl6.svg'.IO;
$out.spurt: SVG.serialize(
svg => [
:width($w), :height($h),
:rect[:width<100%>, :height<100%>, :fill<black>],
:polyline[ :points(@points.join: ','), :fill<black>, :style<stroke:#FF4EA9> ],
],
); |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Scala | Scala | object Sleeper extends App {
print("Enter sleep time in milli sec: ")
val ms = scala.io.StdIn.readInt()
println("Sleeping...")
val sleepStarted = scala.compat.Platform.currentTime
Thread.sleep(ms)
println(s"Awaked after [${scala.compat.Platform.currentTime - sleepStarted} ms]1")
} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Scheme | Scheme |
(use format)
(use srfi-18)
(format #t "Enter a time (in seconds): ")
(let ((time (read))) ; converts input to a number, if possible
(if (number? time)
(begin
(format #t "Sleeping...~&")
(thread-sleep! time)
(format #t "Awake!~&"))
(format #t "You must enter a number~&")))
|
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #PowerShell | PowerShell |
$Label1 = [System.Windows.Forms.Label]@{
Text = 'There have been no clicks yet'
Size = '200, 20' }
$Button1 = [System.Windows.Forms.Button]@{
Text = 'Click me'
Location = '0, 20' }
$Button1.Add_Click(
{
$Script:Clicks++
If ( $Clicks -eq 1 ) { $Label1.Text = "There has been 1 click" }
Else { $Label1.Text = "There have been $Clicks clicks" }
} )
$Form1 = New-Object System.Windows.Forms.Form
$Form1.Controls.AddRange( @( $Label1, $Button1 ) )
$Clicks = 0
$Result = $Form1.ShowDialog()
|
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
Related tasks
Sierpinski triangle/Graphical for graphics images of this pattern.
Sierpinski carpet
| #AppleScript | AppleScript | ------------------- SIERPINKSI TRIANGLE ------------------
-- sierpinski :: Int -> [String]
on sierpinski(n)
if n > 0 then
set previous to sierpinski(n - 1)
set padding to replicate(2 ^ (n - 1), space)
script alignedCentre
on |λ|(s)
concat(padding & s & padding)
end |λ|
end script
script adjacentDuplicates
on |λ|(s)
unwords(replicate(2, s))
end |λ|
end script
-- Previous triangle block centered,
-- and placed on 2 adjacent duplicates.
map(alignedCentre, previous) & map(adjacentDuplicates, previous)
else
{"*"}
end if
end sierpinski
--------------------------- TEST -------------------------
on run
unlines(sierpinski(4))
end run
-------------------- GENERIC FUNCTIONS -------------------
-- concat :: [[a]] -> [a] | [String] -> String
on concat(xs)
if length of xs > 0 and class of (item 1 of xs) is string then
set acc to ""
else
set acc to {}
end if
repeat with i from 1 to length of xs
set acc to acc & item i of xs
end repeat
acc
end concat
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if n < 1 then return out
set dbl to {a}
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
-- unlines, unwords :: [String] -> String
on unlines(xs)
intercalate(linefeed, xs)
end unlines
on unwords(xs)
intercalate(space, xs)
end unwords |
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #BASIC | BASIC |
SCREEN 9
H=.5
P=300
FOR I=1 TO 9^6
N=RND
IF N > 2/3 THEN
X=H+X*H:Y=Y*H
ELSEIF N > 1/3 THEN
X=H^2+X*H:Y=H+Y*H
ELSE
X=X*H:Y=Y*H
END IF
PSET(P-X*P,P-Y*P)
NEXT
|
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical | Sierpinski triangle/Graphical | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
long long x, y, dx, dy, scale, clen, cscale;
typedef struct { double r, g, b; } rgb;
rgb ** pix;
void sc_up()
{
scale *= 2; x *= 2; y *= 2;
cscale *= 3;
}
void h_rgb(long long x, long long y)
{
rgb *p = &pix[y][x];
# define SAT 1
double h = 6.0 * clen / cscale;
double VAL = 1;
double c = SAT * VAL;
double X = c * (1 - fabs(fmod(h, 2) - 1));
switch((int)h) {
case 0: p->r += c; p->g += X; return;
case 1: p->r += X; p->g += c; return;
case 2: p->g += c; p->b += X; return;
case 3: p->g += X; p->b += c; return;
case 4: p->r += X; p->b += c; return;
default:
p->r += c; p->b += X;
}
}
void iter_string(const char * str, int d)
{
long long len;
while (*str != '\0') {
switch(*(str++)) {
case 'X':
if (d) iter_string("XHXVX", d - 1);
else{
clen ++;
h_rgb(x/scale, y/scale);
x += dx;
y -= dy;
}
continue;
case 'V':
len = 1LLU << d;
while (len--) {
clen ++;
h_rgb(x/scale, y/scale);
y += dy;
}
continue;
case 'H':
len = 1LLU << d;
while(len --) {
clen ++;
h_rgb(x/scale, y/scale);
x -= dx;
}
continue;
}
}
}
void sierp(long leng, int depth)
{
long i;
long h = leng + 20, w = leng + 20;
/* allocate pixel buffer */
rgb *buf = malloc(sizeof(rgb) * w * h);
pix = malloc(sizeof(rgb *) * h);
for (i = 0; i < h; i++)
pix[i] = buf + w * i;
memset(buf, 0, sizeof(rgb) * w * h);
/* init coords; scale up to desired; exec string */
x = y = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3;
for (i = 0; i < depth; i++) sc_up();
iter_string("VXH", depth);
/* write color PNM file */
unsigned char *fpix = malloc(w * h * 3);
double maxv = 0, *dbuf = (double*)buf;
for (i = 3 * w * h - 1; i >= 0; i--)
if (dbuf[i] > maxv) maxv = dbuf[i];
for (i = 3 * h * w - 1; i >= 0; i--)
fpix[i] = 255 * dbuf[i] / maxv;
printf("P6\n%ld %ld\n255\n", w, h);
fflush(stdout); /* printf and fwrite may treat buffer differently */
fwrite(fpix, h * w * 3, 1, stdout);
}
int main(int c, char ** v)
{
int size, depth;
depth = (c > 1) ? atoi(v[1]) : 10;
size = 1 << depth;
fprintf(stderr, "size: %d depth: %d\n", size, depth);
sierp(size, depth + 2);
return 0;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.