WeixiangYan/CodeTransOcean huggingface dataset:
Task: Respond to an unknown method call



C#: using System;
using System.Dynamic;

class Example : DynamicObject
{
    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
    {
        result = null;

        Console.WriteLine("This is {0}.", binder.Name);
        return true;
    }
}

class Program
{
    static void Main(string[] args)
    {
        dynamic ex = new Example();

        ex.Foo();
        ex.Bar();
    }
}





Python: class Example(object):
    def foo(self):
        print("this is foo")
    def bar(self):
        print("this is bar")
    def __getattr__(self, name):
        def method(*args):
            print("tried to handle unknown method " + name)
            if args:
                print("it had arguments: " + str(args))
        return method

example = Example()

example.foo()        
example.bar()        
example.grill()      
example.ding("dong")
Task: Closest-pair problem



C#: class Segment
{
    public Segment(PointF p1, PointF p2)
    {
        P1 = p1;
        P2 = p2;
    }

    public readonly PointF P1;
    public readonly PointF P2;

    public float Length()
    {
        return (float)Math.Sqrt(LengthSquared());
    }

    public float LengthSquared()
    {
        return (P1.X - P2.X) * (P1.X - P2.X)
            + (P1.Y - P2.Y) * (P1.Y - P2.Y);
    }
}





Python: 

from random import randint, randrange
from operator import itemgetter, attrgetter

infinity = float('inf')



def bruteForceClosestPair(point):
    numPoints = len(point)
    if numPoints < 2:
        return infinity, (None, None)
    return min( ((abs(point[i] - point[j]), (point[i], point[j]))
                 for i in range(numPoints-1)
                 for j in range(i+1,numPoints)),
                key=itemgetter(0))

def closestPair(point):
    xP = sorted(point, key= attrgetter('real'))
    yP = sorted(point, key= attrgetter('imag'))
    return _closestPair(xP, yP)

def _closestPair(xP, yP):
    numPoints = len(xP)
    if numPoints <= 3:
        return bruteForceClosestPair(xP)
    Pl = xP[:numPoints/2]
    Pr = xP[numPoints/2:]
    Yl, Yr = [], []
    xDivider = Pl[-1].real
    for p in yP:
        if p.real <= xDivider:
            Yl.append(p)
        else:
            Yr.append(p)
    dl, pairl = _closestPair(Pl, Yl)
    dr, pairr = _closestPair(Pr, Yr)
    dm, pairm = (dl, pairl) if dl < dr else (dr, pairr)
    
    closeY = [p for p in yP  if abs(p.real - xDivider) < dm]
    numCloseY = len(closeY)
    if numCloseY > 1:
        
        closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j]))
                         for i in range(numCloseY-1)
                         for j in range(i+1,min(i+8, numCloseY))),
                        key=itemgetter(0))
        return (dm, pairm) if dm <= closestY[0] else closestY
    else:
        return dm, pairm
    
def times():
    
    import timeit

    functions = [bruteForceClosestPair, closestPair]
    for f in functions:
        print 'Time for', f.__name__, timeit.Timer(
            '%s(pointList)' % f.__name__,
            'from closestpair import %s, pointList' % f.__name__).timeit(number=1)
    


pointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)]

if __name__ == '__main__':
    pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)]
    print pointList
    print '  bruteForceClosestPair:', bruteForceClosestPair(pointList)
    print '            closestPair:', closestPair(pointList)
    for i in range(10):
        pointList = [randrange(11)+1j*randrange(11) for i in range(10)]
        print '\n', pointList
        print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)
        print '           closestPair:', closestPair(pointList)
    print '\n'
    times()
    times()
    times()
Task: Address of a variable



C#: int i = 5;
int* p = &i;





Python: var num = 12
var pointer = ptr(num) 

print pointer 

@unsafe 
pointer.addr = 0xFFFE
Task: Inheritance_Single



C#: class Animal
{ 
   
  
}

class Dog : Animal
{ 
   
  
}

class Lab : Dog
{ 
   
  
}

class Collie : Dog
{ 
  
  
}

class Cat : Animal
{ 
  
  
}





Python: class Animal:
  pass 

class Dog(Animal):
  pass 

class Cat(Animal):
  pass 

