WeixiangYan/CodeTransOcean huggingface dataset:
Task: Same fringe

C: #include <stdio.h>
#include <stdlib.h>
#include <ucontext.h>

typedef struct {
	ucontext_t caller, callee;
	char stack[8192];
	void *in, *out;
} co_t;

co_t * co_new(void(*f)(), void *data)
{
	co_t * c = malloc(sizeof(*c));
	getcontext(&c->callee);
	c->in = data;

	c->callee.uc_stack.ss_sp = c->stack;
	c->callee.uc_stack.ss_size = sizeof(c->stack);
	c->callee.uc_link = &c->caller;
	makecontext(&c->callee, f, 1, (int)c);

	return c;
}

void co_del(co_t *c)
{
	free(c);
}

inline void
co_yield(co_t *c, void *data)
{
	c->out = data;
	swapcontext(&c->callee, &c->caller);
}

inline void *
co_collect(co_t *c)
{
	c->out = 0;
	swapcontext(&c->caller, &c->callee);
	return c->out;
}



typedef struct node node;
struct node {
	int v;
	node *left, *right;
};

node *newnode(int v)
{
	node *n = malloc(sizeof(node));
	n->left = n->right = 0;
	n->v = v;
	return n;
}

void tree_insert(node **root, node *n)
{
	while (*root) root = ((*root)->v > n->v)
				? &(*root)->left
				: &(*root)->right;
	*root = n;
}

void tree_trav(int x)
{
	co_t *c = (co_t *) x;

	void trav(node *root) {
		if (!root) return;
		trav(root->left);
		co_yield(c, root);
		trav(root->right);
	}

	trav(c->in);
}

int tree_eq(node *t1, node *t2)
{
	co_t *c1 = co_new(tree_trav, t1);
	co_t *c2 = co_new(tree_trav, t2);

	node *p = 0, *q = 0;
	do {
		p = co_collect(c1);
		q = co_collect(c2);
	} while (p && q && (p->v == q->v));

	co_del(c1);
	co_del(c2);
	return !p && !q;
}

int main()
{
	int x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };
	int y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };
	int z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };

	node *t1 = 0, *t2 = 0, *t3 = 0;

	void mktree(int *buf, node **root) {
		int i;
		for (i = 0; buf[i] >= 0; i++)
			tree_insert(root, newnode(buf[i]));
	}

	mktree(x, &t1); 
	mktree(y, &t2); 
	mktree(z, &t3);

	printf("t1 == t2: %s\n", tree_eq(t1, t2) ? "yes" : "no");
	printf("t1 == t3: %s\n", tree_eq(t1, t3) ? "yes" : "no");

	return 0;
}







Python: try:
    from itertools import zip_longest as izip_longest 
except:
    from itertools import izip_longest                

def fringe(tree):
    
    for node1 in tree:
        if isinstance(node1, tuple):
            for node2 in fringe(node1):
                yield node2
        else:
            yield node1

def same_fringe(tree1, tree2):
    return all(node1 == node2 for node1, node2 in
               izip_longest(fringe(tree1), fringe(tree2)))

if __name__ == '__main__':
    a = 1, 2, 3, 4, 5, 6, 7, 8
    b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))
    c = (((1, 2), 3), 4), 5, 6, 7, 8

    x = 1, 2, 3, 4, 5, 6, 7, 8, 9
    y = 0, 2, 3, 4, 5, 6, 7, 8
    z = 1, 2, (4, 3), 5, 6, 7, 8

    assert same_fringe(a, a)
    assert same_fringe(a, b)
    assert same_fringe(a, c)

    assert not same_fringe(a, x)
    assert not same_fringe(a, y)
    assert not same_fringe(a, z)
Task: Parse command-line arguments

