import "io" for File
import "/pattern" for Pattern
import "/fmt" for Fmt

var yesNo = Fn.new { |b| (b) ? "yes" : "no" }

var plausRatio = 2

var count1 = 0  // [^c]ie
var count2 = 0  // [^c]ei
var count3 = 0  // cie
var count4 = 0  // cei
var count5 = 0  // ^ie
var count6 = 0  // ^ei

var p1 = Pattern.new("^cie")
var p2 = Pattern.new("^cei")

var words = File.read("unixdict.txt").split("\n").map { |w| w.trim() }.where { |w| w != "" }
System.print("The following words fall into more than one category")
System.print("and so are counted more than once:")
for (word in words) {
    var tc1 = count1 + count2 + count3 + count4 + count5 + count6
    if (p1.isMatch(word)) count1 = count1 + 1
    if (p2.isMatch(word)) count2 = count2 + 1
    if (word.contains("cie")) count3 = count3 + 1
    if (word.contains("cei")) count4 = count4 + 1
    if (word.startsWith("ie")) count5 = count5 + 1
    if (word.startsWith("ei")) count6 = count6 + 1
    var tc2 = count1 + count2 + count3 + count4 + count5 + count6
    if ((tc2 -tc1) > 1) System.print("  " + word)
}

System.print("\nChecking plausability of \"i before e except after c\":")
var nFor  = count1 + count5
var nAgst = count2 + count6
var ratio = nFor / nAgst
var plaus = (ratio > plausRatio)
Fmt.print("  Cases for      : $d", nFor)
Fmt.print("  Cases against  : $d", nAgst)
Fmt.print("  Ratio for/agst : $4.2f", ratio)
Fmt.print("  Plausible      : $s", yesNo.call(plaus))

System.print("\nChecking plausability of \"e before i when preceded by c\":")
var ratio2 = count4 / count3
var plaus2 = (ratio2 > plausRatio)
Fmt.print("  Cases for      : $d", count4)
Fmt.print("  Cases against  : $d", count3)
Fmt.print("  Ratio for/agst : $4.2f", ratio2)
Fmt.print("  Plausible      : $s", yesNo.call(plaus2))

Fmt.print("\nPlausible overall: $s", yesNo.call(plaus && plaus2))


open "unixdict.txt" for reading as #1

repeat
    line input #1 pal$
    if instr(pal$, "ie") then
		if instr(pal$, "cie") then CI = CI + 1 else XI = XI + 1 : fi
	endif
    if instr(pal$, "ei") then
		if instr(pal$, "cei") then CE = CE + 1 else XE = XE + 1 : fi
	endif
until eof(1)
close #1

print "CIE: ", CI
print "xIE: ", XI
print "CEI: ", CE
print "xEI: ", XE
print "\nI before E when not preceded by C: ";
if 2 * XI <= CI then print "not "; : fi
print "plausible."
print "E before I when preceded by C: ";
if 2 * CE <= XE then print "not "; : fi
print "plausible."
end