class Lab(Dog):
  pass 

class Collie(Dog):
  pass
Task: Associative array_Creation



C#: System.Collections.HashTable map = new System.Collections.HashTable();
map["key1"] = "foo";





Python: hash = dict()  
hash = dict(red="FF0000", green="00FF00", blue="0000FF")
hash = { 'key1':1, 'key2':2, }
value = hash[key]
Task: Color wheel



C#: 

public MainWindow()
{
    InitializeComponent();
    RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality);
    imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null);
    
    DrawHue(100);
}

void DrawHue(int saturation)
{
    var bmp = (WriteableBitmap)imgMain.Source;

    int centerX = (int)bmp.Width / 2;
    int centerY = (int)bmp.Height / 2;
    int radius = Math.Min(centerX, centerY);
    int radius2 = radius - 40;

    bmp.Lock();
    unsafe{
        var buf = bmp.BackBuffer;
        IntPtr pixLineStart;
        for(int y=0; y < bmp.Height; y++){
            pixLineStart = buf + bmp.BackBufferStride * y;
            double dy = (y - centerY);
            for(int x=0; x < bmp.Width; x++){
                double dx = (x - centerX);
                double dist = Math.Sqrt(dx * dx + dy * dy);
                if (radius2 <= dist && dist <= radius) {
                    double theta = Math.Atan2(dy, dx);
                    double hue = (theta + Math.PI) / (2.0 * Math.PI);
                    *((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100);
                }
            }
        }
    }
    bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480));
    bmp.Unlock();
}

static int HSB_to_RGB(int h, int s, int v)
{
    var rgb = new int[3];

    var baseColor = (h + 60) % 360 / 120;
    var shift = (h + 60) % 360 - (120 * baseColor + 60 );
    var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3;

    
    rgb[baseColor] = 255;
    rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f);

    
    for (var i = 0; i < 3; i++)
        rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f));

    
    for (var i = 0; i < 3; i++)
        rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f);

    return RGB2int(rgb[0], rgb[1], rgb[2]);
}

public static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;





Python: size(300, 300)
background(0)
radius = min(width, height) / 2.0
cx, cy = width / 2, width / 2
for x in range(width):
        for y in range(height):
            rx = x - cx
            ry = y - cy
            s = sqrt(rx ** 2 + ry ** 2) / radius
            if s <= 1.0:
                h = ((atan2(ry, rx) / PI) + 1.0) / 2.0
                colorMode(HSB)
                c = color(int(h * 255), int(s * 255), 255)
                set(x, y, c)
Task: Polymorphism



C#: using System;
class Point
{
  protected int x, y;
  public Point() : this(0) {}
  public Point(int x) : this(x,0) {}
  public Point(int x, int y) { this.x = x; this.y = y; }
  public int X { get { return x; } set { x = value; } }
  public int Y { get { return y; } set { y = value; } }
  public virtual void print() { System.Console.WriteLine("Point"); }
}

public class Circle : Point
{
  private int r;
  public Circle(Point p) : this(p,0) { }
  public Circle(Point p, int r) : base(p) { this.r = r; }
  public Circle() : this(0) { }
  public Circle(int x) : this(x,0) { }
  public Circle(int x, int y) : this(x,y,0) { }
  public Circle(int x, int y, int r) : base(x,y) { this.r = r; }
  public int R { get { return r; } set { r = value; } }
  public override void print() { System.Console.WriteLine("Circle"); }
 
  public static void main(String args[])
  {
    Point p = new Point();
    Point c = new Circle();
    p.print();
    c.print();
  }
}





Python: class Point(object):
    def __init__(self, x=0.0, y=0.0):
        self.x = x
        self.y = y
    def __repr__(self):
        return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)

class Circle(object):
    def __init__(self, center=None, radius=1.0):
        self.center = center or Point()
        self.radius = radius
    def __repr__(self):
        return '<Circle 0x%x x: %f y: %f radius: %f>' % (
            id(self), self.center.x, self.center.y, self.radius)
Task: Align columns



C#: using System;
class ColumnAlignerProgram
{
    delegate string Justification(string s, int width);

    static string[] AlignColumns(string[] lines, Justification justification)
    {
        const char Separator = '$';
        
        string[][] table = new string[lines.Length][];
        int columns = 0;
        for (int i = 0; i < lines.Length; i++)
        {
            string[] row = lines[i].TrimEnd(Separator).Split(Separator);
            if (columns < row.Length) columns = row.Length;
            table[i] = row;
        }
        
        string[][] formattedTable = new string[table.Length][];
        for (int i = 0; i < formattedTable.Length; i++)
        {
            formattedTable[i] = new string[columns];
        }
        for (int j = 0; j < columns; j++)
        {
            
            int columnWidth = 0;
            for (int i = 0; i < table.Length; i++)
            {
                if (j < table[i].Length && columnWidth < table[i][j].Length)
                    columnWidth = table[i][j].Length;
            }
            
            for (int i = 0; i < formattedTable.Length; i++)
            {
                if (j < table[i].Length)
                    formattedTable[i][j] = justification(table[i][j], columnWidth);
                else 
                    formattedTable[i][j] = new String(' ', columnWidth);
            }
        }
        
        string[] result = new string[formattedTable.Length];
        for (int i = 0; i < result.Length; i++)
        {
            result[i] = String.Join(" ", formattedTable[i]);
        }
        return result;
    }

    static string JustifyLeft(string s, int width) { return s.PadRight(width); }
    static string JustifyRight(string s, int width) { return s.PadLeft(width); }
    static string JustifyCenter(string s, int width) 
    { 
        return s.PadLeft((width + s.Length) / 2).PadRight(width); 
    }

    static void Main()
    {
        string[] input = {    
            "Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
            "are$delineated$by$a$single$'dollar'$character,$write$a$program",
            "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$",
            "column$are$separated$by$at$least$one$space.",
            "Further,$allow$for$each$word$in$a$column$to$be$either$left$",
            "justified,$right$justified,$or$center$justified$within$its$column.",
        };

        foreach (string line in AlignColumns(input, JustifyCenter))
        {
            Console.WriteLine(line);
        }
    }
}





Python: from itertools import zip_longest

txt = 
 
parts = [line.rstrip("$").split("$") for line in txt.splitlines()]
widths = [max(len(word) for word in col) 
          for col in zip_longest(*parts, fillvalue='')]
 
for justify in "<_Left ^_Center >_Right".split():
    j, jtext = justify.split('_')
    print(f"{jtext} column-aligned output:\n")
    for line in parts:
        print(' '.join(f"{wrd:{j}{wdth}}" for wdth, wrd in zip(widths, line)))
    print("- " * 52)
Task: URL parser



C#: 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");
        }
    }
}





Python: 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)
Task: Idoneal numbers



C#: using System;

class Program {

  static void Main(string[] args) {
    var sw = System.Diagnostics.Stopwatch.StartNew();
    int a, b, c, i, n, s3, ab; var res = new int[65];
    for (n = 1, i = 0; n < 1850; n++) {
      bool found = true;
      for (a = 1; a < n; a++)
         for (b = a + 1, ab = a * b + a + b; b < n; b++, ab += a + 1) {
            if (ab > n) break;
            for (c = b + 1, s3 = ab + (b + a) * b; c < n; c++, s3 += b + a) {
                if (s3 == n) found = false;
                if (s3 >= n) break;
            }
         }
      if (found) res[i++] = n;
    }
    sw.Stop();
    Console.WriteLine("The 65 known Idoneal numbers:");
    for (i = 0; i < res.Length; i++)
      Console.Write("{0,5}{1}", res[i], i % 13 == 12 ? "\n" : "");
    Console.Write("Calculations took {0} ms", sw.Elapsed.TotalMilliseconds);
  }
}





Python: 


def is_idoneal(num):
    
    for a in range(1, num):
        for b in range(a + 1, num):
            if a * b + a + b > num:
                break
            for c in range(b + 1, num):
                sum3 = a * b + b * c + a * c
                if sum3 == num:
                    return False
                if sum3 > num:
                    break
    return True


row = 0
for n in range(1, 2000):
    if is_idoneal(n):
        row += 1
        print(f'{n:5}', end='\n' if row % 13 == 0 else '')
Task: Base58Check encoding



C#: using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;

namespace Base58CheckEncoding {
    class Program {
        const string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

        static BigInteger ToBigInteger(string value, int @base) {
            const string HEX = "0123456789ABCDEF";
            if (@base < 1 || @base > HEX.Length) {
                throw new ArgumentException("Base is out of range.");
            }

            BigInteger bi = BigInteger.Zero;
            foreach (char c in value) {
                char c2 = Char.ToUpper(c);
                int idx = HEX.IndexOf(c2);
                if (idx == -1 || idx >= @base) {
                    throw new ArgumentOutOfRangeException("Illegal character encountered.");
                }
                bi = bi * @base + idx;
            }

            return bi;
        }

        static string ConvertToBase58(string hash, int @base = 16) {
            BigInteger x;
            if (@base == 16 && hash.Substring(0, 2) == "0x") {
                x = ToBigInteger(hash.Substring(2), @base);
            } else {
                x = ToBigInteger(hash, @base);
            }

            StringBuilder sb = new StringBuilder();
            while (x > 0) {
                BigInteger r = x % 58;
                sb.Append(ALPHABET[(int)r]);
                x = x / 58;
            }

            char[] ca = sb.ToString().ToCharArray();
            Array.Reverse(ca);
            return new string(ca);
        }

        static void Main(string[] args) {
            string s = "25420294593250030202636073700053352635053786165627414518";
            string b = ConvertToBase58(s, 10);
            Console.WriteLine("{0} -> {1}", s, b);

            List<string> hashes = new List<string>() {
                "0x61",
                "0x626262",
                "0x636363",
                "0x73696d706c792061206c6f6e6720737472696e67",
                "0x516b6fcd0f",
                "0xbf4f89001e670274dd",
                "0x572e4794",
                "0xecac89cad93923c02321",
                "0x10c8511e",
            };
            foreach (string hash in hashes) {
                string b58 = ConvertToBase58(hash);
                Console.WriteLine("{0,-56} -> {1}", hash, b58);
            }
        }
    }
}





Python: ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

def convertToBase58(num):
    sb = ''
    while (num > 0):
        r = num % 58
        sb = sb + ALPHABET[r]
        num = num // 58;
    return sb[::-1]

s = 25420294593250030202636073700053352635053786165627414518
b = convertToBase58(s)
print("%-56d -> %s" % (s, b))

hash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]
for num in hash_arr:
    b = convertToBase58(num)
    print("0x%-54x -> %s" % (num, b))
Task: Dynamic variable names



C#: using System;
using System.Dynamic;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        string varname = Console.ReadLine();
        
        dynamic expando = new ExpandoObject();
        var map = expando as IDictionary<string, object>;
        map.Add(varname, "Hello world!");
 
        Console.WriteLine(expando.foo);
    }
}





Python: >>> name = raw_input("Enter a variable name: ")
Enter a variable name: X
>>> globals()[name] = 42
>>> X
42
Task: Largest palindrome product



C#: using System;
class Program {

  static bool isPal(int n) {
    int rev = 0, lr = -1, rem;
    while (n > rev) {
      n = Math.DivRem(n, 10, out rem);
      if (lr < 0 && rem == 0) return false;
      lr = rev; rev = 10 * rev + rem;
      if (n == rev || n == lr) return true;
    } return false; }

  static void Main(string[] args) {
    var sw = System.Diagnostics.Stopwatch.StartNew();
    int x = 900009, y = (int)Math.Sqrt(x), y10, max = 999, max9 = max - 9, z, p, bp = x, ld, c;
    var a = new int[]{ 0,9,0,3,0,0,0,7,0,1 }; string bs = "";
    y /= 11;
    if ((y & 1) == 0) y--;
    if (y % 5 == 0) y -= 2;
    y *= 11;
    while (y <= max) {
      c = 0;
      y10 = y * 10;
      z = max9 + a[ld = y % 10];
      p = y * z;
      while (p >= bp) {
        if (isPal(p)) {
          if (p > bp) bp = p;
          bs = string.Format("{0} x {1} = {2}", y, z - c, bp);
        }
        p -= y10; c += 10;
      }
      y += ld == 3 ? 44 : 22;
    }
    sw.Stop();
    Console.Write("{0} {1} μs", bs, sw.Elapsed.TotalMilliseconds * 1000.0);
  }
}





Python: 

T=[set([(0, 0)])]