C: #include <stdio.h>
int main(int argc, char **argv){
    int i;
    const char *commands[]={"-c", "-p", "-t", "-d", "-a", NULL};
    enum {CREATE,PRINT,TITLE,DATE,AUTH};
    if (argc<2) {
usage:   printf ("Usage: %s [commands]\n" 
            "-c  Create new entry.\n" 
            "-p  Print the latest entry.\n" 
            "-t  Sort by title.\n" 
            "-d  Sort by date.\n" 
            "-a  Sort by author.\n",argv[0]);
        return 0;
    }
    for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++);
    switch (i) {
    case CREATE:
...
    break;
    case PRINT:
...
    break;
...
...
    default:
    printf ("Unknown command..." ...);
    goto usage;
    }
    return 0;
}







Python: from optparse import OptionParser
[...]
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", default=True,
                  help="don't print status messages to stdout")

(options, args) = parser.parse_args()

example:

<yourscript> --file=outfile -q
Task: Show the (decimal) value of a number of 1s appended with a 3, then squared

C: #include <stdio.h>
#include <stdint.h>

uint64_t ones_plus_three(uint64_t ones) {
    uint64_t r = 0;
    while (ones--) r = r*10 + 1;
    return r*10 + 3;
}

int main() {
    uint64_t n;
    for (n=0; n<8; n++) {
        uint64_t x = ones_plus_three(n);
        printf("%8lu^2 = %15lu\n", x, x*x);
    }
    return 0;
}







Python: [print("( " + "1"*i + "3 ) ^ 2 = " + str(int("1"*i + "3")**2)) for i in range(0,8)]
Task: Simulate input_Keyboard

C: #include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>

int main(int argc, char *argv[])
{
  Display *dpy;
  Window win;
  GC gc;
  int scr;
  Atom WM_DELETE_WINDOW;
  XEvent ev;
  XEvent ev2;
  KeySym keysym;
  int loop;

  
  dpy = XOpenDisplay(NULL);
  if (dpy == NULL) {
    fputs("Cannot open display", stderr);
    exit(1);
  }
  scr = XDefaultScreen(dpy);

  
  win = XCreateSimpleWindow(dpy,
          XRootWindow(dpy, scr),
          
          10, 10, 300, 200, 1,
          
          XBlackPixel(dpy, scr), XWhitePixel(dpy, scr));

  
  XStoreName(dpy, win, argv[0]);

  
  XSelectInput(dpy, win, ExposureMask | KeyPressMask | ButtonPressMask);

  
  XMapWindow(dpy, win);
  XFlush(dpy);

  
  gc = XDefaultGC(dpy, scr);

  
  WM_DELETE_WINDOW = XInternAtom(dpy, "WM_DELETE_WINDOW", True);
  XSetWMProtocols(dpy, win, &WM_DELETE_WINDOW, 1);

  
  loop = 1;
  while (loop) {
    XNextEvent(dpy, &ev);
    switch (ev.type)
    {
      case Expose:
        
        {
          char msg1[] = "Clic in the window to generate";
          char msg2[] = "a key press event";
          XDrawString(dpy, win, gc, 10, 20, msg1, sizeof(msg1)-1);
          XDrawString(dpy, win, gc, 10, 35, msg2, sizeof(msg2)-1);
        }
        break;

      case ButtonPress:
        puts("ButtonPress event received");
        
        ev2.type = KeyPress;
        ev2.xkey.state = ShiftMask;
        ev2.xkey.keycode = 24 + (rand() % 33);
        ev2.xkey.same_screen = True;
        XSendEvent(dpy, win, True, KeyPressMask, &ev2);
        break;
   
      case ClientMessage:
        
        if (ev.xclient.data.l[0] == WM_DELETE_WINDOW)
          loop = 0;
        break;
   
      case KeyPress:
        
        puts("KeyPress event received");
        printf("> keycode: %d\n", ev.xkey.keycode);
        
        keysym = XLookupKeysym(&(ev.xkey), 0);
        if (keysym == XK_q ||
            keysym == XK_Escape) {
          loop = 0;
        } else {
          char buffer[] = "  ";
          int nchars = XLookupString(
                &(ev.xkey),
                buffer,
                2,  
                &keysym,
                NULL );
          if (nchars == 1)
            printf("> Key '%c' pressed\n", buffer[0]);
        }
        break;
    }
  }
  XDestroyWindow(dpy, win);
  
  XCloseDisplay(dpy);
  return 1;
}







