Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Produce a language-to-language conversion: from Groovy to C#, same semantics.
import java.net.URI [ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ].each { String url -> URI u = url.toURI() println """ |Parsing $url | scheme = ${u.scheme} | domain = ${u.host} | port = ${(u.port + 1) ? u.port : 'default' } | path = ${u.path ?: u.schemeSpecificPart} | query = ${u.query} | fragment = ${u.fragment}""".stripMargin() }
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Convert this Groovy snippet to C# and keep its semantics consistent.
import java.net.URI [ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ].each { String url -> URI u = url.toURI() println """ |Parsing $url | scheme = ${u.scheme} | domain = ${u.host} | port = ${(u.port + 1) ? u.port : 'default' } | path = ${u.path ?: u.schemeSpecificPart} | query = ${u.query} | fragment = ${u.fragment}""".stripMargin() }
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Write the same code in Java as shown below in Groovy.
import java.net.URI [ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ].each { String url -> URI u = url.toURI() println """ |Parsing $url | scheme = ${u.scheme} | domain = ${u.host} | port = ${(u.port + 1) ? u.port : 'default' } | path = ${u.path ?: u.schemeSpecificPart} | query = ${u.query} | fragment = ${u.fragment}""".stripMargin() }
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Port the provided Groovy code into Java while preserving the original functionality.
import java.net.URI [ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ].each { String url -> URI u = url.toURI() println """ |Parsing $url | scheme = ${u.scheme} | domain = ${u.host} | port = ${(u.port + 1) ? u.port : 'default' } | path = ${u.path ?: u.schemeSpecificPart} | query = ${u.query} | fragment = ${u.fragment}""".stripMargin() }
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Preserve the algorithm and functionality while converting the code from Groovy to Python.
import java.net.URI [ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ].each { String url -> URI u = url.toURI() println """ |Parsing $url | scheme = ${u.scheme} | domain = ${u.host} | port = ${(u.port + 1) ? u.port : 'default' } | path = ${u.path ?: u.schemeSpecificPart} | query = ${u.query} | fragment = ${u.fragment}""".stripMargin() }
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Maintain the same structure and functionality when rewriting this code in Python.
import java.net.URI [ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ].each { String url -> URI u = url.toURI() println """ |Parsing $url | scheme = ${u.scheme} | domain = ${u.host} | port = ${(u.port + 1) ? u.port : 'default' } | path = ${u.path ?: u.schemeSpecificPart} | query = ${u.query} | fragment = ${u.fragment}""".stripMargin() }
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Convert this Groovy snippet to VB and keep its semantics consistent.
import java.net.URI [ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ].each { String url -> URI u = url.toURI() println """ |Parsing $url | scheme = ${u.scheme} | domain = ${u.host} | port = ${(u.port + 1) ? u.port : 'default' } | path = ${u.path ?: u.schemeSpecificPart} | query = ${u.query} | fragment = ${u.fragment}""".stripMargin() }
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Translate this program into VB but keep the logic exactly as in Groovy.
import java.net.URI [ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ].each { String url -> URI u = url.toURI() println """ |Parsing $url | scheme = ${u.scheme} | domain = ${u.host} | port = ${(u.port + 1) ? u.port : 'default' } | path = ${u.path ?: u.schemeSpecificPart} | query = ${u.query} | fragment = ${u.fragment}""".stripMargin() }
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Convert this Groovy block to Go, preserving its control flow and logic.
import java.net.URI [ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ].each { String url -> URI u = url.toURI() println """ |Parsing $url | scheme = ${u.scheme} | domain = ${u.host} | port = ${(u.port + 1) ? u.port : 'default' } | path = ${u.path ?: u.schemeSpecificPart} | query = ${u.query} | fragment = ${u.fragment}""".stripMargin() }
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Convert this Groovy snippet to Go and keep its semantics consistent.
import java.net.URI [ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ].each { String url -> URI u = url.toURI() println """ |Parsing $url | scheme = ${u.scheme} | domain = ${u.host} | port = ${(u.port + 1) ? u.port : 'default' } | path = ${u.path ?: u.schemeSpecificPart} | query = ${u.query} | fragment = ${u.fragment}""".stripMargin() }
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Transform the following Haskell implementation into C#, maintaining the same output and logic.
module Main (main) where import Data.Foldable (for_) import Network.URI ( URI , URIAuth , parseURI , uriAuthority , uriFragment , uriPath , uriPort , uriQuery , uriRegName , uriScheme , uriUserInfo ) uriStrings :: [String] uriStrings = [ "https://bob:pass@example.com/place" , "foo://example.com:8042/over/there?name=ferret#nose" , "urn:example:animal:ferret:nose" , "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" , "ftp://ftp.is.co.za/rfc/rfc1808.txt" , "http://www.ietf.org/rfc/rfc2396.txt#header1" , "ldap://[2001:db8::7]/c=GB?objectClass?one" , "mailto:John.Doe@example.com" , "news:comp.infosystems.www.servers.unix" , "tel:+1-816-555-1212" , "telnet://192.0.2.16:80/" , "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ] trimmedUriScheme :: URI -> String trimmedUriScheme = init . uriScheme trimmedUriUserInfo :: URIAuth -> Maybe String trimmedUriUserInfo uriAuth = case uriUserInfo uriAuth of [] -> Nothing userInfo -> if last userInfo == '@' then Just (init userInfo) else Nothing trimmedUriPath :: URI -> String trimmedUriPath uri = case uriPath uri of '/' : t -> t; p -> p trimmedUriQuery :: URI -> Maybe String trimmedUriQuery uri = case uriQuery uri of '?' : t -> Just t; _ -> Nothing trimmedUriFragment :: URI -> Maybe String trimmedUriFragment uri = case uriFragment uri of '#' : t -> Just t; _ -> Nothing main :: IO () main = do for_ uriStrings $ \uriString -> do case parseURI uriString of Nothing -> putStrLn $ "Could not parse" ++ uriString Just uri -> do putStrLn uriString putStrLn $ " scheme = " ++ trimmedUriScheme uri case uriAuthority uri of Nothing -> return () Just uriAuth -> do case trimmedUriUserInfo uriAuth of Nothing -> return () Just userInfo -> putStrLn $ " user-info = " ++ userInfo putStrLn $ " domain = " ++ uriRegName uriAuth putStrLn $ " port = " ++ uriPort uriAuth putStrLn $ " path = " ++ trimmedUriPath uri case trimmedUriQuery uri of Nothing -> return () Just query -> putStrLn $ " query = " ++ query case trimmedUriFragment uri of Nothing -> return () Just fragment -> putStrLn $ " fragment = " ++ fragment putStrLn ""
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Transform the following Haskell implementation into C#, maintaining the same output and logic.
module Main (main) where import Data.Foldable (for_) import Network.URI ( URI , URIAuth , parseURI , uriAuthority , uriFragment , uriPath , uriPort , uriQuery , uriRegName , uriScheme , uriUserInfo ) uriStrings :: [String] uriStrings = [ "https://bob:pass@example.com/place" , "foo://example.com:8042/over/there?name=ferret#nose" , "urn:example:animal:ferret:nose" , "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" , "ftp://ftp.is.co.za/rfc/rfc1808.txt" , "http://www.ietf.org/rfc/rfc2396.txt#header1" , "ldap://[2001:db8::7]/c=GB?objectClass?one" , "mailto:John.Doe@example.com" , "news:comp.infosystems.www.servers.unix" , "tel:+1-816-555-1212" , "telnet://192.0.2.16:80/" , "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ] trimmedUriScheme :: URI -> String trimmedUriScheme = init . uriScheme trimmedUriUserInfo :: URIAuth -> Maybe String trimmedUriUserInfo uriAuth = case uriUserInfo uriAuth of [] -> Nothing userInfo -> if last userInfo == '@' then Just (init userInfo) else Nothing trimmedUriPath :: URI -> String trimmedUriPath uri = case uriPath uri of '/' : t -> t; p -> p trimmedUriQuery :: URI -> Maybe String trimmedUriQuery uri = case uriQuery uri of '?' : t -> Just t; _ -> Nothing trimmedUriFragment :: URI -> Maybe String trimmedUriFragment uri = case uriFragment uri of '#' : t -> Just t; _ -> Nothing main :: IO () main = do for_ uriStrings $ \uriString -> do case parseURI uriString of Nothing -> putStrLn $ "Could not parse" ++ uriString Just uri -> do putStrLn uriString putStrLn $ " scheme = " ++ trimmedUriScheme uri case uriAuthority uri of Nothing -> return () Just uriAuth -> do case trimmedUriUserInfo uriAuth of Nothing -> return () Just userInfo -> putStrLn $ " user-info = " ++ userInfo putStrLn $ " domain = " ++ uriRegName uriAuth putStrLn $ " port = " ++ uriPort uriAuth putStrLn $ " path = " ++ trimmedUriPath uri case trimmedUriQuery uri of Nothing -> return () Just query -> putStrLn $ " query = " ++ query case trimmedUriFragment uri of Nothing -> return () Just fragment -> putStrLn $ " fragment = " ++ fragment putStrLn ""
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Ensure the translated Java code behaves exactly like the original Haskell snippet.
module Main (main) where import Data.Foldable (for_) import Network.URI ( URI , URIAuth , parseURI , uriAuthority , uriFragment , uriPath , uriPort , uriQuery , uriRegName , uriScheme , uriUserInfo ) uriStrings :: [String] uriStrings = [ "https://bob:pass@example.com/place" , "foo://example.com:8042/over/there?name=ferret#nose" , "urn:example:animal:ferret:nose" , "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" , "ftp://ftp.is.co.za/rfc/rfc1808.txt" , "http://www.ietf.org/rfc/rfc2396.txt#header1" , "ldap://[2001:db8::7]/c=GB?objectClass?one" , "mailto:John.Doe@example.com" , "news:comp.infosystems.www.servers.unix" , "tel:+1-816-555-1212" , "telnet://192.0.2.16:80/" , "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ] trimmedUriScheme :: URI -> String trimmedUriScheme = init . uriScheme trimmedUriUserInfo :: URIAuth -> Maybe String trimmedUriUserInfo uriAuth = case uriUserInfo uriAuth of [] -> Nothing userInfo -> if last userInfo == '@' then Just (init userInfo) else Nothing trimmedUriPath :: URI -> String trimmedUriPath uri = case uriPath uri of '/' : t -> t; p -> p trimmedUriQuery :: URI -> Maybe String trimmedUriQuery uri = case uriQuery uri of '?' : t -> Just t; _ -> Nothing trimmedUriFragment :: URI -> Maybe String trimmedUriFragment uri = case uriFragment uri of '#' : t -> Just t; _ -> Nothing main :: IO () main = do for_ uriStrings $ \uriString -> do case parseURI uriString of Nothing -> putStrLn $ "Could not parse" ++ uriString Just uri -> do putStrLn uriString putStrLn $ " scheme = " ++ trimmedUriScheme uri case uriAuthority uri of Nothing -> return () Just uriAuth -> do case trimmedUriUserInfo uriAuth of Nothing -> return () Just userInfo -> putStrLn $ " user-info = " ++ userInfo putStrLn $ " domain = " ++ uriRegName uriAuth putStrLn $ " port = " ++ uriPort uriAuth putStrLn $ " path = " ++ trimmedUriPath uri case trimmedUriQuery uri of Nothing -> return () Just query -> putStrLn $ " query = " ++ query case trimmedUriFragment uri of Nothing -> return () Just fragment -> putStrLn $ " fragment = " ++ fragment putStrLn ""
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Produce a functionally identical Java code for the snippet given in Haskell.
module Main (main) where import Data.Foldable (for_) import Network.URI ( URI , URIAuth , parseURI , uriAuthority , uriFragment , uriPath , uriPort , uriQuery , uriRegName , uriScheme , uriUserInfo ) uriStrings :: [String] uriStrings = [ "https://bob:pass@example.com/place" , "foo://example.com:8042/over/there?name=ferret#nose" , "urn:example:animal:ferret:nose" , "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" , "ftp://ftp.is.co.za/rfc/rfc1808.txt" , "http://www.ietf.org/rfc/rfc2396.txt#header1" , "ldap://[2001:db8::7]/c=GB?objectClass?one" , "mailto:John.Doe@example.com" , "news:comp.infosystems.www.servers.unix" , "tel:+1-816-555-1212" , "telnet://192.0.2.16:80/" , "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ] trimmedUriScheme :: URI -> String trimmedUriScheme = init . uriScheme trimmedUriUserInfo :: URIAuth -> Maybe String trimmedUriUserInfo uriAuth = case uriUserInfo uriAuth of [] -> Nothing userInfo -> if last userInfo == '@' then Just (init userInfo) else Nothing trimmedUriPath :: URI -> String trimmedUriPath uri = case uriPath uri of '/' : t -> t; p -> p trimmedUriQuery :: URI -> Maybe String trimmedUriQuery uri = case uriQuery uri of '?' : t -> Just t; _ -> Nothing trimmedUriFragment :: URI -> Maybe String trimmedUriFragment uri = case uriFragment uri of '#' : t -> Just t; _ -> Nothing main :: IO () main = do for_ uriStrings $ \uriString -> do case parseURI uriString of Nothing -> putStrLn $ "Could not parse" ++ uriString Just uri -> do putStrLn uriString putStrLn $ " scheme = " ++ trimmedUriScheme uri case uriAuthority uri of Nothing -> return () Just uriAuth -> do case trimmedUriUserInfo uriAuth of Nothing -> return () Just userInfo -> putStrLn $ " user-info = " ++ userInfo putStrLn $ " domain = " ++ uriRegName uriAuth putStrLn $ " port = " ++ uriPort uriAuth putStrLn $ " path = " ++ trimmedUriPath uri case trimmedUriQuery uri of Nothing -> return () Just query -> putStrLn $ " query = " ++ query case trimmedUriFragment uri of Nothing -> return () Just fragment -> putStrLn $ " fragment = " ++ fragment putStrLn ""
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Keep all operations the same but rewrite the snippet in Python.
module Main (main) where import Data.Foldable (for_) import Network.URI ( URI , URIAuth , parseURI , uriAuthority , uriFragment , uriPath , uriPort , uriQuery , uriRegName , uriScheme , uriUserInfo ) uriStrings :: [String] uriStrings = [ "https://bob:pass@example.com/place" , "foo://example.com:8042/over/there?name=ferret#nose" , "urn:example:animal:ferret:nose" , "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" , "ftp://ftp.is.co.za/rfc/rfc1808.txt" , "http://www.ietf.org/rfc/rfc2396.txt#header1" , "ldap://[2001:db8::7]/c=GB?objectClass?one" , "mailto:John.Doe@example.com" , "news:comp.infosystems.www.servers.unix" , "tel:+1-816-555-1212" , "telnet://192.0.2.16:80/" , "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ] trimmedUriScheme :: URI -> String trimmedUriScheme = init . uriScheme trimmedUriUserInfo :: URIAuth -> Maybe String trimmedUriUserInfo uriAuth = case uriUserInfo uriAuth of [] -> Nothing userInfo -> if last userInfo == '@' then Just (init userInfo) else Nothing trimmedUriPath :: URI -> String trimmedUriPath uri = case uriPath uri of '/' : t -> t; p -> p trimmedUriQuery :: URI -> Maybe String trimmedUriQuery uri = case uriQuery uri of '?' : t -> Just t; _ -> Nothing trimmedUriFragment :: URI -> Maybe String trimmedUriFragment uri = case uriFragment uri of '#' : t -> Just t; _ -> Nothing main :: IO () main = do for_ uriStrings $ \uriString -> do case parseURI uriString of Nothing -> putStrLn $ "Could not parse" ++ uriString Just uri -> do putStrLn uriString putStrLn $ " scheme = " ++ trimmedUriScheme uri case uriAuthority uri of Nothing -> return () Just uriAuth -> do case trimmedUriUserInfo uriAuth of Nothing -> return () Just userInfo -> putStrLn $ " user-info = " ++ userInfo putStrLn $ " domain = " ++ uriRegName uriAuth putStrLn $ " port = " ++ uriPort uriAuth putStrLn $ " path = " ++ trimmedUriPath uri case trimmedUriQuery uri of Nothing -> return () Just query -> putStrLn $ " query = " ++ query case trimmedUriFragment uri of Nothing -> return () Just fragment -> putStrLn $ " fragment = " ++ fragment putStrLn ""
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Can you help me rewrite this code in Python instead of Haskell, keeping it the same logically?
module Main (main) where import Data.Foldable (for_) import Network.URI ( URI , URIAuth , parseURI , uriAuthority , uriFragment , uriPath , uriPort , uriQuery , uriRegName , uriScheme , uriUserInfo ) uriStrings :: [String] uriStrings = [ "https://bob:pass@example.com/place" , "foo://example.com:8042/over/there?name=ferret#nose" , "urn:example:animal:ferret:nose" , "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" , "ftp://ftp.is.co.za/rfc/rfc1808.txt" , "http://www.ietf.org/rfc/rfc2396.txt#header1" , "ldap://[2001:db8::7]/c=GB?objectClass?one" , "mailto:John.Doe@example.com" , "news:comp.infosystems.www.servers.unix" , "tel:+1-816-555-1212" , "telnet://192.0.2.16:80/" , "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ] trimmedUriScheme :: URI -> String trimmedUriScheme = init . uriScheme trimmedUriUserInfo :: URIAuth -> Maybe String trimmedUriUserInfo uriAuth = case uriUserInfo uriAuth of [] -> Nothing userInfo -> if last userInfo == '@' then Just (init userInfo) else Nothing trimmedUriPath :: URI -> String trimmedUriPath uri = case uriPath uri of '/' : t -> t; p -> p trimmedUriQuery :: URI -> Maybe String trimmedUriQuery uri = case uriQuery uri of '?' : t -> Just t; _ -> Nothing trimmedUriFragment :: URI -> Maybe String trimmedUriFragment uri = case uriFragment uri of '#' : t -> Just t; _ -> Nothing main :: IO () main = do for_ uriStrings $ \uriString -> do case parseURI uriString of Nothing -> putStrLn $ "Could not parse" ++ uriString Just uri -> do putStrLn uriString putStrLn $ " scheme = " ++ trimmedUriScheme uri case uriAuthority uri of Nothing -> return () Just uriAuth -> do case trimmedUriUserInfo uriAuth of Nothing -> return () Just userInfo -> putStrLn $ " user-info = " ++ userInfo putStrLn $ " domain = " ++ uriRegName uriAuth putStrLn $ " port = " ++ uriPort uriAuth putStrLn $ " path = " ++ trimmedUriPath uri case trimmedUriQuery uri of Nothing -> return () Just query -> putStrLn $ " query = " ++ query case trimmedUriFragment uri of Nothing -> return () Just fragment -> putStrLn $ " fragment = " ++ fragment putStrLn ""
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Ensure the translated VB code behaves exactly like the original Haskell snippet.
module Main (main) where import Data.Foldable (for_) import Network.URI ( URI , URIAuth , parseURI , uriAuthority , uriFragment , uriPath , uriPort , uriQuery , uriRegName , uriScheme , uriUserInfo ) uriStrings :: [String] uriStrings = [ "https://bob:pass@example.com/place" , "foo://example.com:8042/over/there?name=ferret#nose" , "urn:example:animal:ferret:nose" , "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" , "ftp://ftp.is.co.za/rfc/rfc1808.txt" , "http://www.ietf.org/rfc/rfc2396.txt#header1" , "ldap://[2001:db8::7]/c=GB?objectClass?one" , "mailto:John.Doe@example.com" , "news:comp.infosystems.www.servers.unix" , "tel:+1-816-555-1212" , "telnet://192.0.2.16:80/" , "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ] trimmedUriScheme :: URI -> String trimmedUriScheme = init . uriScheme trimmedUriUserInfo :: URIAuth -> Maybe String trimmedUriUserInfo uriAuth = case uriUserInfo uriAuth of [] -> Nothing userInfo -> if last userInfo == '@' then Just (init userInfo) else Nothing trimmedUriPath :: URI -> String trimmedUriPath uri = case uriPath uri of '/' : t -> t; p -> p trimmedUriQuery :: URI -> Maybe String trimmedUriQuery uri = case uriQuery uri of '?' : t -> Just t; _ -> Nothing trimmedUriFragment :: URI -> Maybe String trimmedUriFragment uri = case uriFragment uri of '#' : t -> Just t; _ -> Nothing main :: IO () main = do for_ uriStrings $ \uriString -> do case parseURI uriString of Nothing -> putStrLn $ "Could not parse" ++ uriString Just uri -> do putStrLn uriString putStrLn $ " scheme = " ++ trimmedUriScheme uri case uriAuthority uri of Nothing -> return () Just uriAuth -> do case trimmedUriUserInfo uriAuth of Nothing -> return () Just userInfo -> putStrLn $ " user-info = " ++ userInfo putStrLn $ " domain = " ++ uriRegName uriAuth putStrLn $ " port = " ++ uriPort uriAuth putStrLn $ " path = " ++ trimmedUriPath uri case trimmedUriQuery uri of Nothing -> return () Just query -> putStrLn $ " query = " ++ query case trimmedUriFragment uri of Nothing -> return () Just fragment -> putStrLn $ " fragment = " ++ fragment putStrLn ""
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Write the same code in VB as shown below in Haskell.
module Main (main) where import Data.Foldable (for_) import Network.URI ( URI , URIAuth , parseURI , uriAuthority , uriFragment , uriPath , uriPort , uriQuery , uriRegName , uriScheme , uriUserInfo ) uriStrings :: [String] uriStrings = [ "https://bob:pass@example.com/place" , "foo://example.com:8042/over/there?name=ferret#nose" , "urn:example:animal:ferret:nose" , "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" , "ftp://ftp.is.co.za/rfc/rfc1808.txt" , "http://www.ietf.org/rfc/rfc2396.txt#header1" , "ldap://[2001:db8::7]/c=GB?objectClass?one" , "mailto:John.Doe@example.com" , "news:comp.infosystems.www.servers.unix" , "tel:+1-816-555-1212" , "telnet://192.0.2.16:80/" , "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ] trimmedUriScheme :: URI -> String trimmedUriScheme = init . uriScheme trimmedUriUserInfo :: URIAuth -> Maybe String trimmedUriUserInfo uriAuth = case uriUserInfo uriAuth of [] -> Nothing userInfo -> if last userInfo == '@' then Just (init userInfo) else Nothing trimmedUriPath :: URI -> String trimmedUriPath uri = case uriPath uri of '/' : t -> t; p -> p trimmedUriQuery :: URI -> Maybe String trimmedUriQuery uri = case uriQuery uri of '?' : t -> Just t; _ -> Nothing trimmedUriFragment :: URI -> Maybe String trimmedUriFragment uri = case uriFragment uri of '#' : t -> Just t; _ -> Nothing main :: IO () main = do for_ uriStrings $ \uriString -> do case parseURI uriString of Nothing -> putStrLn $ "Could not parse" ++ uriString Just uri -> do putStrLn uriString putStrLn $ " scheme = " ++ trimmedUriScheme uri case uriAuthority uri of Nothing -> return () Just uriAuth -> do case trimmedUriUserInfo uriAuth of Nothing -> return () Just userInfo -> putStrLn $ " user-info = " ++ userInfo putStrLn $ " domain = " ++ uriRegName uriAuth putStrLn $ " port = " ++ uriPort uriAuth putStrLn $ " path = " ++ trimmedUriPath uri case trimmedUriQuery uri of Nothing -> return () Just query -> putStrLn $ " query = " ++ query case trimmedUriFragment uri of Nothing -> return () Just fragment -> putStrLn $ " fragment = " ++ fragment putStrLn ""
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Convert the following code from Haskell to Go, ensuring the logic remains intact.
module Main (main) where import Data.Foldable (for_) import Network.URI ( URI , URIAuth , parseURI , uriAuthority , uriFragment , uriPath , uriPort , uriQuery , uriRegName , uriScheme , uriUserInfo ) uriStrings :: [String] uriStrings = [ "https://bob:pass@example.com/place" , "foo://example.com:8042/over/there?name=ferret#nose" , "urn:example:animal:ferret:nose" , "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" , "ftp://ftp.is.co.za/rfc/rfc1808.txt" , "http://www.ietf.org/rfc/rfc2396.txt#header1" , "ldap://[2001:db8::7]/c=GB?objectClass?one" , "mailto:John.Doe@example.com" , "news:comp.infosystems.www.servers.unix" , "tel:+1-816-555-1212" , "telnet://192.0.2.16:80/" , "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ] trimmedUriScheme :: URI -> String trimmedUriScheme = init . uriScheme trimmedUriUserInfo :: URIAuth -> Maybe String trimmedUriUserInfo uriAuth = case uriUserInfo uriAuth of [] -> Nothing userInfo -> if last userInfo == '@' then Just (init userInfo) else Nothing trimmedUriPath :: URI -> String trimmedUriPath uri = case uriPath uri of '/' : t -> t; p -> p trimmedUriQuery :: URI -> Maybe String trimmedUriQuery uri = case uriQuery uri of '?' : t -> Just t; _ -> Nothing trimmedUriFragment :: URI -> Maybe String trimmedUriFragment uri = case uriFragment uri of '#' : t -> Just t; _ -> Nothing main :: IO () main = do for_ uriStrings $ \uriString -> do case parseURI uriString of Nothing -> putStrLn $ "Could not parse" ++ uriString Just uri -> do putStrLn uriString putStrLn $ " scheme = " ++ trimmedUriScheme uri case uriAuthority uri of Nothing -> return () Just uriAuth -> do case trimmedUriUserInfo uriAuth of Nothing -> return () Just userInfo -> putStrLn $ " user-info = " ++ userInfo putStrLn $ " domain = " ++ uriRegName uriAuth putStrLn $ " port = " ++ uriPort uriAuth putStrLn $ " path = " ++ trimmedUriPath uri case trimmedUriQuery uri of Nothing -> return () Just query -> putStrLn $ " query = " ++ query case trimmedUriFragment uri of Nothing -> return () Just fragment -> putStrLn $ " fragment = " ++ fragment putStrLn ""
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Generate an equivalent Go version of this Haskell code.
module Main (main) where import Data.Foldable (for_) import Network.URI ( URI , URIAuth , parseURI , uriAuthority , uriFragment , uriPath , uriPort , uriQuery , uriRegName , uriScheme , uriUserInfo ) uriStrings :: [String] uriStrings = [ "https://bob:pass@example.com/place" , "foo://example.com:8042/over/there?name=ferret#nose" , "urn:example:animal:ferret:nose" , "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" , "ftp://ftp.is.co.za/rfc/rfc1808.txt" , "http://www.ietf.org/rfc/rfc2396.txt#header1" , "ldap://[2001:db8::7]/c=GB?objectClass?one" , "mailto:John.Doe@example.com" , "news:comp.infosystems.www.servers.unix" , "tel:+1-816-555-1212" , "telnet://192.0.2.16:80/" , "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ] trimmedUriScheme :: URI -> String trimmedUriScheme = init . uriScheme trimmedUriUserInfo :: URIAuth -> Maybe String trimmedUriUserInfo uriAuth = case uriUserInfo uriAuth of [] -> Nothing userInfo -> if last userInfo == '@' then Just (init userInfo) else Nothing trimmedUriPath :: URI -> String trimmedUriPath uri = case uriPath uri of '/' : t -> t; p -> p trimmedUriQuery :: URI -> Maybe String trimmedUriQuery uri = case uriQuery uri of '?' : t -> Just t; _ -> Nothing trimmedUriFragment :: URI -> Maybe String trimmedUriFragment uri = case uriFragment uri of '#' : t -> Just t; _ -> Nothing main :: IO () main = do for_ uriStrings $ \uriString -> do case parseURI uriString of Nothing -> putStrLn $ "Could not parse" ++ uriString Just uri -> do putStrLn uriString putStrLn $ " scheme = " ++ trimmedUriScheme uri case uriAuthority uri of Nothing -> return () Just uriAuth -> do case trimmedUriUserInfo uriAuth of Nothing -> return () Just userInfo -> putStrLn $ " user-info = " ++ userInfo putStrLn $ " domain = " ++ uriRegName uriAuth putStrLn $ " port = " ++ uriPort uriAuth putStrLn $ " path = " ++ trimmedUriPath uri case trimmedUriQuery uri of Nothing -> return () Just query -> putStrLn $ " query = " ++ query case trimmedUriFragment uri of Nothing -> return () Just fragment -> putStrLn $ " fragment = " ++ fragment putStrLn ""
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Keep all operations the same but rewrite the snippet in C#.
split=:1 :0 ({. ; ] }.~ 1+[)~ i.&m ) uriparts=:3 :0 'server fragment'=. '#' split y 'sa query'=. '?' split server 'scheme authpath'=. ':' split sa scheme;authpath;query;fragment ) queryparts=:3 :0 (0<#y)#<;._1 '?',y ) authpathparts=:3 :0 if. '//' -: 2{.y do. split=. <;.1 y (}.1{::split);;2}.split else. '';y end. ) authparts=:3 :0 if. '@' e. y do. 'userinfo hostport'=. '@' split y else. hostport=. y [ userinfo=.'' end. if. '[' = {.hostport do. 'host_t port_t'=. ']' split hostport assert. (0=#port_t)+.':'={.port_t (':' split userinfo),(host_t,']');}.port_t else. (':' split userinfo),':' split hostport end. ) taskparts=:3 :0 'scheme authpath querystring fragment'=. uriparts y 'auth path'=. authpathparts authpath 'user creds host port'=. authparts auth query=. queryparts querystring export=. ;:'scheme user creds host port path query fragment' (#~ 0<#@>@{:"1) (,. do each) export )
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Please provide an equivalent version of this J code in C#.
split=:1 :0 ({. ; ] }.~ 1+[)~ i.&m ) uriparts=:3 :0 'server fragment'=. '#' split y 'sa query'=. '?' split server 'scheme authpath'=. ':' split sa scheme;authpath;query;fragment ) queryparts=:3 :0 (0<#y)#<;._1 '?',y ) authpathparts=:3 :0 if. '//' -: 2{.y do. split=. <;.1 y (}.1{::split);;2}.split else. '';y end. ) authparts=:3 :0 if. '@' e. y do. 'userinfo hostport'=. '@' split y else. hostport=. y [ userinfo=.'' end. if. '[' = {.hostport do. 'host_t port_t'=. ']' split hostport assert. (0=#port_t)+.':'={.port_t (':' split userinfo),(host_t,']');}.port_t else. (':' split userinfo),':' split hostport end. ) taskparts=:3 :0 'scheme authpath querystring fragment'=. uriparts y 'auth path'=. authpathparts authpath 'user creds host port'=. authparts auth query=. queryparts querystring export=. ;:'scheme user creds host port path query fragment' (#~ 0<#@>@{:"1) (,. do each) export )
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Transform the following J implementation into Java, maintaining the same output and logic.
split=:1 :0 ({. ; ] }.~ 1+[)~ i.&m ) uriparts=:3 :0 'server fragment'=. '#' split y 'sa query'=. '?' split server 'scheme authpath'=. ':' split sa scheme;authpath;query;fragment ) queryparts=:3 :0 (0<#y)#<;._1 '?',y ) authpathparts=:3 :0 if. '//' -: 2{.y do. split=. <;.1 y (}.1{::split);;2}.split else. '';y end. ) authparts=:3 :0 if. '@' e. y do. 'userinfo hostport'=. '@' split y else. hostport=. y [ userinfo=.'' end. if. '[' = {.hostport do. 'host_t port_t'=. ']' split hostport assert. (0=#port_t)+.':'={.port_t (':' split userinfo),(host_t,']');}.port_t else. (':' split userinfo),':' split hostport end. ) taskparts=:3 :0 'scheme authpath querystring fragment'=. uriparts y 'auth path'=. authpathparts authpath 'user creds host port'=. authparts auth query=. queryparts querystring export=. ;:'scheme user creds host port path query fragment' (#~ 0<#@>@{:"1) (,. do each) export )
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Write a version of this J function in Java with identical behavior.
split=:1 :0 ({. ; ] }.~ 1+[)~ i.&m ) uriparts=:3 :0 'server fragment'=. '#' split y 'sa query'=. '?' split server 'scheme authpath'=. ':' split sa scheme;authpath;query;fragment ) queryparts=:3 :0 (0<#y)#<;._1 '?',y ) authpathparts=:3 :0 if. '//' -: 2{.y do. split=. <;.1 y (}.1{::split);;2}.split else. '';y end. ) authparts=:3 :0 if. '@' e. y do. 'userinfo hostport'=. '@' split y else. hostport=. y [ userinfo=.'' end. if. '[' = {.hostport do. 'host_t port_t'=. ']' split hostport assert. (0=#port_t)+.':'={.port_t (':' split userinfo),(host_t,']');}.port_t else. (':' split userinfo),':' split hostport end. ) taskparts=:3 :0 'scheme authpath querystring fragment'=. uriparts y 'auth path'=. authpathparts authpath 'user creds host port'=. authparts auth query=. queryparts querystring export=. ;:'scheme user creds host port path query fragment' (#~ 0<#@>@{:"1) (,. do each) export )
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Keep all operations the same but rewrite the snippet in Python.
split=:1 :0 ({. ; ] }.~ 1+[)~ i.&m ) uriparts=:3 :0 'server fragment'=. '#' split y 'sa query'=. '?' split server 'scheme authpath'=. ':' split sa scheme;authpath;query;fragment ) queryparts=:3 :0 (0<#y)#<;._1 '?',y ) authpathparts=:3 :0 if. '//' -: 2{.y do. split=. <;.1 y (}.1{::split);;2}.split else. '';y end. ) authparts=:3 :0 if. '@' e. y do. 'userinfo hostport'=. '@' split y else. hostport=. y [ userinfo=.'' end. if. '[' = {.hostport do. 'host_t port_t'=. ']' split hostport assert. (0=#port_t)+.':'={.port_t (':' split userinfo),(host_t,']');}.port_t else. (':' split userinfo),':' split hostport end. ) taskparts=:3 :0 'scheme authpath querystring fragment'=. uriparts y 'auth path'=. authpathparts authpath 'user creds host port'=. authparts auth query=. queryparts querystring export=. ;:'scheme user creds host port path query fragment' (#~ 0<#@>@{:"1) (,. do each) export )
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Convert this J snippet to Python and keep its semantics consistent.
split=:1 :0 ({. ; ] }.~ 1+[)~ i.&m ) uriparts=:3 :0 'server fragment'=. '#' split y 'sa query'=. '?' split server 'scheme authpath'=. ':' split sa scheme;authpath;query;fragment ) queryparts=:3 :0 (0<#y)#<;._1 '?',y ) authpathparts=:3 :0 if. '//' -: 2{.y do. split=. <;.1 y (}.1{::split);;2}.split else. '';y end. ) authparts=:3 :0 if. '@' e. y do. 'userinfo hostport'=. '@' split y else. hostport=. y [ userinfo=.'' end. if. '[' = {.hostport do. 'host_t port_t'=. ']' split hostport assert. (0=#port_t)+.':'={.port_t (':' split userinfo),(host_t,']');}.port_t else. (':' split userinfo),':' split hostport end. ) taskparts=:3 :0 'scheme authpath querystring fragment'=. uriparts y 'auth path'=. authpathparts authpath 'user creds host port'=. authparts auth query=. queryparts querystring export=. ;:'scheme user creds host port path query fragment' (#~ 0<#@>@{:"1) (,. do each) export )
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Can you help me rewrite this code in VB instead of J, keeping it the same logically?
split=:1 :0 ({. ; ] }.~ 1+[)~ i.&m ) uriparts=:3 :0 'server fragment'=. '#' split y 'sa query'=. '?' split server 'scheme authpath'=. ':' split sa scheme;authpath;query;fragment ) queryparts=:3 :0 (0<#y)#<;._1 '?',y ) authpathparts=:3 :0 if. '//' -: 2{.y do. split=. <;.1 y (}.1{::split);;2}.split else. '';y end. ) authparts=:3 :0 if. '@' e. y do. 'userinfo hostport'=. '@' split y else. hostport=. y [ userinfo=.'' end. if. '[' = {.hostport do. 'host_t port_t'=. ']' split hostport assert. (0=#port_t)+.':'={.port_t (':' split userinfo),(host_t,']');}.port_t else. (':' split userinfo),':' split hostport end. ) taskparts=:3 :0 'scheme authpath querystring fragment'=. uriparts y 'auth path'=. authpathparts authpath 'user creds host port'=. authparts auth query=. queryparts querystring export=. ;:'scheme user creds host port path query fragment' (#~ 0<#@>@{:"1) (,. do each) export )
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Convert the following code from J to VB, ensuring the logic remains intact.
split=:1 :0 ({. ; ] }.~ 1+[)~ i.&m ) uriparts=:3 :0 'server fragment'=. '#' split y 'sa query'=. '?' split server 'scheme authpath'=. ':' split sa scheme;authpath;query;fragment ) queryparts=:3 :0 (0<#y)#<;._1 '?',y ) authpathparts=:3 :0 if. '//' -: 2{.y do. split=. <;.1 y (}.1{::split);;2}.split else. '';y end. ) authparts=:3 :0 if. '@' e. y do. 'userinfo hostport'=. '@' split y else. hostport=. y [ userinfo=.'' end. if. '[' = {.hostport do. 'host_t port_t'=. ']' split hostport assert. (0=#port_t)+.':'={.port_t (':' split userinfo),(host_t,']');}.port_t else. (':' split userinfo),':' split hostport end. ) taskparts=:3 :0 'scheme authpath querystring fragment'=. uriparts y 'auth path'=. authpathparts authpath 'user creds host port'=. authparts auth query=. queryparts querystring export=. ;:'scheme user creds host port path query fragment' (#~ 0<#@>@{:"1) (,. do each) export )
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Generate a Go translation of this J snippet without changing its computational steps.
split=:1 :0 ({. ; ] }.~ 1+[)~ i.&m ) uriparts=:3 :0 'server fragment'=. '#' split y 'sa query'=. '?' split server 'scheme authpath'=. ':' split sa scheme;authpath;query;fragment ) queryparts=:3 :0 (0<#y)#<;._1 '?',y ) authpathparts=:3 :0 if. '//' -: 2{.y do. split=. <;.1 y (}.1{::split);;2}.split else. '';y end. ) authparts=:3 :0 if. '@' e. y do. 'userinfo hostport'=. '@' split y else. hostport=. y [ userinfo=.'' end. if. '[' = {.hostport do. 'host_t port_t'=. ']' split hostport assert. (0=#port_t)+.':'={.port_t (':' split userinfo),(host_t,']');}.port_t else. (':' split userinfo),':' split hostport end. ) taskparts=:3 :0 'scheme authpath querystring fragment'=. uriparts y 'auth path'=. authpathparts authpath 'user creds host port'=. authparts auth query=. queryparts querystring export=. ;:'scheme user creds host port path query fragment' (#~ 0<#@>@{:"1) (,. do each) export )
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Write a version of this J function in Go with identical behavior.
split=:1 :0 ({. ; ] }.~ 1+[)~ i.&m ) uriparts=:3 :0 'server fragment'=. '#' split y 'sa query'=. '?' split server 'scheme authpath'=. ':' split sa scheme;authpath;query;fragment ) queryparts=:3 :0 (0<#y)#<;._1 '?',y ) authpathparts=:3 :0 if. '//' -: 2{.y do. split=. <;.1 y (}.1{::split);;2}.split else. '';y end. ) authparts=:3 :0 if. '@' e. y do. 'userinfo hostport'=. '@' split y else. hostport=. y [ userinfo=.'' end. if. '[' = {.hostport do. 'host_t port_t'=. ']' split hostport assert. (0=#port_t)+.':'={.port_t (':' split userinfo),(host_t,']');}.port_t else. (':' split userinfo),':' split hostport end. ) taskparts=:3 :0 'scheme authpath querystring fragment'=. uriparts y 'auth path'=. authpathparts authpath 'user creds host port'=. authparts auth query=. queryparts querystring export=. ;:'scheme user creds host port path query fragment' (#~ 0<#@>@{:"1) (,. do each) export )
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Translate the given Julia code snippet into C# without altering its behavior.
using Printf, URIParser const FIELDS = names(URI) function detailview(uri::URI, indentlen::Int=4) indent = " "^indentlen s = String[] for f in FIELDS d = string(getfield(uri, f)) !isempty(d) || continue f != :port || d != "0" || continue push!(s, @sprintf("%s%s: %s", indent, string(f), d)) end join(s, "\n") end test = ["foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "This is not a URI!", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"] isfirst = true for st in test if isfirst isfirst = false else println() end println("Attempting to parse\n \"", st, "\" as a URI:") uri = try URI(st) catch println("URIParser failed to parse this URI, is it OK?") continue end print("This URI is parsable ") if isvalid(uri) println("and appears to be valid.") else println("but may be invalid.") end println(detailview(uri)) end
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Convert the following code from Julia to C#, ensuring the logic remains intact.
using Printf, URIParser const FIELDS = names(URI) function detailview(uri::URI, indentlen::Int=4) indent = " "^indentlen s = String[] for f in FIELDS d = string(getfield(uri, f)) !isempty(d) || continue f != :port || d != "0" || continue push!(s, @sprintf("%s%s: %s", indent, string(f), d)) end join(s, "\n") end test = ["foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "This is not a URI!", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"] isfirst = true for st in test if isfirst isfirst = false else println() end println("Attempting to parse\n \"", st, "\" as a URI:") uri = try URI(st) catch println("URIParser failed to parse this URI, is it OK?") continue end print("This URI is parsable ") if isvalid(uri) println("and appears to be valid.") else println("but may be invalid.") end println(detailview(uri)) end
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Translate this program into Java but keep the logic exactly as in Julia.
using Printf, URIParser const FIELDS = names(URI) function detailview(uri::URI, indentlen::Int=4) indent = " "^indentlen s = String[] for f in FIELDS d = string(getfield(uri, f)) !isempty(d) || continue f != :port || d != "0" || continue push!(s, @sprintf("%s%s: %s", indent, string(f), d)) end join(s, "\n") end test = ["foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "This is not a URI!", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"] isfirst = true for st in test if isfirst isfirst = false else println() end println("Attempting to parse\n \"", st, "\" as a URI:") uri = try URI(st) catch println("URIParser failed to parse this URI, is it OK?") continue end print("This URI is parsable ") if isvalid(uri) println("and appears to be valid.") else println("but may be invalid.") end println(detailview(uri)) end
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Produce a functionally identical Java code for the snippet given in Julia.
using Printf, URIParser const FIELDS = names(URI) function detailview(uri::URI, indentlen::Int=4) indent = " "^indentlen s = String[] for f in FIELDS d = string(getfield(uri, f)) !isempty(d) || continue f != :port || d != "0" || continue push!(s, @sprintf("%s%s: %s", indent, string(f), d)) end join(s, "\n") end test = ["foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "This is not a URI!", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"] isfirst = true for st in test if isfirst isfirst = false else println() end println("Attempting to parse\n \"", st, "\" as a URI:") uri = try URI(st) catch println("URIParser failed to parse this URI, is it OK?") continue end print("This URI is parsable ") if isvalid(uri) println("and appears to be valid.") else println("but may be invalid.") end println(detailview(uri)) end
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Rewrite this program in Python while keeping its functionality equivalent to the Julia version.
using Printf, URIParser const FIELDS = names(URI) function detailview(uri::URI, indentlen::Int=4) indent = " "^indentlen s = String[] for f in FIELDS d = string(getfield(uri, f)) !isempty(d) || continue f != :port || d != "0" || continue push!(s, @sprintf("%s%s: %s", indent, string(f), d)) end join(s, "\n") end test = ["foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "This is not a URI!", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"] isfirst = true for st in test if isfirst isfirst = false else println() end println("Attempting to parse\n \"", st, "\" as a URI:") uri = try URI(st) catch println("URIParser failed to parse this URI, is it OK?") continue end print("This URI is parsable ") if isvalid(uri) println("and appears to be valid.") else println("but may be invalid.") end println(detailview(uri)) end
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Convert the following code from Julia to Python, ensuring the logic remains intact.
using Printf, URIParser const FIELDS = names(URI) function detailview(uri::URI, indentlen::Int=4) indent = " "^indentlen s = String[] for f in FIELDS d = string(getfield(uri, f)) !isempty(d) || continue f != :port || d != "0" || continue push!(s, @sprintf("%s%s: %s", indent, string(f), d)) end join(s, "\n") end test = ["foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "This is not a URI!", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"] isfirst = true for st in test if isfirst isfirst = false else println() end println("Attempting to parse\n \"", st, "\" as a URI:") uri = try URI(st) catch println("URIParser failed to parse this URI, is it OK?") continue end print("This URI is parsable ") if isvalid(uri) println("and appears to be valid.") else println("but may be invalid.") end println(detailview(uri)) end
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Write the same algorithm in VB as shown in this Julia implementation.
using Printf, URIParser const FIELDS = names(URI) function detailview(uri::URI, indentlen::Int=4) indent = " "^indentlen s = String[] for f in FIELDS d = string(getfield(uri, f)) !isempty(d) || continue f != :port || d != "0" || continue push!(s, @sprintf("%s%s: %s", indent, string(f), d)) end join(s, "\n") end test = ["foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "This is not a URI!", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"] isfirst = true for st in test if isfirst isfirst = false else println() end println("Attempting to parse\n \"", st, "\" as a URI:") uri = try URI(st) catch println("URIParser failed to parse this URI, is it OK?") continue end print("This URI is parsable ") if isvalid(uri) println("and appears to be valid.") else println("but may be invalid.") end println(detailview(uri)) end
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Can you help me rewrite this code in VB instead of Julia, keeping it the same logically?
using Printf, URIParser const FIELDS = names(URI) function detailview(uri::URI, indentlen::Int=4) indent = " "^indentlen s = String[] for f in FIELDS d = string(getfield(uri, f)) !isempty(d) || continue f != :port || d != "0" || continue push!(s, @sprintf("%s%s: %s", indent, string(f), d)) end join(s, "\n") end test = ["foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "This is not a URI!", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"] isfirst = true for st in test if isfirst isfirst = false else println() end println("Attempting to parse\n \"", st, "\" as a URI:") uri = try URI(st) catch println("URIParser failed to parse this URI, is it OK?") continue end print("This URI is parsable ") if isvalid(uri) println("and appears to be valid.") else println("but may be invalid.") end println(detailview(uri)) end
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Convert the following code from Julia to Go, ensuring the logic remains intact.
using Printf, URIParser const FIELDS = names(URI) function detailview(uri::URI, indentlen::Int=4) indent = " "^indentlen s = String[] for f in FIELDS d = string(getfield(uri, f)) !isempty(d) || continue f != :port || d != "0" || continue push!(s, @sprintf("%s%s: %s", indent, string(f), d)) end join(s, "\n") end test = ["foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "This is not a URI!", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"] isfirst = true for st in test if isfirst isfirst = false else println() end println("Attempting to parse\n \"", st, "\" as a URI:") uri = try URI(st) catch println("URIParser failed to parse this URI, is it OK?") continue end print("This URI is parsable ") if isvalid(uri) println("and appears to be valid.") else println("but may be invalid.") end println(detailview(uri)) end
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Port the provided Julia code into Go while preserving the original functionality.
using Printf, URIParser const FIELDS = names(URI) function detailview(uri::URI, indentlen::Int=4) indent = " "^indentlen s = String[] for f in FIELDS d = string(getfield(uri, f)) !isempty(d) || continue f != :port || d != "0" || continue push!(s, @sprintf("%s%s: %s", indent, string(f), d)) end join(s, "\n") end test = ["foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "This is not a URI!", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"] isfirst = true for st in test if isfirst isfirst = false else println() end println("Attempting to parse\n \"", st, "\" as a URI:") uri = try URI(st) catch println("URIParser failed to parse this URI, is it OK?") continue end print("This URI is parsable ") if isvalid(uri) println("and appears to be valid.") else println("but may be invalid.") end println(detailview(uri)) end
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Change the following Lua code into C# without altering its purpose.
local url = require('socket.url') local tests = { 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two', 'mailto:John.Doe@example.com', 'news:comp.infosystems.www.servers.unix', 'tel:+1-816-555-1212', 'telnet://192.0.2.16:80/', 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2' } for _, test in ipairs(tests) do local parsed = url.parse(test) io.write('URI: ' .. test .. '\n') for k, v in pairs(parsed) do io.write(string.format(' %s: %s\n', k, v)) end io.write('\n') end
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Rewrite the snippet below in C# so it works the same as the original Lua code.
local url = require('socket.url') local tests = { 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two', 'mailto:John.Doe@example.com', 'news:comp.infosystems.www.servers.unix', 'tel:+1-816-555-1212', 'telnet://192.0.2.16:80/', 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2' } for _, test in ipairs(tests) do local parsed = url.parse(test) io.write('URI: ' .. test .. '\n') for k, v in pairs(parsed) do io.write(string.format(' %s: %s\n', k, v)) end io.write('\n') end
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Produce a language-to-language conversion: from Lua to Java, same semantics.
local url = require('socket.url') local tests = { 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two', 'mailto:John.Doe@example.com', 'news:comp.infosystems.www.servers.unix', 'tel:+1-816-555-1212', 'telnet://192.0.2.16:80/', 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2' } for _, test in ipairs(tests) do local parsed = url.parse(test) io.write('URI: ' .. test .. '\n') for k, v in pairs(parsed) do io.write(string.format(' %s: %s\n', k, v)) end io.write('\n') end
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Convert this Lua block to Python, preserving its control flow and logic.
local url = require('socket.url') local tests = { 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two', 'mailto:John.Doe@example.com', 'news:comp.infosystems.www.servers.unix', 'tel:+1-816-555-1212', 'telnet://192.0.2.16:80/', 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2' } for _, test in ipairs(tests) do local parsed = url.parse(test) io.write('URI: ' .. test .. '\n') for k, v in pairs(parsed) do io.write(string.format(' %s: %s\n', k, v)) end io.write('\n') end
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Convert the following code from Lua to Python, ensuring the logic remains intact.
local url = require('socket.url') local tests = { 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two', 'mailto:John.Doe@example.com', 'news:comp.infosystems.www.servers.unix', 'tel:+1-816-555-1212', 'telnet://192.0.2.16:80/', 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2' } for _, test in ipairs(tests) do local parsed = url.parse(test) io.write('URI: ' .. test .. '\n') for k, v in pairs(parsed) do io.write(string.format(' %s: %s\n', k, v)) end io.write('\n') end
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Transform the following Lua implementation into VB, maintaining the same output and logic.
local url = require('socket.url') local tests = { 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two', 'mailto:John.Doe@example.com', 'news:comp.infosystems.www.servers.unix', 'tel:+1-816-555-1212', 'telnet://192.0.2.16:80/', 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2' } for _, test in ipairs(tests) do local parsed = url.parse(test) io.write('URI: ' .. test .. '\n') for k, v in pairs(parsed) do io.write(string.format(' %s: %s\n', k, v)) end io.write('\n') end
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Generate an equivalent VB version of this Lua code.
local url = require('socket.url') local tests = { 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two', 'mailto:John.Doe@example.com', 'news:comp.infosystems.www.servers.unix', 'tel:+1-816-555-1212', 'telnet://192.0.2.16:80/', 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2' } for _, test in ipairs(tests) do local parsed = url.parse(test) io.write('URI: ' .. test .. '\n') for k, v in pairs(parsed) do io.write(string.format(' %s: %s\n', k, v)) end io.write('\n') end
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Rewrite the snippet below in Go so it works the same as the original Lua code.
local url = require('socket.url') local tests = { 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two', 'mailto:John.Doe@example.com', 'news:comp.infosystems.www.servers.unix', 'tel:+1-816-555-1212', 'telnet://192.0.2.16:80/', 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2' } for _, test in ipairs(tests) do local parsed = url.parse(test) io.write('URI: ' .. test .. '\n') for k, v in pairs(parsed) do io.write(string.format(' %s: %s\n', k, v)) end io.write('\n') end
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Convert this Lua block to Go, preserving its control flow and logic.
local url = require('socket.url') local tests = { 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two', 'mailto:John.Doe@example.com', 'news:comp.infosystems.www.servers.unix', 'tel:+1-816-555-1212', 'telnet://192.0.2.16:80/', 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2' } for _, test in ipairs(tests) do local parsed = url.parse(test) io.write('URI: ' .. test .. '\n') for k, v in pairs(parsed) do io.write(string.format(' %s: %s\n', k, v)) end io.write('\n') end
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Maintain the same structure and functionality when rewriting this code in C#.
URLParse["foo://example.com:8042/over/there?name=ferret#nose"]
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Produce a functionally identical C# code for the snippet given in Mathematica.
URLParse["foo://example.com:8042/over/there?name=ferret#nose"]
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Translate the given Mathematica code snippet into Java without altering its behavior.
URLParse["foo://example.com:8042/over/there?name=ferret#nose"]
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Keep all operations the same but rewrite the snippet in Java.
URLParse["foo://example.com:8042/over/there?name=ferret#nose"]
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Transform the following Mathematica implementation into Python, maintaining the same output and logic.
URLParse["foo://example.com:8042/over/there?name=ferret#nose"]
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Transform the following Mathematica implementation into Python, maintaining the same output and logic.
URLParse["foo://example.com:8042/over/there?name=ferret#nose"]
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Convert this Mathematica block to VB, preserving its control flow and logic.
URLParse["foo://example.com:8042/over/there?name=ferret#nose"]
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Generate a VB translation of this Mathematica snippet without changing its computational steps.
URLParse["foo://example.com:8042/over/there?name=ferret#nose"]
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Translate the given Mathematica code snippet into Go without altering its behavior.
URLParse["foo://example.com:8042/over/there?name=ferret#nose"]
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Port the provided Mathematica code into Go while preserving the original functionality.
URLParse["foo://example.com:8042/over/there?name=ferret#nose"]
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Change the programming language of this snippet from Nim to C# without modifying what it does.
import uri, strformat proc printUri(url: string) = echo url let res = parseUri(url) if res.scheme != "": echo &"\t Scheme: {res.scheme}" if res.hostname != "": echo &"\tHostname: {res.hostname}" if res.username != "": echo &"\tUsername: {res.username}" if res.password != "": echo &"\tPassword: {res.password}" if res.path != "": echo &"\t Path: {res.path}" if res.query != "": echo &"\t Query: {res.query}" if res.port != "": echo &"\t Port: {res.port}" if res.anchor != "": echo &"\t Anchor: {res.anchor}" if res.opaque: echo &"\t Opaque: {res.opaque}" let urls = ["foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"] for url in urls: printUri(url)
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Write a version of this Nim function in C# with identical behavior.
import uri, strformat proc printUri(url: string) = echo url let res = parseUri(url) if res.scheme != "": echo &"\t Scheme: {res.scheme}" if res.hostname != "": echo &"\tHostname: {res.hostname}" if res.username != "": echo &"\tUsername: {res.username}" if res.password != "": echo &"\tPassword: {res.password}" if res.path != "": echo &"\t Path: {res.path}" if res.query != "": echo &"\t Query: {res.query}" if res.port != "": echo &"\t Port: {res.port}" if res.anchor != "": echo &"\t Anchor: {res.anchor}" if res.opaque: echo &"\t Opaque: {res.opaque}" let urls = ["foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"] for url in urls: printUri(url)
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Port the following code from Nim to Java with equivalent syntax and logic.
import uri, strformat proc printUri(url: string) = echo url let res = parseUri(url) if res.scheme != "": echo &"\t Scheme: {res.scheme}" if res.hostname != "": echo &"\tHostname: {res.hostname}" if res.username != "": echo &"\tUsername: {res.username}" if res.password != "": echo &"\tPassword: {res.password}" if res.path != "": echo &"\t Path: {res.path}" if res.query != "": echo &"\t Query: {res.query}" if res.port != "": echo &"\t Port: {res.port}" if res.anchor != "": echo &"\t Anchor: {res.anchor}" if res.opaque: echo &"\t Opaque: {res.opaque}" let urls = ["foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"] for url in urls: printUri(url)
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Generate a Java translation of this Nim snippet without changing its computational steps.
import uri, strformat proc printUri(url: string) = echo url let res = parseUri(url) if res.scheme != "": echo &"\t Scheme: {res.scheme}" if res.hostname != "": echo &"\tHostname: {res.hostname}" if res.username != "": echo &"\tUsername: {res.username}" if res.password != "": echo &"\tPassword: {res.password}" if res.path != "": echo &"\t Path: {res.path}" if res.query != "": echo &"\t Query: {res.query}" if res.port != "": echo &"\t Port: {res.port}" if res.anchor != "": echo &"\t Anchor: {res.anchor}" if res.opaque: echo &"\t Opaque: {res.opaque}" let urls = ["foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"] for url in urls: printUri(url)
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Produce a functionally identical Python code for the snippet given in Nim.
import uri, strformat proc printUri(url: string) = echo url let res = parseUri(url) if res.scheme != "": echo &"\t Scheme: {res.scheme}" if res.hostname != "": echo &"\tHostname: {res.hostname}" if res.username != "": echo &"\tUsername: {res.username}" if res.password != "": echo &"\tPassword: {res.password}" if res.path != "": echo &"\t Path: {res.path}" if res.query != "": echo &"\t Query: {res.query}" if res.port != "": echo &"\t Port: {res.port}" if res.anchor != "": echo &"\t Anchor: {res.anchor}" if res.opaque: echo &"\t Opaque: {res.opaque}" let urls = ["foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"] for url in urls: printUri(url)
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Convert the following code from Nim to Python, ensuring the logic remains intact.
import uri, strformat proc printUri(url: string) = echo url let res = parseUri(url) if res.scheme != "": echo &"\t Scheme: {res.scheme}" if res.hostname != "": echo &"\tHostname: {res.hostname}" if res.username != "": echo &"\tUsername: {res.username}" if res.password != "": echo &"\tPassword: {res.password}" if res.path != "": echo &"\t Path: {res.path}" if res.query != "": echo &"\t Query: {res.query}" if res.port != "": echo &"\t Port: {res.port}" if res.anchor != "": echo &"\t Anchor: {res.anchor}" if res.opaque: echo &"\t Opaque: {res.opaque}" let urls = ["foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"] for url in urls: printUri(url)
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Keep all operations the same but rewrite the snippet in VB.
import uri, strformat proc printUri(url: string) = echo url let res = parseUri(url) if res.scheme != "": echo &"\t Scheme: {res.scheme}" if res.hostname != "": echo &"\tHostname: {res.hostname}" if res.username != "": echo &"\tUsername: {res.username}" if res.password != "": echo &"\tPassword: {res.password}" if res.path != "": echo &"\t Path: {res.path}" if res.query != "": echo &"\t Query: {res.query}" if res.port != "": echo &"\t Port: {res.port}" if res.anchor != "": echo &"\t Anchor: {res.anchor}" if res.opaque: echo &"\t Opaque: {res.opaque}" let urls = ["foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"] for url in urls: printUri(url)
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Write the same algorithm in VB as shown in this Nim implementation.
import uri, strformat proc printUri(url: string) = echo url let res = parseUri(url) if res.scheme != "": echo &"\t Scheme: {res.scheme}" if res.hostname != "": echo &"\tHostname: {res.hostname}" if res.username != "": echo &"\tUsername: {res.username}" if res.password != "": echo &"\tPassword: {res.password}" if res.path != "": echo &"\t Path: {res.path}" if res.query != "": echo &"\t Query: {res.query}" if res.port != "": echo &"\t Port: {res.port}" if res.anchor != "": echo &"\t Anchor: {res.anchor}" if res.opaque: echo &"\t Opaque: {res.opaque}" let urls = ["foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"] for url in urls: printUri(url)
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Convert the following code from Nim to Go, ensuring the logic remains intact.
import uri, strformat proc printUri(url: string) = echo url let res = parseUri(url) if res.scheme != "": echo &"\t Scheme: {res.scheme}" if res.hostname != "": echo &"\tHostname: {res.hostname}" if res.username != "": echo &"\tUsername: {res.username}" if res.password != "": echo &"\tPassword: {res.password}" if res.path != "": echo &"\t Path: {res.path}" if res.query != "": echo &"\t Query: {res.query}" if res.port != "": echo &"\t Port: {res.port}" if res.anchor != "": echo &"\t Anchor: {res.anchor}" if res.opaque: echo &"\t Opaque: {res.opaque}" let urls = ["foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"] for url in urls: printUri(url)
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Write the same algorithm in Go as shown in this Nim implementation.
import uri, strformat proc printUri(url: string) = echo url let res = parseUri(url) if res.scheme != "": echo &"\t Scheme: {res.scheme}" if res.hostname != "": echo &"\tHostname: {res.hostname}" if res.username != "": echo &"\tUsername: {res.username}" if res.password != "": echo &"\tPassword: {res.password}" if res.path != "": echo &"\t Path: {res.path}" if res.query != "": echo &"\t Query: {res.query}" if res.port != "": echo &"\t Port: {res.port}" if res.anchor != "": echo &"\t Anchor: {res.anchor}" if res.opaque: echo &"\t Opaque: {res.opaque}" let urls = ["foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"] for url in urls: printUri(url)
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Rewrite this program in C# while keeping its functionality equivalent to the Perl version.
use warnings; use strict; use URI; for my $uri (do { no warnings 'qw'; qw( foo://example.com:8042/over/there?name=ferret urn:example:animal:ferret:nose jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true ftp://ftp.is.co.za/rfc/rfc1808.txt http://www.ietf.org/rfc/rfc2396.txt ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet://192.0.2.16:80/ urn:oasis:names:specification:docbook:dtd:xml:4.1.2 )}) { my $u = 'URI'->new($uri); print "$uri\n"; for my $part (qw( scheme path fragment authority host port query )) { eval { my $parsed = $u->$part; print "\t", $part, "\t", $parsed, "\n" if defined $parsed; }; } }
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Change the programming language of this snippet from Perl to C# without modifying what it does.
use warnings; use strict; use URI; for my $uri (do { no warnings 'qw'; qw( foo://example.com:8042/over/there?name=ferret urn:example:animal:ferret:nose jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true ftp://ftp.is.co.za/rfc/rfc1808.txt http://www.ietf.org/rfc/rfc2396.txt ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet://192.0.2.16:80/ urn:oasis:names:specification:docbook:dtd:xml:4.1.2 )}) { my $u = 'URI'->new($uri); print "$uri\n"; for my $part (qw( scheme path fragment authority host port query )) { eval { my $parsed = $u->$part; print "\t", $part, "\t", $parsed, "\n" if defined $parsed; }; } }
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Rewrite the snippet below in Java so it works the same as the original Perl code.
use warnings; use strict; use URI; for my $uri (do { no warnings 'qw'; qw( foo://example.com:8042/over/there?name=ferret urn:example:animal:ferret:nose jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true ftp://ftp.is.co.za/rfc/rfc1808.txt http://www.ietf.org/rfc/rfc2396.txt ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet://192.0.2.16:80/ urn:oasis:names:specification:docbook:dtd:xml:4.1.2 )}) { my $u = 'URI'->new($uri); print "$uri\n"; for my $part (qw( scheme path fragment authority host port query )) { eval { my $parsed = $u->$part; print "\t", $part, "\t", $parsed, "\n" if defined $parsed; }; } }
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Rewrite the snippet below in Java so it works the same as the original Perl code.
use warnings; use strict; use URI; for my $uri (do { no warnings 'qw'; qw( foo://example.com:8042/over/there?name=ferret urn:example:animal:ferret:nose jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true ftp://ftp.is.co.za/rfc/rfc1808.txt http://www.ietf.org/rfc/rfc2396.txt ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet://192.0.2.16:80/ urn:oasis:names:specification:docbook:dtd:xml:4.1.2 )}) { my $u = 'URI'->new($uri); print "$uri\n"; for my $part (qw( scheme path fragment authority host port query )) { eval { my $parsed = $u->$part; print "\t", $part, "\t", $parsed, "\n" if defined $parsed; }; } }
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Transform the following Perl implementation into Python, maintaining the same output and logic.
use warnings; use strict; use URI; for my $uri (do { no warnings 'qw'; qw( foo://example.com:8042/over/there?name=ferret urn:example:animal:ferret:nose jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true ftp://ftp.is.co.za/rfc/rfc1808.txt http://www.ietf.org/rfc/rfc2396.txt ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet://192.0.2.16:80/ urn:oasis:names:specification:docbook:dtd:xml:4.1.2 )}) { my $u = 'URI'->new($uri); print "$uri\n"; for my $part (qw( scheme path fragment authority host port query )) { eval { my $parsed = $u->$part; print "\t", $part, "\t", $parsed, "\n" if defined $parsed; }; } }
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Convert the following code from Perl to Python, ensuring the logic remains intact.
use warnings; use strict; use URI; for my $uri (do { no warnings 'qw'; qw( foo://example.com:8042/over/there?name=ferret urn:example:animal:ferret:nose jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true ftp://ftp.is.co.za/rfc/rfc1808.txt http://www.ietf.org/rfc/rfc2396.txt ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet://192.0.2.16:80/ urn:oasis:names:specification:docbook:dtd:xml:4.1.2 )}) { my $u = 'URI'->new($uri); print "$uri\n"; for my $part (qw( scheme path fragment authority host port query )) { eval { my $parsed = $u->$part; print "\t", $part, "\t", $parsed, "\n" if defined $parsed; }; } }
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Change the programming language of this snippet from Perl to VB without modifying what it does.
use warnings; use strict; use URI; for my $uri (do { no warnings 'qw'; qw( foo://example.com:8042/over/there?name=ferret urn:example:animal:ferret:nose jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true ftp://ftp.is.co.za/rfc/rfc1808.txt http://www.ietf.org/rfc/rfc2396.txt ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet://192.0.2.16:80/ urn:oasis:names:specification:docbook:dtd:xml:4.1.2 )}) { my $u = 'URI'->new($uri); print "$uri\n"; for my $part (qw( scheme path fragment authority host port query )) { eval { my $parsed = $u->$part; print "\t", $part, "\t", $parsed, "\n" if defined $parsed; }; } }
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Ensure the translated VB code behaves exactly like the original Perl snippet.
use warnings; use strict; use URI; for my $uri (do { no warnings 'qw'; qw( foo://example.com:8042/over/there?name=ferret urn:example:animal:ferret:nose jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true ftp://ftp.is.co.za/rfc/rfc1808.txt http://www.ietf.org/rfc/rfc2396.txt ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet://192.0.2.16:80/ urn:oasis:names:specification:docbook:dtd:xml:4.1.2 )}) { my $u = 'URI'->new($uri); print "$uri\n"; for my $part (qw( scheme path fragment authority host port query )) { eval { my $parsed = $u->$part; print "\t", $part, "\t", $parsed, "\n" if defined $parsed; }; } }
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Please provide an equivalent version of this Perl code in Go.
use warnings; use strict; use URI; for my $uri (do { no warnings 'qw'; qw( foo://example.com:8042/over/there?name=ferret urn:example:animal:ferret:nose jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true ftp://ftp.is.co.za/rfc/rfc1808.txt http://www.ietf.org/rfc/rfc2396.txt ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet://192.0.2.16:80/ urn:oasis:names:specification:docbook:dtd:xml:4.1.2 )}) { my $u = 'URI'->new($uri); print "$uri\n"; for my $part (qw( scheme path fragment authority host port query )) { eval { my $parsed = $u->$part; print "\t", $part, "\t", $parsed, "\n" if defined $parsed; }; } }
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Port the provided Perl code into Go while preserving the original functionality.
use warnings; use strict; use URI; for my $uri (do { no warnings 'qw'; qw( foo://example.com:8042/over/there?name=ferret urn:example:animal:ferret:nose jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true ftp://ftp.is.co.za/rfc/rfc1808.txt http://www.ietf.org/rfc/rfc2396.txt ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet://192.0.2.16:80/ urn:oasis:names:specification:docbook:dtd:xml:4.1.2 )}) { my $u = 'URI'->new($uri); print "$uri\n"; for my $part (qw( scheme path fragment authority host port query )) { eval { my $parsed = $u->$part; print "\t", $part, "\t", $parsed, "\n" if defined $parsed; }; } }
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Rewrite this program in C# while keeping its functionality equivalent to the PowerShell version.
function Get-ParsedUrl { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [System.Uri] $InputObject ) Process { foreach ($url in $InputObject) { $url | Select-Object -Property Scheme, @{Name="Domain"; Expression={$_.Host}}, Port, @{Name="Path" ; Expression={$_.LocalPath}}, Query, Fragment, AbsolutePath, AbsoluteUri, Authority, HostNameType, IsDefaultPort, IsFile, IsLoopback, PathAndQuery, Segments, IsUnc, OriginalString, DnsSafeHost, IdnHost, IsAbsoluteUri, UserEscaped, UserInfo } } }
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Transform the following PowerShell implementation into C#, maintaining the same output and logic.
function Get-ParsedUrl { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [System.Uri] $InputObject ) Process { foreach ($url in $InputObject) { $url | Select-Object -Property Scheme, @{Name="Domain"; Expression={$_.Host}}, Port, @{Name="Path" ; Expression={$_.LocalPath}}, Query, Fragment, AbsolutePath, AbsoluteUri, Authority, HostNameType, IsDefaultPort, IsFile, IsLoopback, PathAndQuery, Segments, IsUnc, OriginalString, DnsSafeHost, IdnHost, IsAbsoluteUri, UserEscaped, UserInfo } } }
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Write a version of this PowerShell function in Java with identical behavior.
function Get-ParsedUrl { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [System.Uri] $InputObject ) Process { foreach ($url in $InputObject) { $url | Select-Object -Property Scheme, @{Name="Domain"; Expression={$_.Host}}, Port, @{Name="Path" ; Expression={$_.LocalPath}}, Query, Fragment, AbsolutePath, AbsoluteUri, Authority, HostNameType, IsDefaultPort, IsFile, IsLoopback, PathAndQuery, Segments, IsUnc, OriginalString, DnsSafeHost, IdnHost, IsAbsoluteUri, UserEscaped, UserInfo } } }
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Generate an equivalent Java version of this PowerShell code.
function Get-ParsedUrl { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [System.Uri] $InputObject ) Process { foreach ($url in $InputObject) { $url | Select-Object -Property Scheme, @{Name="Domain"; Expression={$_.Host}}, Port, @{Name="Path" ; Expression={$_.LocalPath}}, Query, Fragment, AbsolutePath, AbsoluteUri, Authority, HostNameType, IsDefaultPort, IsFile, IsLoopback, PathAndQuery, Segments, IsUnc, OriginalString, DnsSafeHost, IdnHost, IsAbsoluteUri, UserEscaped, UserInfo } } }
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Port the following code from PowerShell to Python with equivalent syntax and logic.
function Get-ParsedUrl { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [System.Uri] $InputObject ) Process { foreach ($url in $InputObject) { $url | Select-Object -Property Scheme, @{Name="Domain"; Expression={$_.Host}}, Port, @{Name="Path" ; Expression={$_.LocalPath}}, Query, Fragment, AbsolutePath, AbsoluteUri, Authority, HostNameType, IsDefaultPort, IsFile, IsLoopback, PathAndQuery, Segments, IsUnc, OriginalString, DnsSafeHost, IdnHost, IsAbsoluteUri, UserEscaped, UserInfo } } }
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Convert the following code from PowerShell to Python, ensuring the logic remains intact.
function Get-ParsedUrl { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [System.Uri] $InputObject ) Process { foreach ($url in $InputObject) { $url | Select-Object -Property Scheme, @{Name="Domain"; Expression={$_.Host}}, Port, @{Name="Path" ; Expression={$_.LocalPath}}, Query, Fragment, AbsolutePath, AbsoluteUri, Authority, HostNameType, IsDefaultPort, IsFile, IsLoopback, PathAndQuery, Segments, IsUnc, OriginalString, DnsSafeHost, IdnHost, IsAbsoluteUri, UserEscaped, UserInfo } } }
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Convert this PowerShell snippet to VB and keep its semantics consistent.
function Get-ParsedUrl { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [System.Uri] $InputObject ) Process { foreach ($url in $InputObject) { $url | Select-Object -Property Scheme, @{Name="Domain"; Expression={$_.Host}}, Port, @{Name="Path" ; Expression={$_.LocalPath}}, Query, Fragment, AbsolutePath, AbsoluteUri, Authority, HostNameType, IsDefaultPort, IsFile, IsLoopback, PathAndQuery, Segments, IsUnc, OriginalString, DnsSafeHost, IdnHost, IsAbsoluteUri, UserEscaped, UserInfo } } }
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Write the same algorithm in VB as shown in this PowerShell implementation.
function Get-ParsedUrl { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [System.Uri] $InputObject ) Process { foreach ($url in $InputObject) { $url | Select-Object -Property Scheme, @{Name="Domain"; Expression={$_.Host}}, Port, @{Name="Path" ; Expression={$_.LocalPath}}, Query, Fragment, AbsolutePath, AbsoluteUri, Authority, HostNameType, IsDefaultPort, IsFile, IsLoopback, PathAndQuery, Segments, IsUnc, OriginalString, DnsSafeHost, IdnHost, IsAbsoluteUri, UserEscaped, UserInfo } } }
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Transform the following PowerShell implementation into Go, maintaining the same output and logic.
function Get-ParsedUrl { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [System.Uri] $InputObject ) Process { foreach ($url in $InputObject) { $url | Select-Object -Property Scheme, @{Name="Domain"; Expression={$_.Host}}, Port, @{Name="Path" ; Expression={$_.LocalPath}}, Query, Fragment, AbsolutePath, AbsoluteUri, Authority, HostNameType, IsDefaultPort, IsFile, IsLoopback, PathAndQuery, Segments, IsUnc, OriginalString, DnsSafeHost, IdnHost, IsAbsoluteUri, UserEscaped, UserInfo } } }
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Keep all operations the same but rewrite the snippet in Go.
function Get-ParsedUrl { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [System.Uri] $InputObject ) Process { foreach ($url in $InputObject) { $url | Select-Object -Property Scheme, @{Name="Domain"; Expression={$_.Host}}, Port, @{Name="Path" ; Expression={$_.LocalPath}}, Query, Fragment, AbsolutePath, AbsoluteUri, Authority, HostNameType, IsDefaultPort, IsFile, IsLoopback, PathAndQuery, Segments, IsUnc, OriginalString, DnsSafeHost, IdnHost, IsAbsoluteUri, UserEscaped, UserInfo } } }
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Translate the given Racket code snippet into C# without altering its behavior.
#lang racket/base (require racket/match net/url) (define (debug-url-string U) (match-define (url s u h p pa? (list (path/param pas prms) ...) q f) (string->url U)) (printf "URL: ~s~%" U) (printf "-----~a~%" (make-string (string-length (format "~s" U)) #\-)) (when #t (printf "scheme: ~s~%" s)) (when u (printf "user: ~s~%" u)) (when h (printf "host: ~s~%" h)) (when p (printf "port: ~s~%" p)) (printf "path-absolute?: ~s~%" pa?) (printf "path bits: ~s~%" pas) (when (memf pair? prms) (printf "param bits: ~s [interleaved with path bits]~%" prms)) (unless (null? q) (printf "query: ~s~%" q)) (when f (printf "fragment: ~s~%" f)) (newline)) (for-each debug-url-string '("foo://example.com:8042/over/there?name=ferret#nose" "urn:example:animal:ferret:nose" "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" "ftp://ftp.is.co.za/rfc/rfc1808.txt" "http://www.ietf.org/rfc/rfc2396.txt#header1" "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two" "mailto:John.Doe@example.com" "news:comp.infosystems.www.servers.unix" "tel:+1-816-555-1212" "telnet://192.0.2.16:80/" "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"))
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Translate the given Racket code snippet into C# without altering its behavior.
#lang racket/base (require racket/match net/url) (define (debug-url-string U) (match-define (url s u h p pa? (list (path/param pas prms) ...) q f) (string->url U)) (printf "URL: ~s~%" U) (printf "-----~a~%" (make-string (string-length (format "~s" U)) #\-)) (when #t (printf "scheme: ~s~%" s)) (when u (printf "user: ~s~%" u)) (when h (printf "host: ~s~%" h)) (when p (printf "port: ~s~%" p)) (printf "path-absolute?: ~s~%" pa?) (printf "path bits: ~s~%" pas) (when (memf pair? prms) (printf "param bits: ~s [interleaved with path bits]~%" prms)) (unless (null? q) (printf "query: ~s~%" q)) (when f (printf "fragment: ~s~%" f)) (newline)) (for-each debug-url-string '("foo://example.com:8042/over/there?name=ferret#nose" "urn:example:animal:ferret:nose" "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" "ftp://ftp.is.co.za/rfc/rfc1808.txt" "http://www.ietf.org/rfc/rfc2396.txt#header1" "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two" "mailto:John.Doe@example.com" "news:comp.infosystems.www.servers.unix" "tel:+1-816-555-1212" "telnet://192.0.2.16:80/" "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"))
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
Please provide an equivalent version of this Racket code in Java.
#lang racket/base (require racket/match net/url) (define (debug-url-string U) (match-define (url s u h p pa? (list (path/param pas prms) ...) q f) (string->url U)) (printf "URL: ~s~%" U) (printf "-----~a~%" (make-string (string-length (format "~s" U)) #\-)) (when #t (printf "scheme: ~s~%" s)) (when u (printf "user: ~s~%" u)) (when h (printf "host: ~s~%" h)) (when p (printf "port: ~s~%" p)) (printf "path-absolute?: ~s~%" pa?) (printf "path bits: ~s~%" pas) (when (memf pair? prms) (printf "param bits: ~s [interleaved with path bits]~%" prms)) (unless (null? q) (printf "query: ~s~%" q)) (when f (printf "fragment: ~s~%" f)) (newline)) (for-each debug-url-string '("foo://example.com:8042/over/there?name=ferret#nose" "urn:example:animal:ferret:nose" "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" "ftp://ftp.is.co.za/rfc/rfc1808.txt" "http://www.ietf.org/rfc/rfc2396.txt#header1" "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two" "mailto:John.Doe@example.com" "news:comp.infosystems.www.servers.unix" "tel:+1-816-555-1212" "telnet://192.0.2.16:80/" "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"))
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Rewrite the snippet below in Java so it works the same as the original Racket code.
#lang racket/base (require racket/match net/url) (define (debug-url-string U) (match-define (url s u h p pa? (list (path/param pas prms) ...) q f) (string->url U)) (printf "URL: ~s~%" U) (printf "-----~a~%" (make-string (string-length (format "~s" U)) #\-)) (when #t (printf "scheme: ~s~%" s)) (when u (printf "user: ~s~%" u)) (when h (printf "host: ~s~%" h)) (when p (printf "port: ~s~%" p)) (printf "path-absolute?: ~s~%" pa?) (printf "path bits: ~s~%" pas) (when (memf pair? prms) (printf "param bits: ~s [interleaved with path bits]~%" prms)) (unless (null? q) (printf "query: ~s~%" q)) (when f (printf "fragment: ~s~%" f)) (newline)) (for-each debug-url-string '("foo://example.com:8042/over/there?name=ferret#nose" "urn:example:animal:ferret:nose" "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" "ftp://ftp.is.co.za/rfc/rfc1808.txt" "http://www.ietf.org/rfc/rfc2396.txt#header1" "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two" "mailto:John.Doe@example.com" "news:comp.infosystems.www.servers.unix" "tel:+1-816-555-1212" "telnet://192.0.2.16:80/" "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"))
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo: parseAddress("urn:example:animal:ferret:nose"); } static void parseAddress(String a){ System.out.println("Parsing " + a); try{ URI u = new URI(a); System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }
Write a version of this Racket function in Python with identical behavior.
#lang racket/base (require racket/match net/url) (define (debug-url-string U) (match-define (url s u h p pa? (list (path/param pas prms) ...) q f) (string->url U)) (printf "URL: ~s~%" U) (printf "-----~a~%" (make-string (string-length (format "~s" U)) #\-)) (when #t (printf "scheme: ~s~%" s)) (when u (printf "user: ~s~%" u)) (when h (printf "host: ~s~%" h)) (when p (printf "port: ~s~%" p)) (printf "path-absolute?: ~s~%" pa?) (printf "path bits: ~s~%" pas) (when (memf pair? prms) (printf "param bits: ~s [interleaved with path bits]~%" prms)) (unless (null? q) (printf "query: ~s~%" q)) (when f (printf "fragment: ~s~%" f)) (newline)) (for-each debug-url-string '("foo://example.com:8042/over/there?name=ferret#nose" "urn:example:animal:ferret:nose" "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" "ftp://ftp.is.co.za/rfc/rfc1808.txt" "http://www.ietf.org/rfc/rfc2396.txt#header1" "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two" "mailto:John.Doe@example.com" "news:comp.infosystems.www.servers.unix" "tel:+1-816-555-1212" "telnet://192.0.2.16:80/" "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"))
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Please provide an equivalent version of this Racket code in Python.
#lang racket/base (require racket/match net/url) (define (debug-url-string U) (match-define (url s u h p pa? (list (path/param pas prms) ...) q f) (string->url U)) (printf "URL: ~s~%" U) (printf "-----~a~%" (make-string (string-length (format "~s" U)) #\-)) (when #t (printf "scheme: ~s~%" s)) (when u (printf "user: ~s~%" u)) (when h (printf "host: ~s~%" h)) (when p (printf "port: ~s~%" p)) (printf "path-absolute?: ~s~%" pa?) (printf "path bits: ~s~%" pas) (when (memf pair? prms) (printf "param bits: ~s [interleaved with path bits]~%" prms)) (unless (null? q) (printf "query: ~s~%" q)) (when f (printf "fragment: ~s~%" f)) (newline)) (for-each debug-url-string '("foo://example.com:8042/over/there?name=ferret#nose" "urn:example:animal:ferret:nose" "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" "ftp://ftp.is.co.za/rfc/rfc1808.txt" "http://www.ietf.org/rfc/rfc2396.txt#header1" "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two" "mailto:John.Doe@example.com" "news:comp.infosystems.www.servers.unix" "tel:+1-816-555-1212" "telnet://192.0.2.16:80/" "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"))
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Please provide an equivalent version of this Racket code in VB.
#lang racket/base (require racket/match net/url) (define (debug-url-string U) (match-define (url s u h p pa? (list (path/param pas prms) ...) q f) (string->url U)) (printf "URL: ~s~%" U) (printf "-----~a~%" (make-string (string-length (format "~s" U)) #\-)) (when #t (printf "scheme: ~s~%" s)) (when u (printf "user: ~s~%" u)) (when h (printf "host: ~s~%" h)) (when p (printf "port: ~s~%" p)) (printf "path-absolute?: ~s~%" pa?) (printf "path bits: ~s~%" pas) (when (memf pair? prms) (printf "param bits: ~s [interleaved with path bits]~%" prms)) (unless (null? q) (printf "query: ~s~%" q)) (when f (printf "fragment: ~s~%" f)) (newline)) (for-each debug-url-string '("foo://example.com:8042/over/there?name=ferret#nose" "urn:example:animal:ferret:nose" "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" "ftp://ftp.is.co.za/rfc/rfc1808.txt" "http://www.ietf.org/rfc/rfc2396.txt#header1" "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two" "mailto:John.Doe@example.com" "news:comp.infosystems.www.servers.unix" "tel:+1-816-555-1212" "telnet://192.0.2.16:80/" "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"))
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Maintain the same structure and functionality when rewriting this code in VB.
#lang racket/base (require racket/match net/url) (define (debug-url-string U) (match-define (url s u h p pa? (list (path/param pas prms) ...) q f) (string->url U)) (printf "URL: ~s~%" U) (printf "-----~a~%" (make-string (string-length (format "~s" U)) #\-)) (when #t (printf "scheme: ~s~%" s)) (when u (printf "user: ~s~%" u)) (when h (printf "host: ~s~%" h)) (when p (printf "port: ~s~%" p)) (printf "path-absolute?: ~s~%" pa?) (printf "path bits: ~s~%" pas) (when (memf pair? prms) (printf "param bits: ~s [interleaved with path bits]~%" prms)) (unless (null? q) (printf "query: ~s~%" q)) (when f (printf "fragment: ~s~%" f)) (newline)) (for-each debug-url-string '("foo://example.com:8042/over/there?name=ferret#nose" "urn:example:animal:ferret:nose" "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" "ftp://ftp.is.co.za/rfc/rfc1808.txt" "http://www.ietf.org/rfc/rfc2396.txt#header1" "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two" "mailto:John.Doe@example.com" "news:comp.infosystems.www.servers.unix" "tel:+1-816-555-1212" "telnet://192.0.2.16:80/" "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"))
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
Convert the following code from Racket to Go, ensuring the logic remains intact.
#lang racket/base (require racket/match net/url) (define (debug-url-string U) (match-define (url s u h p pa? (list (path/param pas prms) ...) q f) (string->url U)) (printf "URL: ~s~%" U) (printf "-----~a~%" (make-string (string-length (format "~s" U)) #\-)) (when #t (printf "scheme: ~s~%" s)) (when u (printf "user: ~s~%" u)) (when h (printf "host: ~s~%" h)) (when p (printf "port: ~s~%" p)) (printf "path-absolute?: ~s~%" pa?) (printf "path bits: ~s~%" pas) (when (memf pair? prms) (printf "param bits: ~s [interleaved with path bits]~%" prms)) (unless (null? q) (printf "query: ~s~%" q)) (when f (printf "fragment: ~s~%" f)) (newline)) (for-each debug-url-string '("foo://example.com:8042/over/there?name=ferret#nose" "urn:example:animal:ferret:nose" "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" "ftp://ftp.is.co.za/rfc/rfc1808.txt" "http://www.ietf.org/rfc/rfc2396.txt#header1" "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two" "mailto:John.Doe@example.com" "news:comp.infosystems.www.servers.unix" "tel:+1-816-555-1212" "telnet://192.0.2.16:80/" "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"))
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Generate a Go translation of this Racket snippet without changing its computational steps.
#lang racket/base (require racket/match net/url) (define (debug-url-string U) (match-define (url s u h p pa? (list (path/param pas prms) ...) q f) (string->url U)) (printf "URL: ~s~%" U) (printf "-----~a~%" (make-string (string-length (format "~s" U)) #\-)) (when #t (printf "scheme: ~s~%" s)) (when u (printf "user: ~s~%" u)) (when h (printf "host: ~s~%" h)) (when p (printf "port: ~s~%" p)) (printf "path-absolute?: ~s~%" pa?) (printf "path bits: ~s~%" pas) (when (memf pair? prms) (printf "param bits: ~s [interleaved with path bits]~%" prms)) (unless (null? q) (printf "query: ~s~%" q)) (when f (printf "fragment: ~s~%" f)) (newline)) (for-each debug-url-string '("foo://example.com:8042/over/there?name=ferret#nose" "urn:example:animal:ferret:nose" "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" "ftp://ftp.is.co.za/rfc/rfc1808.txt" "http://www.ietf.org/rfc/rfc2396.txt#header1" "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two" "mailto:John.Doe@example.com" "news:comp.infosystems.www.servers.unix" "tel:+1-816-555-1212" "telnet://192.0.2.16:80/" "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"))
package main import ( "fmt" "log" "net" "net/url" ) func main() { for _, in := range []string{ "foo: "urn:example:animal:ferret:nose", "jdbc:mysql: "ftp: "http: "ldap: "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet: "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh: "https: "http: } { fmt.Println(in) u, err := url.Parse(in) if err != nil { log.Println(err) continue } if in != u.String() { fmt.Printf("Note: reassmebles as %q\n", u) } printURL(u) } } func printURL(u *url.URL) { fmt.Println(" Scheme:", u.Scheme) if u.Opaque != "" { fmt.Println(" Opaque:", u.Opaque) } if u.User != nil { fmt.Println(" Username:", u.User.Username()) if pwd, ok := u.User.Password(); ok { fmt.Println(" Password:", pwd) } } if u.Host != "" { if host, port, err := net.SplitHostPort(u.Host); err == nil { fmt.Println(" Host:", host) fmt.Println(" Port:", port) } else { fmt.Println(" Host:", u.Host) } } if u.Path != "" { fmt.Println(" Path:", u.Path) } if u.RawQuery != "" { fmt.Println(" RawQuery:", u.RawQuery) m, err := url.ParseQuery(u.RawQuery) if err == nil { for k, v := range m { fmt.Printf(" Key: %q Values: %q\n", k, v) } } } if u.Fragment != "" { fmt.Println(" Fragment:", u.Fragment) } }
Port the following code from Ruby to C# with equivalent syntax and logic.
require 'uri' test_cases = [ "foo://example.com:8042/over/there?name=ferret "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com", "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64" ] class URI::Generic; alias_method :domain, :host; end test_cases.each do |test_case| puts test_case uri = URI.parse(test_case) %w[ scheme domain port path query fragment user password ].each do |attr| puts " end end
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }