RosettaCodeData/Task/Rosetta-Code-Rank-languages.../Cache-ObjectScript/rosetta-code-rank-languages...

81 lines
2.3 KiB
Plaintext

Class Utils.Net.RosettaCode [ Abstract ]
{
ClassMethod GetTopLanguages(pHost As %String = "", pPath As %String = "", pTop As %Integer = 10) As %Status
{
// check input parameters
If $Match(pHost, "^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$")=0 {
Quit $$$ERROR($$$GeneralError, "Invalid host name.")
}
// create http request and get page
Set req=##class(%Net.HttpRequest).%New()
Set req.Server=pHost
Do req.Get(pPath)
// create xml stream with doc type
Set xml=##class(%Stream.GlobalCharacter).%New()
Set sc=xml.WriteLine("<!DOCTYPE doc_type [")
Set sc=xml.WriteLine($Char(9)_"<!ENTITY nbsp '&#160;'>")
Set sc=xml.WriteLine($Char(9)_"<!ENTITY amp '&#38;'>")
Set sc=xml.WriteLine("]>")
// copy xhtml stream to xml stream
Set xhtml=req.HttpResponse.Data
Set xhtml.LineTerminator=$Char(10)
While 'xhtml.AtEnd {
Set line=xhtml.ReadLine()
If line["!DOCTYPE" Continue
If line["<g:plusone></g:plusone>" {
Continue
Set line="<g:plusone xmlns:g='http://base.google.com/ns/1.0'></g:plusone>"
}
Set sc=xml.WriteLine(line)
}
// create an instance of an %XML.XPATH.Document
Set sc=##class(%XML.XPATH.Document).CreateFromStream(xml, .xdoc)
If $$$ISERR(sc) Quit sc
// evaluate following 'XPath' expression
Set sc=xdoc.EvaluateExpression("//div[@id='bodyContent']//li", "a[contains(@href, '/Category:')]/ancestor::li", .res)
// iterate through list elements
Set array=##class(%ArrayOfDataTypes).%New()
Do {
Set dom=res.GetNext(.key)
If '$IsObject(dom) Quit
// get language name and members
Set lang=""
While dom.Read() {
If 'dom.HasValue Continue
If lang="" {
If $Locate(dom.Value, "User|Tasks|Omit|attention|operations|Solutions by") Quit
Set lang=dom.Value Continue
}
If dom.Value["members" {
Set members=+$ZStrip(dom.Value, "<>P")
Set list=array.GetAt(members)
Set $List(list, $ListLength(list)+1)=lang
Set sc=array.SetAt(list, members)
Quit
}
}
} While key'=""
If array.Count()=0 Quit $$$ERROR($$$GeneralError, "No languages found.")
// show top entries
Write "Top "_pTop_" Languages (as at "_$ZDate($HoroLog, 2)_"):", !
For count=1:1:pTop {
Set members=array.GetPrevious(.key)
If key="" Quit
Write $Justify(count, 3), ". ", key, " - ", $ListToString(members, ", "), !
}
// finished
Quit $$$OK
}
}