Python: import autopy
autopy.key.type_string("Hello, world!") 
autopy.key.type_string("Hello, world!", wpm=60) 
autopy.key.tap(autopy.key.Code.RETURN)
autopy.key.tap(autopy.key.Code.F1)
autopy.key.tap(autopy.key.Code.LEFT_ARROW)
Task: Metaprogramming

C: 
#define STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(!!(COND))*2-1]

#define COMPILE_TIME_ASSERT3(X,L) STATIC_ASSERT(X,static_assertion_at_line_##L)
#define COMPILE_TIME_ASSERT2(X,L) COMPILE_TIME_ASSERT3(X,L)
#define COMPILE_TIME_ASSERT(X)    COMPILE_TIME_ASSERT2(X,__LINE__)

COMPILE_TIME_ASSERT(sizeof(long)==8); 
int main()
{
    COMPILE_TIME_ASSERT(sizeof(int)==4); 
}







Python: from macropy.core.macros import *
from macropy.core.quotes import macros, q, ast, u

macros = Macros()

@macros.expr
def expand(tree, **kw):
    addition = 10
    return q[lambda x: x * ast[tree] + u[addition]]
Task: Numbers with same digit set in base 10 and base 16

C: #include <stdio.h>
#define LIMIT 100000

int digitset(int num, int base) {
    int set;
    for (set = 0; num; num /= base)
        set |= 1 << num % base;
    return set;
}

int main() {
    int i, c = 0;
    for (i = 0; i < LIMIT; i++)
        if (digitset(i,10) == digitset(i,16))
            printf("%6d%c", i, ++c%10 ? ' ' : '\n');
    printf("\n");
    return 0;
}







Python: col = 0
for i in range(100000):
    if set(str(i)) == set(hex(i)[2:]):
        col += 1
        print("{:7}".format(i), end='\n'[:col % 10 == 0])
print()
Task: Largest prime factor

C: #include <stdio.h>
#include <stdlib.h>

int isprime( long int n ) {
    int i=3;
    if(!(n%2)) return 0;
    while( i*i < n ) {
        if(!(n%i)) return 0;
        i+=2;
    }
    return 1;
}

int main(void) {
    long int n=600851475143, j=3;

    while(!isprime(n)) {
        if(!(n%j)) n/=j;
        j+=2;
    }
    printf( "%ld\n", n );
    return 0;
}







Python: 

def isPrime(n):
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False        
    return True

if __name__ == '__main__':
    n = 600851475143
    j = 3
    while not isPrime(n):
        if n % j == 0:
            n /= j
        j += 2
    print(n);
Task: Largest proper divisor of n

C: #include <stdio.h>

unsigned int lpd(unsigned int n) {
    if (n<=1) return 1;
    int i;
    for (i=n-1; i>0; i--)
        if (n%i == 0) return i;   
}

int main() {
    int i;
    for (i=1; i<=100; i++) {
        printf("%3d", lpd(i));
        if (i % 10 == 0) printf("\n");
    }
    return 0;
}







Python: def lpd(n):
    for i in range(n-1,0,-1):
        if n%i==0: return i
    return 1

for i in range(1,101):
    print("{:3}".format(lpd(i)), end=i%10==0 and '\n' or '')
Task: Move-to-front algorithm

C: #include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define MAX_SIZE 100

int move_to_front(char *str,char c)
{
    char *q,*p;
    int shift=0;
    p=(char *)malloc(strlen(str)+1);
    strcpy(p,str);
    q=strchr(p,c); 
    shift=q-p;      
    strncpy(str+1,p,shift);
    str[0]=c;
    free(p);
  
    return shift;
}