fcn wcnt(wordList,altrs,aAdjust,bltrs,bAdjust,text){
   a:=wordList.reduce('wrap(cnt,word){ cnt+word.holds(altrs) },0) - aAdjust;
   b:=wordList.reduce('wrap(cnt,word){ cnt+word.holds(bltrs) },0) - bAdjust;
   ratio:=a.toFloat()/b;
   "%s is %splausible".fmt(text,ratio<2 and "im" or "").println();
   "  %d cases for and %d cases against is a ratio of %.3f.".fmt(a,b,ratio).println();
   return(a,b,ratio);
}
wordList:=File("unixdict.txt").read();


with AWS.Client;
with AWS.Response;
with Ada.Text_IO; use Ada.Text_IO;
procedure GetHttps is
begin
   Put_Line (AWS.Response.Message_Body (AWS.Client.Get (
      URL => "https://sourceforge.net/")));
end GetHttps;


URL      := "https://sourceforge.net/"
WININET_Init()
msgbox % html := UrlGetContents(URL)
WININET_UnInit()
return
#include urlgetcontents.ahk
#include wininet.ahk


OPTION TLS TRUE
website$ = "www.google.com"

OPEN website$ & ":443" FOR NETWORK AS mynet

SEND "GET / HTTP/1.1\r\nHost: " & website$ & "\r\n\r\n" TO mynet
WHILE WAIT(mynet, 1000)
    RECEIVE dat$ FROM mynet
    total$ = total$ & dat$
    IF REGEX(dat$, "\r\n\r\n$") THEN BREAK           : ' Quit receiving data when end indicator was reached
WEND

CLOSE NETWORK mynet

PRINT REPLACE$(total$, "\r\n[0-9a-fA-F]+\r\n", "\r\n", TRUE) : ' Remove chunk indicators from HTML data


:: Must have curl.exe
curl.exe -k -s -L https://sourceforge.net/


#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
CURL *curl;
char buffer[CURL_ERROR_SIZE];
int main(void) {
    if ((curl = curl_easy_init()) != NULL) {
        curl_easy_setopt(curl, CURLOPT_URL, "https://sourceforge.net/");
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, buffer);
        if (curl_easy_perform(curl) != CURLE_OK) {
            fprintf(stderr, "%s\n", buffer);
            return EXIT_FAILURE;
        }
        curl_easy_cleanup(curl);
    }
    return EXIT_SUCCESS;
}


using System;
using System.Net;

class Program
{
    static void Main(string[] args)
    {
        var client = new WebClient();
        var data = client.DownloadString("https://www.google.com");

        Console.WriteLine(data);
    }
}


(use '[clojure.contrib.duck-streams :only (slurp*)])
(print (slurp* "https://sourceforge.net"))


auto data = get("https://sourceforge.net");
writeln(data);


(defun wget-drakma-string (url &optional (out *standard-output*))
  "Grab the body as a string, and write it to out."
  (write-string (drakma:http-request url) out))

(defun wget-drakma-stream (url &optional (out *standard-output*))
  "Grab the body as a stream, and write it to out."
  (loop with body = (drakma:http-request url :want-stream t)
        for line = (read-line body nil nil)
        while line do (write-line line)
        finally (close body)))

;; Use
(wget-drakma-stream "https://sourceforge.net")


program ShowHTTPS;

{$APPTYPE CONSOLE}

uses IdHttp, IdSSLOpenSSL;

var
  s: string;
  lHTTP: TIdHTTP;
begin
  lHTTP := TIdHTTP.Create(nil);
  try
    lHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(lHTTP);
    lHTTP.HandleRedirects := True;
    s := lHTTP.Get('https://sourceforge.net/');
    Writeln(s);
  finally
    lHTTP.Free;
  end;
end.


;; asynchronous call back definition
(define (success name text) (writeln 'Loaded name) (writeln text))
;;
(file->string success "https:/sourceforge.net")


-module(main).
-export([main/1]).

main([Url|[]]) ->
   inets:start(),
   ssl:start(),
   case http:request(get, {URL, []}, [{ssl,[{verify,0}]}], []) of
       {ok, {_V, _H, Body}} -> io:fwrite("~p~n",[Body]);
       {error, Res} -> io:fwrite("~p~n", [Res])
   end.


#light
let wget (url : string) =
    let c = new System.Net.WebClient()
    c.DownloadString(url)


package main

import (
    "io"
    "log"
    "net/http"
    "os"
)

func main() {
    r, err := http.Get("https://sourceforge.net/")
    if err != nil {
        log.Fatalln(err)
    }
    io.Copy(os.Stdout, r.Body)
}


new URL("https://sourceforge.net").eachLine { println it }


#!/usr/bin/runhaskell

import Network.HTTP.Conduit
import qualified Data.ByteString.Lazy as L
import Network (withSocketsDo)

main = withSocketsDo
    $ simpleHttp "https://sourceforge.net/" >>= L.putStr


# Requires Unicon version 13
procedure main(arglist)
    url := (\arglist[1] | "https://sourceforge.net/")
    w := open(url, "m-") | stop("Cannot open " || url)
    while write(read(w))
    close(w)
end


connection = URL new("https://sourceforge.net") openConnection
scanner = Scanner new(connection getInputStream)

while(scanner hasNext,
  scanner next println
)


   #page=: gethttp'https://sourceforge.net'
0
   #page=: '--no-check-certificate' gethttp'https://sourceforge.net'
900


URL url = new URL("https://sourceforge.net");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
Scanner scanner = new Scanner(connection.getInputStream());

while (scanner.hasNext()) {
    System.out.println(scanner.next());
}


fetch("https://sourceforge.net").then(function (response) {
    return response.text();
}).then(function (body) {
    return body;
});


# v0.6.0

using Requests

str = readstring(get("https://sourceforge.net/"))


// version 1.1.2
import java.net.URL
import javax.net.ssl.HttpsURLConnection
import java.io.InputStreamReader
import java.util.Scanner

fun main(args: Array<String>) {
    val url = URL("https://en.wikipedia.org/wiki/Main_Page")
    val connection = url.openConnection() as HttpsURLConnection
    val isr = InputStreamReader(connection.inputStream)
    val sc = Scanner(isr)
    while (sc.hasNextLine()) println(sc.nextLine())
    sc.close()
}


local(x = curl('https://sourceforge.net'))
local(y = #x->result)
#y->asString


ch = xtra("Curl").new()
CURLOPT_URL = 10002
ch.setOption(CURLOPT_URL, "https://sourceforge.net")
res = ch.exec(1)
if integerP(res) then
  put "Error:" && curl_error(res)
else
  put "Result:" && res.readRawString(res.length)
end if
-- "Result: <!doctype html> ..."


libURLSetSSLVerification true  --check cert
get URL "https://sourceforge.net/"


string sURL = "https://SourceForge.Net/";
key kHttpRequestId;
default {
	state_entry() {
		kHttpRequestId = llHTTPRequest(sURL, [], "");
	}
	http_response(key kRequestId, integer iStatus, list lMetaData, string sBody) {
		if(kRequestId==kHttpRequestId) {
			llOwnerSay("Status="+(string)iStatus);
			integer x = 0;
			for(x=0 ; x<llGetListLength(lMetaData) ; x++) {
				llOwnerSay("llList2String(lMetaData, "+(string)x+")="+llList2String(lMetaData, x));
			}
			list lBody = llParseString2List(sBody, ["\n"], []);
			for(x=0 ; x<llGetListLength(lBody) ; x++) {
				llOwnerSay("llList2String(lBody, "+(string)x+")="+llList2String(lBody, x));
			}
		}
	}
}


local request = require('http.request')
local headers, stream = request.new_from_uri("https://sourceforge.net/"):go()
local body = stream:get_body_as_string()
local status = headers:get(':status')
io.write(string.format('Status: %d\nBody: %s\n', status, body)


content := URL:-Get( "https://www.google.ca/" );


using System;
using System.Console;
using System.Net;
using System.IO;

module HTTP
{
    Main() : void
    {
        def wc = WebClient();
        def myStream = wc.OpenRead(https://sourceforge.com);
        def sr = StreamReader(myStream);

        WriteLine(sr.ReadToEnd());
        myStream.Close()
    }
}


import httpclient

var client = newHttpClient()
echo client.getContent("https://sourceforge.net")


use HTTP;

class HttpsTest {
  function : Main(args : String[]) ~ Nil {
    client := HttpsClient->New();
    lines := client->Get("https://sourceforge.net");
    each(i : lines) {
      lines->Get(i)->As(String)->PrintLine();
    };
  }
}


(import (lib curl))

(define curl (make-curl))
(curl 'url "https://www.w3.org/")
(curl 'perform)


{$mode objfpc}{$H+}
uses fphttpclient;

var
  s: string;
  hc: tfphttpclient;

begin
  hc := tfphttpclient.create(nil);
  try
    s := hc.get('https://www.example.com')
  finally
    hc.free
  end;
  writeln(s)
end.


use strict;
use LWP::UserAgent;

my $url = 'https://www.rosettacode.org';
my $response = LWP::UserAgent->new->get( $url );

$response->is_success or die "Failed to GET '$url': ", $response->status_line;

print $response->as_string;


without js
include builtins\libcurl.e
curl_global_init()
atom curl = curl_easy_init()
curl_easy_setopt(curl, CURLOPT_URL, "https://sourceforge.net/")
object res = curl_easy_perform_ex(curl)
curl_easy_cleanup(curl)
curl_global_cleanup()

puts(1,res)


(in '(curl "https://sourceforge.net")  # Open a pipe to 'curl'
   (out NIL (echo)) )                  # Echo to standard output


int main() {
    write("%s\n", Protocols.HTTP.get_url_data("https://sourceforge.net"));
}


$wc = New-Object Net.WebClient
$wc.DownloadString('https://sourceforge.net')


library(RCurl)
webpage <- getURL("https://sourceforge.net/", .opts=list(followlocation=TRUE, ssl.verifyhost=FALSE, ssl.verifypeer=FALSE))


#lang racket
(require net/url)
(copy-port (get-pure-port (string->url "https://www.google.com")
                          #:redirections 100)
           (current-output-port))


use WWW;
say get 'https://sourceforge.net/';


      Dim sock As New HTTPSecureSocket
      Print(sock.Get("https://sourceforge.net", 10))  //set the timeout period to 10 seconds.


cStr= download("http://sourceforge.net/")
see cStr + nl


require 'net/https'
require 'uri'
require 'pp'

uri = URI.parse('https://sourceforge.net')
http = Net::HTTP.new(uri.host,uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

http.start do
  content = http.get(uri)
  p [content.code, content.message]
  pp content.to_hash
  puts content.body
end


extern crate reqwest;

fn main() {
    let response = match reqwest::blocking::get("https://sourceforge.net") {
        Ok(response) => response,
        Err(e) => panic!("error encountered while making request: {:?}", e),
    };

    println!("{}", response.text().unwrap());
}


import scala.io.Source

object HttpsTest extends App {
  System.setProperty("http.agent", "*")

  Source.fromURL("https://sourceforge.net").getLines.foreach(println)
}


$ include "seed7_05.s7i";
  include "gethttps.s7i";
  include "utf8.s7i";

const proc: main is func
  begin
    writeln(STD_UTF8_OUT, getHttps("sourceforge.net"));
  end func;


var lwp = require('LWP::UserAgent');    # LWP::Protocol::https is needed
var url = 'https://rosettacode.org';

var ua = lwp.new(
    agent    => 'Mozilla/5.0',
    ssl_opts => Hash.new(verify_hostname => 1),
);

var resp = ua.get(url);
resp.is_success || die "Failed to GET #{url.dump}: #{resp.status_line}";
print resp.decoded_content;


import Foundation

// With https
let request = NSURLRequest(URL: NSURL(string: "https://sourceforge.net")!)

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) {res, data, err in // callback

    // data is binary
    if (data != nil) {
        let string = NSString(data: data!, encoding: NSUTF8StringEncoding)
        println(string)
    }
}

CFRunLoopRun() // dispatch


package require http
package require tls

# Tell the http package what to do with “https:” URLs.
#
# First argument is the protocol name, second the default port, and
# third the connection builder command
http::register "https" 443 ::tls::socket

# Make a secure connection, which is almost identical to normal
# connections except for the different protocol in the URL.
set token [http::geturl "https://sourceforge.net/"]

# Now as for conventional use of the “http” package
puts [http::data $token]
http::cleanup $token


$$ MODE TUSCRIPT
SET DATEN = REQUEST ("https://sourceforge.net")
*{daten}


Option Explicit

Const sURL="https://sourceforge.net/"

Dim oHTTP
Set oHTTP = CreateObject("Microsoft.XmlHTTP")

On Error Resume Next
oHTTP.Open "GET", sURL, False
oHTTP.Send ""
If Err.Number = 0 Then
     WScript.Echo oHTTP.responseText
Else
     Wscript.Echo "error " & Err.Number & ": " & Err.Description
End If

Set oHTTP = Nothing


Sub Main()
Dim HttpReq As WinHttp.WinHttpRequest
'  in the "references" dialog of the IDE, check
'  "Microsoft WinHTTP Services, version 5.1" (winhttp.dll)
Const HTTPREQUEST_PROXYSETTING_PROXY        As Long = 2
Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1     As Long = &H80&
Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1   As Long = &H200&
Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2   As Long = &H800&
#Const USE_PROXY = 1
  Set HttpReq = New WinHttp.WinHttpRequest
  HttpReq.Open "GET", "https://groups.google.com/robots.txt"
  HttpReq.Option(WinHttpRequestOption_SecureProtocols) = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 Or _
                                                         WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 Or _
                                                         WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2
#If USE_PROXY Then
  HttpReq.SetProxy HTTPREQUEST_PROXYSETTING_PROXY, "my_proxy:80"
#End If
  HttpReq.SetTimeouts 1000, 1000, 1000, 1000
  HttpReq.Send
  Debug.Print HttpReq.ResponseText
End Sub


Imports System.Net

Dim client As WebClient = New WebClient()
Dim content As String = client.DownloadString("https://sourceforge.net")
Console.WriteLine(content)


/* https.wren */

var CURLOPT_URL = 10002
var CURLOPT_FOLLOWLOCATION = 52
var CURLOPT_ERRORBUFFER = 10010

foreign class Curl {
    construct easyInit() {}

    foreign easySetOpt(opt, param)

    foreign easyPerform()

    foreign easyCleanup()
}

var curl = Curl.easyInit()
if (curl == 0) {
    System.print("Error initializing cURL.")
    return
}
curl.easySetOpt(CURLOPT_URL, "https://www.w3.org/")
curl.easySetOpt(CURLOPT_FOLLOWLOCATION, 1)
curl.easySetOpt(CURLOPT_ERRORBUFFER, 0) // buffer to be supplied by C

var status = curl.easyPerform()
if (status != 0) {
    System.print("Failed to perform task.")
    return
}
curl.easyCleanup()


zkl: var ZC=Import("zklCurl")
zkl: var data=ZC().get("https://sourceforge.net")
L(Data(36,265),826,0)


      Width% = 320
      Height% = 240

      VDU 23,22,Width%;Height%;8,16,16,128
      *DISPLAY Pentagon.bmp
      OFF

      DIM hist%(Width%-1, Height%-1)

      rs = 2 * SQR(Width%^2 + Height%^2) / Height% : REM Radial step
      ts = PI / Width% : REM Angular step
      h% = Height% / 2

      REM Hough transform:
      FOR y% = 0 TO Height%-1
        FOR x% = 0 TO Width%-1
          IF TINT(x%*2, y%*2) = 0 THEN
            FOR t% = 0 TO Width%-1
              th = t% * ts
              r% = (x%*COS(th) + y%*SIN(th)) / rs + h% + 0.5
              hist%(t%,r%) += 1
            NEXT
          ENDIF
        NEXT
      NEXT y%

      REM Find max:
      max% = 0
      FOR y% = 0 TO Height%-1
        FOR x% = 0 TO Width%-1
          IF hist%(x%,y%) > max% max% = hist%(x%,y%)
        NEXT
      NEXT y%

      REM Plot:
      GCOL 1
      FOR y% = 0 TO Height%-1
        FOR x% = 0 TO Width%-1
          c% = 255 * hist%(x%,y%) / max%
          COLOUR 1, c%, c%, c%
          LINE x%*2,y%*2,x%*2,y%*2
        NEXT
      NEXT y%

      REPEAT
        WAIT 1
      UNTIL FALSE


import std.math, grayscale_image;

Image!Gray houghTransform(in Image!Gray im,
                          in size_t hx=460, in size_t hy=360)
pure nothrow in {
    assert(im !is null);
    assert(hx > 0 && hy > 0);
    assert((hy & 1) == 0, "hy argument must be even.");
} body {
    auto result = new Image!Gray(hx, hy);
    result.clear(Gray.white);

    immutable double rMax = hypot(im.nx, im.ny);
    immutable double dr = rMax / (hy / 2.0);
    immutable double dTh = PI / hx;

    foreach (immutable y; 0 .. im.ny) {
        foreach (immutable x; 0 .. im.nx) {
            if (im[x, y] == Gray.white)
                continue;
            foreach (immutable iTh; 0 .. hx) {
                immutable double th = dTh * iTh;
                immutable double r = x * cos(th) + y * sin(th);
                immutable iry = hy / 2 - cast(int)floor(r / dr + 0.5);
                if (result[iTh, iry] > Gray(0))
                    result[iTh, iry]--;
            }
        }
    }
    return result;
}

void main() {
    (new Image!RGB)
    .loadPPM6("Pentagon.ppm")
    .rgb2grayImage()
    .houghTransform()
    .savePGM("Pentagon_hough.pgm");
}


package main

import (
    "fmt"
    "image"
    "image/color"
    "image/draw"
    "image/png"
    "math"
    "os"
)

func hough(im image.Image, ntx, mry int) draw.Image {
    nimx := im.Bounds().Max.X
    mimy := im.Bounds().Max.Y

    him := image.NewGray(image.Rect(0, 0, ntx, mry))
    draw.Draw(him, him.Bounds(), image.NewUniform(color.White),
        image.Point{}, draw.Src)

    rmax := math.Hypot(float64(nimx), float64(mimy))
    dr := rmax / float64(mry/2)
    dth := math.Pi / float64(ntx)

    for jx := 0; jx < nimx; jx++ {
        for iy := 0; iy < mimy; iy++ {
            col := color.GrayModel.Convert(im.At(jx, iy)).(color.Gray)
            if col.Y == 255 {
                continue
            }
            for jtx := 0; jtx < ntx; jtx++ {
                th := dth * float64(jtx)
                r := float64(jx)*math.Cos(th) + float64(iy)*math.Sin(th)
                iry := mry/2 - int(math.Floor(r/dr+.5))
                col = him.At(jtx, iry).(color.Gray)
                if col.Y > 0 {
                    col.Y--
                    him.SetGray(jtx, iry, col)
                }
            }
        }
    }
    return him
}

func main() {
    f, err := os.Open("Pentagon.png")
    if err != nil {
        fmt.Println(err)
        return
    }
    pent, err := png.Decode(f)
    if err != nil {
        fmt.Println(err)
        return
    }
    if err = f.Close(); err != nil {
        fmt.Println(err)
    }
    h := hough(pent, 460, 360)
    if f, err = os.Create("hough.png"); err != nil {
        fmt.Println(err)
        return
    }
    if err = png.Encode(f, h); err != nil {
        fmt.Println(err)
    }
    if cErr := f.Close(); cErr != nil && err == nil {
        fmt.Println(err)
    }
}


import Control.Monad (forM_, when)
import Data.Array ((!))
import Data.Array.ST (newArray, writeArray, readArray, runSTArray)
import qualified Data.Foldable as F (maximum)
import System.Environment (getArgs, getProgName)

-- Library JuicyPixels:
import Codec.Picture
       (DynamicImage(ImageRGB8, ImageRGBA8), Image, PixelRGB8(PixelRGB8),
        PixelRGBA8(PixelRGBA8), imageWidth, imageHeight, pixelAt,
        generateImage, readImage, pixelMap, savePngImage)
import Codec.Picture.Types (extractLumaPlane, dropTransparency)

dot
  :: Num a
  => (a, a) -> (a, a) -> a
dot (x1, y1) (x2, y2) = x1 * x2 + y1 * y2

mag
  :: Floating a
  => (a, a) -> a
mag a = sqrt $ dot a a

sub
  :: Num a
  => (a, a) -> (a, a) -> (a, a)
sub (x1, y1) (x2, y2) = (x1 - x2, y1 - y2)

fromIntegralP
  :: (Integral a, Num b)
  => (a, a) -> (b, b)
fromIntegralP (x, y) = (fromIntegral x, fromIntegral y)

{-
  Create a Hough space image with y+ measuring the distance from
  the center of the input image on the range of 0 to half the hypotenuse
  and x+ measuring from [0, 2 * pi].
  The origin is in the upper left, so y is increasing down.
  The image is scaled according to thetaSize and distSize.
-}
hough :: Image PixelRGB8 -> Int -> Int -> Image PixelRGB8
hough image thetaSize distSize = hImage
  where
    width = imageWidth image
    height = imageHeight image
    wMax = width - 1
    hMax = height - 1
    xCenter = wMax `div` 2
    yCenter = hMax `div` 2
    lumaMap = extractLumaPlane image
    gradient x y =
      let orig = pixelAt lumaMap x y
          x_ = pixelAt lumaMap (min (x + 1) wMax) y
          y_ = pixelAt lumaMap x (min (y + 1) hMax)
      in fromIntegralP (orig - x_, orig - y_)
    gradMap =
      [ ((x, y), gradient x y)
      | x <- [0 .. wMax]
      , y <- [0 .. hMax] ]
    -- The longest distance from the center, half the hypotenuse of the image.
    distMax :: Double
    distMax = (sqrt . fromIntegral $ height ^ 2 + width ^ 2) / 2
    {-
      The accumulation bins of the polar values.
      For each value in the gradient image, if the gradient length exceeds
      some threshold, consider it evidence of a line and plot all of the
      lines that go through that point in Hough space.
    -}
    accBin =
      runSTArray $
      do arr <- newArray ((0, 0), (thetaSize, distSize)) 0
         forM_ gradMap $
           \((x, y), grad) -> do
             let (x_, y_) = fromIntegralP $ (xCenter, yCenter) `sub` (x, y)
             when (mag grad > 127) $
               forM_ [0 .. thetaSize] $
               \theta -> do
                 let theta_ =
                       fromIntegral theta * 360 / fromIntegral thetaSize / 180 *
                       pi :: Double
                     dist = cos theta_ * x_ + sin theta_ * y_
                     dist_ = truncate $ dist * fromIntegral distSize / distMax
                     idx = (theta, dist_)
                 when (dist_ >= 0 && dist_ < distSize) $
                   do old <- readArray arr idx
                      writeArray arr idx $ old + 1
         return arr
    maxAcc = F.maximum accBin
    -- The image representation of the accumulation bins.
    hTransform x y =
      let l = 255 - truncate ((accBin ! (x, y)) / maxAcc * 255)
      in PixelRGB8 l l l
    hImage = generateImage hTransform thetaSize distSize

houghIO :: FilePath -> FilePath -> Int -> Int -> IO ()
houghIO path outpath thetaSize distSize = do
  image <- readImage path
  case image of
    Left err -> putStrLn err
    Right (ImageRGB8 image_) -> doImage image_
    Right (ImageRGBA8 image_) -> doImage $ pixelMap dropTransparency image_
    _ -> putStrLn "Expecting RGB8 or RGBA8 image"
  where
    doImage image = do
      let houghImage = hough image thetaSize distSize
      savePngImage outpath $ ImageRGB8 houghImage

main :: IO ()
main = do
  args <- getArgs
  prog <- getProgName
  case args of
    [path, outpath, thetaSize, distSize] ->
      houghIO path outpath (read thetaSize) (read distSize)
    _ ->
      putStrLn $
      "Usage: " ++ prog ++ " <image-file> <out-file.png> <width> <height>"


NB.*houghTransform v Produces a density plot of image y in hough space
NB. y is picture as an array with 1 at non-white points,
NB. x is resolution (width,height) of resulting image
houghTransform=: dyad define
  'w h'=. x                               NB. width and height of target image
  theta=. o. (%~ 0.5+i.) w                NB. theta in radians from 0 to π
  rho=. (4$.$. |.y) +/ .* 2 1 o./theta    NB. rho for each pixel at each theta
  'min max'=. (,~-) +/&.:*: $y            NB. min/max possible rho
  rho=. <. 0.5+ h * (rho-min) % max-min   NB. Rescale rho from 0 to h and round to int
  |.([: <:@(#/.~) (i.h)&,)"1&.|: rho      NB. consolidate into picture
)


import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.*;

public class HoughTransform
{
  public static ArrayData houghTransform(ArrayData inputData, int thetaAxisSize, int rAxisSize, int minContrast)
  {
    int width = inputData.width;
    int height = inputData.height;
    int maxRadius = (int)Math.ceil(Math.hypot(width, height));
    int halfRAxisSize = rAxisSize >>> 1;
    ArrayData outputData = new ArrayData(thetaAxisSize, rAxisSize);
    // x output ranges from 0 to pi
    // y output ranges from -maxRadius to maxRadius
    double[] sinTable = new double[thetaAxisSize];
    double[] cosTable = new double[thetaAxisSize];
    for (int theta = thetaAxisSize - 1; theta >= 0; theta--)
    {
      double thetaRadians = theta * Math.PI / thetaAxisSize;
      sinTable[theta] = Math.sin(thetaRadians);
      cosTable[theta] = Math.cos(thetaRadians);
    }

    for (int y = height - 1; y >= 0; y--)
    {
      for (int x = width - 1; x >= 0; x--)
      {
        if (inputData.contrast(x, y, minContrast))
        {
          for (int theta = thetaAxisSize - 1; theta >= 0; theta--)
          {
            double r = cosTable[theta] * x + sinTable[theta] * y;
            int rScaled = (int)Math.round(r * halfRAxisSize / maxRadius) + halfRAxisSize;
            outputData.accumulate(theta, rScaled, 1);
          }
        }
      }
    }
    return outputData;
  }

  public static class ArrayData
  {
    public final int[] dataArray;
    public final int width;
    public final int height;

    public ArrayData(int width, int height)
    {
      this(new int[width * height], width, height);
    }

    public ArrayData(int[] dataArray, int width, int height)
    {
      this.dataArray = dataArray;
      this.width = width;
      this.height = height;
    }

    public int get(int x, int y)
    {  return dataArray[y * width + x];  }

    public void set(int x, int y, int value)
    {  dataArray[y * width + x] = value;  }

    public void accumulate(int x, int y, int delta)
    {  set(x, y, get(x, y) + delta);  }

    public boolean contrast(int x, int y, int minContrast)
    {
      int centerValue = get(x, y);
      for (int i = 8; i >= 0; i--)
      {
        if (i == 4)
          continue;
        int newx = x + (i % 3) - 1;
        int newy = y + (i / 3) - 1;
        if ((newx < 0) || (newx >= width) || (newy < 0) || (newy >= height))
          continue;
        if (Math.abs(get(newx, newy) - centerValue) >= minContrast)
          return true;
      }
      return false;
    }

    public int getMax()
    {
      int max = dataArray[0];
      for (int i = width * height - 1; i > 0; i--)
        if (dataArray[i] > max)
          max = dataArray[i];
      return max;
    }
  }

  public static ArrayData getArrayDataFromImage(String filename) throws IOException
  {
    BufferedImage inputImage = ImageIO.read(new File(filename));
    int width = inputImage.getWidth();
    int height = inputImage.getHeight();
    int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);
    ArrayData arrayData = new ArrayData(width, height);
    // Flip y axis when reading image
    for (int y = 0; y < height; y++)
    {
      for (int x = 0; x < width; x++)
      {
        int rgbValue = rgbData[y * width + x];
        rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11);
        arrayData.set(x, height - 1 - y, rgbValue);
      }
    }
    return arrayData;
  }

  public static void writeOutputImage(String filename, ArrayData arrayData) throws IOException
  {
    int max = arrayData.getMax();
    BufferedImage outputImage = new BufferedImage(arrayData.width, arrayData.height, BufferedImage.TYPE_INT_ARGB);
    for (int y = 0; y < arrayData.height; y++)
    {
      for (int x = 0; x < arrayData.width; x++)
      {
        int n = Math.min((int)Math.round(arrayData.get(x, y) * 255.0 / max), 255);
        outputImage.setRGB(x, arrayData.height - 1 - y, (n << 16) | (n << 8) | 0x90 | -0x01000000);
      }
    }
    ImageIO.write(outputImage, "PNG", new File(filename));
    return;
  }

  public static void main(String[] args) throws IOException
  {
    ArrayData inputData = getArrayDataFromImage(args[0]);
    int minContrast = (args.length >= 4) ? 64 : Integer.parseInt(args[4]);
    ArrayData outputData = houghTransform(inputData, Integer.parseInt(args[2]), Integer.parseInt(args[3]), minContrast);
    writeOutputImage(args[1], outputData);
    return;
  }
}


using ImageFeatures

img = fill(false,5,5)
img[3,:] .= true

println(hough_transform_standard(img))


import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO

internal class ArrayData(val dataArray: IntArray, val width: Int, val height: Int) {

    constructor(width: Int, height: Int) : this(IntArray(width * height), width, height)

    operator fun get(x: Int, y: Int) = dataArray[y * width + x]

    operator fun set(x: Int, y: Int, value: Int) {
        dataArray[y * width + x] = value
    }

    operator fun invoke(thetaAxisSize: Int, rAxisSize: Int, minContrast: Int): ArrayData {
        val maxRadius = Math.ceil(Math.hypot(width.toDouble(), height.toDouble())).toInt()
        val halfRAxisSize = rAxisSize.ushr(1)
        val outputData = ArrayData(thetaAxisSize, rAxisSize)
        // x output ranges from 0 to pi
        // y output ranges from -maxRadius to maxRadius
        val sinTable = DoubleArray(thetaAxisSize)
        val cosTable = DoubleArray(thetaAxisSize)
        for (theta in thetaAxisSize - 1 downTo 0) {
            val thetaRadians = theta * Math.PI / thetaAxisSize
            sinTable[theta] = Math.sin(thetaRadians)
            cosTable[theta] = Math.cos(thetaRadians)
        }

        for (y in height - 1 downTo 0)
            for (x in width - 1 downTo 0)
                if (contrast(x, y, minContrast))
                    for (theta in thetaAxisSize - 1 downTo 0) {
                        val r = cosTable[theta] * x + sinTable[theta] * y
                        val rScaled = Math.round(r * halfRAxisSize / maxRadius).toInt() + halfRAxisSize
                        outputData.accumulate(theta, rScaled, 1)
                    }

        return outputData
    }

    fun writeOutputImage(filename: String) {
        val max = dataArray.max()!!
        val image = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB)
        for (y in 0..height - 1)
            for (x in 0..width - 1) {
                val n = Math.min(Math.round(this[x, y] * 255.0 / max).toInt(), 255)
                image.setRGB(x, height - 1 - y, n shl 16 or (n shl 8) or 0x90 or -0x01000000)
            }

        ImageIO.write(image, "PNG", File(filename))
    }

    private fun accumulate(x: Int, y: Int, delta: Int) {
        set(x, y, get(x, y) + delta)
    }

    private fun contrast(x: Int, y: Int, minContrast: Int): Boolean {
        val centerValue = get(x, y)
        for (i in 8 downTo 0)
            if (i != 4) {
                val newx = x + i % 3 - 1
                val newy = y + i / 3 - 1
                if (newx >= 0 && newx < width && newy >= 0 && newy < height
                        && Math.abs(get(newx, newy) - centerValue) >= minContrast)
                    return true
            }
        return false
    }
}

internal fun readInputFromImage(filename: String): ArrayData {
    val image = ImageIO.read(File(filename))
    val w = image.width
    val h = image.height
    val rgbData = image.getRGB(0, 0, w, h, null, 0, w)
    // flip y axis when reading image
    val array = ArrayData(w, h)
    for (y in 0..h - 1)
        for (x in 0..w - 1) {
            var rgb = rgbData[y * w + x]
            rgb = ((rgb and 0xFF0000).ushr(16) * 0.30 + (rgb and 0xFF00).ushr(8) * 0.59 + (rgb and 0xFF) * 0.11).toInt()
            array[x, h - 1 - y] = rgb
        }

    return array
}

fun main(args: Array<out String>) {
    val inputData = readInputFromImage(args[0])
    val minContrast = if (args.size >= 4) 64 else args[4].toInt()
    inputData(args[2].toInt(), args[3].toInt(), minContrast).writeOutputImage(args[1])
}


with(ImageTools):
img := Read("pentagon.png")[..,..,1]:
img_x := Convolution (img, Matrix ([[1,2,1], [0,0,0],[-1,-2,-1]])):
img_y := Convolution (img, Matrix ([[-1,0,1],[-2,0,2],[-1,0,1]])):
img := Array (abs (img_x) + abs (img_y), datatype=float[8]):
countPixels := proc(M)
	local r,c,i,j,row,col:
	row := Array([]);
	col := Array([]);
	r,c := LinearAlgebra:-Dimensions(M);
	for i from 1 to r do
		for j from 1 to c do
			if M[i,j] <> 0 then
				ArrayTools:-Append(row, i, inplace=true):
				ArrayTools:-Append(col, j, inplace=true):
			end if:
		end do:
	end do:
	return row,col:
end proc:
row,col := countPixels(img);
pTheta := proc(acc,r,c,x,y)
	local j, pos:
	for j from 1 to c do
		pos := ceil(x*cos((j-1)*Pi/180)+y*sin((j-1)*Pi/180)+r/2):
		acc[pos,j] := acc[pos,j]+1;
	end do:
end proc:
HoughTransform := proc(img,row,col)
   local r,c,pMax,theta,numThetas,numPs,acc,i:
   r,c := LinearAlgebra:-Dimensions(img);
   pMax := ceil(sqrt(r^2+c^2)):
   theta := [seq(evalf(i), i = 1..181, 1)]:
   numThetas := numelems(theta):
   numPs := 2*pMax+1:
   acc := Matrix(numPs, numThetas, fill=0,datatype=integer[4]):
   for i from 1 to numelems(row) do
   	pTheta(acc,numPs,numThetas,col[i],row[i]):
   end do:
   return acc;
end proc:
result :=HoughTransform(img,row,col);
Embed(Scale(FitIntensity(Create(result)), 1..500,1..500));


import lenientops, math
import grayscale_image

const White = 255

func houghTransform*(img: GrayImage; hx = 460; hy = 360): GrayImage =
  assert not img.isNil
  assert hx > 0 and hy > 0
  assert (hy and 1) == 0, "hy argument must be even"

  result = newGrayImage(hx, hy)
  result.fill(White)

  let rMax = hypot(img.w.toFloat, img.h.toFloat)
  let dr = rMax / (hy / 2)
  let dTh = PI / hx

  for y in 0..<img.h:
    for x in 0..<img.w:
      if img[x, y] == White: continue
      for iTh in 0..<hx:
        let th = dTh * iTh
        let r = x * cos(th) + y * sin(th)
        let iry = hy div 2 - (r / dr).toInt
        if result[iTh, iry] > 0:
          result[iTh, iry] = result[iTh, iry] - 1

when isMainModule:
  import nimPNG
  import bitmap

  const Input = "Pentagon.png"
  const Output = "Hough.png"

  let pngImage = loadPNG24(seq[byte], Input).get()
  let grayImage = newGrayImage(pngImage.width, pngImage.height)

  # Convert to grayscale.
  for i in 0..grayImage.pixels.high:
    grayImage.pixels[i] = Luminance(0.2126 * pngImage.data[3 * i] +
                                    0.7152 * pngImage.data[3 * i + 1] +
                                    0.0722 * pngImage.data[3 * i + 2] + 0.5)

  # Apply Hough transform and convert to an RGB image.
  let houghImage = grayImage.houghTransform().toImage()

  # Save into a PNG file.
  # As nimPNG expects a sequence of bytes, not a sequence of colors, we have to make a copy.
  var data = newSeqOfCap[byte](houghImage.pixels.len * 3)
  for color in houghImage.pixels:
    data.add([color.r, color.g, color.b])
  discard savePNG24(Output, data, houghImage.w, houghImage.h)


use strict;
use warnings;

use Imager;

use constant pi => 3.14159265;

sub hough {
    my($im)     = shift;
    my($width)  = shift || 460;
    my($height) = shift || 360;
    $height = 2 * int $height/2;

    $height = 2 * int $height/2;
    my($xsize, $ysize) = ($im->getwidth, $im->getheight);
    my $ht = Imager->new(xsize => $width, ysize => $height);
    my @canvas;
    for my $i (0..$height-1) { for my $j (0..$width-1) { $canvas[$i][$j] = 255 } }
    $ht->box(filled => 1, color => 'white');

    my $rmax = sqrt($xsize**2 + $ysize**2);
    my $dr   = 2 * $rmax / $height;
    my $dth  = pi / $width;

    for my $x (0..$xsize-1) {
      for my $y (0..$ysize-1) {
        my $col = $im->getpixel(x => $x, y => $y);
        my($r,$g,$b) = $col->rgba;
        next if $r==255; # && $g==255 && $b==255;
        for my $k (0..$width) {
            my $th = $dth*$k;
            my $r2 = ($x*cos($th) + $y*sin($th));
            my $iry = ($height/2 + int($r2/$dr + 0.5));
            $ht->setpixel(x => $k, y => $iry, color => [ ($canvas[$iry][$k]--) x 3] );
        }
      }
    }
    return $ht;
}

my $img = Imager->new;
$img->read(file => 'ref/pentagon.png') or die "Cannot read: ", $img->errstr;
my $ht = hough($img);
$ht->write(file => 'hough_transform.png');


-- demo\rosetta\Hough_transform.exw
without js -- IupImage, imImage, im_width/height/pixel, allocate,
            -- imFileImageLoadBitmap, IupImageFromImImage
include pGUI.e

function hypot(atom a,b) return sqrt(a*a+b*b) end function

function hough_transform(imImage im, integer width=460, height=360)
    height = 2*floor(height / 2)
    integer xsize = im_width(im),
            ysize = im_height(im)
    sequence canvas = repeat(repeat(255,width),height)
    atom rmax = hypot(xsize, ysize),
         dr = 2*(rmax / height),
         dth = (PI / width)
    for y=0 to ysize-1 do
        for x=0 to xsize-1 do
            integer {r,g,b} = im_pixel(im, x, y)
            if r!=255 then
                for k=1 to width do
                    atom th = dth*(k-1),
                         r2 = (x*cos(th) + y*sin(th))
                    integer iry = (height/2 + floor(r2/dr + 0.5))+1,
                            cik = canvas[iry][k] - 1
                    if cik>=0 then
                        canvas[iry][k] = cik
                    end if
                end for
            end if
        end for
    end for
    canvas = flatten(canvas) -- (needed by IupImage)
    Ihandle new_img = IupImage(width, height, canvas)
    for c=0 to 255 do
        IupSetStrAttributeId(new_img,"",c,"%d %d %d",{c,c,c})
    end for
    return new_img
end function

IupOpen()

atom pError = allocate(machine_word())
imImage im1 = imFileImageLoadBitmap("Pentagon320.png",0,pError)
if im1=NULL then ?"error opening Pentagon320.png" abort(0) end if
Ihandln image1 = IupImageFromImImage(im1),
        image2 = hough_transform(im1),
        label1 = IupLabel(),
        label2 = IupLabel()
IupSetAttributeHandle(label1, "IMAGE", image1)
IupSetAttributeHandle(label2, "IMAGE", image2)

Ihandle dlg = IupDialog(IupHbox({label1, label2}))
IupSetAttribute(dlg, "TITLE", "Hough transform")
IupShow(dlg)
if platform()!=JS then -- (no chance...)
    IupMainLoop()
    IupClose()
end if


from math import hypot, pi, cos, sin
from PIL import Image

def hough(im, ntx=460, mry=360):
    "Calculate Hough transform."
    pim = im.load()
    nimx, mimy = im.size
    mry = int(mry/2)*2          #Make sure that this is even
    him = Image.new("L", (ntx, mry), 255)
    phim = him.load()

    rmax = hypot(nimx, mimy)
    dr = rmax / (mry/2)
    dth = pi / ntx

    for jx in xrange(nimx):
        for iy in xrange(mimy):
            col = pim[jx, iy]
            if col == 255: continue
            for jtx in xrange(ntx):
                th = dth * jtx
                r = jx*cos(th) + iy*sin(th)
                iry = mry/2 + int(r/dr+0.5)
                phim[jtx, iry] -= 1
    return him

def test():
    "Test Hough transform with pentagon."
    im = Image.open("pentagon.png").convert("L")
    him = hough(im)
    him.save("ho5.bmp")

if __name__ == "__main__": test()


use GD;

my $filename = 'pentagon.ppm';
my $in = open($filename, :r, :enc<iso-8859-1>);
my ($type, $dim, $depth) = $in.lines[^3];
my ($xsize,$ysize) = split ' ', $dim;

my ($width, $height) = 460, 360;
my $image = GD::Image.new($width, $height);

my @canvas = [255 xx $width] xx $height;

my $rmax = sqrt($xsize**2 + $ysize**2);
my $dr   = 2 * $rmax / $height;
my $dth  = π / $width;

my $pixel = 0;
my %cstore;
for $in.lines.ords -> $r, $g, $b {
    $pixel++;
    next if $r > 130;

    my $x =       $pixel % $xsize;
    my $y = floor $pixel / $xsize;

    (^$width).map: -> $k {
        my $th = $dth*$k;
        my $r = ($x*cos($th) + $y*sin($th));
        my $iry = ($height/2 + ($r/$dr).round(1)).Int;
        my $c = '#' ~ (@canvas[$iry][$k]--).base(16) x 3;
        %cstore{$c} = $image.colorAllocate($c) if %cstore{$c}:!exists;
        $image.pixel($k, $iry, %cstore{$c});
    }
}

my $png_fh = $image.open("hough-transform.png", "wb");
$image.output($png_fh, GD_PNG);
$png_fh.close;


require 'mathn'
require 'rubygems'
require 'gd2'
include GD2

def hough_transform(img)
  mx, my = img.w*0.5, img.h*0.5
  max_d = Math.sqrt(mx**2 + my**2)
  min_d = max_d * -1
  hough = Hash.new(0)
  (0..img.w).each do |x|
    puts "#{x} of #{img.w}"
    (0..img.h).each do |y|
      if img.pixel2color(img.get_pixel(x,y)).g > 32
        (0...180).each do |a|
          rad = a * (Math::PI / 180.0)
          d = (x-mx) * Math.cos(rad) + (y-my) * Math.sin(rad)
          hough["#{a.to_i}_#{d.to_i}"] = hough["#{a.to_i}_#{d.to_i}"] + 1
        end
      end
    end
  end
  heat = GD2::Image.import 'heatmap.png'
  out = GD2::Image::TrueColor.new(180,max_d*2)
  max = hough.values.max
  p max
  hough.each_pair do |k,v|
    a,d = k.split('_').map(&:to_i)
    c = (v / max) * 255
    c = heat.get_pixel(c,0)
    out.set_pixel(a, max_d + d, c)
  end
  out
end


//! Contributed by Gavin Baker <[email protected]>
//! Adapted from the Go version

use std::fs::File;
use std::io::{self, BufRead, BufReader, BufWriter, Read, Write};
use std::iter::repeat;

/// Simple 8-bit grayscale image
struct ImageGray8 {
    width: usize,
    height: usize,
    data: Vec<u8>,
}

fn load_pgm(filename: &str) -> io::Result<ImageGray8> {
    // Open file
    let mut file = BufReader::new(File::open(filename)?);

    // Read header
    let mut magic_in = String::new();
    let _ = file.read_line(&mut magic_in)?;
    let mut width_in = String::new();
    let _ = file.read_line(&mut width_in)?;
    let mut height_in = String::new();
    let _ = file.read_line(&mut height_in)?;
    let mut maxval_in = String::new();
    let _ = file.read_line(&mut maxval_in)?;

    assert_eq!(magic_in, "P5\n");
    assert_eq!(maxval_in, "255\n");

    // Parse header
    let width = width_in
        .trim()
        .parse::<usize>()
        .map_err(|_| io::ErrorKind::InvalidData)?;
    let height: usize = height_in
        .trim()
        .parse::<usize>()
        .map_err(|_| io::ErrorKind::InvalidData)?;

    println!("Reading pgm file {}: {} x {}", filename, width, height);

    // Create image and allocate buffer
    let mut img = ImageGray8 {
        width,
        height,
        data: vec![],
    };

    // Read image data
    let expected_bytes = width * height;
    let bytes_read = file.read_to_end(&mut img.data)?;
    if bytes_read != expected_bytes {
        let kind = if bytes_read < expected_bytes {
            io::ErrorKind::UnexpectedEof
        } else {
            io::ErrorKind::InvalidData
        };
        let msg = format!("expected {} bytes", expected_bytes);
        return Err(io::Error::new(kind, msg));
    }

    Ok(img)
}

fn save_pgm(img: &ImageGray8, filename: &str) {
    // Open file
    let mut file = BufWriter::new(File::create(filename).unwrap());

    // Write header
    if let Err(e) = writeln!(&mut file, "P5\n{}\n{}\n255", img.width, img.height) {
        println!("Failed to write header: {}", e);
    }

    println!(
        "Writing pgm file {}: {} x {}",
        filename, img.width, img.height
    );

    // Write binary image data
    if let Err(e) = file.write_all(&(img.data[..])) {
        println!("Failed to image data: {}", e);
    }
}

#[allow(clippy::cast_precision_loss)]
#[allow(clippy::clippy::cast_possible_truncation)]
fn hough(image: &ImageGray8, out_width: usize, out_height: usize) -> ImageGray8 {
    let in_width = image.width;
    let in_height = image.height;

    // Allocate accumulation buffer
    let out_height = ((out_height / 2) * 2) as usize;
    let mut accum = ImageGray8 {
        width: out_width,
        height: out_height,
        data: repeat(255).take(out_width * out_height).collect(),
    };

    // Transform extents
    let rmax = (in_width as f64).hypot(in_height as f64);
    let dr = rmax / (out_height / 2) as f64;
    let dth = std::f64::consts::PI / out_width as f64;

    // Process input image in raster order
    for y in 0..in_height {
        for x in 0..in_width {
            let in_idx = y * in_width + x;
            let col = image.data[in_idx];
            if col == 255 {
                continue;
            }

            // Project into rho,theta space
            for jtx in 0..out_width {
                let th = dth * (jtx as f64);
                let r = (x as f64) * (th.cos()) + (y as f64) * (th.sin());

                let iry = out_height as i64 / 2 - (r / (dr as f64) + 0.5).floor() as i64;
                #[allow(clippy::clippy::cast_sign_loss)]
                let out_idx = (jtx as i64 + iry * out_width as i64) as usize;
                let col = accum.data[out_idx];
                if col > 0 {
                    accum.data[out_idx] = col - 1;
                }
            }
        }
    }
    accum
}

fn main() -> io::Result<()> {
    let image = load_pgm("resources/Pentagon.pgm")?;
    let accum = hough(&image, 460, 360);
    save_pgm(&accum, "hough.pgm");
    Ok(())
}


import java.awt.image._
import java.io.File
import javax.imageio._

object HoughTransform extends App {
    override def main(args: Array[String]) {
        val inputData = readDataFromImage(args(0))
        val minContrast = if (args.length >= 4) 64 else args(4).toInt
        inputData(args(2).toInt, args(3).toInt, minContrast).writeOutputImage(args(1))
    }

    private def readDataFromImage(filename: String) = {
        val image = ImageIO.read(new File(filename))
        val width = image.getWidth
        val height = image.getHeight
        val rgbData = image.getRGB(0, 0, width, height, null, 0, width)
        val arrayData = new ArrayData(width, height)
        for (y <- 0 until height; x <- 0 until width) {
            var rgb = rgbData(y * width + x)
            rgb = (((rgb & 0xFF0000) >>> 16) * 0.30 + ((rgb & 0xFF00) >>> 8) * 0.59 +
                    (rgb & 0xFF) * 0.11).toInt
            arrayData(x, height - 1 - y) = rgb
        }
        arrayData
    }
}

class ArrayData(val width: Int, val height: Int) {
    def update(x: Int, y: Int, value: Int) {
        dataArray(x)(y) = value
    }

    def apply(thetaAxisSize: Int, rAxisSize: Int, minContrast: Int) = {
        val maxRadius = Math.ceil(Math.hypot(width, height)).toInt
        val halfRAxisSize = rAxisSize >>> 1
        val outputData = new ArrayData(thetaAxisSize, rAxisSize)
        val sinTable = Array.ofDim[Double](thetaAxisSize)
        val cosTable = sinTable.clone()
        for (theta <- thetaAxisSize - 1 until -1 by -1) {
            val thetaRadians = theta * Math.PI / thetaAxisSize
            sinTable(theta) = Math.sin(thetaRadians)
            cosTable(theta) = Math.cos(thetaRadians)
        }
        for (y <- height - 1 until -1 by -1; x <- width - 1 until -1 by -1)
            if (contrast(x, y, minContrast))
                for (theta <- thetaAxisSize - 1 until -1 by -1) {
                    val r = cosTable(theta) * x + sinTable(theta) * y
                    val rScaled = Math.round(r * halfRAxisSize / maxRadius).toInt + halfRAxisSize
                    outputData.dataArray(theta)(rScaled) += 1
                }

        outputData
    }

    def writeOutputImage(filename: String) {
        var max = Int.MinValue
        for (y <- 0 until height; x <- 0 until width) {
            val v = dataArray(x)(y)
            if (v > max) max = v
        }
        val image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB)
        for (y <- 0 until height; x <- 0 until width) {
            val n = Math.min(Math.round(dataArray(x)(y) * 255.0 / max).toInt, 255)
            image.setRGB(x, height - 1 - y, (n << 16) | (n << 8) | 0x90 | -0x01000000)
        }
        ImageIO.write(image, "PNG", new File(filename))
    }

    private def contrast(x: Int, y: Int, minContrast: Int): Boolean = {
        val centerValue = dataArray(x)(y)
        for (i <- 8 until -1 by -1 if i != 4) {
            val newx = x + (i % 3) - 1
            val newy = y + (i / 3) - 1
            if (newx >= 0 && newx < width && newy >= 0 && newy < height &&
                    Math.abs(dataArray(newx)(newy) - centerValue) >= minContrast)
                return true
        }

        false
    }

    private val dataArray = Array.ofDim[Int](width, height)
}


import <Utilities/Sequence.sl>;
import <Utilities/Math.sl>;

hough: int(2) * int * int * int -> int(2);
hough(image(2), thetaAxisSize, rAxisSize, minContrast) :=
    let
        initialResult[r,theta] := 0 foreach r within 1 ... rAxisSize, theta within 1 ... thetaAxisSize;

        result := houghHelper(image, minContrast, 1, 1, initialResult);

        max := vectorMax(vectorMax(result));
    in
        255 - min(round((result * 255 / max)), 255);

houghHelper(image(2), minContrast, x, y, result(2)) :=
    let
        thetaAxisSize := size(head(result));
        rAxisSize := size(result);

        width := size(head(image));
        height := size(image);
        maxRadius := ceiling(sqrt(width^2 + height^2));
        halfRAxisSize := rAxisSize / 2;

        rs[theta] := round((cos(theta) * x + sin(theta) * y) * halfRAxisSize / maxRadius) + halfRAxisSize
                     foreach theta within (0 ... (thetaAxisSize-1)) * pi / thetaAxisSize;

        newResult[r,theta] := result[r,theta] + 1 when rs[theta] = r-1 else result[r,theta];

        nextResult := result when not checkContrast(image, x, y, minContrast) else newResult;

        nextX := 1 when x = width else x + 1;
        nextY := y + 1 when x = width else y;
    in
        nextResult when x = width and y = height
    else
        houghHelper(image, minContrast, nextX, nextY, nextResult);

checkContrast(image(2), x, y, minContrast) :=
    let
        neighbors[i,j] := image[i,j] when i > 0 and i < size(image) and j > 0 and j < size(image[i])
                          foreach i within y-1 ... y+1,
                                  j within x-1 ... x+1;
    in
        some(some(abs(image[y,x] - neighbors) >= minContrast));


require('Imager')

func hough(im, width=460, height=360) {

    height = 2*floor(height / 2)

    var xsize = im.getwidth
    var ysize = im.getheight

    var ht = %s|Imager|.new(xsize => width, ysize => height)
    var canvas = height.of { width.of(255) }

    ht.box(filled => true, color => 'white')

    var rmax = hypot(xsize, ysize)
    var dr = 2*(rmax / height)
    var dth = (Num.pi / width)

    for y,x in (^ysize ~X ^xsize) {
        var col = im.getpixel(x => x, y => y)
        var (r,g,b) = col.rgba
        (r==255 && g==255 && b==255) && next
        for k in ^width {
            var th = dth*k
            var r = (x*cos(th) + y*sin(th))
            var iry = (height/2 + int(r/dr + 0.5))
            ht.setpixel(x => k, y => iry, color => 3.of(--canvas[iry][k]))
        }
    }

    return ht
}

var img = %s|Imager|.new(file => 'Pentagon.png')
var ht = hough(img)
ht.write(file => 'Hough transform.png')


import "graphics" for Canvas, Color, ImageData
import "dome" for Window, Process
import "math" for Math

var Hypot = Fn.new { |x, y| (x*x + y*y).sqrt }

class ArrayData {
    construct new(width, height) {
        _width  = width
        _height = height
        _dataArray = List.filled(width * height, 0)
    }

    width  { _width }
    height { _height }

    [x, y] { _dataArray[y * _width + x] }

    [x, y]=(v) { _dataArray[y * _width + x] = v }

    transform(thetaAxisSize, rAxisSize, minContrast) {
        var maxRadius = Math.ceil(Hypot.call(_width, _height))
        var halfRAxisSize = rAxisSize >> 1
        var outputData = ArrayData.new(thetaAxisSize, rAxisSize)
        // x output ranges from 0 to pi
        // y output ranges from -maxRadius to maxRadius
        var sinTable = List.filled(thetaAxisSize, 0)
        var cosTable = List.filled(thetaAxisSize, 0)
        for (theta in thetaAxisSize - 1..0) {
            var thetaRadians = theta * Num.pi / thetaAxisSize
            sinTable[theta] = Math.sin(thetaRadians)
            cosTable[theta] = Math.cos(thetaRadians)
        }
        for (y in _height - 1..0) {
            for (x in _width - 1..0) {
                if (contrast(x, y, minContrast)) {
                    for (theta in thetaAxisSize - 1..0) {
                        var r = cosTable[theta] * x + sinTable[theta] * y
                        var rScaled = Math.round(r * halfRAxisSize / maxRadius) + halfRAxisSize
                        outputData.accumulate(theta, rScaled, 1)
                    }
                }
            }
        }
        return outputData
    }

    accumulate(x, y, delta) { this[x, y] = this[x, y] + delta }

    contrast(x, y, minContrast) {
        var centerValue = this[x, y]
        for (i in 8..0) {
            if (i != 4) {
                var newx = x + i % 3 - 1
                var newy = y + (i / 3).truncate - 1
                if (newx >= 0 && newx < width && newy >= 0 && newy < height &&
                    Math.abs(this[newx, newy] - centerValue) >= minContrast) return true
            }
        }
        return false
    }

    max {
        var max = _dataArray[0]
        for (i in width * height - 1..1) {
            if (_dataArray[i] > max) max = _dataArray[i]
        }
        return max
    }
}

class HoughTransform {
    construct new(inFile, outFile, width, height, minCont) {
        Window.title = "Hough Transform"
        Window.resize(width, height)
        Canvas.resize(width, height)
        _width   = width
        _height  = height
        _inFile  = inFile
        _outFile = outFile
        _minCont = minCont
    }

    init() {
        var dataArray = readInputFromImage(_inFile)
        dataArray = dataArray.transform(_width, _height, _minCont)
        writeOutputImage(_outFile, dataArray)
    }

    readInputFromImage(filename) {
        var inputImage = ImageData.loadFromFile(filename)
        var width  = inputImage.width
        var height = inputImage.height
        var rgbData = []
        for (y in 0...height) {
            for (x in 0...width) rgbData.add(inputImage.pget(x, y))
        }
        var arrayData = ArrayData.new(width, height)
        // Flip y axis when reading image
        for (y in 0...height) {
            for (x in 0...width) {
                var rgbValue = rgbData[y * width + x]
                rgbValue = (rgbValue.r * 0.3 + rgbValue.g * 0.59 + rgbValue.b * 0.11).floor
                arrayData[x, height - 1 - y] = rgbValue
            }
        }
        return arrayData
    }

    writeOutputImage(filename, arrayData) {
        var max = arrayData.max
        var outputImage = ImageData.create(filename, arrayData.width, arrayData.height)
        for (y in 0...arrayData.height) {
            for (x in 0...arrayData.width) {
                var n = Math.min(Math.round(arrayData[x, y] * 255 / max), 255)
                var c = Color.new(n, n, 0x90)
                outputImage.pset(x, arrayData.height - 1 - y, c)
             }
        }
        outputImage.draw(0, 0)
        outputImage.saveToFile(filename)
    }

    update() {}

    draw(alpha) {}
}

var args = Process.args
System.print(args)
if (args.count != 7) Fiber.abort("There should be exactly 5 command line arguments.")
var inFile  = args[2]
var outFile = args[3]
var width   = Num.fromString(args[4])
var height  = Num.fromString(args[5])
var minCont = Num.fromString(args[6])
var Game = HoughTransform.new(inFile, outFile, width, height, minCont)


const WHITE=0xffFFff, X=0x010101;
fcn houghTransform(image,hx=460,hy=360){
   if(hy.isOdd) hy-=1; // hy argument must be even
   out:=PPM(hx,hy,WHITE);
   rMax:=image.w.toFloat().hypot(image.h);
   dr,dTh:=rMax/(hy/2), (0.0).pi/hx;

   foreach y,x in (image.h,image.w){
      if(image[x,y]==WHITE) continue;
      foreach iTh in (hx){
         th,r:=dTh*iTh, th.cos()*x + th.sin()*y;
	 iry:=hy/2 + (r/dr + 0.5).floor();  // y==0 is top
	 if(out[iTh,iry]>0) out[iTh,iry]=out[iTh,iry] - X;
      }
   }
   out
}


with Ada.Text_IO; use Ada.Text_IO;
with GNAT.Sockets;

procedure Demo is
begin
   Put_Line (GNAT.Sockets.Host_Name);
end Demo;


STRING hostname;
get(read OF execve child pipe("/bin/hostname","hostname",""), hostname);
print(("hostname: ", hostname, new line))


$ awk 'BEGIN{print ENVIRON["HOST"]}'
E51A08ZD


      INSTALL @lib$+"SOCKLIB"
      PROC_initsockets
      PRINT "hostname: " FN_gethostname
      PROC_exitsockets


#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <unistd.h>

int main(void)
{
 char name[_POSIX_HOST_NAME_MAX + 1];
 return gethostname(name, sizeof name) == -1 || printf("%s\n", name) < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}


(.. java.net.InetAddress getLocalHost getHostName)


       identification division.
       program-id. hostname.

       data division.
       working-storage section.
       01 hostname pic x(256).
       01 nullpos  pic 999 value 1.

       procedure division.
       call "gethostname" using hostname by value length of hostname
       string hostname delimited by low-value into hostname
           with pointer nullpos
       display "Host: " hostname(1 : nullpos - 1)
       goback.
       end program hostname.


os = require 'os'
console.log os.hostname()


(defun get-host-name ()
    #+(or sbcl ccl) (machine-instance)
    #+clisp (let ((s (machine-instance))) (subseq s 0 (position #\Space s)))
    #-(or sbcl ccl clisp) (error "get-host-name not implemented"))


import std.stdio, std.socket;

void main() {
    writeln(Socket.hostName());
}


program ShowHostName;

{$APPTYPE CONSOLE}

uses Windows;

var
  lHostName: array[0..255] of char;
  lBufferSize: DWORD;
begin
  lBufferSize := 256;
  if GetComputerName(lHostName, lBufferSize) then
    Writeln(lHostName)
  else
    Writeln('error getting host name');
end.


program HostTest
  character(len=128) :: name
  call hostnm(name)
  print *, name
end program HostTest


' FB 1.05.0 Win64

' On Windows 10, the command line utility HOSTNAME.EXE prints the 'hostname' to the console.
' We can execute this remotely and read from its 'stdin' stream as follows:

Dim As String hostname
Open Pipe "hostname" For Input As #1
Input #1, hostname
Close #1
Print hostname
Print
Print "Press any key to quit"
Sleep


Public Sub Main()

Print System.Host

End


package main

import (
	"fmt"
	"os"
)

func main() {
	fmt.Println(os.Hostname())
}


import Network.BSD
main = do hostName <- getHostName
          putStrLn hostName


NB. Load the socket libraries

  load 'socket'
  coinsert 'jsocket'

NB. fetch and implicitly display the hostname

  > {: sdgethostname ''

NB. If fetching the hostname is the only reason for loading the socket libraries,
NB. and the hostname is fetched only once, then use a 'one-liner' to accomplish it:

  > {: sdgethostname coinsert 'jsocket' [ load 'socket'


import java.net.*;
class DiscoverHostName {
 public static void main(final String[] args) {
  try {
   System.out.println(InetAddress.getLocalHost().getHostName());
  } catch (UnknownHostException e) { // Doesn't actually happen, but Java requires it be handled.
  }
 }
}


var network = new ActiveXObject('WScript.Network');
var hostname = network.computerName;
WScript.echo(hostname);


HOST=$(hostname) jq -n --arg hostname $(hostname) '[env.HOST, $hostname]'


var hn = exec("hostname", {retAll:true}).data.trim();


// version 1.1.4

import java.net.InetAddress

fun main(args: Array<String>) {
    println(InetAddress.getLocalHost().hostName)
}


lpBuffer$=Space$(128) + Chr$(0)
struct SIZE,sz As Long
SIZE.sz.struct=Len(lpBuffer$)

calldll #kernel32, "GetComputerNameA",lpBuffer$ as ptr, SIZE as struct, result as Long
CurrentComputerName$=Trim$(Left$(lpBuffer$, SIZE.sz.struct))

print CurrentComputerName$


implement Hostname;

include "sys.m"; sys: Sys;
include "draw.m";

Hostname: module {
	init: fn(nil: ref Draw->Context, nil: list of string);
};

init(nil: ref Draw->Context, nil: list of string)
{
	sys = load Sys Sys->PATH;
	buf := array[Sys->ATOMICIO] of byte;

	fd := sys->open("/dev/sysname", Sys->OREAD);
	if(fd == nil)
		die("Couldn't open /dev/sysname");

	n := sys->read(fd, buf, len buf - 1);
	if(n < 1)
		die("Couldn't read /dev/sysname");

	buf[n++] = byte '\n';
	sys->write(sys->fildes(1), buf, n);
}

die(s: string)
{
	sys->fprint(sys->fildes(2), "hostname: %s: %r", s);
	raise "fail:errors";
}


sx = xtra("Shell").new()
if the platform contains "win" then
  hostname = sx.shell_cmd("hostname", ["eol":RETURN]).line[1] -- win 7 or later
else
  hostname = sx.shell_cmd("hostname", RETURN).line[1]
end if


socket = require "socket"
print( socket.dns.gethostname() )


Module Host {
      \\ one way
      Print computer$
      \\ second way
      Declare objNetwork "WScript.Network"
      With objNetwork,  "ComputerName" as cName$
      Print cName$, cName$=Computer$
      Declare objNetwork Nothing
}
Host


MODULE Hostname EXPORTS Main;

IMPORT IO, OSConfig;

BEGIN
  IO.Put(OSConfig.HostName() & "\n");
END Hostname.


/* NetRexx */
options replace format comments java crossref savelog symbols binary

say InetAddress.getLocalHost.getHostName


MODULE HostName;
IMPORT
  OS:ProcessParameters,
  Out;
BEGIN
  Out.Object("Host: " + ProcessParameters.GetEnv("HOSTNAME"));Out.Ln
END HostName.


use Net;

bundle Default {
  class Hello {
    function : Main(args : String[]) ~ Nil {
      TCPSocket->HostName()->PrintLine();
    }
  }
}


NSLog(@"%@", [[NSProcessInfo processInfo] hostName]);


str = externstr("hostname")[1];
str = externstr("uname -n")[1];


Program HostName;

uses
  unix;

begin
  writeln('The name of this computer is: ', GetHostName);
end.


without js -- (system_exec, file i/o)
constant tmp = "hostname.txt",
         cmd = iff(platform()=WINDOWS?"hostname":"uname -n")
{} = system_exec(sprintf("%s > %s",{cmd,tmp}),4)
string host = trim(get_text(tmp))
{} = delete_file("hostname.txt")
?host


import System;

int main(){
   write(gethostname() + "\n");
}


SET serveroutput ON
BEGIN
  DBMS_OUTPUT.PUT_LINE(UTL_INADDR.GET_HOST_NAME);
END;


import socket
host = socket.gethostname()


#lang racket/base
(require racket/os)
(gethostname)


say value('COMPUTERNAME',,"ENVIRONMENT")
say value('OS',,"ENVIRONMENT")


require 'socket'
host = Socket.gethostname


print Platform$    ' OS where Run BASIC is being hosted
print UserInfo$    ' Information about the user's web browser
print UserAddress$ ' IP address of the user


fn main() {
    match hostname::get_hostname() {
        Some(host) => println!("hostname: {}", host),
        None => eprintln!("Could not get hostname!"),
    }
}


$ include "seed7_05.s7i";
  include "socket.s7i";

const proc: main is func
  begin
    writeln(getHostname);
  end func;


var sys = frequire('Sys::Hostname');
var host = sys.hostname;


SELECT HOST_NAME FROM SYSIBMADM.ENV_SYS_INFO


2 import gethostname
1024 chars is-array foo
foo 1024 gethostname
foo type


out (ursa.net.localhost.name) endl console


#import cli

hostname = ~&hmh+ (ask bash)/<>+ <'hostname'>!


Set objNetwork = CreateObject("WScript.Network")
WScript.Echo objNetwork.ComputerName


Option Explicit

Private Declare Function GetComputerName Lib "kernel32.dll" Alias "GetComputerNameW" _
  (ByVal lpBuffer As Long, ByRef nSize As Long) As Long

Private Const MAX_COMPUTERNAME_LENGTH As Long = 31
Private Const NO_ERR As Long = 0

Private Function Hostname() As String
Dim i As Long, l As Long, s As String
  s = Space$(MAX_COMPUTERNAME_LENGTH)
  l = Len(s) + 1
  i = GetComputerName(StrPtr(s), l)
  Debug.Assert i <> 0
  Debug.Assert l <> 0
  Hostname = Left$(s, l)
End Function

Sub Main()
  Debug.Assert Hostname() = Environ$("COMPUTERNAME")
End Sub


/* hostname.wren */
class Host {
    foreign static name() // the code for this is provided by Go
}

System.print(Host.name())


USING: formatting kernel make math math.parser math.primes
math.primes.factors math.ranges present prettyprint sequences
sequences.extras ;

: squish ( seq -- n ) [ present ] map-concat dec> ;

: next ( m -- n ) factors squish ; inline

: (chain) ( n -- ) [ dup prime? ] [ dup , next ] until , ;

: chain ( n -- seq ) [ (chain) ] { } make ;

: prime. ( n -- ) dup "HP%d = %d\n" printf ;

: setup ( seq -- n s r ) unclip-last swap dup length 1 [a,b] ;

: multi. ( n -- ) chain setup [ "HP%d(%d) = " printf ] 2each . ;

: chain. ( n -- ) dup prime? [ prime. ] [ multi. ] if ;

2 20 [a,b] [ chain. ] each


package main

import (
    "fmt"
    "math/big"
    "rcu"
    "sort"
)

var zero = new(big.Int)
var one = big.NewInt(1)
var two = big.NewInt(2)
var three = big.NewInt(3)
var four = big.NewInt(4)
var five = big.NewInt(5)
var six = big.NewInt(6)

// simple wheel based prime factors routine for BigInt
func primeFactorsWheel(m *big.Int) []*big.Int {
    n := new(big.Int).Set(m)
    t := new(big.Int)
    inc := []*big.Int{four, two, four, two, four, six, two, six}
    var factors []*big.Int
    for t.Rem(n, two).Cmp(zero) == 0 {
        factors = append(factors, two)
        n.Quo(n, two)
    }
    for t.Rem(n, three).Cmp(zero) == 0 {
        factors = append(factors, three)
        n.Quo(n, three)
    }
    for t.Rem(n, five).Cmp(zero) == 0 {
        factors = append(factors, five)
        n.Quo(n, five)
    }
    k := big.NewInt(7)
    i := 0
    for t.Mul(k, k).Cmp(n) <= 0 {
        if t.Rem(n, k).Cmp(zero) == 0 {
            factors = append(factors, new(big.Int).Set(k))
            n.Quo(n, k)
        } else {
            k.Add(k, inc[i])
            i = (i + 1) % 8
        }
    }
    if n.Cmp(one) > 0 {
        factors = append(factors, n)
    }
    return factors
}

func pollardRho(n *big.Int) *big.Int {
    g := func(x, n *big.Int) *big.Int {
        x2 := new(big.Int)
        x2.Mul(x, x)
        x2.Add(x2, one)
        return x2.Mod(x2, n)
    }
    x, y, d := new(big.Int).Set(two), new(big.Int).Set(two), new(big.Int).Set(one)
    t, z := new(big.Int), new(big.Int).Set(one)
    count := 0
    for {
        x = g(x, n)
        y = g(g(y, n), n)
        t.Sub(x, y)
        t.Abs(t)
        t.Mod(t, n)
        z.Mul(z, t)
        count++
        if count == 100 {
            d.GCD(nil, nil, z, n)
            if d.Cmp(one) != 0 {
                break
            }
            z.Set(one)
            count = 0
        }
    }
    if d.Cmp(n) == 0 {
        return new(big.Int)
    }
    return d
}

func primeFactors(m *big.Int) []*big.Int {
    n := new(big.Int).Set(m)
    var factors []*big.Int
    lim := big.NewInt(1e9)
    for n.Cmp(one) > 0 {
        if n.Cmp(lim) > 0 {
            d := pollardRho(n)
            if d.Cmp(zero) != 0 {
                factors = append(factors, primeFactorsWheel(d)...)
                n.Quo(n, d)
                if n.ProbablyPrime(10) {
                    factors = append(factors, n)
                    break
                }
            } else {
                factors = append(factors, primeFactorsWheel(n)...)
                break
            }
        } else {
            factors = append(factors, primeFactorsWheel(n)...)
            break
        }
    }
    sort.Slice(factors, func(i, j int) bool { return factors[i].Cmp(factors[j]) < 0 })
    return factors
}

func main() {
    list := make([]int, 20)
    for i := 2; i <= 20; i++ {
        list[i-2] = i
    }
    list[19] = 65
    for _, i := range list {
        if rcu.IsPrime(i) {
            fmt.Printf("HP%d = %d\n", i, i)
            continue
        }
        n := 1
        j := big.NewInt(int64(i))
        h := []*big.Int{j}
        for {
            pf := primeFactors(j)
            k := ""
            for _, f := range pf {
                k += fmt.Sprintf("%d", f)
            }
            j, _ = new(big.Int).SetString(k, 10)
            h = append(h, j)
            if j.ProbablyPrime(10) {
                for l := n; l > 0; l-- {
                    fmt.Printf("HP%d(%d) = ", h[n-l], l)
                }
                fmt.Println(h[n])
                break
            } else {
                n++
            }
        }
    }
}


using Primes

function homeprimechain(n::BigInt)
    isprime(n) && return [n]
    concat = prod(string(i)^j for (i, j) in factor(n).pe)
    return pushfirst!(homeprimechain(parse(BigInt, concat)), n)
end
homeprimechain(n::Integer) = homeprimechain(BigInt(n))

function printHPiter(n, numperline = 4)
    chain = homeprimechain(n)
    len = length(chain)
    for (i, ent) in enumerate(chain)
        print(i < len ? "HP$ent" * "($(len - i)) = " * (i % numperline == 0 ? "\n" : "") : "$ent is prime.\n\n")
    end
end

for i in [2:20; 65]
   print("Home Prime chain for $i: ")
   printHPiter(i)
end


ClearAll[HP, HPChain]
HP[n_] := FromDigits[Catenate[IntegerDigits /@ Sort[Catenate[ConstantArray @@@ FactorInteger[n]]]]]
HPChain[n_] := NestWhileList[HP, n, PrimeQ/*Not]
Row[Prepend["Home prime chain for " <> ToString[#] <> ": "]@Riffle[HPChain[#], ", "]] & /@ Range[2, 20] // Column
Row[Prepend["Home prime chain for 65: "]@Riffle[HPChain[65], ", "]]


import algorithm, sequtils, strformat, strutils
import bignum

let
  Two = newInt(2)
  Three = newInt(3)
  Five = newInt(5)

proc primeFactorsWheel(n: Int): seq[Int] =
  const Inc = [4, 2, 4, 2, 4, 6, 2, 6]
  var n = n
  while (n mod 2).isZero:
    result.add Two
    n = n div 2
  while (n mod 3).isZero:
    result.add Three
    n = n div 3
  while (n mod 5).isZero:
    result.add Five
    n = n div 5
  var k = 7
  var i = 0
  while k * k <= n:
    if (n mod k).isZero:
      result.add newInt(k)
      n = n div k
    else:
      inc k, Inc[i]
      i = (i + 1) and 7
  if n > 1: result.add n

func pollardRho(n : Int): Int =

  func g(x, y: Int): Int = (x * x + 1) mod y

  var x, y = newInt(2)
  var z, d = newInt(1)
  var count = 0
  while true:
    x = g(x, n)
    y = g(g(y, n), n)
    d = abs(x - y) mod n
    z *= d
    inc count
    if count == 100:
      d = gcd(z, n)
      if d != 1: break
      z = newInt(1)
      count = 0
  if d == n: return newInt(0)
  result = d

proc primeFactors(n: Int): seq[Int] =
  var n = n
  while n > 1:
    if n > 100_000_000:
      let d = pollardRho(n)
      if not d.isZero:
        result.add primeFactorsWheel(d)
        n = n div d
        if n.probablyPrime(25) != 0:
          result.add n
          break
      else:
        result.add primeFactorsWheel(n)
        break
    else:
      result.add primeFactorsWheel(n)
      break
  result.sort()

let list = toSeq(2..20) & 65
for i in list:
  if i in [2, 3, 5, 7, 11, 13, 17, 19]:
    echo &"HP{i} = {i}"
    continue
  var n = 1
  var j = newInt(i)
  var h = @[j]
  while true:
    j = newInt(primeFactors(j).join())
    h.add j
    if j.probablyPrime(25) != 0:
      for k in countdown(n, 1):
        stdout.write &"HP{h[n-k]}({k}) = "
      echo h[n]
      break
    else:
      inc n


use strict;
use warnings;
use ntheory 'factor';

for my $m (2..20, 65) {
    my (@steps, @factors) = $m;
    push @steps, join '_', @factors while (@factors = factor $steps[-1] =~ s/_//gr) > 1;
    my $step = $#steps;
    if ($step >= 1) { print 'HP' . $_ . "($step) = " and --$step or last for @steps }
    else            { print "HP$m = " }
    print "$steps[-1]\n";
}


with javascript_semantics
requires("1.0.0")
include mpfr.e

procedure test(integer n)
    string s = sprintf("%d",n), lastp = ""
    sequence res = {s}
    atom t0 = time()
    while true do
        s = substitute(s,"_","")
        sequence rr = mpz_pollard_rho(s,true)
        if length(rr)=1 then exit end if
        s = join(rr,"_")
        res = append(res,s)
    end while
    atom t = time()-t0
    integer niter = length(res)-1
    string iter = iff(niter>1?sprintf("(%d)",niter):""),
           e = iff(t>0.1?" ["&elapsed(t)&"]":"")
    s = sprintf("HP%d%s = ",{n,iter})
    if niter=0 then
        printf(1,"%s%d %s\n",{s,n,e})
    else
        for i=2 to niter do
            niter -= 1
            printf(1,"%sHP%s(%d)\n",{s,res[i],niter})
            if i=2 then
                s = repeat(' ',length(s))
                s[-2] = '='
            end if
        end for
        printf(1,"%s%s %s\n",{s,res[$],e})
    end if
end procedure
papply(tagset(20,2)&65,test)


use Prime::Factor;

my $start = now;

(flat 2..20, 65).map: -> $m {
    my ($now, @steps, @factors) = now, $m;

    @steps.push: @factors.join('_') while (@factors = prime-factors @steps[*-1].Int) > 1;

    say (my $step = +@steps) > 1 ?? (@steps[0..*-2].map( { "HP$_\({--$step})" } ).join: ' = ') !! ("HP$m"),
      " = ", @steps[*-1], "  ({(now - $now).fmt("%0.3f")} seconds)";
}

say "Total elapsed time: {(now - $start).fmt("%0.3f")} seconds\n";

say 'HP49:';
my ($now, @steps, @factors) = now, 49;
my $step = 0;
while (@factors = prime-factors @steps[*-1].Int) > 1 {
    @steps.push: @factors.join('_');
    say "HP{@steps[$step].Int}\(n - {$step++}) = ", @steps[*-1], "  ({(now - $now).fmt("%0.3f")} seconds)";
    $now = now;
    last if $step > 30;
}


/*REXX program finds and displays the   home prime   of a range of positive integers.   */
numeric digits 20                                /*ensure handling of larger integers.  */
parse arg  LO HI .                               /*obtain optional arguments from the CL*/
if LO=='' | LO=="," then LO=  2                  /*Not specified?  Then use the default.*/
if HI=='' | HI=="," then HI= 20                  /* "     "         "   "   "     "     */
@hpc= 'home prime chain for '                    /*a literal used in two SAY statements.*/
                                 w= length(HI)   /*HI width, used for output alignment. */
       do j=max(2, LO)  to HI                    /*find home primes for an integer range*/
       pf= factr(j);             f= words(pf)    /*get prime factors; number of factors.*/
       if f==1  then do;  say @hpc j": "  j  ' is prime.';  iterate;  end   /*J is prime*/
       xxx.1= j                                  /*save  J  in the first array element. */
                do n=2  until #==1               /*keep processing until we find a prime*/
                xxx.n= space(pf, 0)              /*obtain factors of a concatenated p.f.*/
                pf= factr(xxx.n);   #= words(pf) /*assign factors to PF;  # of factors. */
                end   /*n*/
       ee= n                                     /*save  EE  as the final (last) prime. */
       n= n - 1;   z= n                          /*adjust N (for DO loop); assign N to Z*/
       $=                                        /*nullify the string of   home primes. */
                do m=1  for n                    /*build a list  ($)  of     "     "    */
                $= $  'HP'xxx.m"("z') ─► '       /*concatenate to string of  "     "    */
                z= z - 1                         /*decrease the index counter by unity. */
                end   /*m*/                      /* [↑]  the index counter is decreasing*/

       say @hpc right(j, w)":"   $   xxx.ee  ' is prime.'  /*show string of home primes.*/
       end   /*n*/
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
factr: procedure;  parse arg x 1 d,$             /*set X, D  to argument 1;  $  to null.*/
       if x==1  then return ''                   /*handle the special case of   X = 1.  */
         do  while x//2==0; $= $ 2; x= x% 2; end /*append all the  2  factors of new  X.*/
         do  while x//3==0; $= $ 3; x= x% 3; end /*   "    "   "   3     "     "  "   " */
         do  while x//5==0; $= $ 5; x= x% 5; end /*   "    "   "   5     "     "  "   " */
         do  while x//7==0; $= $ 7; x= x% 7; end /*   "    "   "   7     "     "  "   " */
       q= 1;                              r= 0   /*R:  will be iSqrt(x).             ___*/
         do  while q<=x; q=q*4; end              /*these two lines compute integer  √ X */
         do  while q>1;  q=q%4; _= d-r-q; r= r%2; if _>=0  then do; d= _; r= r+q; end; end

         do k=11  by 6  to r                     /*insure that  J  isn't divisible by 3.*/
         parse var k  ''  -1  _                  /*obtain the last decimal digit of  K. */
         if _\==5  then  do  while x//k==0;  $=$ k;  x=x%k;  end    /*maybe reduce by K.*/
         if _ ==3  then iterate                  /*Is next  Y  is divisible by 5?  Skip.*/
         y= k+2;         do  while x//y==0;  $=$ y;  x=x%y;  end    /*maybe reduce by Y.*/
         end   /*k*/
                                                 /* [↓]  The $ list has a leading blank.*/
       if x==1  then return $                    /*Is residual=unity? Then don't append.*/
                     return $ x                  /*return   $   with appended residual. */


for n in (2..20, 65) {

    var steps = []
    var orig = n

    for (var f = n.factor; true; f = n.factor) {
        steps << f
        n = Num(f.join)
        break if n.is_prime
    }

    say ("HP(#{orig}) = ", steps.map { .join('_') }.join(' -> '))
}


import "/math" for Int
import "/big" for BigInt

var list = (2..20).toList
list.add(65)
for (i in list) {
    if (Int.isPrime(i)) {
        System.print("HP%(i) = %(i)")
        continue
    }
    var n = 1
    var j = BigInt.new(i)
    var h = [j]
    while (true) {
        var k = BigInt.primeFactors(j).reduce("") { |acc, f| acc + f.toString }
        j = BigInt.new(k)
        h.add(j)
        if (j.isProbablePrime(2)) {
            for (l in n...0) System.write("HP%(h[n-l])(%(l)) = ")
            System.print(h[n])
            break
        } else {
            n = n + 1
        }
    }
}


"http://www.rosettacode.org" net:get drop >s .


report z_http.

cl_http_client=>create_by_url(
  exporting
    url                = `http://rosettacode.org/robots.txt`
  importing
    client             = data(http_client)
  exceptions
    argument_not_found = 1
    plugin_not_active  = 2
    internal_error     = 3
    others             = 4 ).

if sy-subrc <> 0.
  data(error_message) = switch string( sy-subrc
    when 1 then `argument_not_found`
    when 2 then `plugin_not_active`
    when 3 then `internal_error`
    when 4 then `other error` ).

  write error_message.
  exit.
endif.

data(rest_http_client) = cast if_rest_client( new cl_rest_http_client( http_client ) ).

rest_http_client->get( ).

data(response_string) = rest_http_client->get_response_entity( )->get_string_data( ).

split response_string at cl_abap_char_utilities=>newline into table data(output_table).

loop at output_table assigning field-symbol(<output_line>).
  write / <output_line>.
endloop.


package
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.net.*;

    public class RequestExample extends Sprite
    {
        public function RequestExample()
        {
            var loader:URLLoader = new URLLoader();
            loader.addEventListener(Event.COMPLETE, loadComplete);
            loader.load(new URLRequest("http://www.rosettacode.org"));
        }

        private function loadComplete(evt:Event):void
        {
            trace(evt.target.data);
        }
    }
}


with Ada.Text_IO; use Ada.Text_IO;

with AWS.Client;
with AWS.Response;

procedure HTTP_Request is
begin
   Put_Line (AWS.Response.Message_Body (AWS.Client.Get (URL => "http://www.rosettacode.org")));
end HTTP_Request;


STRING domain="rosettacode.org";
STRING page="wiki/Main_Page";

STRING re success="^HTTP/[0-9.]* 200";
STRING re result description="^HTTP/[0-9.]* [0-9]+ [a-zA-Z ]*";
STRING re doctype ="\s\s<!DOCTYPE html PUBLIC ""[^>]+"">\s+";

PROC html page = (REF STRING page) BOOL: (
     BOOL out=grep in string(re success, page, NIL, NIL) = 0;
     IF INT start, end;
        grep in string(re result description, page, start, end) = 0
     THEN
        page:=page[end+1:];
        IF grep in string(re doctype, page, start, end) = 0
        THEN page:=page[start+2:]
        ELSE print ("unknown format retrieving page")
        FI
     ELSE print ("unknown error retrieving page")
     FI;
     out
);

IF STRING reply;
   INT rc =
      http content (reply, domain, "http://"+domain+"/"+page, 0);
   rc = 0 AND html page (reply)
THEN print (reply)
ELSE print (strerror (rc))
FI


#include <hopper.h>
main:
   s=`curl -s -L https://rosettacode.org/wiki/HTTP`
   {s}len, lenght=0, mov(lenght)
   {"Size = ",lenght,"\nContent = \n",s}println
exit(0)


UrlDownloadToFile, http://rosettacode.org, url.html
Run, cmd /k type url.html


BEGIN {
  site="en.wikipedia.org"
  path="/wiki/"
  name="Rosetta_Code"

  server = "/inet/tcp/0/" site "/80"
  print "GET " path name " HTTP/1.0" |& server
  print "Host: " site |& server
  print "\r\n\r\n" |& server

  while ( (server |& getline fish) > 0 ) {
    if ( ++scale == 1 )
      ship = fish
    else
      ship = ship "\n" fish
  }
  close(server)

  print ship
}


'
' Read and display a website
'
IF AMOUNT(ARGUMENT$) = 1 THEN
    website$ = "www.basic-converter.org"
ELSE
    website$ = TOKEN$(ARGUMENT$, 2)
ENDIF

OPEN website$ & ":80" FOR NETWORK AS mynet
SEND "GET / HTTP/1.1\r\nHost: " & website$ & "\r\n\r\n" TO mynet
REPEAT
    RECEIVE dat$ FROM mynet
    total$ = total$ & dat$
UNTIL ISFALSE(WAIT(mynet, 500))
CLOSE NETWORK mynet
PRINT total$


      SYS "LoadLibrary", "URLMON.DLL" TO urlmon%
      SYS "GetProcAddress", urlmon%, "URLDownloadToFileA" TO URLDownloadToFile

      url$ = "http://www.bbcbasic.co.uk/aboutus.html"
      file$ = @tmp$ + "rosetta.tmp"
      SYS URLDownloadToFile, 0, url$, file$, 0, 0 TO fail%
      IF fail% ERROR 100, "File download failed"

      OSCLI "TYPE """ + file$ + """"


#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>

int
main(void)
{
        CURL *curl;
        char buffer[CURL_ERROR_SIZE];

        if ((curl = curl_easy_init()) != NULL) {
                curl_easy_setopt(curl, CURLOPT_URL, "http://www.rosettacode.org/");
                curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
                curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, buffer);
                if (curl_easy_perform(curl) != CURLE_OK) {
                        fprintf(stderr, "%s\n", buffer);
                        return EXIT_FAILURE;
                }
                curl_easy_cleanup(curl);
        }
        return EXIT_SUCCESS;
}


using System;
using System.Text;
using System.Net;

class Program
{
    static void Main(string[] args)
    {
        WebClient wc = new WebClient();
        string content = wc.DownloadString("http://www.google.com");
        Console.WriteLine(content);
    }
}


#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>

int main() {
	WSADATA wsaData;
	WSAStartup( MAKEWORD( 2, 2 ), &wsaData );

	addrinfo *result = NULL;
	addrinfo hints;

	ZeroMemory( &hints, sizeof( hints ) );
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;

	getaddrinfo( "74.125.45.100", "80", &hints, &result ); // http://www.google.com

	SOCKET s = socket( result->ai_family, result->ai_socktype, result->ai_protocol );

	connect( s, result->ai_addr, (int)result->ai_addrlen );

	freeaddrinfo( result );

	send( s, "GET / HTTP/1.0\n\n", 16, 0 );

	char buffer[512];
	int bytes;

	do {
		bytes = recv( s, buffer, 512, 0 );

		if ( bytes > 0 )
			std::cout.write(buffer, bytes);
	} while ( bytes > 0 );

	return 0;
}


USER>Set HttpRequest=##class(%Net.HttpRequest).%New()
USER>Set HttpRequest.Server="checkip.dyndns.org"
USER>Do HttpRequest.Get("/")
USER>Do HttpRequest.HttpResponse.Data.OutputToDevice()


(defn get-http [url]
  (let [sc (java.util.Scanner.
	    (.openStream (java.net.URL. url)))]
    (while (.hasNext sc)
      (println (.nextLine sc)))))
(get-http "http://www.rosettacode.org")


COBOL  >>SOURCE FORMAT IS FIXED
       identification division.
       program-id. curl-rosetta.

       environment division.
       configuration section.
       repository.
           function read-url
           function all intrinsic.

       data division.
       working-storage section.

       copy "gccurlsym.cpy".

       01 web-page             pic x(16777216).
       01 curl-status          usage binary-long.

       01 cli                  pic x(7) external.
          88 helping           values "-h", "-help", "help", spaces.
          88 displaying        value "display".
          88 summarizing       value "summary".

      *> ***************************************************************
       procedure division.
       accept cli from command-line
       if helping then
           display "./curl-rosetta [help|display|summary]"
           goback
       end-if

      *>
      *> Read a web resource into fixed ram.
      *>   Caller is in charge of sizing the buffer,
      *>     (or getting trickier with the write callback)
      *> Pass URL and working-storage variable,
      *>   get back libcURL error code or 0 for success

       move read-url("http://www.rosettacode.org", web-page)
         to curl-status

       perform check
       perform show

       goback.
      *> ***************************************************************

      *> Now tesing the result, relying on the gccurlsym
      *>   GnuCOBOL Curl Symbol copy book
       check.
       if curl-status not equal zero then
           display
               curl-status " "
               CURLEMSG(curl-status) upon syserr
       end-if
       .

      *> And display the page
       show.
       if summarizing then
           display "Length: " stored-char-length(web-page)
       end-if
       if displaying then
           display trim(web-page trailing) with no advancing
       end-if
       .

       REPLACE ALSO ==:EXCEPTION-HANDLERS:== BY
       ==
      *> informational warnings and abends
       soft-exception.
         display space upon syserr
         display "--Exception Report-- " upon syserr
         display "Time of exception:   " current-date upon syserr
         display "Module:              " module-id upon syserr
         display "Module-path:         " module-path upon syserr
         display "Module-source:       " module-source upon syserr
         display "Exception-file:      " exception-file upon syserr
         display "Exception-status:    " exception-status upon syserr
         display "Exception-location:  " exception-location upon syserr
         display "Exception-statement: " exception-statement upon syserr
       .

       hard-exception.
           perform soft-exception
           stop run returning 127
       .
       ==.

       end program curl-rosetta.
      *> ***************************************************************

      *> ***************************************************************
      *>
      *> The function hiding all the curl details
      *>
      *> Purpose:   Call libcURL and read into memory
      *> ***************************************************************
       identification division.
       function-id. read-url.

       environment division.
       configuration section.
       repository.
           function all intrinsic.

       data division.
       working-storage section.

       copy "gccurlsym.cpy".

       replace also ==:CALL-EXCEPTION:== by
       ==
           on exception
               perform hard-exception
       ==.

       01 curl-handle          usage pointer.
       01 callback-handle      usage procedure-pointer.
       01 memory-block.
          05 memory-address    usage pointer sync.
          05 memory-size       usage binary-long sync.
          05 running-total     usage binary-long sync.
       01 curl-result          usage binary-long.

       01 cli                  pic x(7) external.
          88 helping           values "-h", "-help", "help", spaces.
          88 displaying        value "display".
          88 summarizing       value "summary".

       linkage section.
       01 url                  pic x any length.
       01 buffer               pic x any length.
       01 curl-status          usage binary-long.

      *> ***************************************************************
       procedure division using url buffer returning curl-status.
       if displaying or summarizing then
           display "Read: " url upon syserr
       end-if

      *> initialize libcurl, hint at missing library if need be
       call "curl_global_init" using by value CURL_GLOBAL_ALL
           on exception
               display
                   "need libcurl, link with -lcurl" upon syserr
               stop run returning 1
       end-call

      *> initialize handle
       call "curl_easy_init" returning curl-handle
           :CALL-EXCEPTION:
       end-call
       if curl-handle equal NULL then
           display "no curl handle" upon syserr
           stop run returning 1
       end-if

      *> Set the URL
       call "curl_easy_setopt" using
           by value curl-handle
           by value CURLOPT_URL
           by reference concatenate(trim(url trailing), x"00")
           :CALL-EXCEPTION:
       end-call

      *> follow all redirects
       call "curl_easy_setopt" using
           by value curl-handle
           by value CURLOPT_FOLLOWLOCATION
           by value 1
           :CALL-EXCEPTION:
       end-call

      *> set the call back to write to memory
       set callback-handle to address of entry "curl-write-callback"
       call "curl_easy_setopt" using
           by value curl-handle
           by value CURLOPT_WRITEFUNCTION
           by value callback-handle
           :CALL-EXCEPTION:
       end-call

      *> set the curl handle data handling structure
       set memory-address to address of buffer
       move length(buffer) to memory-size
       move 1 to running-total

       call "curl_easy_setopt" using
           by value curl-handle
           by value CURLOPT_WRITEDATA
           by value address of memory-block
           :CALL-EXCEPTION:
       end-call

      *> some servers demand an agent
       call "curl_easy_setopt" using
           by value curl-handle
           by value CURLOPT_USERAGENT
           by reference concatenate("libcurl-agent/1.0", x"00")
           :CALL-EXCEPTION:
       end-call

      *> let curl do all the hard work
       call "curl_easy_perform" using
           by value curl-handle
           returning curl-result
           :CALL-EXCEPTION:
       end-call

      *> the call back will handle filling ram, return the result code
       move curl-result to curl-status

      *> curl clean up, more important if testing cookies
       call "curl_easy_cleanup" using
           by value curl-handle
           returning omitted
           :CALL-EXCEPTION:
       end-call

       goback.

       :EXCEPTION-HANDLERS:

       end function read-url.
      *> ***************************************************************

      *> ***************************************************************
      *> Supporting libcurl callback
       identification division.
       program-id. curl-write-callback.

       environment division.
       configuration section.
       repository.
           function all intrinsic.

       data division.
       working-storage section.
       01 real-size            usage binary-long.

      *> libcURL will pass a pointer to this structure in the callback
       01 memory-block         based.
          05 memory-address    usage pointer sync.
          05 memory-size       usage binary-long sync.
          05 running-total     usage binary-long sync.

       01 content-buffer       pic x(65536) based.
       01 web-space            pic x(16777216) based.
       01 left-over            usage binary-long.

       linkage section.
       01 contents             usage pointer.
       01 element-size         usage binary-long.
       01 element-count        usage binary-long.
       01 memory-structure     usage pointer.

      *> ***************************************************************
       procedure division
           using
              by value contents
              by value element-size
              by value element-count
              by value memory-structure
          returning real-size.

       set address of memory-block to memory-structure
       compute real-size = element-size * element-count end-compute

      *> Fence off the end of buffer
       compute
           left-over = memory-size - running-total
       end-compute
       if left-over > 0 and < real-size then
           move left-over to real-size
       end-if

      *> if there is more buffer, and data not zero length
       if (left-over > 0) and (real-size > 1) then
           set address of content-buffer to contents
           set address of web-space to memory-address

           move content-buffer(1:real-size)
             to web-space(running-total:real-size)

           add real-size to running-total
       else
           display "curl buffer sizing problem" upon syserr
       end-if

       goback.
       end program curl-write-callback.


  <cfhttp url="http://www.rosettacode.org" result="result">
  <cfoutput>#result.FileContent#</cfoutput>


(defun wget-clisp (url)
    (ext:with-http-input (stream url)
        (loop for line = (read-line stream nil nil)
            while line
            do (format t "~a~%" line))))


require "http/client"

HTTP::Client.get("http://google.com")


void main() {
  import std.stdio, std.net.curl;
  writeln(get("http://google.com"));
}


import 'dart:io';
void main(){
  var url = 'http://rosettacode.org';
  var client = new HttpClient();
  client.getUrl(Uri.parse(url))
        .then((HttpClientRequest request)   => request.close())
        .then((HttpClientResponse response) => response.pipe(stdout));
}


program HTTP;

{$APPTYPE CONSOLE}

{$DEFINE DEBUG}

uses
  Classes,
  httpsend; // Synapse httpsend class

var
  Response: TStrings;
  HTTPObj: THTTPSend;

begin
  HTTPObj := THTTPSend.Create;
  try
    { Stringlist object to capture HTML returned
      from URL }
    Response := TStringList.Create;
    try
      if HTTPObj.HTTPMethod('GET','http://www.mgis.uk.com') then
        begin
          { Load HTTP Document into Stringlist }
          Response.LoadFromStream(HTTPObj.Document);
          { Write the response to the console window }
          Writeln(Response.Text);
        end
        else
        Writeln('Error retrieving data');

    finally
      Response.Free;
    end;

  finally
    HTTPObj.Free;
  end;

  // Keep console window open
  Readln;

end.


select "http"
select "std"

http("http://www.rosettacode.org", ::echo)


when (def t := <http://www.rosettacode.org> <- getText()) -> {
    println(t)
}


;; asynchronous call back definition
(define (success name text) (writeln 'Loaded name) (writeln text))
;;
(file->string success "http://www.google.com")


(let ((buffer (url-retrieve-synchronously "http://www.rosettacode.org")))
  (unwind-protect
      (with-current-buffer buffer
        (message "%s" (buffer-substring url-http-end-of-headers (point-max))))
    (kill-buffer buffer)))


-module(main).
-export([main/1]).

main([Url|[]]) ->
   inets:start(),
   case http:request(Url) of
       {ok, {_V, _H, Body}} -> io:fwrite("~p~n",[Body]);
       {error, Res} -> io:fwrite("~p~n", [Res])
   end.


let wget (url : string) =
    use c = new System.Net.WebClient()
    c.DownloadString(url)

printfn "%s" (wget "http://www.rosettacode.org/")


USE: http.client
"http://www.rosettacode.org" http-get nip print


include unix/socket.fs

s" localhost" 80 open-socket
dup s\" GET / HTTP/1.0\n\n" rot write-socket
dup pad 8092 read-socket  type
close-socket


Dim As String urlfile
urlfile="start http://rosettacode.org/wiki/Main_Page"

Print urlfile

Shell(urlfile)

Print !"\n--- pulsa RETURN para continuar ---"
Sleep


#listix#

   <main>
      LOOP, TEXT FILE, http://www.rosettacode.org
          , BODY, @<value>


package main

import (
    "io"
    "log"
    "net/http"
    "os"
)

func main() {
    r, err := http.Get("http://rosettacode.org/robots.txt")
    if err != nil {
        log.Fatalln(err)
    }
    io.Copy(os.Stdout, r.Body)
}


new URL("http://www.rosettacode.org").eachLine { println it }


Start,Programs,Applications,Mozilla Firefox,Inputbox:address bar>www.rosettacode.org,Button:Go,
Click:Area:browser window,Type:[Control A],[Control C],Start,Programs,Accessories,Notepad,
Menu:Edit,Paste


import Network.Browser
import Network.HTTP
import Network.URI

main = do
    rsp <- Network.Browser.browse $ do
        setAllowRedirects True
        setOutHandler $ const (return ())
        request $ getRequest "http://www.rosettacode.org/"
    putStrLn $ rspBody $ snd rsp


link cfunc
procedure main(arglist)
   get(arglist[1])
end

procedure get(url)
   local f, host, port, path
   url ? {
         ="http://" | ="HTTP://"
         host := tab(upto(':/') | 0)
         if not (=":" & (port := integer(tab(upto('/'))))) then port := 80
         if pos(0) then path := "/" else path := tab(0)
   }
   write(host)
   write(path)
   f := tconnect(host, port) | stop("Unable to connect")
   writes(f, "GET ", path | "/" ," HTTP/1.0\r\n\r\n")
   while write(read(f))
end


import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.Charset;

public class Main {
    public static void main(String[] args) {
        var request = HttpRequest.newBuilder(URI.create("https://www.rosettacode.org"))
                .GET()
                .build();

        HttpClient.newHttpClient()
                .sendAsync(request, HttpResponse.BodyHandlers.ofString(Charset.defaultCharset()))
                .thenApply(HttpResponse::body)
                .thenAccept(System.out::println)
                .join();
    }
}


var req = new XMLHttpRequest();
req.onload = function() {
  console.log(this.responseText);
};

req.open('get', 'http://rosettacode.org', true);
req.send()