def double(it):
    for a, b in it:
        yield a, b
        yield b, a

def tails(n):
    
    if len(T)<=n:
        l = set()
        for i in range(10):
            for j in range(i, 10):
                I = i*10**(n-1)
                J = j*10**(n-1)
                it = tails(n-1)
                if I!=J: it = double(it)
                for t1, t2 in it:
                    if ((I+t1)*(J+t2)+1)%10**n == 0:
                        l.add((I+t1, J+t2))
        T.append(l)
    return T[n]

def largestPalindrome(n):
    
    m, tail = 0, n // 2
    head = n - tail
    up = 10**head
    for L in range(1, 9*10**(head-1)+1):
        
        m = 0
        sol = None
        for i in range(1, L + 1):
            lo = max(i, int(up - (up - L + 1)**2 / (up - i)) + 1)
            hi = int(up - (up - L)**2 / (up - i))
            for j in range(lo, hi + 1):
                I = (up-i) * 10**tail
                J = (up-j) * 10**tail
                it = tails(tail)
                if I!=J: it = double(it)
                    for t1, t2 in it:
                        val = (I + t1)*(J + t2)
                        s = str(val)
                        if s == s[::-1] and val>m:
                            sol = (I + t1, J + t2)
                            m = val

        if m:
            print("{:2d}\t{:4d}".format(n, m % 1337), sol, sol[0] * sol[1])
            return m % 1337
    return 0

if __name__ == "__main__":
    for k in range(1, 14):
        largestPalindrome(k)
Task: Commatizing numbers



C#: static string[] inputs = {
	"pi=3.14159265358979323846264338327950288419716939937510582097494459231",
	"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).",
	"\"-in Aus$+1411.8millions\"",
	"===US$0017440 millions=== (in 2000 dollars)"
};

void Main()
{
	inputs.Select(s => Commatize(s, 0, 3, ","))
              .ToList()
              .ForEach(Console.WriteLine);
}

string Commatize(string text, int startPosition, int interval, string separator)
{
	var matches = Regex.Matches(text.Substring(startPosition), "[0-9]*");
	var x = matches.Cast<Match>().Select(match => Commatize(match, interval, separator, text)).ToList();
	return string.Join("", x);
}


string Commatize(Match match, int interval, string separator, string original)
{
	if (match.Length <= interval)
		return original.Substring(match.Index, 
                match.Index == original.Length ? 0 : Math.Max(match.Length, 1));
	
	return string.Join(separator, match.Value.Split(interval));
}

public static class Extension
{
	public static string[] Split(this string source, int interval)
	{
		return SplitImpl(source, interval).ToArray();
	}
	
	static IEnumerable<string>SplitImpl(string source, int interval)
	{
		for	(int i = 1; i < source.Length; i++)
		{
			if (i % interval != 0) continue;
			
			yield return source.Substring(i - interval, interval);
		}
	}
}





Python: import re as RegEx


def Commatize( _string, _startPos=0, _periodLen=3, _separator="," ):
	outString = ""
	strPos = 0
	matches = RegEx.findall( "[0-9]*", _string )

	for match in matches[:-1]:
		if not match:
			outString += _string[ strPos ]
			strPos += 1
		else:
			if len(match) > _periodLen:
				leadIn = match[:_startPos]
				periods =  [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ]
				outString += leadIn + _separator.join( periods )
			else:
				outString += match

			strPos += len( match )

	return outString



print ( Commatize( "pi=3.14159265358979323846264338327950288419716939937510582097494459231", 0, 5, " " ) )
print ( Commatize( "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", 0, 3, "." ))
print ( Commatize( "\"-in Aus$+1411.8millions\"" ))
print ( Commatize( "===US$0017440 millions=== (in 2000 dollars)" ))
print ( Commatize( "123.e8000 is pretty big." ))
print ( Commatize( "The land area of the earth is 57268900(29% of the surface) square miles." ))
print ( Commatize( "Ain't no numbers in this here words, nohow, no way, Jose." ))
print ( Commatize( "James was never known as 0000000007" ))
print ( Commatize( "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe." ))
print ( Commatize( "␢␢␢$-140000±100 millions." ))
print ( Commatize( "6/9/1946 was a good year for some." ))