void decode(int* pass,int size,char *sym)
{
    int i,index;
    char c;
    char table[]="abcdefghijklmnopqrstuvwxyz";
    for(i=0;i<size;i++)
    {
        c=table[pass[i]];
        index=move_to_front(table,c);
        if(pass[i]!=index) printf("there is an error");
        sym[i]=c;
    }
    sym[size]='\0';
}

void encode(char *sym,int size,int *pass)
{
    int i=0;
    char c;
    char table[]="abcdefghijklmnopqrstuvwxyz";
    for(i=0;i<size;i++)
    {
        c=sym[i];
        pass[i]=move_to_front(table,c);
    }
}

int check(char *sym,int size,int *pass)
{
    int *pass2=malloc(sizeof(int)*size);
    char *sym2=malloc(sizeof(char)*size);
    int i,val=1;

    encode(sym,size,pass2);
    i=0;
    while(i<size && pass[i]==pass2[i])i++;
    if(i!=size)val=0;

    decode(pass,size,sym2);
    if(strcmp(sym,sym2)!=0)val=0;

    free(sym2);
    free(pass2);

    return val;
}

int main()
{
    char sym[3][MAX_SIZE]={"broood","bananaaa","hiphophiphop"};
    int pass[MAX_SIZE]={0};
    int i,len,j;
    for(i=0;i<3;i++)
    {
        len=strlen(sym[i]);
        encode(sym[i],len,pass);
        printf("%s : [",sym[i]);
        for(j=0;j<len;j++)
            printf("%d ",pass[j]);
        printf("]\n");
        if(check(sym[i],len,pass))
            printf("Correct :)\n");
        else
            printf("Incorrect :(\n");
    }
    return 0;
}







Python: from __future__ import print_function
from string import ascii_lowercase

SYMBOLTABLE = list(ascii_lowercase)

def move2front_encode(strng, symboltable):
    sequence, pad = [], symboltable[::]
    for char in strng:
        indx = pad.index(char)
        sequence.append(indx)
        pad = [pad.pop(indx)] + pad
    return sequence

def move2front_decode(sequence, symboltable):
    chars, pad = [], symboltable[::]
    for indx in sequence:
        char = pad[indx]
        chars.append(char)
        pad = [pad.pop(indx)] + pad
    return ''.join(chars)

if __name__ == '__main__':
    for s in ['broood', 'bananaaa', 'hiphophiphop']:
        encode = move2front_encode(s, SYMBOLTABLE)
        print('%14r encodes to %r' % (s, encode), end=', ')
        decode = move2front_decode(encode, SYMBOLTABLE)
        print('which decodes back to %r' % decode)
        assert s == decode, 'Whoops!'
Task: Active Directory_Search for a user

C: #include <ldap.h>

char *name, *password;
...

LDAP *ld = ldap_init("ldap.somewhere.com", 389);
ldap_simple_bind_s(ld, name, password);

LDAPMessage **result;
ldap_search_s(ld, "dc=somewhere,dc=com", LDAP_SCOPE_SUBTREE,
	
	"(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))",
	NULL, 
	0,  
	result); 



ldap_msgfree(*result);	
ldap_unbind(ld);	







Python: Import-Module ActiveDirectory

$searchData = "user name"
$searchBase = "DC=example,DC=com"


get-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase
Task: Singular value decomposition

C: #include <stdio.h>
#include <gsl/gsl_linalg.h>


void gsl_matrix_print(const gsl_matrix *M) {
    int rows = M->size1;
    int cols = M->size2;
    for (int i = 0; i < rows; i++) {
        printf("|");
        for (int j = 0; j < cols; j++) {
            printf("% 12.10f ", gsl_matrix_get(M, i, j));
        }
        printf("\b|\n");
    }
    printf("\n");
}

int main(){
    double a[] = {3, 0, 4, 5};
    gsl_matrix_view A = gsl_matrix_view_array(a, 2, 2);
    gsl_matrix *V = gsl_matrix_alloc(2, 2);
    gsl_vector *S = gsl_vector_alloc(2);
    gsl_vector *work = gsl_vector_alloc(2);

    
    gsl_linalg_SV_decomp(&A.matrix, V, S, work);
    gsl_matrix_transpose(V);
    double s[] = {S->data[0], 0, 0, S->data[1]};
    gsl_matrix_view SM = gsl_matrix_view_array(s, 2, 2);

    printf("U:\n");
    gsl_matrix_print(&A.matrix);

    printf("S:\n");
    gsl_matrix_print(&SM.matrix);

    printf("VT:\n");
    gsl_matrix_print(V);
    
    gsl_matrix_free(V);
    gsl_vector_free(S);
    gsl_vector_free(work);
    return 0;
}







Python: from numpy import *
A = matrix([[3, 0], [4, 5]])
U, Sigma, VT = linalg.svd(A)
print(U)
print(Sigma)
print(VT)
Task: Sum of first n cubes

C: #include <stdio.h>

int main() {
    for (int i = 0, sum = 0; i < 50; ++i) {
        sum += i * i * i;
        printf("%7d%c", sum, (i + 1) % 5 == 0 ? '\n' : ' ');
    }
    return 0;
}







Python: def main():
    fila = 0
    lenCubos = 51

    print("Suma de N cubos para n = [0..49]\n")

    for n in range(1, lenCubos):
        sumCubos = 0
        for m in range(1, n):
            sumCubos = sumCubos + (m ** 3)
            
        fila += 1
        print(f'{sumCubos:7} ', end='')
        if fila % 5 == 0:
            print(" ")

    print(f"\nEncontrados {fila} cubos.")

if __name__ == '__main__': main()
Task: Test integerness

C: #include <stdio.h>
#include <complex.h>
#include <math.h>


#define FMTSPEC(arg) _Generic((arg), \
    float: "%f", double: "%f", \
    long double: "%Lf", unsigned int: "%u", \
    unsigned long: "%lu", unsigned long long: "%llu", \
    int: "%d", long: "%ld", long long: "%lld", \
    default: "(invalid type (%p)")

#define CMPPARTS(x, y) ((long double complex)((long double)(x) + \
            I * (long double)(y)))

#define TEST_CMPL(i, j)\
    printf(FMTSPEC(i), i), printf(" + "), printf(FMTSPEC(j), j), \
    printf("i = %s\n", (isint(CMPPARTS(i, j)) ? "true" : "false"))

#define TEST_REAL(i)\
    printf(FMTSPEC(i), i), printf(" = %s\n", (isint(i) ? "true" : "false"))


static inline int isint(long double complex n)
{
    return cimagl(n) == 0 && nearbyintl(creall(n)) == creall(n);
}

int main(void)
{
    TEST_REAL(0);
    TEST_REAL(-0);
    TEST_REAL(-2);
    TEST_REAL(-2.00000000000001);
    TEST_REAL(5);
    TEST_REAL(7.3333333333333);
    TEST_REAL(3.141592653589);
    TEST_REAL(-9.223372036854776e18);
    TEST_REAL(5e-324);
    TEST_REAL(NAN);
    TEST_CMPL(6, 0);
    TEST_CMPL(0, 1);
    TEST_CMPL(0, 0);
    TEST_CMPL(3.4, 0);

    
    double complex test1 = 5 + 0*I,
                   test2 = 3.4f,
                   test3 = 3,
                   test4 = 0 + 1.2*I;

    printf("Test 1 (5+i) = %s\n", isint(test1) ? "true" : "false");
    printf("Test 2 (3.4+0i) = %s\n", isint(test2) ? "true" : "false");
    printf("Test 3 (3+0i) = %s\n", isint(test3) ? "true" : "false");
    printf("Test 4 (0+1.2i) = %s\n", isint(test4) ? "true" : "false");
}







Python: >>> def isint(f): 
    return complex(f).imag == 0 and complex(f).real.is_integer()

>>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))]
[True, True, True, False, False, False]

>>> 
...
>>> isint(25.000000)
True
>>> isint(24.999999)
False
>>> isint(25.000100)
False
>>> isint(-2.1e120)
True
>>> isint(-5e-2)
False
>>> isint(float('nan'))
False
>>> isint(float('inf'))
False
>>> isint(5.0+0.0j)
True
>>> isint(5-5j)
False
Task: Execute a system command

C: #include <stdlib.h>

int main()
{
    system("ls");
    return 0;
}







Python: import os
exit_code = os.system('ls')       
output    = os.popen('ls').read()
Task: XML validation

C: #include <libxml/xmlschemastypes.h>

int main(int argC, char** argV)
{
	if (argC <= 2) {
		printf("Usage: %s <XML Document Name> <XSD Document Name>\n", argV[0]);
		return 0;
	}
	
	xmlDocPtr doc;
	xmlSchemaPtr schema = NULL;
	xmlSchemaParserCtxtPtr ctxt;
	char *XMLFileName = argV[1];
	char *XSDFileName = argV[2];
	int ret;

	xmlLineNumbersDefault(1);

	ctxt = xmlSchemaNewParserCtxt(XSDFileName);

	xmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);
	schema = xmlSchemaParse(ctxt);
	xmlSchemaFreeParserCtxt(ctxt);


	doc = xmlReadFile(XMLFileName, NULL, 0);

	if (doc == NULL){
		fprintf(stderr, "Could not parse %s\n", XMLFileName);
	}
	else{
		xmlSchemaValidCtxtPtr ctxt;

		ctxt = xmlSchemaNewValidCtxt(schema);
		xmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);
		ret = xmlSchemaValidateDoc(ctxt, doc);
		
		if (ret == 0){
			printf("%s validates\n", XMLFileName);
		}
		else if (ret > 0){
			printf("%s fails to validate\n", XMLFileName);
		}
		else{
			printf("%s validation generated an internal error\n", XMLFileName);
		}
		xmlSchemaFreeValidCtxt(ctxt);
		xmlFreeDoc(doc);
	}


	if(schema != NULL)
		xmlSchemaFree(schema);

	xmlSchemaCleanupTypes();
	xmlCleanupParser();
	xmlMemoryDump();

	return 0;
}







Python: 
from __future__ import print_function
import lxml
from lxml import etree

if __name__=="__main__":

	parser = etree.XMLParser(dtd_validation=True)
	schema_root = etree.XML()
	schema = etree.XMLSchema(schema_root)

	
	parser = etree.XMLParser(schema = schema)
	try:
		root = etree.fromstring("<a>5</a>", parser)
		print ("Finished validating good xml")
	except lxml.etree.XMLSyntaxError as err:
		print (err)

	
	parser = etree.XMLParser(schema = schema)
	try:
		root = etree.fromstring("<a>5<b>foobar</b></a>", parser)
	except lxml.etree.XMLSyntaxError as err:
		print (err)
Task: Longest increasing subsequence

C: #include <stdio.h>
#include <stdlib.h>

struct node {
	int val, len;
	struct node *next;
};

void lis(int *v, int len)
{
	int i;
	struct node *p, *n = calloc(len, sizeof *n);
	for (i = 0; i < len; i++)
		n[i].val = v[i];

	for (i = len; i--; ) {
		
		for (p = n + i; p++ < n + len; ) {
			if (p->val > n[i].val && p->len >= n[i].len) {
				n[i].next = p;
				n[i].len = p->len + 1;
			}
		}
	}

	
	for (i = 0, p = n; i < len; i++)
		if (n[i].len > p->len) p = n + i;

	do printf(" %d", p->val); while ((p = p->next));
	putchar('\n');

	free(n);
}

int main(void)
{
	int x[] = { 3, 2, 6, 4, 5, 1 };
	int y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };

	lis(x, sizeof(x) / sizeof(int));
	lis(y, sizeof(y) / sizeof(int));
	return 0;
}







Python: def longest_increasing_subsequence(X):
    
    N = len(X)
    P = [0] * N
    M = [0] * (N+1)
    L = 0
    for i in range(N):
       lo = 1
       hi = L
       while lo <= hi:
           mid = (lo+hi)//2
           if (X[M[mid]] < X[i]):
               lo = mid+1
           else:
               hi = mid-1
    
       newL = lo
       P[i] = M[newL-1]
       M[newL] = i
    
       if (newL > L):
           L = newL
    
    S = []
    k = M[L]
    for i in range(L-1, -1, -1):
        S.append(X[k])
        k = P[k]
    return S[::-1]

if __name__ == '__main__':
    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:
        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))
Task: Scope modifiers

C: int a;          
static int p;   

extern float v; 


int code(int arg)
{
  int myp;        
                  
                  
  static int myc; 
                  
                  
                  
                  
}


static void code2(void)
{
  v = v * 1.02;    
  
}







Python: >>> x="From global scope"
>>> def outerfunc():
    x = "From scope at outerfunc"

    def scoped_local():
        x = "scope local"
        return "scoped_local scope gives x = " + x
    print(scoped_local())

    def scoped_nonlocal():
        nonlocal x
        return "scoped_nonlocal scope gives x = " + x
    print(scoped_nonlocal())

    def scoped_global():
        global x
        return "scoped_global scope gives x = " + x
    print(scoped_global())

    def scoped_notdefinedlocally():
        return "scoped_notdefinedlocally scope gives x = " + x
    print(scoped_notdefinedlocally())

    
>>> outerfunc()
scoped_local scope gives x = scope local
scoped_nonlocal scope gives x = From scope at outerfunc
scoped_global scope gives x = From global scope
scoped_notdefinedlocally scope gives x = From global scope
>>>
Task: Hough transform

C: #include "SL_Generated.h"
#include "CImg.h"

using namespace cimg_library;

int main( int argc, char** argv )
{
    string fileName = "Pentagon.bmp";
    if(argc > 1) fileName = argv[1];
    int thetaAxisSize = 640; if(argc > 2) thetaAxisSize = atoi(argv[2]);
    int rAxisSize = 480; if(argc > 3) rAxisSize = atoi(argv[3]);
    int minContrast = 64; if(argc > 4) minContrast = atoi(argv[4]);
    int threads = 0; if(argc > 5) threads = atoi(argv[5]);
    char titleBuffer[200];
    SLTimer t;

    CImg<int> image(fileName.c_str());
    int imageDimensions[] = {image.height(), image.width(), 0};
    Sequence<Sequence<int> > imageSeq((void*) image.data(), imageDimensions);
    Sequence< Sequence<int> > result;

    sl_init(threads);

    t.start();
    sl_hough(imageSeq, thetaAxisSize, rAxisSize, minContrast, threads, result);
    t.stop();
    
    CImg<int> resultImage(result[1].size(), result.size());
    for(int y = 0; y < result.size(); y++)
        for(int x = 0; x < result[y+1].size(); x++)
            resultImage(x,result.size() - 1 - y) = result[y+1][x+1];
    
    sprintf(titleBuffer, "SequenceL Hough Transformation: %d X %d Image to %d X %d Result | %d Cores | Processed in %f sec\0", 
                         image.width(), image.height(), resultImage.width(), resultImage.height(), threads, t.getTime());
    resultImage.display(titleBuffer);

    sl_done();
    return 0;
}







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


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

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

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


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


if __name__ == "__main__": test()