From 7bd04cd4e5d46c4ac829015725cfa520235eb594 Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Fri, 13 Feb 2015 11:51:46 -0500 Subject: [PATCH 01/26] working version f1_score: .84 --- lang_orig.py | 134 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 lang_orig.py diff --git a/lang_orig.py b/lang_orig.py new file mode 100644 index 0000000..6235f95 --- /dev/null +++ b/lang_orig.py @@ -0,0 +1,134 @@ +import os +from sklearn import metrics +from sklearn.cross_validation import cross_val_score +import os.path +import pandas as pd +import csv +import nltk +from textblob import TextBlob as tb +from sklearn.cross_validation import train_test_split +from sklearn.naive_bayes import BernoulliNB + +from sklearn.feature_extraction.text import CountVectorizer + +def read_train_files(): + file_list = [] + for root, dirs, files in os.walk("./train/bench"): + for name in files: + file_list.append(os.path.join(root, name)) + for name in dirs: + file_list.append((os.path.join(root, name))) + return file_list + +def all_extensions(file_list): + return set([os.path.splitext(file)[1] for file in file_list]) + +def get_extension(file): + return os.path.splitext(file)[1] + +def get_language(ext): + if ext in ['.clj', '.cljs', '.edn', '.clojure']: + return 'Clojure' + elif ext in ['.hs', '.lhs','ghc']: + return 'Haskell' + elif ext in ['.java', '.class', '.jar']: + return 'Java' + elif ext in ['.js', '.javascript']: + return 'Javascript' + elif ext in ['.pl', '.pm', '.t', '.pod','.perl']: + return 'Perl' + elif ext in ['.php', '.phtml', '.php4', '.php3', '.php5', '.phps']: + return 'PHP' + elif ext in ['.ocaml','.ml']: + return 'Ocaml' + elif ext in ['.py', '.pyw', '.pyc', '.pyo', '.pyd', '.python3']: + return "Python" + elif ext in ['.rb', '.rbw', '.jruby']: + return "Ruby" + elif ext in ['.scala']: + return 'Scala' + elif ext in ['.scm', '.ss','.racket']: + return "Scheme" + elif ext in ['.tcl']: + return "Tcl" + return None + +def read_train_data(): + files = read_train_files() + main_list=[] + for file in files: + ext = get_extension(file) + lang = get_language(ext) + if lang != None: + file_lang = [] + with open(file,errors="surrogateescape") as in_file: + texto = in_file.read() + main_list.append([texto,lang]) + return main_list + +def join_all_code(content): + all_code = [] + for ind, row in content.iterrows(): + all_code.append(row['Code']) + return ''.join(all_code) + +def tokenize(content): + return nltk.word_tokenize(content) + +def word_freq(word, code): + if len(code.words) == 0: + return 0 + else: + return code.word_counts[word] / len(code.words) + +def print_word_score(sorted_list): + i=0 + for word, score in sorted_list: + print(word,score) + i+=1 + if i == 10: + break + +docu = read_train_data() +datadf = pd.DataFrame(docu, columns = ['Code', 'Language']) +#print(datadf.head()) +#print(datadf.shape) +#print(datadf['Language'].value_counts()) +all_code = join_all_code(datadf) +tokens = tokenize(all_code) +all_tokens = ' '.join(tokens) +token_blob = tb(all_tokens) +scores = {word: word_freq(word,token_blob) for word in token_blob.words} +sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True) + +print_word_score(sorted_words) + +exclude_list = ['i','n','0','1','a'] +#Interesting find: the words "from",'m','on' should not be excluded. Performance lowers" +final = {} +for word, score in sorted_words: + if score > 0.001 and word not in exclude_list: + final[word] = round(score,5) + +super_final = [] + +for ind, row in datadf.iterrows(): + mydict = {} + for word, score in final.items(): + if row['Code'].find(word) != -1: + mydict[word] = score + super_final.append(mydict) + +from sklearn.feature_extraction import DictVectorizer +vec = DictVectorizer() +new_x = vec.fit_transform(super_final).toarray() +new_x + +x_train, x_test, y_train, y_test = train_test_split(new_x, datadf['Language'].values, test_size=0.4, random_state=0) +clf = BernoulliNB() +clf = clf.fit(x_train, y_train) +predicted = clf.predict(x_test) +print(metrics.classification_report(y_test, predicted)) +print(metrics.confusion_matrix(y_test, predicted)) +print(metrics.f1_score(y_test, predicted)) +scores = cross_val_score(clf, new_x,datadf['Language'].values, cv=5) From 9def4e7b6aa0cc09bbaaeb4ad5a1c0a1fd0ea862 Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Fri, 13 Feb 2015 11:59:50 -0500 Subject: [PATCH 02/26] Added decisin tree model. Worked better. 0.92 --- lang_orig.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/lang_orig.py b/lang_orig.py index 6235f95..75b26ee 100644 --- a/lang_orig.py +++ b/lang_orig.py @@ -1,15 +1,15 @@ import os -from sklearn import metrics -from sklearn.cross_validation import cross_val_score import os.path import pandas as pd -import csv import nltk from textblob import TextBlob as tb +from sklearn import metrics +from sklearn.cross_validation import cross_val_score from sklearn.cross_validation import train_test_split from sklearn.naive_bayes import BernoulliNB - from sklearn.feature_extraction.text import CountVectorizer +from sklearn.tree import DecisionTreeClassifier +from sklearn import tree def read_train_files(): file_list = [] @@ -132,3 +132,11 @@ def print_word_score(sorted_list): print(metrics.confusion_matrix(y_test, predicted)) print(metrics.f1_score(y_test, predicted)) scores = cross_val_score(clf, new_x,datadf['Language'].values, cv=5) + +clf = tree.DecisionTreeClassifier() +clf = clf.fit(x_train, y_train) +predicted = clf.predict(x_test) +print(metrics.classification_report(y_test, predicted)) +print(metrics.confusion_matrix(y_test, predicted)) +print(metrics.f1_score(y_test, predicted)) +scores = cross_val_score(clf, new_x,datadf['Language'].values, cv=5) From 75272fb45925604a1ae7a177dcf86cca4959b799 Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sat, 14 Feb 2015 17:42:05 -0500 Subject: [PATCH 03/26] testing with new files --- lang_orig.py | 204 ++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 143 insertions(+), 61 deletions(-) diff --git a/lang_orig.py b/lang_orig.py index 75b26ee..7c49338 100644 --- a/lang_orig.py +++ b/lang_orig.py @@ -2,44 +2,47 @@ import os.path import pandas as pd import nltk +import re from textblob import TextBlob as tb from sklearn import metrics from sklearn.cross_validation import cross_val_score from sklearn.cross_validation import train_test_split +from sklearn.feature_extraction import DictVectorizer from sklearn.naive_bayes import BernoulliNB +from sklearn.linear_model import LogisticRegression from sklearn.feature_extraction.text import CountVectorizer from sklearn.tree import DecisionTreeClassifier from sklearn import tree -def read_train_files(): + +def read_files(dir_path): file_list = [] - for root, dirs, files in os.walk("./train/bench"): + for root, dirs, files in os.walk(dir_path): for name in files: file_list.append(os.path.join(root, name)) for name in dirs: file_list.append((os.path.join(root, name))) return file_list -def all_extensions(file_list): - return set([os.path.splitext(file)[1] for file in file_list]) def get_extension(file): return os.path.splitext(file)[1] + def get_language(ext): if ext in ['.clj', '.cljs', '.edn', '.clojure']: return 'Clojure' - elif ext in ['.hs', '.lhs','ghc']: + elif ext in ['.hs', '.lhs', 'ghc']: return 'Haskell' elif ext in ['.java', '.class', '.jar']: return 'Java' elif ext in ['.js', '.javascript']: return 'Javascript' - elif ext in ['.pl', '.pm', '.t', '.pod','.perl']: + elif ext in ['.pl', '.pm', '.t', '.pod', '.perl']: return 'Perl' elif ext in ['.php', '.phtml', '.php4', '.php3', '.php5', '.phps']: return 'PHP' - elif ext in ['.ocaml','.ml']: + elif ext in ['.ocaml', '.ml']: return 'Ocaml' elif ext in ['.py', '.pyw', '.pyc', '.pyo', '.pyd', '.python3']: return "Python" @@ -47,33 +50,49 @@ def get_language(ext): return "Ruby" elif ext in ['.scala']: return 'Scala' - elif ext in ['.scm', '.ss','.racket']: + elif ext in ['.scm', '.ss', '.racket']: return "Scheme" elif ext in ['.tcl']: return "Tcl" return None def read_train_data(): - files = read_train_files() - main_list=[] + files = read_files("./train/bench") + main_list = [] for file in files: ext = get_extension(file) lang = get_language(ext) if lang != None: file_lang = [] - with open(file,errors="surrogateescape") as in_file: + with open(file, errors="surrogateescape") as in_file: + texto = in_file.read() + main_list.append([texto, lang]) + datadf = pd.DataFrame(main_list, columns = ['Code', 'Language']) + return datadf + +def read_test_data(): + files = read_files("./test") + main_list = [] + for file in files: + with open(file, errors="surrogateescape") as in_file: texto = in_file.read() - main_list.append([texto,lang]) - return main_list + file_name = re.findall(r'\d+', file) + main_list.append([texto,file_name[0]]) + file_content = pd.DataFrame(main_list, columns=['Code', 'Filename']) + file_info = pd.read_csv('./test.csv', dtype={'Filename': str, 'Language': str}) + datadf = pd.merge(file_info, file_content, on=['Filename']) + del datadf['Filename'] + return datadf def join_all_code(content): - all_code = [] - for ind, row in content.iterrows(): - all_code.append(row['Code']) - return ''.join(all_code) + all_content = [row["Code"] for ind, row in content.iterrows()] + return ' '.join(all_content) + def tokenize(content): - return nltk.word_tokenize(content) + tokens = nltk.word_tokenize(content) + return ' '.join(tokens) + def word_freq(word, code): if len(code.words) == 0: @@ -81,6 +100,7 @@ def word_freq(word, code): else: return code.word_counts[word] / len(code.words) + def print_word_score(sorted_list): i=0 for word, score in sorted_list: @@ -89,54 +109,116 @@ def print_word_score(sorted_list): if i == 10: break -docu = read_train_data() -datadf = pd.DataFrame(docu, columns = ['Code', 'Language']) -#print(datadf.head()) -#print(datadf.shape) -#print(datadf['Language'].value_counts()) -all_code = join_all_code(datadf) -tokens = tokenize(all_code) -all_tokens = ' '.join(tokens) -token_blob = tb(all_tokens) -scores = {word: word_freq(word,token_blob) for word in token_blob.words} -sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True) - -print_word_score(sorted_words) - -exclude_list = ['i','n','0','1','a'] -#Interesting find: the words "from",'m','on' should not be excluded. Performance lowers" -final = {} -for word, score in sorted_words: - if score > 0.001 and word not in exclude_list: - final[word] = round(score,5) +def return_tokenized_data(datadf): + all_code = join_all_code(datadf) + all_tokens = tokenize(all_code) + return tb(all_tokens) -super_final = [] -for ind, row in datadf.iterrows(): +def calculate_scores(token_blob): + scores = {word: word_freq(word,token_blob) for word in token_blob.words} + return sorted(scores.items(), key=lambda x: x[1], reverse=True) + +def select_features(word_list): + exclude_list = ['i','n','0','1','a'] + final = {} + counter = 0 + for word, score in word_list: + if word not in exclude_list: + final[word] = round(score,5) + counter += 1 + if counter == 200: + break + print("features#", len(final)) + return final + +def select_features_new_test(word_list, final): + final_list = {} + for key in final: + found = 0 + for word, score in word_list: + if word == key: + found = score + break + final_list[key] = round(found,5) + return final_list + + +def create_vectors(final,data): + super_final = [] + for ind, row in data.iterrows(): mydict = {} for word, score in final.items(): if row['Code'].find(word) != -1: mydict[word] = score super_final.append(mydict) + vec = DictVectorizer() + return vec.fit_transform(super_final).toarray() -from sklearn.feature_extraction import DictVectorizer -vec = DictVectorizer() -new_x = vec.fit_transform(super_final).toarray() -new_x - -x_train, x_test, y_train, y_test = train_test_split(new_x, datadf['Language'].values, test_size=0.4, random_state=0) -clf = BernoulliNB() -clf = clf.fit(x_train, y_train) -predicted = clf.predict(x_test) -print(metrics.classification_report(y_test, predicted)) -print(metrics.confusion_matrix(y_test, predicted)) -print(metrics.f1_score(y_test, predicted)) -scores = cross_val_score(clf, new_x,datadf['Language'].values, cv=5) - -clf = tree.DecisionTreeClassifier() -clf = clf.fit(x_train, y_train) -predicted = clf.predict(x_test) -print(metrics.classification_report(y_test, predicted)) -print(metrics.confusion_matrix(y_test, predicted)) -print(metrics.f1_score(y_test, predicted)) -scores = cross_val_score(clf, new_x,datadf['Language'].values, cv=5) +def create_vectors1(final,data): + super_final = [] + for ind, row in data.iterrows(): + mydict = {} + for word, score in final.items(): + if row['Code'].find(word) != -1: + mydict[word] = score + else: + mydict[word] = 0 + super_final.append(mydict) + vec = DictVectorizer() + return vec.fit_transform(super_final).toarray() + +def test_model(x,y,model): + if model == 'tree': + clf = tree.DecisionTreeClassifier() + elif model == 'bernoulli': + clf = BernoulliNB() + x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.4, random_state=0) + clf = clf.fit(x_train, y_train) + predicted = clf.predict(x_test) + print('predicted',predicted) + print(metrics.classification_report(y_test, predicted)) + print(metrics.f1_score(y_test, predicted)) + scores = cross_val_score(clf, x, y, cv=5) + return scores, clf + + +def test_new_models(data, final_words, clf): + new_target = data['Language'].values + token_blob = return_tokenized_data(data) + word_list = calculate_scores(token_blob) + final = select_features_new_test(word_list, final_words) + print('elemfinal',final) + print('final_words',final_words) + #vec = DictVectorizer() + #new_x = vec.fit_transform(final).toarray() + + new_x = create_vectors1(final,data) + print('subzero',len(new_x[0])) + print('new',new_x) + predicted = clf.predict(new_x) + for pp in range(len(predicted)): + print('predicted',predicted[pp],new_target[pp]) + print(new_target) + + #print(metrics.classification_report(new_target, predicted)) + #print(metrics.f1_score(new_target, predicted)) + #scores = cross_val_score(clf, new_x, new_target) + +if __name__ == '__main__': + datadf = read_train_data() + target = datadf['Language'].values + read_test_data() + token_blob = return_tokenized_data(datadf) + word_list = calculate_scores(token_blob) + #print(word_list) + final_words = select_features(word_list) + print("final wordsoriginal", final_words) + new_x = create_vectors(final_words,datadf) + print('subzeroorig',len(new_x[0])) + print("newxorig",new_x) + #print(final_words) + bernoulli_score = test_model(new_x, target, 'bernoulli') + tree_score, clf_model = test_model(new_x, target, 'tree') + test_data = read_test_data() + test_new_models(test_data, final_words, clf_model) From c366d879fabf668a5ffac849f82fd0e1a74e7180 Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sun, 15 Feb 2015 11:07:15 -0500 Subject: [PATCH 04/26] script to scrape 60 files for each language --- rosetta_scraper.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 rosetta_scraper.py diff --git a/rosetta_scraper.py b/rosetta_scraper.py new file mode 100644 index 0000000..bc51a2f --- /dev/null +++ b/rosetta_scraper.py @@ -0,0 +1,44 @@ +import requests +from bs4 import BeautifulSoup + +r = requests.get('http://rosettacode.org/wiki/Category:Programming_Tasks') + +soup = BeautifulSoup(r.content) + +languages = [("Haskell","hs") + ("Clojure","clojure"), + ("Java","java"), + ("JavaScript","js"), + ("OCaml","ocaml"), + ("Perl","perl"), + ("PHP","php"), + ("Python","py"), + ("Ruby","rb"), + ("Scala","scala"), + ("Scheme","ss"), + ("Tcl","tcl")] + +for lang, ext in languages: + print(lang,ext) + my_links = soup.find_all("a") + pruned_list = my_links[7:] + i = 1 + for link in pruned_list: + new_link ="http://rosettacode.org{}#{}".format(link.get("href"), lang) + #print(new_link) + try: + r = requests.get(new_link) + soup1 = BeautifulSoup(r.content) + data= soup1.find_all("pre",{"class":"{} highlighted_source".format(lang.lower())}) + + for item in data: + for tag in item.contents: + tag.br.replace_with("\n") + with open("./rosetta/file{}.{}".format(i,ext), "w") as text_file: + text_file.write(item.get_text(" ")) + i +=1 + except: + pass + if i ==61: + break + From 334ae420ad96dd71243f1219cfb657270ba03e23 Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sun, 15 Feb 2015 11:51:58 -0500 Subject: [PATCH 05/26] working version. lacking better structuring --- lang_orig.py | 47 ++++++++++++++++++----------------------------- 1 file changed, 18 insertions(+), 29 deletions(-) diff --git a/lang_orig.py b/lang_orig.py index 7c49338..f97e1b7 100644 --- a/lang_orig.py +++ b/lang_orig.py @@ -57,7 +57,7 @@ def get_language(ext): return None def read_train_data(): - files = read_files("./train/bench") + files = read_files("./rosetta") main_list = [] for file in files: ext = get_extension(file) @@ -145,17 +145,6 @@ def select_features_new_test(word_list, final): def create_vectors(final,data): - super_final = [] - for ind, row in data.iterrows(): - mydict = {} - for word, score in final.items(): - if row['Code'].find(word) != -1: - mydict[word] = score - super_final.append(mydict) - vec = DictVectorizer() - return vec.fit_transform(super_final).toarray() - -def create_vectors1(final,data): super_final = [] for ind, row in data.iterrows(): mydict = {} @@ -188,36 +177,36 @@ def test_new_models(data, final_words, clf): token_blob = return_tokenized_data(data) word_list = calculate_scores(token_blob) final = select_features_new_test(word_list, final_words) - print('elemfinal',final) - print('final_words',final_words) - #vec = DictVectorizer() - #new_x = vec.fit_transform(final).toarray() - - new_x = create_vectors1(final,data) - print('subzero',len(new_x[0])) - print('new',new_x) + new_x = create_vectors(final,data) predicted = clf.predict(new_x) for pp in range(len(predicted)): print('predicted',predicted[pp],new_target[pp]) - print(new_target) - #print(metrics.classification_report(new_target, predicted)) - #print(metrics.f1_score(new_target, predicted)) - #scores = cross_val_score(clf, new_x, new_target) + +def test_model(x,y,model): + if model == 'tree': + clf = tree.DecisionTreeClassifier() + elif model == 'bernoulli': + clf = BernoulliNB() + x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.4, random_state=0) + clf = clf.fit(x_train, y_train) + predicted = clf.predict(x_test) + print('predicted',predicted) + print(metrics.classification_report(y_test, predicted)) + print(metrics.f1_score(y_test, predicted)) + scores = cross_val_score(clf, x, y, cv=5) + return scores, clf + if __name__ == '__main__': datadf = read_train_data() target = datadf['Language'].values + print(datadf.groupby('Language').count()) read_test_data() token_blob = return_tokenized_data(datadf) word_list = calculate_scores(token_blob) - #print(word_list) final_words = select_features(word_list) - print("final wordsoriginal", final_words) new_x = create_vectors(final_words,datadf) - print('subzeroorig',len(new_x[0])) - print("newxorig",new_x) - #print(final_words) bernoulli_score = test_model(new_x, target, 'bernoulli') tree_score, clf_model = test_model(new_x, target, 'tree') test_data = read_test_data() From 284aca085ca9fc9914f8e6e1c18fb3f375f007ee Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sun, 15 Feb 2015 15:53:24 -0500 Subject: [PATCH 06/26] Code to train the model --- lang_orig.py | 60 ++++++++-------------------------------------------- 1 file changed, 9 insertions(+), 51 deletions(-) diff --git a/lang_orig.py b/lang_orig.py index f97e1b7..bf45461 100644 --- a/lang_orig.py +++ b/lang_orig.py @@ -1,5 +1,6 @@ import os import os.path +import pickle import pandas as pd import nltk import re @@ -70,19 +71,6 @@ def read_train_data(): datadf = pd.DataFrame(main_list, columns = ['Code', 'Language']) return datadf -def read_test_data(): - files = read_files("./test") - main_list = [] - for file in files: - with open(file, errors="surrogateescape") as in_file: - texto = in_file.read() - file_name = re.findall(r'\d+', file) - main_list.append([texto,file_name[0]]) - file_content = pd.DataFrame(main_list, columns=['Code', 'Filename']) - file_info = pd.read_csv('./test.csv', dtype={'Filename': str, 'Language': str}) - datadf = pd.merge(file_info, file_content, on=['Filename']) - del datadf['Filename'] - return datadf def join_all_code(content): all_content = [row["Code"] for ind, row in content.iterrows()] @@ -101,14 +89,6 @@ def word_freq(word, code): return code.word_counts[word] / len(code.words) -def print_word_score(sorted_list): - i=0 - for word, score in sorted_list: - print(word,score) - i+=1 - if i == 10: - break - def return_tokenized_data(datadf): all_code = join_all_code(datadf) all_tokens = tokenize(all_code) @@ -119,30 +99,20 @@ def calculate_scores(token_blob): scores = {word: word_freq(word,token_blob) for word in token_blob.words} return sorted(scores.items(), key=lambda x: x[1], reverse=True) + def select_features(word_list): - exclude_list = ['i','n','0','1','a'] - final = {} + exclude_list = ['l','6','d','x1','x2','5','j','m','w','i','e','g','4','v','n','0','1','a','x','n','y','b','2','c','s','3'] + final={} counter = 0 for word, score in word_list: if word not in exclude_list: final[word] = round(score,5) counter += 1 - if counter == 200: + if counter == 160: break print("features#", len(final)) return final -def select_features_new_test(word_list, final): - final_list = {} - for key in final: - found = 0 - for word, score in word_list: - if word == key: - found = score - break - final_list[key] = round(found,5) - return final_list - def create_vectors(final,data): super_final = [] @@ -172,17 +142,6 @@ def test_model(x,y,model): return scores, clf -def test_new_models(data, final_words, clf): - new_target = data['Language'].values - token_blob = return_tokenized_data(data) - word_list = calculate_scores(token_blob) - final = select_features_new_test(word_list, final_words) - new_x = create_vectors(final,data) - predicted = clf.predict(new_x) - for pp in range(len(predicted)): - print('predicted',predicted[pp],new_target[pp]) - - def test_model(x,y,model): if model == 'tree': clf = tree.DecisionTreeClassifier() @@ -191,7 +150,7 @@ def test_model(x,y,model): x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.4, random_state=0) clf = clf.fit(x_train, y_train) predicted = clf.predict(x_test) - print('predicted',predicted) + #print('predicted',predicted) print(metrics.classification_report(y_test, predicted)) print(metrics.f1_score(y_test, predicted)) scores = cross_val_score(clf, x, y, cv=5) @@ -201,13 +160,12 @@ def test_model(x,y,model): if __name__ == '__main__': datadf = read_train_data() target = datadf['Language'].values - print(datadf.groupby('Language').count()) - read_test_data() token_blob = return_tokenized_data(datadf) word_list = calculate_scores(token_blob) final_words = select_features(word_list) + #print("word_list for model", final_words) new_x = create_vectors(final_words,datadf) bernoulli_score = test_model(new_x, target, 'bernoulli') tree_score, clf_model = test_model(new_x, target, 'tree') - test_data = read_test_data() - test_new_models(test_data, final_words, clf_model) + pickle.dump( clf_model, open( "model.p", "wb" ) ) + pickle.dump( final_words, open( "features.p", "wb" ) ) From ee9fa0995aef8c859c25ece937aaa82ce4ab0232 Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sun, 15 Feb 2015 15:53:54 -0500 Subject: [PATCH 07/26] Code to scrate Rosetta files --- rosetta_scraper.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/rosetta_scraper.py b/rosetta_scraper.py index bc51a2f..4559b6a 100644 --- a/rosetta_scraper.py +++ b/rosetta_scraper.py @@ -5,7 +5,7 @@ soup = BeautifulSoup(r.content) -languages = [("Haskell","hs") +languages = [("Haskell","hs"), ("Clojure","clojure"), ("Java","java"), ("JavaScript","js"), @@ -41,4 +41,3 @@ pass if i ==61: break - From 4ccc76ddf426607cfafcb1d634265285749a5812 Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sun, 15 Feb 2015 15:54:22 -0500 Subject: [PATCH 08/26] Tests Predictions on the new files --- classify.py | 108 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 classify.py diff --git a/classify.py b/classify.py new file mode 100644 index 0000000..8cb5b74 --- /dev/null +++ b/classify.py @@ -0,0 +1,108 @@ +import pickle +import os +import os.path +import pandas as pd +import nltk +import re +import numpy as np +from textblob import TextBlob as tb +from sklearn import metrics +from sklearn.cross_validation import cross_val_score +from sklearn.cross_validation import train_test_split +from sklearn.feature_extraction import DictVectorizer +from sklearn.naive_bayes import BernoulliNB +from sklearn.linear_model import LogisticRegression +from sklearn.feature_extraction.text import CountVectorizer +from sklearn.tree import DecisionTreeClassifier +from sklearn import tree +import lang_orig as lg + +def read_test_data(): + files = lg.read_files("./test") + main_list = [] + for file in files: + with open(file, errors="surrogateescape") as in_file: + texto = in_file.read() + file_name = re.findall(r'\d+', file) + main_list.append([texto,file_name[0]]) + file_content = pd.DataFrame(main_list, columns=['Code', 'Filename']) + file_info = pd.read_csv('./test.csv', dtype={'Filename': str, 'Language': str}) + datadf = pd.merge(file_info, file_content, on=['Filename']) + del datadf['Filename'] + return datadf + +def select_features_new_test(word_list, final): + final_list = {} + #exclude_list = ['l','6','d','x1','x2','5','j','m','w','i','e','g','4','v','n','0','1','a','x','n','y','b','2','c','s','3'] + for key in final: + found = 0 + for word, score in word_list: + # if word not in exclude_list: + if word == key: + found = score + break + final_list[key] = round(found,5) + return final_list + +#def test_new_models(data, final_words, clf): +# new_target = data['Language'].values +# token_blob = return_tokenized_data(data) +# word_list = calculate_scores(token_blob) +# final = select_features_new_test(word_list, final_words) +# print('newmodelx word list',final) +# new_x = create_vectors(final,data) +# print('nwx',new_x) +# predicted = clf.predict(new_x) +# for pp in range(len(predicted)): +# print('predicted',predicted[pp],new_target[pp]) +# scores = cross_val_score(clf, new_x, new_target, cv=2) +# print(metrics.confusion_matrix(new_target, predicted)) +# print(metrics.classification_report(new_target, predicted)) + #print(metrics.f1_score(new_target, predicted)) + +def setup_data(): + cls = pickle.load( open( "model.p", "rb" ) ) + final_features = pickle.load( open( "features.p", "rb" ) ) + return final_features, cls + +def return_tokens(code): + tokens = nltk.word_tokenize(code) + return tb(' '.join(tokens)) + +def create_vectors_new_test(features): + vec = DictVectorizer() + return vec.fit_transform(features).toarray() + +def predict(code, model, final_features): + token_blob = return_tokens(code) + word_list = lg.calculate_scores(token_blob) + features = select_features_new_test(word_list, final_features) + #print('newmodelx word list',final) + #print(features) + new_x = create_vectors_new_test(features) + #print('nwx',new_x) + predicted = model.predict(new_x) + predicted_probs = model.predict_proba(new_x) + return predicted, predicted_probs + +def print_probabilities(probas, model): + for ind in range(len(probas[0])): + print(model.classes_[ind],':',probas[0][ind]) + + +def test_all_new_files(test_data, model, final_features): + agreement = 0 + total = 0 + for ind, row in test_data.iterrows(): + + predicted, probas = predict(row['Code'], model, final_features) + print("I predicted: {}. It was: {}".format(predicted[0], row['Language'])) + #print_probabilities(probas, model) + total +=1 + if predicted[0].lower() == row['Language'].lower(): + agreement +=1 + print("Success Rate of Classification:",round(agreement*100/total,2)) + +test_data = read_test_data() +model_features, model = setup_data() +test_all_new_files(test_data, model, model_features) From 32d6b8fd3ee4a4ad6f85b909a594ac039009d779 Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sun, 15 Feb 2015 15:55:00 -0500 Subject: [PATCH 09/26] Executable to predict language for a file containing code --- classify_snippet.py | 65 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100755 classify_snippet.py diff --git a/classify_snippet.py b/classify_snippet.py new file mode 100755 index 0000000..0a4202f --- /dev/null +++ b/classify_snippet.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +import pickle +import os +import os.path +import pandas as pd +import nltk +import re +import numpy as np +from textblob import TextBlob as tb +from sklearn.feature_extraction import DictVectorizer +from sklearn.tree import DecisionTreeClassifier +from sklearn import tree +import lang_orig as lg +import sys + +def select_features_new_test(word_list, final): + final_list = {} + for key in final: + found = 0 + for word, score in word_list: + if word == key: + found = score + break + final_list[key] = round(found,5) + return final_list + + +def setup_data(): + cls = pickle.load( open( "model.p", "rb" ) ) + final_features = pickle.load( open( "features.p", "rb" ) ) + return final_features, cls + +def return_tokens(code): + tokens = nltk.word_tokenize(code) + return tb(' '.join(tokens)) + +def create_vectors_new_test(features): + vec = DictVectorizer() + return vec.fit_transform(features).toarray() + +def predict(code, model, final_features): + token_blob = return_tokens(code) + word_list = lg.calculate_scores(token_blob) + features = select_features_new_test(word_list, final_features) + new_x = create_vectors_new_test(features) + predicted = model.predict(new_x) + predicted_probs = model.predict_proba(new_x) + return predicted, predicted_probs + +def print_probabilities(probas, model): + print("Probabilites for my prediction:") + for ind in range(len(probas[0])): + print(model.classes_[ind],':',round(probas[0][ind],2)) + +def read_code(): + file_name = sys.argv[1] + myfile = open(file_name) + myfile_content = myfile.read() + return myfile_content + +model_features, model = setup_data() +code = read_code() +predicted, predicted_probs = predict(code, model, model_features) +print("I think this code is:{}".format(predicted[0])) +print_probabilities(predicted_probs, model) From c083eb78215f25d2a538b1818c0abb032f2ed98c Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sun, 15 Feb 2015 16:09:43 -0500 Subject: [PATCH 10/26] Final code to train the model --- lang_orig.py | 42 +++++++++++++----------------------------- 1 file changed, 13 insertions(+), 29 deletions(-) diff --git a/lang_orig.py b/lang_orig.py index bf45461..a63c4f3 100644 --- a/lang_orig.py +++ b/lang_orig.py @@ -10,7 +10,6 @@ from sklearn.cross_validation import train_test_split from sklearn.feature_extraction import DictVectorizer from sklearn.naive_bayes import BernoulliNB -from sklearn.linear_model import LogisticRegression from sklearn.feature_extraction.text import CountVectorizer from sklearn.tree import DecisionTreeClassifier from sklearn import tree @@ -57,18 +56,19 @@ def get_language(ext): return "Tcl" return None + def read_train_data(): files = read_files("./rosetta") main_list = [] for file in files: ext = get_extension(file) lang = get_language(ext) - if lang != None: + if lang is not None: file_lang = [] with open(file, errors="surrogateescape") as in_file: texto = in_file.read() main_list.append([texto, lang]) - datadf = pd.DataFrame(main_list, columns = ['Code', 'Language']) + datadf = pd.DataFrame(main_list, columns=['Code', 'Language']) return datadf @@ -96,25 +96,25 @@ def return_tokenized_data(datadf): def calculate_scores(token_blob): - scores = {word: word_freq(word,token_blob) for word in token_blob.words} + scores = {word: word_freq(word, token_blob) + for word in token_blob.words} return sorted(scores.items(), key=lambda x: x[1], reverse=True) def select_features(word_list): - exclude_list = ['l','6','d','x1','x2','5','j','m','w','i','e','g','4','v','n','0','1','a','x','n','y','b','2','c','s','3'] - final={} + exclude_list = ['l', '6', 'd', 'x1', 'x2', '5', 'j', 'm', 'w', 'i', 'e', 'g', '4', 'v', 'n', '0', '1', 'a', 'x', 'n', 'y', 'b', '2', 'c', 's', '3'] + final = {} counter = 0 for word, score in word_list: if word not in exclude_list: - final[word] = round(score,5) + final[word] = round(score, 5) counter += 1 if counter == 160: break - print("features#", len(final)) return final -def create_vectors(final,data): +def create_vectors(final, data): super_final = [] for ind, row in data.iterrows(): mydict = {} @@ -127,22 +127,8 @@ def create_vectors(final,data): vec = DictVectorizer() return vec.fit_transform(super_final).toarray() -def test_model(x,y,model): - if model == 'tree': - clf = tree.DecisionTreeClassifier() - elif model == 'bernoulli': - clf = BernoulliNB() - x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.4, random_state=0) - clf = clf.fit(x_train, y_train) - predicted = clf.predict(x_test) - print('predicted',predicted) - print(metrics.classification_report(y_test, predicted)) - print(metrics.f1_score(y_test, predicted)) - scores = cross_val_score(clf, x, y, cv=5) - return scores, clf - -def test_model(x,y,model): +def test_model(x, y, model): if model == 'tree': clf = tree.DecisionTreeClassifier() elif model == 'bernoulli': @@ -150,7 +136,6 @@ def test_model(x,y,model): x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.4, random_state=0) clf = clf.fit(x_train, y_train) predicted = clf.predict(x_test) - #print('predicted',predicted) print(metrics.classification_report(y_test, predicted)) print(metrics.f1_score(y_test, predicted)) scores = cross_val_score(clf, x, y, cv=5) @@ -163,9 +148,8 @@ def test_model(x,y,model): token_blob = return_tokenized_data(datadf) word_list = calculate_scores(token_blob) final_words = select_features(word_list) - #print("word_list for model", final_words) - new_x = create_vectors(final_words,datadf) + new_x = create_vectors(final_words, datadf) bernoulli_score = test_model(new_x, target, 'bernoulli') tree_score, clf_model = test_model(new_x, target, 'tree') - pickle.dump( clf_model, open( "model.p", "wb" ) ) - pickle.dump( final_words, open( "features.p", "wb" ) ) + pickle.dump(clf_model, open("model.p", "wb")) + pickle.dump(final_words, open("features.p", "wb")) From 072bf6acb401828c4c7e985ffb3c3c9e05375510 Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sun, 15 Feb 2015 16:15:26 -0500 Subject: [PATCH 11/26] Tested new files. Rate of success: 80% --- classify.py | 50 ++++++++++++++------------------------------------ 1 file changed, 14 insertions(+), 36 deletions(-) diff --git a/classify.py b/classify.py index 8cb5b74..b6fdc3c 100644 --- a/classify.py +++ b/classify.py @@ -6,17 +6,12 @@ import re import numpy as np from textblob import TextBlob as tb -from sklearn import metrics -from sklearn.cross_validation import cross_val_score -from sklearn.cross_validation import train_test_split from sklearn.feature_extraction import DictVectorizer -from sklearn.naive_bayes import BernoulliNB -from sklearn.linear_model import LogisticRegression -from sklearn.feature_extraction.text import CountVectorizer from sklearn.tree import DecisionTreeClassifier from sklearn import tree import lang_orig as lg + def read_test_data(): files = lg.read_files("./test") main_list = [] @@ -24,84 +19,67 @@ def read_test_data(): with open(file, errors="surrogateescape") as in_file: texto = in_file.read() file_name = re.findall(r'\d+', file) - main_list.append([texto,file_name[0]]) + main_list.append([texto, file_name[0]]) file_content = pd.DataFrame(main_list, columns=['Code', 'Filename']) file_info = pd.read_csv('./test.csv', dtype={'Filename': str, 'Language': str}) datadf = pd.merge(file_info, file_content, on=['Filename']) del datadf['Filename'] return datadf + def select_features_new_test(word_list, final): final_list = {} - #exclude_list = ['l','6','d','x1','x2','5','j','m','w','i','e','g','4','v','n','0','1','a','x','n','y','b','2','c','s','3'] for key in final: found = 0 for word, score in word_list: - # if word not in exclude_list: if word == key: found = score break - final_list[key] = round(found,5) + final_list[key] = round(found, 5) return final_list -#def test_new_models(data, final_words, clf): -# new_target = data['Language'].values -# token_blob = return_tokenized_data(data) -# word_list = calculate_scores(token_blob) -# final = select_features_new_test(word_list, final_words) -# print('newmodelx word list',final) -# new_x = create_vectors(final,data) -# print('nwx',new_x) -# predicted = clf.predict(new_x) -# for pp in range(len(predicted)): -# print('predicted',predicted[pp],new_target[pp]) -# scores = cross_val_score(clf, new_x, new_target, cv=2) -# print(metrics.confusion_matrix(new_target, predicted)) -# print(metrics.classification_report(new_target, predicted)) - #print(metrics.f1_score(new_target, predicted)) def setup_data(): - cls = pickle.load( open( "model.p", "rb" ) ) - final_features = pickle.load( open( "features.p", "rb" ) ) + cls = pickle.load(open("model.p", "rb")) + final_features = pickle.load(open("features.p", "rb")) return final_features, cls + def return_tokens(code): tokens = nltk.word_tokenize(code) return tb(' '.join(tokens)) + def create_vectors_new_test(features): vec = DictVectorizer() return vec.fit_transform(features).toarray() + def predict(code, model, final_features): token_blob = return_tokens(code) word_list = lg.calculate_scores(token_blob) features = select_features_new_test(word_list, final_features) - #print('newmodelx word list',final) - #print(features) new_x = create_vectors_new_test(features) - #print('nwx',new_x) predicted = model.predict(new_x) predicted_probs = model.predict_proba(new_x) return predicted, predicted_probs + def print_probabilities(probas, model): for ind in range(len(probas[0])): - print(model.classes_[ind],':',probas[0][ind]) + print(model.classes_[ind], ':', probas[0][ind]) def test_all_new_files(test_data, model, final_features): agreement = 0 total = 0 for ind, row in test_data.iterrows(): - predicted, probas = predict(row['Code'], model, final_features) print("I predicted: {}. It was: {}".format(predicted[0], row['Language'])) - #print_probabilities(probas, model) - total +=1 + total += 1 if predicted[0].lower() == row['Language'].lower(): - agreement +=1 - print("Success Rate of Classification:",round(agreement*100/total,2)) + agreement += 1 + print("Success Rate of Classification:", round(agreement * 100 / total, 2)) test_data = read_test_data() model_features, model = setup_data() From ba0735b2071c1d885185e6efff9cbc15aebc5d42 Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sun, 15 Feb 2015 16:19:36 -0500 Subject: [PATCH 12/26] executable ready to predict code passed as an argument --- classify_snippet.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/classify_snippet.py b/classify_snippet.py index 0a4202f..038b8a4 100755 --- a/classify_snippet.py +++ b/classify_snippet.py @@ -13,6 +13,7 @@ import lang_orig as lg import sys + def select_features_new_test(word_list, final): final_list = {} for key in final: @@ -21,23 +22,26 @@ def select_features_new_test(word_list, final): if word == key: found = score break - final_list[key] = round(found,5) + final_list[key] = round(found, 5) return final_list def setup_data(): - cls = pickle.load( open( "model.p", "rb" ) ) - final_features = pickle.load( open( "features.p", "rb" ) ) + cls = pickle.load(open("model.p", "rb")) + final_features = pickle.load(open("features.p", "rb")) return final_features, cls + def return_tokens(code): tokens = nltk.word_tokenize(code) return tb(' '.join(tokens)) + def create_vectors_new_test(features): vec = DictVectorizer() return vec.fit_transform(features).toarray() + def predict(code, model, final_features): token_blob = return_tokens(code) word_list = lg.calculate_scores(token_blob) @@ -47,10 +51,12 @@ def predict(code, model, final_features): predicted_probs = model.predict_proba(new_x) return predicted, predicted_probs + def print_probabilities(probas, model): print("Probabilites for my prediction:") for ind in range(len(probas[0])): - print(model.classes_[ind],':',round(probas[0][ind],2)) + print(model.classes_[ind], ':', round(probas[0][ind], 2)) + def read_code(): file_name = sys.argv[1] @@ -58,6 +64,7 @@ def read_code(): myfile_content = myfile.read() return myfile_content + model_features, model = setup_data() code = read_code() predicted, predicted_probs = predict(code, model, model_features) From d78b4800b18ebf6322d2375d8b8874d828e12501 Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sun, 15 Feb 2015 16:29:51 -0500 Subject: [PATCH 13/26] demonstration of how the model works --- Model_Demonstration.ipynb | 253 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 253 insertions(+) create mode 100644 Model_Demonstration.ipynb diff --git a/Model_Demonstration.ipynb b/Model_Demonstration.ipynb new file mode 100644 index 0000000..20c2d99 --- /dev/null +++ b/Model_Demonstration.ipynb @@ -0,0 +1,253 @@ +{ + "metadata": { + "name": "", + "signature": "sha256:0d827c0e391d23b4bc1ca4d6c493c6326814689fd4a5f9eeff11b3df08b00194" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "code", + "collapsed": false, + "input": [ + "import pickle\n", + "import os\n", + "import os.path\n", + "import pandas as pd\n", + "import nltk\n", + "import re\n", + "import numpy as np\n", + "from textblob import TextBlob as tb\n", + "from sklearn.feature_extraction import DictVectorizer\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn import tree\n", + "import lang_orig as lg\n", + "import sys" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 24 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "def setup_data():\n", + " cls = pickle.load(open(\"model.p\", \"rb\"))\n", + " final_features = pickle.load(open(\"features.p\", \"rb\"))\n", + " return final_features, cls" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 25 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "def read_code(file_name):\n", + " myfile = open(file_name)\n", + " myfile_content = myfile.read()\n", + " return myfile_content" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 26 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "def select_features_new_test(word_list, final):\n", + " final_list = {}\n", + " for key in final:\n", + " found = 0\n", + " for word, score in word_list:\n", + " if word == key:\n", + " found = score\n", + " break\n", + " final_list[key] = round(found, 5)\n", + " return final_list" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 27 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "def return_tokens(code):\n", + " tokens = nltk.word_tokenize(code)\n", + " return tb(' '.join(tokens))" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 28 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "def create_vectors_new_test(features):\n", + " vec = DictVectorizer()\n", + " return vec.fit_transform(features).toarray()\n" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 29 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "def predict(code, model, final_features):\n", + " token_blob = return_tokens(code)\n", + " word_list = lg.calculate_scores(token_blob)\n", + " features = select_features_new_test(word_list, final_features)\n", + " new_x = create_vectors_new_test(features)\n", + " predicted = model.predict(new_x)\n", + " predicted_probs = model.predict_proba(new_x)\n", + " return predicted, predicted_probs" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 30 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "def print_probabilities(probas, model):\n", + " print(\"Probabilites for my prediction:\")\n", + " for ind in range(len(probas[0])):\n", + " print(model.classes_[ind], ':', round(probas[0][ind], 2))" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 31 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "model_features, model = setup_data()\n", + "file_name = \"./rosetta/file50.js\"\n", + "code = read_code(file_name)\n", + "predicted, predicted_probs = predict(code, model, model_features)\n", + "print(\"I think this code is:{}\".format(predicted[0]))\n", + "print_probabilities(predicted_probs, model)" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "I think this code is:Javascript\n", + "Probabilites for my prediction:\n", + "Clojure : 0.0\n", + "Haskell : 0.0\n", + "Java : 0.0\n", + "Javascript : 1.0\n", + "Ocaml : 0.0\n", + "PHP : 0.0\n", + "Perl : 0.0\n", + "Python : 0.0\n", + "Ruby : 0.0\n", + "Scala : 0.0\n", + "Scheme : 0.0\n", + "Tcl : 0.0\n" + ] + } + ], + "prompt_number": 32 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "file_name = \"./rosetta/file8.py\"\n", + "code = read_code(file_name)\n", + "predicted, predicted_probs = predict(code, model, model_features)\n", + "print(\"I think this code is:{}\".format(predicted[0]))\n", + "print_probabilities(predicted_probs, model)" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "I think this code is:Python\n", + "Probabilites for my prediction:\n", + "Clojure : 0.0\n", + "Haskell : 0.0\n", + "Java : 0.0\n", + "Javascript : 0.0\n", + "Ocaml : 0.0\n", + "PHP : 0.0\n", + "Perl : 0.0\n", + "Python : 1.0\n", + "Ruby : 0.0\n", + "Scala : 0.0\n", + "Scheme : 0.0\n", + "Tcl : 0.0\n" + ] + } + ], + "prompt_number": 39 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "file_name = \"./rosetta/file15.php\"\n", + "code = read_code(file_name)\n", + "predicted, predicted_probs = predict(code, model, model_features)\n", + "print(\"I think this code is:{}\".format(predicted[0]))\n", + "print_probabilities(predicted_probs, model)" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "I think this code is:Perl\n", + "Probabilites for my prediction:\n", + "Clojure : 0.0\n", + "Haskell : 0.33\n", + "Java : 0.0\n", + "Javascript : 0.0\n", + "Ocaml : 0.0\n", + "PHP : 0.0\n", + "Perl : 0.67\n", + "Python : 0.0\n", + "Ruby : 0.0\n", + "Scala : 0.0\n", + "Scheme : 0.0\n", + "Tcl : 0.0\n" + ] + } + ], + "prompt_number": 40 + } + ], + "metadata": {} + } + ] +} \ No newline at end of file From a6316f25f8d8ee47967346f0bd886b2d567e7418 Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sun, 15 Feb 2015 16:33:38 -0500 Subject: [PATCH 14/26] demonstration of how the model works with correct and incorrect predictions --- Model_Demonstration.ipynb | 45 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/Model_Demonstration.ipynb b/Model_Demonstration.ipynb index 20c2d99..8800d3f 100644 --- a/Model_Demonstration.ipynb +++ b/Model_Demonstration.ipynb @@ -1,13 +1,29 @@ { "metadata": { "name": "", - "signature": "sha256:0d827c0e391d23b4bc1ca4d6c493c6326814689fd4a5f9eeff11b3df08b00194" + "signature": "sha256:e0082f203d7aab01fa97782998c62980e66e72f9a5e75450c8b11cb7ffdd64f0" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ + { + "cell_type": "heading", + "level": 2, + "metadata": {}, + "source": [ + "Predicting the programming language for a piece of code" + ] + }, + { + "cell_type": "heading", + "level": 4, + "metadata": {}, + "source": [ + "This model is a Decision Tree with 160 features and predicts the right language approximately 78% of the time." + ] + }, { "cell_type": "code", "collapsed": false, @@ -28,8 +44,7 @@ ], "language": "python", "metadata": {}, - "outputs": [], - "prompt_number": 24 + "outputs": [] }, { "cell_type": "code", @@ -137,6 +152,14 @@ "outputs": [], "prompt_number": 31 }, + { + "cell_type": "heading", + "level": 4, + "metadata": {}, + "source": [ + "This is an example of a correct prediction" + ] + }, { "cell_type": "code", "collapsed": false, @@ -174,6 +197,14 @@ ], "prompt_number": 32 }, + { + "cell_type": "heading", + "level": 4, + "metadata": {}, + "source": [ + "Another correct prediction" + ] + }, { "cell_type": "code", "collapsed": false, @@ -210,6 +241,14 @@ ], "prompt_number": 39 }, + { + "cell_type": "heading", + "level": 4, + "metadata": {}, + "source": [ + "This is an incorrect prediction" + ] + }, { "cell_type": "code", "collapsed": false, From 286ab3d4a40df1feab3260ae5e16bef37ccdf5ff Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sun, 15 Feb 2015 16:41:53 -0500 Subject: [PATCH 15/26] tests --- tests/test_lang.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 tests/test_lang.py diff --git a/tests/test_lang.py b/tests/test_lang.py new file mode 100644 index 0000000..fa53dad --- /dev/null +++ b/tests/test_lang.py @@ -0,0 +1,16 @@ +import lang_orig1 as lang +import pandas as pd + +mylist = [["for i j do na ; ;", "lang1"], ["while do never?", "lang2"]] +mylistdf = pd.DataFrame(mylist, columns = ['Code', 'Language']) + +def test_join_all_code(): + assert lang.join_all_code(mylistdf) == 'for i j do na while do never' + +def test_return_tokenized_data(content): + print(lang.return_tokenized_data(content)) + +test_return_tokenized_data(mylistdf) +mydict={'word':'dddd','score':4} +ana = pd.DataFrame(mydict) +print(ana) From a2575b20ce2c3b879fa32a02120edd0455af44d7 Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sun, 15 Feb 2015 16:42:18 -0500 Subject: [PATCH 16/26] final files --- programming-language-classifier/classify.py | 86 ++++++++++ .../classify_snippet.py | 72 ++++++++ programming-language-classifier/lang_orig.py | 155 ++++++++++++++++++ 3 files changed, 313 insertions(+) create mode 100644 programming-language-classifier/classify.py create mode 100755 programming-language-classifier/classify_snippet.py create mode 100644 programming-language-classifier/lang_orig.py diff --git a/programming-language-classifier/classify.py b/programming-language-classifier/classify.py new file mode 100644 index 0000000..b6fdc3c --- /dev/null +++ b/programming-language-classifier/classify.py @@ -0,0 +1,86 @@ +import pickle +import os +import os.path +import pandas as pd +import nltk +import re +import numpy as np +from textblob import TextBlob as tb +from sklearn.feature_extraction import DictVectorizer +from sklearn.tree import DecisionTreeClassifier +from sklearn import tree +import lang_orig as lg + + +def read_test_data(): + files = lg.read_files("./test") + main_list = [] + for file in files: + with open(file, errors="surrogateescape") as in_file: + texto = in_file.read() + file_name = re.findall(r'\d+', file) + main_list.append([texto, file_name[0]]) + file_content = pd.DataFrame(main_list, columns=['Code', 'Filename']) + file_info = pd.read_csv('./test.csv', dtype={'Filename': str, 'Language': str}) + datadf = pd.merge(file_info, file_content, on=['Filename']) + del datadf['Filename'] + return datadf + + +def select_features_new_test(word_list, final): + final_list = {} + for key in final: + found = 0 + for word, score in word_list: + if word == key: + found = score + break + final_list[key] = round(found, 5) + return final_list + + +def setup_data(): + cls = pickle.load(open("model.p", "rb")) + final_features = pickle.load(open("features.p", "rb")) + return final_features, cls + + +def return_tokens(code): + tokens = nltk.word_tokenize(code) + return tb(' '.join(tokens)) + + +def create_vectors_new_test(features): + vec = DictVectorizer() + return vec.fit_transform(features).toarray() + + +def predict(code, model, final_features): + token_blob = return_tokens(code) + word_list = lg.calculate_scores(token_blob) + features = select_features_new_test(word_list, final_features) + new_x = create_vectors_new_test(features) + predicted = model.predict(new_x) + predicted_probs = model.predict_proba(new_x) + return predicted, predicted_probs + + +def print_probabilities(probas, model): + for ind in range(len(probas[0])): + print(model.classes_[ind], ':', probas[0][ind]) + + +def test_all_new_files(test_data, model, final_features): + agreement = 0 + total = 0 + for ind, row in test_data.iterrows(): + predicted, probas = predict(row['Code'], model, final_features) + print("I predicted: {}. It was: {}".format(predicted[0], row['Language'])) + total += 1 + if predicted[0].lower() == row['Language'].lower(): + agreement += 1 + print("Success Rate of Classification:", round(agreement * 100 / total, 2)) + +test_data = read_test_data() +model_features, model = setup_data() +test_all_new_files(test_data, model, model_features) diff --git a/programming-language-classifier/classify_snippet.py b/programming-language-classifier/classify_snippet.py new file mode 100755 index 0000000..038b8a4 --- /dev/null +++ b/programming-language-classifier/classify_snippet.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python +import pickle +import os +import os.path +import pandas as pd +import nltk +import re +import numpy as np +from textblob import TextBlob as tb +from sklearn.feature_extraction import DictVectorizer +from sklearn.tree import DecisionTreeClassifier +from sklearn import tree +import lang_orig as lg +import sys + + +def select_features_new_test(word_list, final): + final_list = {} + for key in final: + found = 0 + for word, score in word_list: + if word == key: + found = score + break + final_list[key] = round(found, 5) + return final_list + + +def setup_data(): + cls = pickle.load(open("model.p", "rb")) + final_features = pickle.load(open("features.p", "rb")) + return final_features, cls + + +def return_tokens(code): + tokens = nltk.word_tokenize(code) + return tb(' '.join(tokens)) + + +def create_vectors_new_test(features): + vec = DictVectorizer() + return vec.fit_transform(features).toarray() + + +def predict(code, model, final_features): + token_blob = return_tokens(code) + word_list = lg.calculate_scores(token_blob) + features = select_features_new_test(word_list, final_features) + new_x = create_vectors_new_test(features) + predicted = model.predict(new_x) + predicted_probs = model.predict_proba(new_x) + return predicted, predicted_probs + + +def print_probabilities(probas, model): + print("Probabilites for my prediction:") + for ind in range(len(probas[0])): + print(model.classes_[ind], ':', round(probas[0][ind], 2)) + + +def read_code(): + file_name = sys.argv[1] + myfile = open(file_name) + myfile_content = myfile.read() + return myfile_content + + +model_features, model = setup_data() +code = read_code() +predicted, predicted_probs = predict(code, model, model_features) +print("I think this code is:{}".format(predicted[0])) +print_probabilities(predicted_probs, model) diff --git a/programming-language-classifier/lang_orig.py b/programming-language-classifier/lang_orig.py new file mode 100644 index 0000000..a63c4f3 --- /dev/null +++ b/programming-language-classifier/lang_orig.py @@ -0,0 +1,155 @@ +import os +import os.path +import pickle +import pandas as pd +import nltk +import re +from textblob import TextBlob as tb +from sklearn import metrics +from sklearn.cross_validation import cross_val_score +from sklearn.cross_validation import train_test_split +from sklearn.feature_extraction import DictVectorizer +from sklearn.naive_bayes import BernoulliNB +from sklearn.feature_extraction.text import CountVectorizer +from sklearn.tree import DecisionTreeClassifier +from sklearn import tree + + +def read_files(dir_path): + file_list = [] + for root, dirs, files in os.walk(dir_path): + for name in files: + file_list.append(os.path.join(root, name)) + for name in dirs: + file_list.append((os.path.join(root, name))) + return file_list + + +def get_extension(file): + return os.path.splitext(file)[1] + + +def get_language(ext): + if ext in ['.clj', '.cljs', '.edn', '.clojure']: + return 'Clojure' + elif ext in ['.hs', '.lhs', 'ghc']: + return 'Haskell' + elif ext in ['.java', '.class', '.jar']: + return 'Java' + elif ext in ['.js', '.javascript']: + return 'Javascript' + elif ext in ['.pl', '.pm', '.t', '.pod', '.perl']: + return 'Perl' + elif ext in ['.php', '.phtml', '.php4', '.php3', '.php5', '.phps']: + return 'PHP' + elif ext in ['.ocaml', '.ml']: + return 'Ocaml' + elif ext in ['.py', '.pyw', '.pyc', '.pyo', '.pyd', '.python3']: + return "Python" + elif ext in ['.rb', '.rbw', '.jruby']: + return "Ruby" + elif ext in ['.scala']: + return 'Scala' + elif ext in ['.scm', '.ss', '.racket']: + return "Scheme" + elif ext in ['.tcl']: + return "Tcl" + return None + + +def read_train_data(): + files = read_files("./rosetta") + main_list = [] + for file in files: + ext = get_extension(file) + lang = get_language(ext) + if lang is not None: + file_lang = [] + with open(file, errors="surrogateescape") as in_file: + texto = in_file.read() + main_list.append([texto, lang]) + datadf = pd.DataFrame(main_list, columns=['Code', 'Language']) + return datadf + + +def join_all_code(content): + all_content = [row["Code"] for ind, row in content.iterrows()] + return ' '.join(all_content) + + +def tokenize(content): + tokens = nltk.word_tokenize(content) + return ' '.join(tokens) + + +def word_freq(word, code): + if len(code.words) == 0: + return 0 + else: + return code.word_counts[word] / len(code.words) + + +def return_tokenized_data(datadf): + all_code = join_all_code(datadf) + all_tokens = tokenize(all_code) + return tb(all_tokens) + + +def calculate_scores(token_blob): + scores = {word: word_freq(word, token_blob) + for word in token_blob.words} + return sorted(scores.items(), key=lambda x: x[1], reverse=True) + + +def select_features(word_list): + exclude_list = ['l', '6', 'd', 'x1', 'x2', '5', 'j', 'm', 'w', 'i', 'e', 'g', '4', 'v', 'n', '0', '1', 'a', 'x', 'n', 'y', 'b', '2', 'c', 's', '3'] + final = {} + counter = 0 + for word, score in word_list: + if word not in exclude_list: + final[word] = round(score, 5) + counter += 1 + if counter == 160: + break + return final + + +def create_vectors(final, data): + super_final = [] + for ind, row in data.iterrows(): + mydict = {} + for word, score in final.items(): + if row['Code'].find(word) != -1: + mydict[word] = score + else: + mydict[word] = 0 + super_final.append(mydict) + vec = DictVectorizer() + return vec.fit_transform(super_final).toarray() + + +def test_model(x, y, model): + if model == 'tree': + clf = tree.DecisionTreeClassifier() + elif model == 'bernoulli': + clf = BernoulliNB() + x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.4, random_state=0) + clf = clf.fit(x_train, y_train) + predicted = clf.predict(x_test) + print(metrics.classification_report(y_test, predicted)) + print(metrics.f1_score(y_test, predicted)) + scores = cross_val_score(clf, x, y, cv=5) + return scores, clf + + +if __name__ == '__main__': + datadf = read_train_data() + target = datadf['Language'].values + token_blob = return_tokenized_data(datadf) + word_list = calculate_scores(token_blob) + final_words = select_features(word_list) + new_x = create_vectors(final_words, datadf) + bernoulli_score = test_model(new_x, target, 'bernoulli') + tree_score, clf_model = test_model(new_x, target, 'tree') + pickle.dump(clf_model, open("model.p", "wb")) + pickle.dump(final_words, open("features.p", "wb")) From 26785ca6aa1654fbab9c4f3fc402f23c82533194 Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sun, 15 Feb 2015 16:45:03 -0500 Subject: [PATCH 17/26] final files --- .../Model_Demonstration.ipynb | 292 ++++++++++++++++++ programming-language-classifier/features.p | Bin 0 -> 7994 bytes programming-language-classifier/model.p | Bin 0 -> 29058 bytes 3 files changed, 292 insertions(+) create mode 100644 programming-language-classifier/Model_Demonstration.ipynb create mode 100644 programming-language-classifier/features.p create mode 100644 programming-language-classifier/model.p diff --git a/programming-language-classifier/Model_Demonstration.ipynb b/programming-language-classifier/Model_Demonstration.ipynb new file mode 100644 index 0000000..8800d3f --- /dev/null +++ b/programming-language-classifier/Model_Demonstration.ipynb @@ -0,0 +1,292 @@ +{ + "metadata": { + "name": "", + "signature": "sha256:e0082f203d7aab01fa97782998c62980e66e72f9a5e75450c8b11cb7ffdd64f0" + }, + "nbformat": 3, + "nbformat_minor": 0, + "worksheets": [ + { + "cells": [ + { + "cell_type": "heading", + "level": 2, + "metadata": {}, + "source": [ + "Predicting the programming language for a piece of code" + ] + }, + { + "cell_type": "heading", + "level": 4, + "metadata": {}, + "source": [ + "This model is a Decision Tree with 160 features and predicts the right language approximately 78% of the time." + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "import pickle\n", + "import os\n", + "import os.path\n", + "import pandas as pd\n", + "import nltk\n", + "import re\n", + "import numpy as np\n", + "from textblob import TextBlob as tb\n", + "from sklearn.feature_extraction import DictVectorizer\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn import tree\n", + "import lang_orig as lg\n", + "import sys" + ], + "language": "python", + "metadata": {}, + "outputs": [] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "def setup_data():\n", + " cls = pickle.load(open(\"model.p\", \"rb\"))\n", + " final_features = pickle.load(open(\"features.p\", \"rb\"))\n", + " return final_features, cls" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 25 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "def read_code(file_name):\n", + " myfile = open(file_name)\n", + " myfile_content = myfile.read()\n", + " return myfile_content" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 26 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "def select_features_new_test(word_list, final):\n", + " final_list = {}\n", + " for key in final:\n", + " found = 0\n", + " for word, score in word_list:\n", + " if word == key:\n", + " found = score\n", + " break\n", + " final_list[key] = round(found, 5)\n", + " return final_list" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 27 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "def return_tokens(code):\n", + " tokens = nltk.word_tokenize(code)\n", + " return tb(' '.join(tokens))" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 28 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "def create_vectors_new_test(features):\n", + " vec = DictVectorizer()\n", + " return vec.fit_transform(features).toarray()\n" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 29 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "def predict(code, model, final_features):\n", + " token_blob = return_tokens(code)\n", + " word_list = lg.calculate_scores(token_blob)\n", + " features = select_features_new_test(word_list, final_features)\n", + " new_x = create_vectors_new_test(features)\n", + " predicted = model.predict(new_x)\n", + " predicted_probs = model.predict_proba(new_x)\n", + " return predicted, predicted_probs" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 30 + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "def print_probabilities(probas, model):\n", + " print(\"Probabilites for my prediction:\")\n", + " for ind in range(len(probas[0])):\n", + " print(model.classes_[ind], ':', round(probas[0][ind], 2))" + ], + "language": "python", + "metadata": {}, + "outputs": [], + "prompt_number": 31 + }, + { + "cell_type": "heading", + "level": 4, + "metadata": {}, + "source": [ + "This is an example of a correct prediction" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "model_features, model = setup_data()\n", + "file_name = \"./rosetta/file50.js\"\n", + "code = read_code(file_name)\n", + "predicted, predicted_probs = predict(code, model, model_features)\n", + "print(\"I think this code is:{}\".format(predicted[0]))\n", + "print_probabilities(predicted_probs, model)" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "I think this code is:Javascript\n", + "Probabilites for my prediction:\n", + "Clojure : 0.0\n", + "Haskell : 0.0\n", + "Java : 0.0\n", + "Javascript : 1.0\n", + "Ocaml : 0.0\n", + "PHP : 0.0\n", + "Perl : 0.0\n", + "Python : 0.0\n", + "Ruby : 0.0\n", + "Scala : 0.0\n", + "Scheme : 0.0\n", + "Tcl : 0.0\n" + ] + } + ], + "prompt_number": 32 + }, + { + "cell_type": "heading", + "level": 4, + "metadata": {}, + "source": [ + "Another correct prediction" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "file_name = \"./rosetta/file8.py\"\n", + "code = read_code(file_name)\n", + "predicted, predicted_probs = predict(code, model, model_features)\n", + "print(\"I think this code is:{}\".format(predicted[0]))\n", + "print_probabilities(predicted_probs, model)" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "I think this code is:Python\n", + "Probabilites for my prediction:\n", + "Clojure : 0.0\n", + "Haskell : 0.0\n", + "Java : 0.0\n", + "Javascript : 0.0\n", + "Ocaml : 0.0\n", + "PHP : 0.0\n", + "Perl : 0.0\n", + "Python : 1.0\n", + "Ruby : 0.0\n", + "Scala : 0.0\n", + "Scheme : 0.0\n", + "Tcl : 0.0\n" + ] + } + ], + "prompt_number": 39 + }, + { + "cell_type": "heading", + "level": 4, + "metadata": {}, + "source": [ + "This is an incorrect prediction" + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "file_name = \"./rosetta/file15.php\"\n", + "code = read_code(file_name)\n", + "predicted, predicted_probs = predict(code, model, model_features)\n", + "print(\"I think this code is:{}\".format(predicted[0]))\n", + "print_probabilities(predicted_probs, model)" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "I think this code is:Perl\n", + "Probabilites for my prediction:\n", + "Clojure : 0.0\n", + "Haskell : 0.33\n", + "Java : 0.0\n", + "Javascript : 0.0\n", + "Ocaml : 0.0\n", + "PHP : 0.0\n", + "Perl : 0.67\n", + "Python : 0.0\n", + "Ruby : 0.0\n", + "Scala : 0.0\n", + "Scheme : 0.0\n", + "Tcl : 0.0\n" + ] + } + ], + "prompt_number": 40 + } + ], + "metadata": {} + } + ] +} \ No newline at end of file diff --git a/programming-language-classifier/features.p b/programming-language-classifier/features.p new file mode 100644 index 0000000000000000000000000000000000000000..ac84ac74709cef0b40b3e05e623592c6610ae97f GIT binary patch literal 7994 zcmZXZcYIV;9>t>|AR>Z_QY~OX5F|mGA}ENU0!j&l&Lnxs3{1)I%nV78t6br#*c*a~ zfQSWqFT3`(ipnlxFRSRPtFkr}`?}{hb2Ib!>_6X^&+nY`yXC!k@6BX!Gb1HEt1>}D zrZS$Y?5k)!HHGTdvRg&7l9G~ikdfV;G_%s&$R0f_TC!G`O3%qeYNf^aiWX|gAeO9^ zmIZ&SY~|?T4Tp4n>Vth33S7C4UFMR#zp=-83<^2%^ z($>j7R@xb9AM&fPulgr#?A5QlEJA;C&LM+rAp1Gl-%1A~2lzliIZzXkd*A7O&PNw9 zp|eg^&I_tC($PsLE1ivW@tKg;Ra3KXoHpS1x59Hp^Tx;yD%`9MJ#u8H|&7bVWy-qFu00z?|+L?m3`=Tl*EyyoT(o>}|hC%rh9 zp08L&&Tw+3l?g^B`iQSjQuovquMGL~&3)+hjgpyoQYJeow=%`Z)Llo(i4~fwe)Q$& zm?s|cD+&OvXquDhR%RHP8Cp?Znx&b@dz-Gg;+9#=|^x-6JC1WJ(V_|WD z=BCemeM;Xw|71@0zqFs!J87`eXk?*}`1)Duj`JQg_@2}KYN~^pq%3k`tekD+oX~1= z%HrH={@A-k!&7_sL_C(xh;?$Vl_f@&h7vi&X`->q^A**j4r>}Cl8MN9PR_S-fstjQ zM71gxY9iPaUpMsh)_x5<xsKD?@%2u2p~Wlc+lvNy{oH*I8L@<{c7VuO-9x_S!d-2BkR3iufCjeqb4dktUGH!ucdyqk)&*Ja+8&t zjocFMpOjnGU0kisCRHOFo!n;Sb|ZI$+^pZJ?)02zAJ};SeDBhMa+j04t=wbe-jJL1 z`_w&g$>k&7er5yRdNpzYaH$Yha}$DKT3V*fEmL|TYxzig z#>ul*o-^{ik2DD{tFhs_V!;^y_Ut zmWb2_@`{sJt!y^(cb_Oq|Ikb@Xzj+c_v_7!p3OR>s$`3k*Q{(c^16={ls7c7>oX%# znU*)5yk+HWBkzP}rNX=FpE~l3s`tmtZyF(+Ny~dq-na6Bk$;9qQ02p1;_1h4YQOp; zCiEO7gIc|nf8=DFm5+^l;xi%bUz(cPe8kcZH-=FE<(a(#cm=wj246PZXuEH6vTbAOGrrTm8)9L9#Xzm2aGUYvns5 z--l-AwH=yDY*~NMjnfADRBogi`N7GLR(2ZsDU|Zs&zhQj#)3I--+2d9df^R`U!44E z{!$&$v4PhE{K;4{1x6^A`Zi`JyUUSue)rZy~T9PM&XUrsx>&#{Ie zj=iZlv?VR}Ar0D*zCqE}o<(gjqt&Y2vxlF;7WxR`$qgb^QS3|AVL#Ghf6|}>>6?U& z2e7Pdimw5Bu_q##C=R6L(2=z0L>hD^eUE~x3v1dSa{lK}B|AOJd8m|(Bm#7$kf^Fq-t~Ces*} zG(L5gn;u_O_yUhpDLR}+TAWTAj3s>sy#adPI99bu@L>AO`)hCT3n(qacnS_@kQQf> z1{2880_d5@iiRg|coFlZe|S1FdP0xBsvRFM|dq(MN28suCxtZ9S9V;f_gv#+v&?rk~~$;7HqOVRPw zLtDg1gL$NH5%SGvRhv}qatY_&J`ktokRUCRq(O@GJ#-uMwmKHIMdaIO$9BH(1%D=L z`TCNEP;&rjktPi?WT-{nmSs^}6yF8(GHoow0tycGq(uX1&`A2c_bg;3w}g{#?mn#J zJU@O-gx~XU7Bz=Oq=g|3&L%_S=WXY(s4Zsx`Blr)>bv=Kkq+WDSWL;mk{0KZ21`ia zLC;vuwUjk&5G}do`8!5;@pGsS;+Y5>HHY&^i}Oi?3&_wM^0s9xYK!v1`?q$lif|Pd zQgXP6w78fwxP%PNA?Lc3HEmG5BkD7Q-!`*}WEz)Ib-0|gxPmmelJq^o#;aJ?HpQEo ze(3p;#nn_CmXj9OkOnJA-=fL1k|m9&512LNnqQart&E^HjcX}6tRgM0BMnxQp=IP; z*R!S#BC9{j?);-W8|Zm%=!Z2F9M+N+>qvteNFVo}^{i-k*V}0gZe-nI18H#+X>c>? zv;3>12Dk8_(Rn*=7`y$X5Bw>tibr@E-%8D4BWZCPX>dE~=Ng|v8;G}ugr z)~=?%v!wCp<26Sv8ubd}dg@9C;2#tmwvZODkp^2ypZ1>DS zRhd{SiJvJu{6bp%N*eq|`X;+Le`j4A#e&{jpN;ItMtU~N1`NO-R2=?GTKq{Gl<*qz zJ(^6rv83@yTf1CW^Gkom^%fILRtF8(oti^4(xN$Oum|ZI6m2b7%h5+us_yew zMJ!R5LI&+AI_yhY>_-~xPx=;m;=Qi}tJ);HVA-aQkJtDnb=k@|UvLhf=x`uu(UCOh zM24DpUuRaeN%6;Qo#cX4tQuV?Idmm0x{(G4k)fsJTnDqJ4T`^_vQUyq;Se4j4kazR zlLkFVALn1{IgCdQrwczr>Pe0zYH>Ifha*UfBT0jvq)#`Qj$%pU#c#?ilvFmN7mp6T zNsFUNgFa+vY5NlLqCaPwVMX(-f98E|VI6U9nAX9=y$z%*RyL z9rO~gm_`~*Cw(|?nZbfas~2t?eb@eHHBGw#GbuRCA}wZ<26M>pv>Py&mE4*?DcS$$ z2bcMAGl;P6P)S-;kp|UdXxt0}7Bm`99MtaO;lmi!^H3iR5TJ&dLoI0$B@JSvj~8w8 zSkxB9pY2#E;q7WZj}CFtB0(A?$K}?N%1+zLP=?VWO;O0Kw8w31`T9r2J|$tqTwlHPTVGI7yB8c8`GH}frS(u z&LS-qkp_kg&A|K4W>uTa^GTm?GF`w@E?)RLtx7tZz%nWh7m^kikp>r&p}3kZVJSELA3MKv z_qKOAeZ4B{a4G8!mys5ilLl9iKAg8)$%00AePCAQUO}#+=5RG>v79uxhV*g0fbzB# zENY8sg-13EC5`>Cl1GPYNsCpa!F8n1^Dp(R=264N`;G2t4fyhMJtc=Vq{Uj&U>)h> s1=kI%BBNY_om;2kt_n7ytkO literal 0 HcmV?d00001 diff --git a/programming-language-classifier/model.p b/programming-language-classifier/model.p new file mode 100644 index 0000000000000000000000000000000000000000..90df34cfcc624e70546d870e45707ac73cf3efc0 GIT binary patch literal 29058 zcmeHQ3v^RO8ouROBafn$hal8iArz>kyeh95TA+nMX+yyj3TcvFNNAd7lACIaxD}-Z zU02t2MOoG@qU#G0SE{RvM|^9QJ-WVKg~F=fvFzcjN73DN-I;s;A(tC_dXpw4t-Z(7 zFaON{&;0YvKhFejU2liK!Y$f-o(#z+it-=Be9__ZyQ)0JG$q$<^ZQ-vT%ylFgz?vt zgiWNE(K1L7gi6~rR%*G<>ZvLh{iJt+C6T5&n7-(@l0FVkpwe5D;i&S78I=LI8|=}QxqIc$|~GR)GOelE-} zB*SHkLeb|YBP{(`VvXdi@{o(=baTL7Lq^Jm%N;hijf|3YmOGqcrARK3ODT4^$!Jj` zW9)K`9&1%V@&+WzUWzHfay~86V_hfOBb16I4esvupTpz%S;W< zzD}9RG$*C;ax)prXiV5b#yJ({T-n5^FgM;z(m8Xp$%M0+6C^UxzAZO#0Cj~uWRgTO z?2Pa$%p`LYnQW9jQX(LWS2~4NI@L_3u}YuXLZ;J78EGr0O(!#yTC>gMN?NNkslX^V z-7T(@tPZEkT~21o4fna$J9)}1xubvxGTU+#I?nYW4L7@aen=_a9`$1rL z#q)(`lE*v`Wh&op%B&}goU^HMQaxGhMD&BPo|v3-oq48|da}ehhkh7dPnHHu*_4_j zi4@qkV}%1dzeNA9B(0rkj2^y!0g6#}(!LjhKxB_B^40Pzp$)uIan^ zsNde~BWcr4qTAJWDK(gN2Yc>OKo|u`p~c^{0`+<0-nYIUaT0mdb}iMIjS=>2Q9!5# zq)?WfWJfQ2V=TS({Z@q4c7lZ2_+d}A0zxhz1w8TH4Jcup?Z^)|wIYMsuF;Fxuwsv2 z0pT)03U%cPxyW1j{Pu4)w4#rL>9oWO%*Hu;oC*j_04bE+oV6M?e>vfS14XUq)nGbp zxf8P~j6I?P!Wuvd*i*k6eKTo&<3|^?qKAX&G)KfNB-vA_fG`q}0$wxJfigdM=ki0Z ze}(Q2rVB!f1G9;SJxdi3@&PHdOvzY+hTb{4Z|RCwZ5&ceXJF&45m}YR$xAm7eM-?V1CO4u>{TB^V~4kb*+e(D`(f4@j%eSfV>~6 z*m7+8Vw7_tZFh5OE6Ra<8R`l#TPWBwSplIKkV4sAOBNtSY(?3@boyxt9t?6OASf~k zr$3a7hHX3b{rWIhgh z2lMg9#sz5V`wg%B`>hj*w@1mIh%W#=-ruTnTka__qgTl&`rmQHc~{hp_(HH74mb;t z!J;80Xk+r;yrZ?BAs!z}b{b9wJvN=O$F2bT+p^<}N}%a5;&H5Gr{Ie~Zz!M#kV4An z%2KqIw$3uqFIUU+JU{m=MzOv(ru@nCIsOW z8UY1f3~1#QP@H{wE%4HU_V!a&T60^$Enssgj+6Q$X)>KnoxRT=2FH zr7t-!=E_6I5ud-5?6LS#&`Sg4)9K>J%;%Ds$^$jt~Uqtwe!o@ zO|{jDpPUGpU-&*?HrQ`MgGx>Aq(bGJLSxJI8Q5WL}y9 zb~6FB^DZB^+WCd=gLr&#e`zuJ&Fy({GamHDi*`QKYZqyJMrx;xYrTGI<3+EXw%_ML zobdHa+wU~UXrz4_vLDO=yIep%o>;sbtu2Olc{5}`sMpU(+ZU~V=i_D(v`@89Ir!b_ z5@_GYA??cpeSV%w1DS$+{!_%Rvmey1?Z zHiO=3Kt69%QQjAnH7zRLZ2SW8{hO>-Hy{AoiPWwX+GPXe`(G+H?wI36o3}4N z>k{lMej0qx`GT`J0P zwm-M!l`P}S5swG${Y#|%uGdaG53YlDtq0WZTemJ6`1T!^10m;kz4d9wpI$p{Ke)g@ zFCdqx*m(V;W@Ppb8(HCawT| zH{cjR3i7>MNAIPy^I4?4@O!o@@Gm*&r+n^6{F|qum#GQy`#dFkhVFTn-{&cI({t(#6y@HIS*`2DJqJw-P!+Vf_l{eCt0 zbseDAPoGTaVWhg}qMG^m8qnwGXuiLr$@0E+e$&RuwatgnIM9=!E*IB;Tnng*3;g1# zB4pgZ{jIe*e?h8!FxAY_%}XkjtH3i{W~eY>Uz_T^n?UD2+azkv2^2ITu! zCe|*uq5B5R{&dHfFOYV>R0sOk1M>NsiY=p3oTyg5*MB$UzCdrB^?`B~i2T0%1}Nu7 zK)h2wqaYk0jF{Is>H-P@_fZFj_zR9^~@Gb8l zRlBL?0=yOUe+{S|M<*VBDzNy+*U(tVS0EQ}1Nk<t5vlh1bmx|X zZvwqr0k!L9orOi(Ga=*lX3+m7plZH5SkY=mjsHSx->cXY^8J|JIJ*?em7xyfTR{F5 zAm49MvFrv{ewQ2X+VxK_FVV954e)pep!S@jB!3pQ@%LM(=T1N;AceTPSG)`S`aPg_ zAJW#n#@(R56Hq(vw)Oqd4$%J{plW`_x80D_<>Feqj_Hl-{?L8}M&UnzyyvWRS!n$J zy;781y(Fjq(IY71to%IO2=YUK{63qCjf0+Eg#KCef$+%IcSH6syFmYsfP5cAMfrCn zAO3e={)lUuL*~JILH~ZhWIzV&UjM=CiqcNMegLJa(gk52-VO47fZBP!aHwtfdBgT1 z?L4TL&y=(3!@Bob(VAZ#fchTiM^ozIG}2L%D*e&zw_t|`3fZC$3Wf(xIvZA;yPY<(K{Zr`?^T&_5%-1 zfc$=+it_KJlylYFA@hXZ`c(Hvw8*)-$8A6GM}gtG?X>lgWfCd0%fA$@wz&iJr;A1W zSCwY=tIFkOQY`Sfvj-mZOdt#e^%u^LJtEy4D>M2!$1!MJq&b922R1bwB5$x zb~S!dAt^$;pDe5ciMrd_fjT;3`m^&7cZ4mKZM4c!71{H#`!kRjCvnr+MX z?0)Yqe23ePaP{LYPW1W{t9S~VzbMaV@v?8z+Ydc@Jq&aP17VL#oleE7T%Fa^fA^?Y zGfH|mO67!GOb6?Y^}IMLO#foF{)9_wyy=I_W32t}@c0TdE@IuDu2z1B`G*Eas~o-j z4aa&lyN6!1#%*$(@Meq?KeW-&*>S9`zenyI22yd9>xp)GQFbq0iksL;JVkpPN4vau z>5q8#BU0WYwTm?$@#I&j?QVCRM953K<+h>F)%eWnAU|ELy=`<`w@aSa!G4W*Lc)!^aP_0z{-5hTd#u0j z2)CckbsU82Z@c=qT@6J+ub$50denLthyeri-*?BL)Hp0M(s?LSyJ%BzuKWnM-f;D! z%~QMO;dV8;gu=Pv`CQf8B|4=8PIeVuqwQyB@6)68eRT)Ay2rE|Fc9s1liqQqSFamT ztg8v_@zGwsu1exb33rY&-Hx};p)Gc`M5*69tzRScH&VOUF@H`=p4$c=(f*xbTlI9j z@noe$u7bDR(bol99aRC3L@cJK0(J}gf8Mf}2?pPES3=)(m&8(C9{vh9`Bj5t6@4w< z0F63XT_C>^julZZdL<_*RTAjC`y|mv-(yJD$ZzCZ@AA0FTKR2pey`gl(M)2MbL^sD zB4w5#nkr>2Vl(xU>-5 Date: Sun, 15 Feb 2015 16:46:09 -0500 Subject: [PATCH 18/26] final code --- .../rosetta_scraper.py | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 programming-language-classifier/rosetta_scraper.py diff --git a/programming-language-classifier/rosetta_scraper.py b/programming-language-classifier/rosetta_scraper.py new file mode 100644 index 0000000..4559b6a --- /dev/null +++ b/programming-language-classifier/rosetta_scraper.py @@ -0,0 +1,43 @@ +import requests +from bs4 import BeautifulSoup + +r = requests.get('http://rosettacode.org/wiki/Category:Programming_Tasks') + +soup = BeautifulSoup(r.content) + +languages = [("Haskell","hs"), + ("Clojure","clojure"), + ("Java","java"), + ("JavaScript","js"), + ("OCaml","ocaml"), + ("Perl","perl"), + ("PHP","php"), + ("Python","py"), + ("Ruby","rb"), + ("Scala","scala"), + ("Scheme","ss"), + ("Tcl","tcl")] + +for lang, ext in languages: + print(lang,ext) + my_links = soup.find_all("a") + pruned_list = my_links[7:] + i = 1 + for link in pruned_list: + new_link ="http://rosettacode.org{}#{}".format(link.get("href"), lang) + #print(new_link) + try: + r = requests.get(new_link) + soup1 = BeautifulSoup(r.content) + data= soup1.find_all("pre",{"class":"{} highlighted_source".format(lang.lower())}) + + for item in data: + for tag in item.contents: + tag.br.replace_with("\n") + with open("./rosetta/file{}.{}".format(i,ext), "w") as text_file: + text_file.write(item.get_text(" ")) + i +=1 + except: + pass + if i ==61: + break From 996d9191b599d33f9dbb0888859c03101ffdaf38 Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sun, 15 Feb 2015 16:47:57 -0500 Subject: [PATCH 19/26] final requirements --- requirements.txt | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 9170871..ce8d4be 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,8 @@ +os +os.path +pickle +pandas +nltk +re +textblob scikit-learn -textblob \ No newline at end of file From 54bed251bfe595c3dbb4109df642e0bec5d578b8 Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sun, 15 Feb 2015 16:54:43 -0500 Subject: [PATCH 20/26] Explanation of files provided --- README.md | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8380c5f..0cf989f 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,26 @@ +There are 5 python files: + +1- rosetta_scraper.py: scrapes rosetta's web site for 60 examples of +code for each of the languages in this analysis + +2- lang_orig.py: This is the code used to train the model and to select the model with best performance. The best performance was found to be +a decision tree with 160 features (representing the proportion of occurrence for the most used words including punctuation in the code) + +3- classify.py: Tests the selected model with the new files provided. The model predicts the code correctly approx. 80% of the time. + +4- classify_snippets.py: This file expects to receive the name of a file as argument and then prints the predicted language as well as the +probabilities for each language. + +5- Model_Demonstration.ipynb shows how the model is used to predict the language for a given piece of code. + +There are 2 objects saved with pickle: the model and the final features for the model. + + + + + + +**************************************************** # Classify code snippets into programming languages ## Description @@ -99,4 +122,3 @@ You may want to add some command-line flags to your program. You could allow peo * [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) * [Rosetta Code](http://rosettacode.org/wiki/Rosetta_Code) * [Working with Text Files](https://opentechschool.github.io/python-data-intro/core/text-files.html) - From d19d9117d3af6609c92c0e2ffac755851d6decdd Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sun, 15 Feb 2015 16:59:27 -0500 Subject: [PATCH 21/26] deleted model --- Model_Demonstration.ipynb | 292 -------------------------------------- lang_orig.py | 155 -------------------- 2 files changed, 447 deletions(-) delete mode 100644 Model_Demonstration.ipynb delete mode 100644 lang_orig.py diff --git a/Model_Demonstration.ipynb b/Model_Demonstration.ipynb deleted file mode 100644 index 8800d3f..0000000 --- a/Model_Demonstration.ipynb +++ /dev/null @@ -1,292 +0,0 @@ -{ - "metadata": { - "name": "", - "signature": "sha256:e0082f203d7aab01fa97782998c62980e66e72f9a5e75450c8b11cb7ffdd64f0" - }, - "nbformat": 3, - "nbformat_minor": 0, - "worksheets": [ - { - "cells": [ - { - "cell_type": "heading", - "level": 2, - "metadata": {}, - "source": [ - "Predicting the programming language for a piece of code" - ] - }, - { - "cell_type": "heading", - "level": 4, - "metadata": {}, - "source": [ - "This model is a Decision Tree with 160 features and predicts the right language approximately 78% of the time." - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "import pickle\n", - "import os\n", - "import os.path\n", - "import pandas as pd\n", - "import nltk\n", - "import re\n", - "import numpy as np\n", - "from textblob import TextBlob as tb\n", - "from sklearn.feature_extraction import DictVectorizer\n", - "from sklearn.tree import DecisionTreeClassifier\n", - "from sklearn import tree\n", - "import lang_orig as lg\n", - "import sys" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "def setup_data():\n", - " cls = pickle.load(open(\"model.p\", \"rb\"))\n", - " final_features = pickle.load(open(\"features.p\", \"rb\"))\n", - " return final_features, cls" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 25 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "def read_code(file_name):\n", - " myfile = open(file_name)\n", - " myfile_content = myfile.read()\n", - " return myfile_content" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 26 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "def select_features_new_test(word_list, final):\n", - " final_list = {}\n", - " for key in final:\n", - " found = 0\n", - " for word, score in word_list:\n", - " if word == key:\n", - " found = score\n", - " break\n", - " final_list[key] = round(found, 5)\n", - " return final_list" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 27 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "def return_tokens(code):\n", - " tokens = nltk.word_tokenize(code)\n", - " return tb(' '.join(tokens))" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 28 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "def create_vectors_new_test(features):\n", - " vec = DictVectorizer()\n", - " return vec.fit_transform(features).toarray()\n" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 29 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "def predict(code, model, final_features):\n", - " token_blob = return_tokens(code)\n", - " word_list = lg.calculate_scores(token_blob)\n", - " features = select_features_new_test(word_list, final_features)\n", - " new_x = create_vectors_new_test(features)\n", - " predicted = model.predict(new_x)\n", - " predicted_probs = model.predict_proba(new_x)\n", - " return predicted, predicted_probs" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 30 - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "def print_probabilities(probas, model):\n", - " print(\"Probabilites for my prediction:\")\n", - " for ind in range(len(probas[0])):\n", - " print(model.classes_[ind], ':', round(probas[0][ind], 2))" - ], - "language": "python", - "metadata": {}, - "outputs": [], - "prompt_number": 31 - }, - { - "cell_type": "heading", - "level": 4, - "metadata": {}, - "source": [ - "This is an example of a correct prediction" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "model_features, model = setup_data()\n", - "file_name = \"./rosetta/file50.js\"\n", - "code = read_code(file_name)\n", - "predicted, predicted_probs = predict(code, model, model_features)\n", - "print(\"I think this code is:{}\".format(predicted[0]))\n", - "print_probabilities(predicted_probs, model)" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "output_type": "stream", - "stream": "stdout", - "text": [ - "I think this code is:Javascript\n", - "Probabilites for my prediction:\n", - "Clojure : 0.0\n", - "Haskell : 0.0\n", - "Java : 0.0\n", - "Javascript : 1.0\n", - "Ocaml : 0.0\n", - "PHP : 0.0\n", - "Perl : 0.0\n", - "Python : 0.0\n", - "Ruby : 0.0\n", - "Scala : 0.0\n", - "Scheme : 0.0\n", - "Tcl : 0.0\n" - ] - } - ], - "prompt_number": 32 - }, - { - "cell_type": "heading", - "level": 4, - "metadata": {}, - "source": [ - "Another correct prediction" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "file_name = \"./rosetta/file8.py\"\n", - "code = read_code(file_name)\n", - "predicted, predicted_probs = predict(code, model, model_features)\n", - "print(\"I think this code is:{}\".format(predicted[0]))\n", - "print_probabilities(predicted_probs, model)" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "output_type": "stream", - "stream": "stdout", - "text": [ - "I think this code is:Python\n", - "Probabilites for my prediction:\n", - "Clojure : 0.0\n", - "Haskell : 0.0\n", - "Java : 0.0\n", - "Javascript : 0.0\n", - "Ocaml : 0.0\n", - "PHP : 0.0\n", - "Perl : 0.0\n", - "Python : 1.0\n", - "Ruby : 0.0\n", - "Scala : 0.0\n", - "Scheme : 0.0\n", - "Tcl : 0.0\n" - ] - } - ], - "prompt_number": 39 - }, - { - "cell_type": "heading", - "level": 4, - "metadata": {}, - "source": [ - "This is an incorrect prediction" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "file_name = \"./rosetta/file15.php\"\n", - "code = read_code(file_name)\n", - "predicted, predicted_probs = predict(code, model, model_features)\n", - "print(\"I think this code is:{}\".format(predicted[0]))\n", - "print_probabilities(predicted_probs, model)" - ], - "language": "python", - "metadata": {}, - "outputs": [ - { - "output_type": "stream", - "stream": "stdout", - "text": [ - "I think this code is:Perl\n", - "Probabilites for my prediction:\n", - "Clojure : 0.0\n", - "Haskell : 0.33\n", - "Java : 0.0\n", - "Javascript : 0.0\n", - "Ocaml : 0.0\n", - "PHP : 0.0\n", - "Perl : 0.67\n", - "Python : 0.0\n", - "Ruby : 0.0\n", - "Scala : 0.0\n", - "Scheme : 0.0\n", - "Tcl : 0.0\n" - ] - } - ], - "prompt_number": 40 - } - ], - "metadata": {} - } - ] -} \ No newline at end of file diff --git a/lang_orig.py b/lang_orig.py deleted file mode 100644 index a63c4f3..0000000 --- a/lang_orig.py +++ /dev/null @@ -1,155 +0,0 @@ -import os -import os.path -import pickle -import pandas as pd -import nltk -import re -from textblob import TextBlob as tb -from sklearn import metrics -from sklearn.cross_validation import cross_val_score -from sklearn.cross_validation import train_test_split -from sklearn.feature_extraction import DictVectorizer -from sklearn.naive_bayes import BernoulliNB -from sklearn.feature_extraction.text import CountVectorizer -from sklearn.tree import DecisionTreeClassifier -from sklearn import tree - - -def read_files(dir_path): - file_list = [] - for root, dirs, files in os.walk(dir_path): - for name in files: - file_list.append(os.path.join(root, name)) - for name in dirs: - file_list.append((os.path.join(root, name))) - return file_list - - -def get_extension(file): - return os.path.splitext(file)[1] - - -def get_language(ext): - if ext in ['.clj', '.cljs', '.edn', '.clojure']: - return 'Clojure' - elif ext in ['.hs', '.lhs', 'ghc']: - return 'Haskell' - elif ext in ['.java', '.class', '.jar']: - return 'Java' - elif ext in ['.js', '.javascript']: - return 'Javascript' - elif ext in ['.pl', '.pm', '.t', '.pod', '.perl']: - return 'Perl' - elif ext in ['.php', '.phtml', '.php4', '.php3', '.php5', '.phps']: - return 'PHP' - elif ext in ['.ocaml', '.ml']: - return 'Ocaml' - elif ext in ['.py', '.pyw', '.pyc', '.pyo', '.pyd', '.python3']: - return "Python" - elif ext in ['.rb', '.rbw', '.jruby']: - return "Ruby" - elif ext in ['.scala']: - return 'Scala' - elif ext in ['.scm', '.ss', '.racket']: - return "Scheme" - elif ext in ['.tcl']: - return "Tcl" - return None - - -def read_train_data(): - files = read_files("./rosetta") - main_list = [] - for file in files: - ext = get_extension(file) - lang = get_language(ext) - if lang is not None: - file_lang = [] - with open(file, errors="surrogateescape") as in_file: - texto = in_file.read() - main_list.append([texto, lang]) - datadf = pd.DataFrame(main_list, columns=['Code', 'Language']) - return datadf - - -def join_all_code(content): - all_content = [row["Code"] for ind, row in content.iterrows()] - return ' '.join(all_content) - - -def tokenize(content): - tokens = nltk.word_tokenize(content) - return ' '.join(tokens) - - -def word_freq(word, code): - if len(code.words) == 0: - return 0 - else: - return code.word_counts[word] / len(code.words) - - -def return_tokenized_data(datadf): - all_code = join_all_code(datadf) - all_tokens = tokenize(all_code) - return tb(all_tokens) - - -def calculate_scores(token_blob): - scores = {word: word_freq(word, token_blob) - for word in token_blob.words} - return sorted(scores.items(), key=lambda x: x[1], reverse=True) - - -def select_features(word_list): - exclude_list = ['l', '6', 'd', 'x1', 'x2', '5', 'j', 'm', 'w', 'i', 'e', 'g', '4', 'v', 'n', '0', '1', 'a', 'x', 'n', 'y', 'b', '2', 'c', 's', '3'] - final = {} - counter = 0 - for word, score in word_list: - if word not in exclude_list: - final[word] = round(score, 5) - counter += 1 - if counter == 160: - break - return final - - -def create_vectors(final, data): - super_final = [] - for ind, row in data.iterrows(): - mydict = {} - for word, score in final.items(): - if row['Code'].find(word) != -1: - mydict[word] = score - else: - mydict[word] = 0 - super_final.append(mydict) - vec = DictVectorizer() - return vec.fit_transform(super_final).toarray() - - -def test_model(x, y, model): - if model == 'tree': - clf = tree.DecisionTreeClassifier() - elif model == 'bernoulli': - clf = BernoulliNB() - x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.4, random_state=0) - clf = clf.fit(x_train, y_train) - predicted = clf.predict(x_test) - print(metrics.classification_report(y_test, predicted)) - print(metrics.f1_score(y_test, predicted)) - scores = cross_val_score(clf, x, y, cv=5) - return scores, clf - - -if __name__ == '__main__': - datadf = read_train_data() - target = datadf['Language'].values - token_blob = return_tokenized_data(datadf) - word_list = calculate_scores(token_blob) - final_words = select_features(word_list) - new_x = create_vectors(final_words, datadf) - bernoulli_score = test_model(new_x, target, 'bernoulli') - tree_score, clf_model = test_model(new_x, target, 'tree') - pickle.dump(clf_model, open("model.p", "wb")) - pickle.dump(final_words, open("features.p", "wb")) From 0b47c5c464df97dd38214a0149183f44d59c3f87 Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sun, 15 Feb 2015 17:00:03 -0500 Subject: [PATCH 22/26] removed file --- classify.py | 86 ----------------------------------------------------- 1 file changed, 86 deletions(-) delete mode 100644 classify.py diff --git a/classify.py b/classify.py deleted file mode 100644 index b6fdc3c..0000000 --- a/classify.py +++ /dev/null @@ -1,86 +0,0 @@ -import pickle -import os -import os.path -import pandas as pd -import nltk -import re -import numpy as np -from textblob import TextBlob as tb -from sklearn.feature_extraction import DictVectorizer -from sklearn.tree import DecisionTreeClassifier -from sklearn import tree -import lang_orig as lg - - -def read_test_data(): - files = lg.read_files("./test") - main_list = [] - for file in files: - with open(file, errors="surrogateescape") as in_file: - texto = in_file.read() - file_name = re.findall(r'\d+', file) - main_list.append([texto, file_name[0]]) - file_content = pd.DataFrame(main_list, columns=['Code', 'Filename']) - file_info = pd.read_csv('./test.csv', dtype={'Filename': str, 'Language': str}) - datadf = pd.merge(file_info, file_content, on=['Filename']) - del datadf['Filename'] - return datadf - - -def select_features_new_test(word_list, final): - final_list = {} - for key in final: - found = 0 - for word, score in word_list: - if word == key: - found = score - break - final_list[key] = round(found, 5) - return final_list - - -def setup_data(): - cls = pickle.load(open("model.p", "rb")) - final_features = pickle.load(open("features.p", "rb")) - return final_features, cls - - -def return_tokens(code): - tokens = nltk.word_tokenize(code) - return tb(' '.join(tokens)) - - -def create_vectors_new_test(features): - vec = DictVectorizer() - return vec.fit_transform(features).toarray() - - -def predict(code, model, final_features): - token_blob = return_tokens(code) - word_list = lg.calculate_scores(token_blob) - features = select_features_new_test(word_list, final_features) - new_x = create_vectors_new_test(features) - predicted = model.predict(new_x) - predicted_probs = model.predict_proba(new_x) - return predicted, predicted_probs - - -def print_probabilities(probas, model): - for ind in range(len(probas[0])): - print(model.classes_[ind], ':', probas[0][ind]) - - -def test_all_new_files(test_data, model, final_features): - agreement = 0 - total = 0 - for ind, row in test_data.iterrows(): - predicted, probas = predict(row['Code'], model, final_features) - print("I predicted: {}. It was: {}".format(predicted[0], row['Language'])) - total += 1 - if predicted[0].lower() == row['Language'].lower(): - agreement += 1 - print("Success Rate of Classification:", round(agreement * 100 / total, 2)) - -test_data = read_test_data() -model_features, model = setup_data() -test_all_new_files(test_data, model, model_features) From ae5f584379a4b0c08bb9b4550f53f057f835112d Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sun, 15 Feb 2015 17:00:25 -0500 Subject: [PATCH 23/26] deleted file --- classify_snippet.py | 72 --------------------------------------------- 1 file changed, 72 deletions(-) delete mode 100755 classify_snippet.py diff --git a/classify_snippet.py b/classify_snippet.py deleted file mode 100755 index 038b8a4..0000000 --- a/classify_snippet.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env python -import pickle -import os -import os.path -import pandas as pd -import nltk -import re -import numpy as np -from textblob import TextBlob as tb -from sklearn.feature_extraction import DictVectorizer -from sklearn.tree import DecisionTreeClassifier -from sklearn import tree -import lang_orig as lg -import sys - - -def select_features_new_test(word_list, final): - final_list = {} - for key in final: - found = 0 - for word, score in word_list: - if word == key: - found = score - break - final_list[key] = round(found, 5) - return final_list - - -def setup_data(): - cls = pickle.load(open("model.p", "rb")) - final_features = pickle.load(open("features.p", "rb")) - return final_features, cls - - -def return_tokens(code): - tokens = nltk.word_tokenize(code) - return tb(' '.join(tokens)) - - -def create_vectors_new_test(features): - vec = DictVectorizer() - return vec.fit_transform(features).toarray() - - -def predict(code, model, final_features): - token_blob = return_tokens(code) - word_list = lg.calculate_scores(token_blob) - features = select_features_new_test(word_list, final_features) - new_x = create_vectors_new_test(features) - predicted = model.predict(new_x) - predicted_probs = model.predict_proba(new_x) - return predicted, predicted_probs - - -def print_probabilities(probas, model): - print("Probabilites for my prediction:") - for ind in range(len(probas[0])): - print(model.classes_[ind], ':', round(probas[0][ind], 2)) - - -def read_code(): - file_name = sys.argv[1] - myfile = open(file_name) - myfile_content = myfile.read() - return myfile_content - - -model_features, model = setup_data() -code = read_code() -predicted, predicted_probs = predict(code, model, model_features) -print("I think this code is:{}".format(predicted[0])) -print_probabilities(predicted_probs, model) From 7e2a4d00b54c0c36af854d127fb953cd034cb3f4 Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Sun, 15 Feb 2015 17:00:44 -0500 Subject: [PATCH 24/26] deleted file --- rosetta_scraper.py | 43 ------------------------------------------- 1 file changed, 43 deletions(-) delete mode 100644 rosetta_scraper.py diff --git a/rosetta_scraper.py b/rosetta_scraper.py deleted file mode 100644 index 4559b6a..0000000 --- a/rosetta_scraper.py +++ /dev/null @@ -1,43 +0,0 @@ -import requests -from bs4 import BeautifulSoup - -r = requests.get('http://rosettacode.org/wiki/Category:Programming_Tasks') - -soup = BeautifulSoup(r.content) - -languages = [("Haskell","hs"), - ("Clojure","clojure"), - ("Java","java"), - ("JavaScript","js"), - ("OCaml","ocaml"), - ("Perl","perl"), - ("PHP","php"), - ("Python","py"), - ("Ruby","rb"), - ("Scala","scala"), - ("Scheme","ss"), - ("Tcl","tcl")] - -for lang, ext in languages: - print(lang,ext) - my_links = soup.find_all("a") - pruned_list = my_links[7:] - i = 1 - for link in pruned_list: - new_link ="http://rosettacode.org{}#{}".format(link.get("href"), lang) - #print(new_link) - try: - r = requests.get(new_link) - soup1 = BeautifulSoup(r.content) - data= soup1.find_all("pre",{"class":"{} highlighted_source".format(lang.lower())}) - - for item in data: - for tag in item.contents: - tag.br.replace_with("\n") - with open("./rosetta/file{}.{}".format(i,ext), "w") as text_file: - text_file.write(item.get_text(" ")) - i +=1 - except: - pass - if i ==61: - break From e28914d553dff689b9db9e245f84b3a09a1606d2 Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Mon, 16 Feb 2015 07:23:50 -0500 Subject: [PATCH 25/26] update file paths after putting files in hacker structure --- programming-language-classifier/classify.py | 4 ++-- programming-language-classifier/lang_orig.py | 2 +- programming-language-classifier/rosetta_scraper.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/programming-language-classifier/classify.py b/programming-language-classifier/classify.py index b6fdc3c..a32eed6 100644 --- a/programming-language-classifier/classify.py +++ b/programming-language-classifier/classify.py @@ -13,7 +13,7 @@ def read_test_data(): - files = lg.read_files("./test") + files = lg.read_files("../test") main_list = [] for file in files: with open(file, errors="surrogateescape") as in_file: @@ -21,7 +21,7 @@ def read_test_data(): file_name = re.findall(r'\d+', file) main_list.append([texto, file_name[0]]) file_content = pd.DataFrame(main_list, columns=['Code', 'Filename']) - file_info = pd.read_csv('./test.csv', dtype={'Filename': str, 'Language': str}) + file_info = pd.read_csv('../test.csv', dtype={'Filename': str, 'Language': str}) datadf = pd.merge(file_info, file_content, on=['Filename']) del datadf['Filename'] return datadf diff --git a/programming-language-classifier/lang_orig.py b/programming-language-classifier/lang_orig.py index a63c4f3..7b7ad62 100644 --- a/programming-language-classifier/lang_orig.py +++ b/programming-language-classifier/lang_orig.py @@ -58,7 +58,7 @@ def get_language(ext): def read_train_data(): - files = read_files("./rosetta") + files = read_files("../rosetta") main_list = [] for file in files: ext = get_extension(file) diff --git a/programming-language-classifier/rosetta_scraper.py b/programming-language-classifier/rosetta_scraper.py index 4559b6a..dd27492 100644 --- a/programming-language-classifier/rosetta_scraper.py +++ b/programming-language-classifier/rosetta_scraper.py @@ -34,7 +34,7 @@ for item in data: for tag in item.contents: tag.br.replace_with("\n") - with open("./rosetta/file{}.{}".format(i,ext), "w") as text_file: + with open("../rosetta/file{}.{}".format(i,ext), "w") as text_file: text_file.write(item.get_text(" ")) i +=1 except: From 74d94a275ccc790b30e94be214753f16d1178edf Mon Sep 17 00:00:00 2001 From: Ana Maria Echeverri Date: Mon, 16 Feb 2015 07:31:20 -0500 Subject: [PATCH 26/26] added scraped files --- rosetta/file1.clojure | 1 + rosetta/file1.hs | 1 + rosetta/file1.java | 1 + rosetta/file1.js | 1 + rosetta/file1.ocaml | 1 + rosetta/file1.perl | 1 + rosetta/file1.php | 1 + rosetta/file1.py | 1 + rosetta/file1.rb | 1 + rosetta/file1.scala | 1 + rosetta/file1.ss | 1 + rosetta/file1.tcl | 1 + rosetta/file10.clojure | 1 + rosetta/file10.hs | 1 + rosetta/file10.java | 1 + rosetta/file10.js | 1 + rosetta/file10.ocaml | 1 + rosetta/file10.perl | 1 + rosetta/file10.php | 1 + rosetta/file10.py | 1 + rosetta/file10.rb | 1 + rosetta/file10.scala | 1 + rosetta/file10.ss | 1 + rosetta/file10.tcl | 1 + rosetta/file11.clojure | 1 + rosetta/file11.hs | 1 + rosetta/file11.java | 1 + rosetta/file11.js | 1 + rosetta/file11.ocaml | 1 + rosetta/file11.perl | 1 + rosetta/file11.php | 1 + rosetta/file11.py | 1 + rosetta/file11.rb | 1 + rosetta/file11.scala | 1 + rosetta/file11.ss | 1 + rosetta/file11.tcl | 1 + rosetta/file12.clojure | 1 + rosetta/file12.hs | 1 + rosetta/file12.java | 1 + rosetta/file12.js | 1 + rosetta/file12.ocaml | 1 + rosetta/file12.perl | 1 + rosetta/file12.php | 1 + rosetta/file12.py | 1 + rosetta/file12.rb | 1 + rosetta/file12.scala | 1 + rosetta/file12.ss | 1 + rosetta/file12.tcl | 1 + rosetta/file13.clojure | 1 + rosetta/file13.hs | 1 + rosetta/file13.java | 1 + rosetta/file13.js | 1 + rosetta/file13.ocaml | 1 + rosetta/file13.perl | 1 + rosetta/file13.php | 1 + rosetta/file13.py | 1 + rosetta/file13.rb | 1 + rosetta/file13.scala | 1 + rosetta/file13.ss | 1 + rosetta/file13.tcl | 1 + rosetta/file14.clojure | 1 + rosetta/file14.hs | 1 + rosetta/file14.java | 2 ++ rosetta/file14.js | 1 + rosetta/file14.ocaml | 1 + rosetta/file14.perl | 1 + rosetta/file14.php | 1 + rosetta/file14.py | 1 + rosetta/file14.rb | 1 + rosetta/file14.scala | 1 + rosetta/file14.ss | 1 + rosetta/file14.tcl | 1 + rosetta/file15.clojure | 1 + rosetta/file15.hs | 1 + rosetta/file15.java | 1 + rosetta/file15.js | 1 + rosetta/file15.ocaml | 1 + rosetta/file15.perl | 1 + rosetta/file15.php | 1 + rosetta/file15.py | 1 + rosetta/file15.rb | 1 + rosetta/file15.scala | 1 + rosetta/file15.ss | 1 + rosetta/file15.tcl | 1 + rosetta/file16.clojure | 1 + rosetta/file16.hs | 1 + rosetta/file16.java | 1 + rosetta/file16.js | 1 + rosetta/file16.ocaml | 1 + rosetta/file16.perl | 1 + rosetta/file16.php | 1 + rosetta/file16.py | 1 + rosetta/file16.rb | 1 + rosetta/file16.scala | 1 + rosetta/file16.ss | 1 + rosetta/file16.tcl | 1 + rosetta/file17.clojure | 1 + rosetta/file17.hs | 1 + rosetta/file17.java | 1 + rosetta/file17.js | 1 + rosetta/file17.ocaml | 1 + rosetta/file17.perl | 1 + rosetta/file17.php | 1 + rosetta/file17.py | 1 + rosetta/file17.rb | 1 + rosetta/file17.scala | 1 + rosetta/file17.ss | 1 + rosetta/file17.tcl | 1 + rosetta/file18.clojure | 1 + rosetta/file18.hs | 1 + rosetta/file18.java | 1 + rosetta/file18.js | 1 + rosetta/file18.ocaml | 1 + rosetta/file18.perl | 1 + rosetta/file18.php | 1 + rosetta/file18.py | 1 + rosetta/file18.rb | 1 + rosetta/file18.scala | 1 + rosetta/file18.ss | 1 + rosetta/file18.tcl | 1 + rosetta/file19.clojure | 1 + rosetta/file19.hs | 1 + rosetta/file19.java | 1 + rosetta/file19.js | 1 + rosetta/file19.ocaml | 1 + rosetta/file19.perl | 1 + rosetta/file19.php | 1 + rosetta/file19.py | 1 + rosetta/file19.rb | 1 + rosetta/file19.scala | 1 + rosetta/file19.ss | 1 + rosetta/file19.tcl | 1 + rosetta/file2.clojure | 1 + rosetta/file2.hs | 1 + rosetta/file2.java | 1 + rosetta/file2.js | 1 + rosetta/file2.ocaml | 1 + rosetta/file2.perl | 1 + rosetta/file2.php | 1 + rosetta/file2.py | 1 + rosetta/file2.rb | 1 + rosetta/file2.scala | 1 + rosetta/file2.ss | 1 + rosetta/file2.tcl | 1 + rosetta/file20.clojure | 1 + rosetta/file20.hs | 1 + rosetta/file20.java | 1 + rosetta/file20.js | 1 + rosetta/file20.ocaml | 1 + rosetta/file20.perl | 1 + rosetta/file20.php | 1 + rosetta/file20.py | 1 + rosetta/file20.rb | 1 + rosetta/file20.scala | 1 + rosetta/file20.ss | 1 + rosetta/file20.tcl | 1 + rosetta/file21.clojure | 1 + rosetta/file21.hs | 1 + rosetta/file21.java | 1 + rosetta/file21.js | 1 + rosetta/file21.ocaml | 1 + rosetta/file21.perl | 1 + rosetta/file21.php | 1 + rosetta/file21.py | 1 + rosetta/file21.rb | 1 + rosetta/file21.scala | 2 ++ rosetta/file21.ss | 1 + rosetta/file21.tcl | 1 + rosetta/file22.clojure | 1 + rosetta/file22.hs | 1 + rosetta/file22.java | 1 + rosetta/file22.js | 1 + rosetta/file22.ocaml | 1 + rosetta/file22.perl | 1 + rosetta/file22.php | 1 + rosetta/file22.py | 1 + rosetta/file22.rb | 1 + rosetta/file22.scala | 2 ++ rosetta/file22.ss | 1 + rosetta/file22.tcl | 1 + rosetta/file23.clojure | 1 + rosetta/file23.hs | 1 + rosetta/file23.java | 1 + rosetta/file23.js | 1 + rosetta/file23.ocaml | 1 + rosetta/file23.perl | 1 + rosetta/file23.php | 1 + rosetta/file23.py | 1 + rosetta/file23.rb | 1 + rosetta/file23.scala | 1 + rosetta/file23.ss | 1 + rosetta/file23.tcl | 1 + rosetta/file24.clojure | 1 + rosetta/file24.hs | 1 + rosetta/file24.java | 1 + rosetta/file24.js | 1 + rosetta/file24.ocaml | 1 + rosetta/file24.perl | 1 + rosetta/file24.php | 1 + rosetta/file24.py | 1 + rosetta/file24.rb | 1 + rosetta/file24.scala | 1 + rosetta/file24.ss | 1 + rosetta/file24.tcl | 1 + rosetta/file25.clojure | 1 + rosetta/file25.hs | 1 + rosetta/file25.java | 1 + rosetta/file25.js | 1 + rosetta/file25.ocaml | 1 + rosetta/file25.perl | 1 + rosetta/file25.php | 1 + rosetta/file25.py | 1 + rosetta/file25.rb | 1 + rosetta/file25.scala | 1 + rosetta/file25.ss | 1 + rosetta/file25.tcl | 1 + rosetta/file26.clojure | 1 + rosetta/file26.hs | 1 + rosetta/file26.java | 1 + rosetta/file26.js | 1 + rosetta/file26.ocaml | 1 + rosetta/file26.perl | 1 + rosetta/file26.php | 1 + rosetta/file26.py | 1 + rosetta/file26.rb | 1 + rosetta/file26.scala | 1 + rosetta/file26.ss | 1 + rosetta/file26.tcl | 1 + rosetta/file27.clojure | 1 + rosetta/file27.hs | 1 + rosetta/file27.java | 1 + rosetta/file27.js | 1 + rosetta/file27.ocaml | 1 + rosetta/file27.perl | 1 + rosetta/file27.php | 1 + rosetta/file27.py | 1 + rosetta/file27.rb | 1 + rosetta/file27.scala | 1 + rosetta/file27.ss | 1 + rosetta/file27.tcl | 1 + rosetta/file28.clojure | 1 + rosetta/file28.hs | 1 + rosetta/file28.java | 1 + rosetta/file28.js | 1 + rosetta/file28.ocaml | 1 + rosetta/file28.perl | 1 + rosetta/file28.php | 1 + rosetta/file28.py | 1 + rosetta/file28.rb | 1 + rosetta/file28.scala | 1 + rosetta/file28.ss | 1 + rosetta/file28.tcl | 1 + rosetta/file29.clojure | 1 + rosetta/file29.hs | 1 + rosetta/file29.java | 1 + rosetta/file29.js | 1 + rosetta/file29.ocaml | 1 + rosetta/file29.perl | 1 + rosetta/file29.php | 1 + rosetta/file29.py | 1 + rosetta/file29.rb | 1 + rosetta/file29.scala | 1 + rosetta/file29.ss | 1 + rosetta/file29.tcl | 1 + rosetta/file3.clojure | 1 + rosetta/file3.hs | 1 + rosetta/file3.java | 1 + rosetta/file3.js | 1 + rosetta/file3.ocaml | 1 + rosetta/file3.perl | 1 + rosetta/file3.php | 1 + rosetta/file3.py | 1 + rosetta/file3.rb | 1 + rosetta/file3.scala | 1 + rosetta/file3.ss | 1 + rosetta/file3.tcl | 1 + rosetta/file30.clojure | 1 + rosetta/file30.hs | 1 + rosetta/file30.java | 1 + rosetta/file30.js | 1 + rosetta/file30.ocaml | 1 + rosetta/file30.perl | 1 + rosetta/file30.php | 1 + rosetta/file30.py | 1 + rosetta/file30.rb | 1 + rosetta/file30.scala | 1 + rosetta/file30.ss | 1 + rosetta/file30.tcl | 1 + rosetta/file31.clojure | 1 + rosetta/file31.hs | 1 + rosetta/file31.java | 1 + rosetta/file31.js | 1 + rosetta/file31.ocaml | 1 + rosetta/file31.perl | 1 + rosetta/file31.php | 1 + rosetta/file31.py | 1 + rosetta/file31.rb | 1 + rosetta/file31.scala | 1 + rosetta/file31.ss | 1 + rosetta/file31.tcl | 1 + rosetta/file32.clojure | 1 + rosetta/file32.hs | 1 + rosetta/file32.java | 1 + rosetta/file32.js | 1 + rosetta/file32.ocaml | 1 + rosetta/file32.perl | 1 + rosetta/file32.php | 1 + rosetta/file32.py | 1 + rosetta/file32.rb | 1 + rosetta/file32.scala | 1 + rosetta/file32.ss | 1 + rosetta/file32.tcl | 1 + rosetta/file33.clojure | 1 + rosetta/file33.hs | 1 + rosetta/file33.java | 1 + rosetta/file33.js | 1 + rosetta/file33.ocaml | 1 + rosetta/file33.perl | 1 + rosetta/file33.php | 1 + rosetta/file33.py | 1 + rosetta/file33.rb | 1 + rosetta/file33.scala | 1 + rosetta/file33.ss | 1 + rosetta/file33.tcl | 1 + rosetta/file34.clojure | 1 + rosetta/file34.hs | 1 + rosetta/file34.java | 1 + rosetta/file34.js | 1 + rosetta/file34.ocaml | 1 + rosetta/file34.perl | 1 + rosetta/file34.php | 1 + rosetta/file34.py | 1 + rosetta/file34.rb | 1 + rosetta/file34.scala | 1 + rosetta/file34.ss | 1 + rosetta/file34.tcl | 1 + rosetta/file35.clojure | 1 + rosetta/file35.hs | 1 + rosetta/file35.java | 1 + rosetta/file35.js | 1 + rosetta/file35.ocaml | 1 + rosetta/file35.perl | 1 + rosetta/file35.php | 1 + rosetta/file35.py | 1 + rosetta/file35.rb | 1 + rosetta/file35.scala | 1 + rosetta/file35.ss | 1 + rosetta/file35.tcl | 1 + rosetta/file36.clojure | 1 + rosetta/file36.hs | 1 + rosetta/file36.java | 1 + rosetta/file36.js | 1 + rosetta/file36.ocaml | 1 + rosetta/file36.perl | 1 + rosetta/file36.php | 1 + rosetta/file36.py | 1 + rosetta/file36.rb | 1 + rosetta/file36.scala | 1 + rosetta/file36.ss | 1 + rosetta/file36.tcl | 1 + rosetta/file37.clojure | 1 + rosetta/file37.hs | 1 + rosetta/file37.java | 1 + rosetta/file37.js | 1 + rosetta/file37.ocaml | 2 ++ rosetta/file37.perl | 1 + rosetta/file37.php | 1 + rosetta/file37.py | 1 + rosetta/file37.rb | 1 + rosetta/file37.scala | 1 + rosetta/file37.ss | 1 + rosetta/file37.tcl | 1 + rosetta/file38.clojure | 1 + rosetta/file38.hs | 1 + rosetta/file38.java | 1 + rosetta/file38.js | 1 + rosetta/file38.ocaml | 1 + rosetta/file38.perl | 1 + rosetta/file38.php | 1 + rosetta/file38.py | 1 + rosetta/file38.rb | 1 + rosetta/file38.scala | 1 + rosetta/file38.ss | 1 + rosetta/file38.tcl | 1 + rosetta/file39.clojure | 1 + rosetta/file39.hs | 1 + rosetta/file39.java | 1 + rosetta/file39.js | 1 + rosetta/file39.ocaml | 1 + rosetta/file39.perl | 1 + rosetta/file39.php | 1 + rosetta/file39.py | 1 + rosetta/file39.rb | 1 + rosetta/file39.scala | 1 + rosetta/file39.ss | 1 + rosetta/file39.tcl | 1 + rosetta/file4.clojure | 1 + rosetta/file4.hs | 1 + rosetta/file4.java | 1 + rosetta/file4.js | 1 + rosetta/file4.ocaml | 1 + rosetta/file4.perl | 1 + rosetta/file4.php | 2 ++ rosetta/file4.py | 1 + rosetta/file4.rb | 1 + rosetta/file4.scala | 1 + rosetta/file4.ss | 1 + rosetta/file4.tcl | 1 + rosetta/file40.clojure | 1 + rosetta/file40.hs | 1 + rosetta/file40.java | 1 + rosetta/file40.js | 1 + rosetta/file40.ocaml | 1 + rosetta/file40.perl | 1 + rosetta/file40.php | 1 + rosetta/file40.py | 1 + rosetta/file40.rb | 1 + rosetta/file40.scala | 1 + rosetta/file40.ss | 1 + rosetta/file40.tcl | 1 + rosetta/file41.clojure | 1 + rosetta/file41.hs | 1 + rosetta/file41.java | 1 + rosetta/file41.js | 1 + rosetta/file41.ocaml | 1 + rosetta/file41.perl | 1 + rosetta/file41.php | 1 + rosetta/file41.py | 1 + rosetta/file41.rb | 1 + rosetta/file41.scala | 1 + rosetta/file41.ss | 1 + rosetta/file41.tcl | 1 + rosetta/file42.clojure | 1 + rosetta/file42.hs | 1 + rosetta/file42.java | 1 + rosetta/file42.js | 1 + rosetta/file42.ocaml | 1 + rosetta/file42.perl | 1 + rosetta/file42.php | 1 + rosetta/file42.py | 1 + rosetta/file42.rb | 1 + rosetta/file42.scala | 1 + rosetta/file42.ss | 1 + rosetta/file42.tcl | 1 + rosetta/file43.clojure | 1 + rosetta/file43.hs | 1 + rosetta/file43.java | 1 + rosetta/file43.js | 1 + rosetta/file43.ocaml | 1 + rosetta/file43.perl | 1 + rosetta/file43.php | 1 + rosetta/file43.py | 1 + rosetta/file43.rb | 1 + rosetta/file43.scala | 1 + rosetta/file43.ss | 1 + rosetta/file43.tcl | 1 + rosetta/file44.clojure | 1 + rosetta/file44.hs | 1 + rosetta/file44.java | 1 + rosetta/file44.js | 1 + rosetta/file44.ocaml | 1 + rosetta/file44.perl | 1 + rosetta/file44.php | 1 + rosetta/file44.py | 1 + rosetta/file44.rb | 1 + rosetta/file44.scala | 1 + rosetta/file44.ss | 1 + rosetta/file44.tcl | 1 + rosetta/file45.clojure | 1 + rosetta/file45.hs | 1 + rosetta/file45.java | 1 + rosetta/file45.js | 1 + rosetta/file45.ocaml | 1 + rosetta/file45.perl | 1 + rosetta/file45.php | 1 + rosetta/file45.py | 1 + rosetta/file45.rb | 1 + rosetta/file45.scala | 1 + rosetta/file45.ss | 1 + rosetta/file45.tcl | 1 + rosetta/file46.clojure | 1 + rosetta/file46.hs | 1 + rosetta/file46.java | 1 + rosetta/file46.js | 1 + rosetta/file46.ocaml | 1 + rosetta/file46.perl | 1 + rosetta/file46.php | 1 + rosetta/file46.py | 1 + rosetta/file46.rb | 1 + rosetta/file46.scala | 1 + rosetta/file46.ss | 1 + rosetta/file46.tcl | 1 + rosetta/file47.clojure | 1 + rosetta/file47.hs | 1 + rosetta/file47.java | 1 + rosetta/file47.js | 1 + rosetta/file47.ocaml | 1 + rosetta/file47.perl | 1 + rosetta/file47.php | 1 + rosetta/file47.py | 1 + rosetta/file47.rb | 1 + rosetta/file47.scala | 1 + rosetta/file47.ss | 1 + rosetta/file47.tcl | 1 + rosetta/file48.clojure | 1 + rosetta/file48.hs | 1 + rosetta/file48.java | 1 + rosetta/file48.js | 1 + rosetta/file48.ocaml | 1 + rosetta/file48.perl | 1 + rosetta/file48.php | 1 + rosetta/file48.py | 1 + rosetta/file48.rb | 1 + rosetta/file48.scala | 1 + rosetta/file48.ss | 1 + rosetta/file48.tcl | 1 + rosetta/file49.clojure | 1 + rosetta/file49.hs | 1 + rosetta/file49.java | 1 + rosetta/file49.js | 1 + rosetta/file49.ocaml | 1 + rosetta/file49.perl | 1 + rosetta/file49.php | 1 + rosetta/file49.py | 1 + rosetta/file49.rb | 1 + rosetta/file49.scala | 1 + rosetta/file49.ss | 1 + rosetta/file49.tcl | 1 + rosetta/file5.clojure | 1 + rosetta/file5.hs | 1 + rosetta/file5.java | 1 + rosetta/file5.js | 1 + rosetta/file5.ocaml | 1 + rosetta/file5.perl | 1 + rosetta/file5.php | 1 + rosetta/file5.py | 1 + rosetta/file5.rb | 1 + rosetta/file5.scala | 1 + rosetta/file5.ss | 1 + rosetta/file5.tcl | 1 + rosetta/file50.clojure | 1 + rosetta/file50.hs | 1 + rosetta/file50.java | 1 + rosetta/file50.js | 1 + rosetta/file50.ocaml | 1 + rosetta/file50.perl | 1 + rosetta/file50.php | 1 + rosetta/file50.py | 1 + rosetta/file50.rb | 1 + rosetta/file50.scala | 1 + rosetta/file50.ss | 1 + rosetta/file50.tcl | 1 + rosetta/file51.clojure | 1 + rosetta/file51.hs | 1 + rosetta/file51.java | 1 + rosetta/file51.js | 1 + rosetta/file51.ocaml | 1 + rosetta/file51.perl | 1 + rosetta/file51.php | 1 + rosetta/file51.py | 1 + rosetta/file51.rb | 1 + rosetta/file51.scala | 1 + rosetta/file51.ss | 1 + rosetta/file51.tcl | 1 + rosetta/file52.clojure | 1 + rosetta/file52.hs | 1 + rosetta/file52.java | 1 + rosetta/file52.js | 1 + rosetta/file52.ocaml | 1 + rosetta/file52.perl | 1 + rosetta/file52.php | 1 + rosetta/file52.py | 1 + rosetta/file52.rb | 1 + rosetta/file52.scala | 1 + rosetta/file52.ss | 1 + rosetta/file52.tcl | 1 + rosetta/file53.clojure | 1 + rosetta/file53.hs | 1 + rosetta/file53.java | 1 + rosetta/file53.js | 1 + rosetta/file53.ocaml | 1 + rosetta/file53.perl | 1 + rosetta/file53.php | 1 + rosetta/file53.py | 1 + rosetta/file53.rb | 1 + rosetta/file53.scala | 1 + rosetta/file53.ss | 1 + rosetta/file53.tcl | 1 + rosetta/file54.clojure | 1 + rosetta/file54.hs | 1 + rosetta/file54.java | 1 + rosetta/file54.js | 1 + rosetta/file54.ocaml | 1 + rosetta/file54.perl | 1 + rosetta/file54.php | 1 + rosetta/file54.py | 1 + rosetta/file54.rb | 1 + rosetta/file54.scala | 1 + rosetta/file54.ss | 1 + rosetta/file54.tcl | 1 + rosetta/file55.clojure | 1 + rosetta/file55.hs | 1 + rosetta/file55.java | 1 + rosetta/file55.js | 1 + rosetta/file55.ocaml | 1 + rosetta/file55.perl | 1 + rosetta/file55.php | 1 + rosetta/file55.py | 1 + rosetta/file55.rb | 1 + rosetta/file55.scala | 1 + rosetta/file55.ss | 1 + rosetta/file55.tcl | 1 + rosetta/file56.clojure | 1 + rosetta/file56.hs | 1 + rosetta/file56.java | 1 + rosetta/file56.js | 1 + rosetta/file56.ocaml | 1 + rosetta/file56.perl | 1 + rosetta/file56.php | 1 + rosetta/file56.py | 1 + rosetta/file56.rb | 1 + rosetta/file56.scala | 1 + rosetta/file56.ss | 1 + rosetta/file56.tcl | 1 + rosetta/file57.clojure | 1 + rosetta/file57.hs | 1 + rosetta/file57.java | 1 + rosetta/file57.js | 1 + rosetta/file57.ocaml | 1 + rosetta/file57.perl | 1 + rosetta/file57.php | 1 + rosetta/file57.py | 1 + rosetta/file57.rb | 1 + rosetta/file57.scala | 1 + rosetta/file57.ss | 1 + rosetta/file57.tcl | 1 + rosetta/file58.clojure | 1 + rosetta/file58.hs | 1 + rosetta/file58.java | 1 + rosetta/file58.js | 1 + rosetta/file58.ocaml | 1 + rosetta/file58.perl | 1 + rosetta/file58.php | 1 + rosetta/file58.py | 1 + rosetta/file58.rb | 1 + rosetta/file58.scala | 1 + rosetta/file58.ss | 1 + rosetta/file58.tcl | 1 + rosetta/file59.clojure | 1 + rosetta/file59.hs | 1 + rosetta/file59.java | 1 + rosetta/file59.js | 1 + rosetta/file59.ocaml | 1 + rosetta/file59.perl | 1 + rosetta/file59.php | 1 + rosetta/file59.py | 1 + rosetta/file59.rb | 1 + rosetta/file59.scala | 1 + rosetta/file59.ss | 1 + rosetta/file59.tcl | 1 + rosetta/file6.clojure | 1 + rosetta/file6.hs | 1 + rosetta/file6.java | 1 + rosetta/file6.js | 1 + rosetta/file6.ocaml | 1 + rosetta/file6.perl | 1 + rosetta/file6.php | 1 + rosetta/file6.py | 1 + rosetta/file6.rb | 1 + rosetta/file6.scala | 1 + rosetta/file6.ss | 1 + rosetta/file6.tcl | 1 + rosetta/file60.clojure | 1 + rosetta/file60.hs | 1 + rosetta/file60.java | 1 + rosetta/file60.js | 1 + rosetta/file60.ocaml | 1 + rosetta/file60.perl | 1 + rosetta/file60.php | 1 + rosetta/file60.py | 1 + rosetta/file60.rb | 1 + rosetta/file60.scala | 1 + rosetta/file60.ss | 1 + rosetta/file60.tcl | 1 + rosetta/file7.clojure | 1 + rosetta/file7.hs | 1 + rosetta/file7.java | 1 + rosetta/file7.js | 1 + rosetta/file7.ocaml | 1 + rosetta/file7.perl | 1 + rosetta/file7.php | 1 + rosetta/file7.py | 1 + rosetta/file7.rb | 1 + rosetta/file7.scala | 1 + rosetta/file7.ss | 1 + rosetta/file7.tcl | 1 + rosetta/file8.clojure | 1 + rosetta/file8.hs | 1 + rosetta/file8.java | 1 + rosetta/file8.js | 1 + rosetta/file8.ocaml | 1 + rosetta/file8.perl | 1 + rosetta/file8.php | 1 + rosetta/file8.py | 1 + rosetta/file8.rb | 1 + rosetta/file8.scala | 1 + rosetta/file8.ss | 1 + rosetta/file8.tcl | 1 + rosetta/file9.clojure | 1 + rosetta/file9.hs | 1 + rosetta/file9.java | 1 + rosetta/file9.js | 1 + rosetta/file9.ocaml | 1 + rosetta/file9.perl | 1 + rosetta/file9.php | 1 + rosetta/file9.py | 1 + rosetta/file9.rb | 1 + rosetta/file9.scala | 1 + rosetta/file9.ss | 1 + rosetta/file9.tcl | 1 + 720 files changed, 725 insertions(+) create mode 100644 rosetta/file1.clojure create mode 100644 rosetta/file1.hs create mode 100644 rosetta/file1.java create mode 100644 rosetta/file1.js create mode 100644 rosetta/file1.ocaml create mode 100644 rosetta/file1.perl create mode 100644 rosetta/file1.php create mode 100644 rosetta/file1.py create mode 100644 rosetta/file1.rb create mode 100644 rosetta/file1.scala create mode 100644 rosetta/file1.ss create mode 100644 rosetta/file1.tcl create mode 100644 rosetta/file10.clojure create mode 100644 rosetta/file10.hs create mode 100644 rosetta/file10.java create mode 100644 rosetta/file10.js create mode 100644 rosetta/file10.ocaml create mode 100644 rosetta/file10.perl create mode 100644 rosetta/file10.php create mode 100644 rosetta/file10.py create mode 100644 rosetta/file10.rb create mode 100644 rosetta/file10.scala create mode 100644 rosetta/file10.ss create mode 100644 rosetta/file10.tcl create mode 100644 rosetta/file11.clojure create mode 100644 rosetta/file11.hs create mode 100644 rosetta/file11.java create mode 100644 rosetta/file11.js create mode 100644 rosetta/file11.ocaml create mode 100644 rosetta/file11.perl create mode 100644 rosetta/file11.php create mode 100644 rosetta/file11.py create mode 100644 rosetta/file11.rb create mode 100644 rosetta/file11.scala create mode 100644 rosetta/file11.ss create mode 100644 rosetta/file11.tcl create mode 100644 rosetta/file12.clojure create mode 100644 rosetta/file12.hs create mode 100644 rosetta/file12.java create mode 100644 rosetta/file12.js create mode 100644 rosetta/file12.ocaml create mode 100644 rosetta/file12.perl create mode 100644 rosetta/file12.php create mode 100644 rosetta/file12.py create mode 100644 rosetta/file12.rb create mode 100644 rosetta/file12.scala create mode 100644 rosetta/file12.ss create mode 100644 rosetta/file12.tcl create mode 100644 rosetta/file13.clojure create mode 100644 rosetta/file13.hs create mode 100644 rosetta/file13.java create mode 100644 rosetta/file13.js create mode 100644 rosetta/file13.ocaml create mode 100644 rosetta/file13.perl create mode 100644 rosetta/file13.php create mode 100644 rosetta/file13.py create mode 100644 rosetta/file13.rb create mode 100644 rosetta/file13.scala create mode 100644 rosetta/file13.ss create mode 100644 rosetta/file13.tcl create mode 100644 rosetta/file14.clojure create mode 100644 rosetta/file14.hs create mode 100644 rosetta/file14.java create mode 100644 rosetta/file14.js create mode 100644 rosetta/file14.ocaml create mode 100644 rosetta/file14.perl create mode 100644 rosetta/file14.php create mode 100644 rosetta/file14.py create mode 100644 rosetta/file14.rb create mode 100644 rosetta/file14.scala create mode 100644 rosetta/file14.ss create mode 100644 rosetta/file14.tcl create mode 100644 rosetta/file15.clojure create mode 100644 rosetta/file15.hs create mode 100644 rosetta/file15.java create mode 100644 rosetta/file15.js create mode 100644 rosetta/file15.ocaml create mode 100644 rosetta/file15.perl create mode 100644 rosetta/file15.php create mode 100644 rosetta/file15.py create mode 100644 rosetta/file15.rb create mode 100644 rosetta/file15.scala create mode 100644 rosetta/file15.ss create mode 100644 rosetta/file15.tcl create mode 100644 rosetta/file16.clojure create mode 100644 rosetta/file16.hs create mode 100644 rosetta/file16.java create mode 100644 rosetta/file16.js create mode 100644 rosetta/file16.ocaml create mode 100644 rosetta/file16.perl create mode 100644 rosetta/file16.php create mode 100644 rosetta/file16.py create mode 100644 rosetta/file16.rb create mode 100644 rosetta/file16.scala create mode 100644 rosetta/file16.ss create mode 100644 rosetta/file16.tcl create mode 100644 rosetta/file17.clojure create mode 100644 rosetta/file17.hs create mode 100644 rosetta/file17.java create mode 100644 rosetta/file17.js create mode 100644 rosetta/file17.ocaml create mode 100644 rosetta/file17.perl create mode 100644 rosetta/file17.php create mode 100644 rosetta/file17.py create mode 100644 rosetta/file17.rb create mode 100644 rosetta/file17.scala create mode 100644 rosetta/file17.ss create mode 100644 rosetta/file17.tcl create mode 100644 rosetta/file18.clojure create mode 100644 rosetta/file18.hs create mode 100644 rosetta/file18.java create mode 100644 rosetta/file18.js create mode 100644 rosetta/file18.ocaml create mode 100644 rosetta/file18.perl create mode 100644 rosetta/file18.php create mode 100644 rosetta/file18.py create mode 100644 rosetta/file18.rb create mode 100644 rosetta/file18.scala create mode 100644 rosetta/file18.ss create mode 100644 rosetta/file18.tcl create mode 100644 rosetta/file19.clojure create mode 100644 rosetta/file19.hs create mode 100644 rosetta/file19.java create mode 100644 rosetta/file19.js create mode 100644 rosetta/file19.ocaml create mode 100644 rosetta/file19.perl create mode 100644 rosetta/file19.php create mode 100644 rosetta/file19.py create mode 100644 rosetta/file19.rb create mode 100644 rosetta/file19.scala create mode 100644 rosetta/file19.ss create mode 100644 rosetta/file19.tcl create mode 100644 rosetta/file2.clojure create mode 100644 rosetta/file2.hs create mode 100644 rosetta/file2.java create mode 100644 rosetta/file2.js create mode 100644 rosetta/file2.ocaml create mode 100644 rosetta/file2.perl create mode 100644 rosetta/file2.php create mode 100644 rosetta/file2.py create mode 100644 rosetta/file2.rb create mode 100644 rosetta/file2.scala create mode 100644 rosetta/file2.ss create mode 100644 rosetta/file2.tcl create mode 100644 rosetta/file20.clojure create mode 100644 rosetta/file20.hs create mode 100644 rosetta/file20.java create mode 100644 rosetta/file20.js create mode 100644 rosetta/file20.ocaml create mode 100644 rosetta/file20.perl create mode 100644 rosetta/file20.php create mode 100644 rosetta/file20.py create mode 100644 rosetta/file20.rb create mode 100644 rosetta/file20.scala create mode 100644 rosetta/file20.ss create mode 100644 rosetta/file20.tcl create mode 100644 rosetta/file21.clojure create mode 100644 rosetta/file21.hs create mode 100644 rosetta/file21.java create mode 100644 rosetta/file21.js create mode 100644 rosetta/file21.ocaml create mode 100644 rosetta/file21.perl create mode 100644 rosetta/file21.php create mode 100644 rosetta/file21.py create mode 100644 rosetta/file21.rb create mode 100644 rosetta/file21.scala create mode 100644 rosetta/file21.ss create mode 100644 rosetta/file21.tcl create mode 100644 rosetta/file22.clojure create mode 100644 rosetta/file22.hs create mode 100644 rosetta/file22.java create mode 100644 rosetta/file22.js create mode 100644 rosetta/file22.ocaml create mode 100644 rosetta/file22.perl create mode 100644 rosetta/file22.php create mode 100644 rosetta/file22.py create mode 100644 rosetta/file22.rb create mode 100644 rosetta/file22.scala create mode 100644 rosetta/file22.ss create mode 100644 rosetta/file22.tcl create mode 100644 rosetta/file23.clojure create mode 100644 rosetta/file23.hs create mode 100644 rosetta/file23.java create mode 100644 rosetta/file23.js create mode 100644 rosetta/file23.ocaml create mode 100644 rosetta/file23.perl create mode 100644 rosetta/file23.php create mode 100644 rosetta/file23.py create mode 100644 rosetta/file23.rb create mode 100644 rosetta/file23.scala create mode 100644 rosetta/file23.ss create mode 100644 rosetta/file23.tcl create mode 100644 rosetta/file24.clojure create mode 100644 rosetta/file24.hs create mode 100644 rosetta/file24.java create mode 100644 rosetta/file24.js create mode 100644 rosetta/file24.ocaml create mode 100644 rosetta/file24.perl create mode 100644 rosetta/file24.php create mode 100644 rosetta/file24.py create mode 100644 rosetta/file24.rb create mode 100644 rosetta/file24.scala create mode 100644 rosetta/file24.ss create mode 100644 rosetta/file24.tcl create mode 100644 rosetta/file25.clojure create mode 100644 rosetta/file25.hs create mode 100644 rosetta/file25.java create mode 100644 rosetta/file25.js create mode 100644 rosetta/file25.ocaml create mode 100644 rosetta/file25.perl create mode 100644 rosetta/file25.php create mode 100644 rosetta/file25.py create mode 100644 rosetta/file25.rb create mode 100644 rosetta/file25.scala create mode 100644 rosetta/file25.ss create mode 100644 rosetta/file25.tcl create mode 100644 rosetta/file26.clojure create mode 100644 rosetta/file26.hs create mode 100644 rosetta/file26.java create mode 100644 rosetta/file26.js create mode 100644 rosetta/file26.ocaml create mode 100644 rosetta/file26.perl create mode 100644 rosetta/file26.php create mode 100644 rosetta/file26.py create mode 100644 rosetta/file26.rb create mode 100644 rosetta/file26.scala create mode 100644 rosetta/file26.ss create mode 100644 rosetta/file26.tcl create mode 100644 rosetta/file27.clojure create mode 100644 rosetta/file27.hs create mode 100644 rosetta/file27.java create mode 100644 rosetta/file27.js create mode 100644 rosetta/file27.ocaml create mode 100644 rosetta/file27.perl create mode 100644 rosetta/file27.php create mode 100644 rosetta/file27.py create mode 100644 rosetta/file27.rb create mode 100644 rosetta/file27.scala create mode 100644 rosetta/file27.ss create mode 100644 rosetta/file27.tcl create mode 100644 rosetta/file28.clojure create mode 100644 rosetta/file28.hs create mode 100644 rosetta/file28.java create mode 100644 rosetta/file28.js create mode 100644 rosetta/file28.ocaml create mode 100644 rosetta/file28.perl create mode 100644 rosetta/file28.php create mode 100644 rosetta/file28.py create mode 100644 rosetta/file28.rb create mode 100644 rosetta/file28.scala create mode 100644 rosetta/file28.ss create mode 100644 rosetta/file28.tcl create mode 100644 rosetta/file29.clojure create mode 100644 rosetta/file29.hs create mode 100644 rosetta/file29.java create mode 100644 rosetta/file29.js create mode 100644 rosetta/file29.ocaml create mode 100644 rosetta/file29.perl create mode 100644 rosetta/file29.php create mode 100644 rosetta/file29.py create mode 100644 rosetta/file29.rb create mode 100644 rosetta/file29.scala create mode 100644 rosetta/file29.ss create mode 100644 rosetta/file29.tcl create mode 100644 rosetta/file3.clojure create mode 100644 rosetta/file3.hs create mode 100644 rosetta/file3.java create mode 100644 rosetta/file3.js create mode 100644 rosetta/file3.ocaml create mode 100644 rosetta/file3.perl create mode 100644 rosetta/file3.php create mode 100644 rosetta/file3.py create mode 100644 rosetta/file3.rb create mode 100644 rosetta/file3.scala create mode 100644 rosetta/file3.ss create mode 100644 rosetta/file3.tcl create mode 100644 rosetta/file30.clojure create mode 100644 rosetta/file30.hs create mode 100644 rosetta/file30.java create mode 100644 rosetta/file30.js create mode 100644 rosetta/file30.ocaml create mode 100644 rosetta/file30.perl create mode 100644 rosetta/file30.php create mode 100644 rosetta/file30.py create mode 100644 rosetta/file30.rb create mode 100644 rosetta/file30.scala create mode 100644 rosetta/file30.ss create mode 100644 rosetta/file30.tcl create mode 100644 rosetta/file31.clojure create mode 100644 rosetta/file31.hs create mode 100644 rosetta/file31.java create mode 100644 rosetta/file31.js create mode 100644 rosetta/file31.ocaml create mode 100644 rosetta/file31.perl create mode 100644 rosetta/file31.php create mode 100644 rosetta/file31.py create mode 100644 rosetta/file31.rb create mode 100644 rosetta/file31.scala create mode 100644 rosetta/file31.ss create mode 100644 rosetta/file31.tcl create mode 100644 rosetta/file32.clojure create mode 100644 rosetta/file32.hs create mode 100644 rosetta/file32.java create mode 100644 rosetta/file32.js create mode 100644 rosetta/file32.ocaml create mode 100644 rosetta/file32.perl create mode 100644 rosetta/file32.php create mode 100644 rosetta/file32.py create mode 100644 rosetta/file32.rb create mode 100644 rosetta/file32.scala create mode 100644 rosetta/file32.ss create mode 100644 rosetta/file32.tcl create mode 100644 rosetta/file33.clojure create mode 100644 rosetta/file33.hs create mode 100644 rosetta/file33.java create mode 100644 rosetta/file33.js create mode 100644 rosetta/file33.ocaml create mode 100644 rosetta/file33.perl create mode 100644 rosetta/file33.php create mode 100644 rosetta/file33.py create mode 100644 rosetta/file33.rb create mode 100644 rosetta/file33.scala create mode 100644 rosetta/file33.ss create mode 100644 rosetta/file33.tcl create mode 100644 rosetta/file34.clojure create mode 100644 rosetta/file34.hs create mode 100644 rosetta/file34.java create mode 100644 rosetta/file34.js create mode 100644 rosetta/file34.ocaml create mode 100644 rosetta/file34.perl create mode 100644 rosetta/file34.php create mode 100644 rosetta/file34.py create mode 100644 rosetta/file34.rb create mode 100644 rosetta/file34.scala create mode 100644 rosetta/file34.ss create mode 100644 rosetta/file34.tcl create mode 100644 rosetta/file35.clojure create mode 100644 rosetta/file35.hs create mode 100644 rosetta/file35.java create mode 100644 rosetta/file35.js create mode 100644 rosetta/file35.ocaml create mode 100644 rosetta/file35.perl create mode 100644 rosetta/file35.php create mode 100644 rosetta/file35.py create mode 100644 rosetta/file35.rb create mode 100644 rosetta/file35.scala create mode 100644 rosetta/file35.ss create mode 100644 rosetta/file35.tcl create mode 100644 rosetta/file36.clojure create mode 100644 rosetta/file36.hs create mode 100644 rosetta/file36.java create mode 100644 rosetta/file36.js create mode 100644 rosetta/file36.ocaml create mode 100644 rosetta/file36.perl create mode 100644 rosetta/file36.php create mode 100644 rosetta/file36.py create mode 100644 rosetta/file36.rb create mode 100644 rosetta/file36.scala create mode 100644 rosetta/file36.ss create mode 100644 rosetta/file36.tcl create mode 100644 rosetta/file37.clojure create mode 100644 rosetta/file37.hs create mode 100644 rosetta/file37.java create mode 100644 rosetta/file37.js create mode 100644 rosetta/file37.ocaml create mode 100644 rosetta/file37.perl create mode 100644 rosetta/file37.php create mode 100644 rosetta/file37.py create mode 100644 rosetta/file37.rb create mode 100644 rosetta/file37.scala create mode 100644 rosetta/file37.ss create mode 100644 rosetta/file37.tcl create mode 100644 rosetta/file38.clojure create mode 100644 rosetta/file38.hs create mode 100644 rosetta/file38.java create mode 100644 rosetta/file38.js create mode 100644 rosetta/file38.ocaml create mode 100644 rosetta/file38.perl create mode 100644 rosetta/file38.php create mode 100644 rosetta/file38.py create mode 100644 rosetta/file38.rb create mode 100644 rosetta/file38.scala create mode 100644 rosetta/file38.ss create mode 100644 rosetta/file38.tcl create mode 100644 rosetta/file39.clojure create mode 100644 rosetta/file39.hs create mode 100644 rosetta/file39.java create mode 100644 rosetta/file39.js create mode 100644 rosetta/file39.ocaml create mode 100644 rosetta/file39.perl create mode 100644 rosetta/file39.php create mode 100644 rosetta/file39.py create mode 100644 rosetta/file39.rb create mode 100644 rosetta/file39.scala create mode 100644 rosetta/file39.ss create mode 100644 rosetta/file39.tcl create mode 100644 rosetta/file4.clojure create mode 100644 rosetta/file4.hs create mode 100644 rosetta/file4.java create mode 100644 rosetta/file4.js create mode 100644 rosetta/file4.ocaml create mode 100644 rosetta/file4.perl create mode 100644 rosetta/file4.php create mode 100644 rosetta/file4.py create mode 100644 rosetta/file4.rb create mode 100644 rosetta/file4.scala create mode 100644 rosetta/file4.ss create mode 100644 rosetta/file4.tcl create mode 100644 rosetta/file40.clojure create mode 100644 rosetta/file40.hs create mode 100644 rosetta/file40.java create mode 100644 rosetta/file40.js create mode 100644 rosetta/file40.ocaml create mode 100644 rosetta/file40.perl create mode 100644 rosetta/file40.php create mode 100644 rosetta/file40.py create mode 100644 rosetta/file40.rb create mode 100644 rosetta/file40.scala create mode 100644 rosetta/file40.ss create mode 100644 rosetta/file40.tcl create mode 100644 rosetta/file41.clojure create mode 100644 rosetta/file41.hs create mode 100644 rosetta/file41.java create mode 100644 rosetta/file41.js create mode 100644 rosetta/file41.ocaml create mode 100644 rosetta/file41.perl create mode 100644 rosetta/file41.php create mode 100644 rosetta/file41.py create mode 100644 rosetta/file41.rb create mode 100644 rosetta/file41.scala create mode 100644 rosetta/file41.ss create mode 100644 rosetta/file41.tcl create mode 100644 rosetta/file42.clojure create mode 100644 rosetta/file42.hs create mode 100644 rosetta/file42.java create mode 100644 rosetta/file42.js create mode 100644 rosetta/file42.ocaml create mode 100644 rosetta/file42.perl create mode 100644 rosetta/file42.php create mode 100644 rosetta/file42.py create mode 100644 rosetta/file42.rb create mode 100644 rosetta/file42.scala create mode 100644 rosetta/file42.ss create mode 100644 rosetta/file42.tcl create mode 100644 rosetta/file43.clojure create mode 100644 rosetta/file43.hs create mode 100644 rosetta/file43.java create mode 100644 rosetta/file43.js create mode 100644 rosetta/file43.ocaml create mode 100644 rosetta/file43.perl create mode 100644 rosetta/file43.php create mode 100644 rosetta/file43.py create mode 100644 rosetta/file43.rb create mode 100644 rosetta/file43.scala create mode 100644 rosetta/file43.ss create mode 100644 rosetta/file43.tcl create mode 100644 rosetta/file44.clojure create mode 100644 rosetta/file44.hs create mode 100644 rosetta/file44.java create mode 100644 rosetta/file44.js create mode 100644 rosetta/file44.ocaml create mode 100644 rosetta/file44.perl create mode 100644 rosetta/file44.php create mode 100644 rosetta/file44.py create mode 100644 rosetta/file44.rb create mode 100644 rosetta/file44.scala create mode 100644 rosetta/file44.ss create mode 100644 rosetta/file44.tcl create mode 100644 rosetta/file45.clojure create mode 100644 rosetta/file45.hs create mode 100644 rosetta/file45.java create mode 100644 rosetta/file45.js create mode 100644 rosetta/file45.ocaml create mode 100644 rosetta/file45.perl create mode 100644 rosetta/file45.php create mode 100644 rosetta/file45.py create mode 100644 rosetta/file45.rb create mode 100644 rosetta/file45.scala create mode 100644 rosetta/file45.ss create mode 100644 rosetta/file45.tcl create mode 100644 rosetta/file46.clojure create mode 100644 rosetta/file46.hs create mode 100644 rosetta/file46.java create mode 100644 rosetta/file46.js create mode 100644 rosetta/file46.ocaml create mode 100644 rosetta/file46.perl create mode 100644 rosetta/file46.php create mode 100644 rosetta/file46.py create mode 100644 rosetta/file46.rb create mode 100644 rosetta/file46.scala create mode 100644 rosetta/file46.ss create mode 100644 rosetta/file46.tcl create mode 100644 rosetta/file47.clojure create mode 100644 rosetta/file47.hs create mode 100644 rosetta/file47.java create mode 100644 rosetta/file47.js create mode 100644 rosetta/file47.ocaml create mode 100644 rosetta/file47.perl create mode 100644 rosetta/file47.php create mode 100644 rosetta/file47.py create mode 100644 rosetta/file47.rb create mode 100644 rosetta/file47.scala create mode 100644 rosetta/file47.ss create mode 100644 rosetta/file47.tcl create mode 100644 rosetta/file48.clojure create mode 100644 rosetta/file48.hs create mode 100644 rosetta/file48.java create mode 100644 rosetta/file48.js create mode 100644 rosetta/file48.ocaml create mode 100644 rosetta/file48.perl create mode 100644 rosetta/file48.php create mode 100644 rosetta/file48.py create mode 100644 rosetta/file48.rb create mode 100644 rosetta/file48.scala create mode 100644 rosetta/file48.ss create mode 100644 rosetta/file48.tcl create mode 100644 rosetta/file49.clojure create mode 100644 rosetta/file49.hs create mode 100644 rosetta/file49.java create mode 100644 rosetta/file49.js create mode 100644 rosetta/file49.ocaml create mode 100644 rosetta/file49.perl create mode 100644 rosetta/file49.php create mode 100644 rosetta/file49.py create mode 100644 rosetta/file49.rb create mode 100644 rosetta/file49.scala create mode 100644 rosetta/file49.ss create mode 100644 rosetta/file49.tcl create mode 100644 rosetta/file5.clojure create mode 100644 rosetta/file5.hs create mode 100644 rosetta/file5.java create mode 100644 rosetta/file5.js create mode 100644 rosetta/file5.ocaml create mode 100644 rosetta/file5.perl create mode 100644 rosetta/file5.php create mode 100644 rosetta/file5.py create mode 100644 rosetta/file5.rb create mode 100644 rosetta/file5.scala create mode 100644 rosetta/file5.ss create mode 100644 rosetta/file5.tcl create mode 100644 rosetta/file50.clojure create mode 100644 rosetta/file50.hs create mode 100644 rosetta/file50.java create mode 100644 rosetta/file50.js create mode 100644 rosetta/file50.ocaml create mode 100644 rosetta/file50.perl create mode 100644 rosetta/file50.php create mode 100644 rosetta/file50.py create mode 100644 rosetta/file50.rb create mode 100644 rosetta/file50.scala create mode 100644 rosetta/file50.ss create mode 100644 rosetta/file50.tcl create mode 100644 rosetta/file51.clojure create mode 100644 rosetta/file51.hs create mode 100644 rosetta/file51.java create mode 100644 rosetta/file51.js create mode 100644 rosetta/file51.ocaml create mode 100644 rosetta/file51.perl create mode 100644 rosetta/file51.php create mode 100644 rosetta/file51.py create mode 100644 rosetta/file51.rb create mode 100644 rosetta/file51.scala create mode 100644 rosetta/file51.ss create mode 100644 rosetta/file51.tcl create mode 100644 rosetta/file52.clojure create mode 100644 rosetta/file52.hs create mode 100644 rosetta/file52.java create mode 100644 rosetta/file52.js create mode 100644 rosetta/file52.ocaml create mode 100644 rosetta/file52.perl create mode 100644 rosetta/file52.php create mode 100644 rosetta/file52.py create mode 100644 rosetta/file52.rb create mode 100644 rosetta/file52.scala create mode 100644 rosetta/file52.ss create mode 100644 rosetta/file52.tcl create mode 100644 rosetta/file53.clojure create mode 100644 rosetta/file53.hs create mode 100644 rosetta/file53.java create mode 100644 rosetta/file53.js create mode 100644 rosetta/file53.ocaml create mode 100644 rosetta/file53.perl create mode 100644 rosetta/file53.php create mode 100644 rosetta/file53.py create mode 100644 rosetta/file53.rb create mode 100644 rosetta/file53.scala create mode 100644 rosetta/file53.ss create mode 100644 rosetta/file53.tcl create mode 100644 rosetta/file54.clojure create mode 100644 rosetta/file54.hs create mode 100644 rosetta/file54.java create mode 100644 rosetta/file54.js create mode 100644 rosetta/file54.ocaml create mode 100644 rosetta/file54.perl create mode 100644 rosetta/file54.php create mode 100644 rosetta/file54.py create mode 100644 rosetta/file54.rb create mode 100644 rosetta/file54.scala create mode 100644 rosetta/file54.ss create mode 100644 rosetta/file54.tcl create mode 100644 rosetta/file55.clojure create mode 100644 rosetta/file55.hs create mode 100644 rosetta/file55.java create mode 100644 rosetta/file55.js create mode 100644 rosetta/file55.ocaml create mode 100644 rosetta/file55.perl create mode 100644 rosetta/file55.php create mode 100644 rosetta/file55.py create mode 100644 rosetta/file55.rb create mode 100644 rosetta/file55.scala create mode 100644 rosetta/file55.ss create mode 100644 rosetta/file55.tcl create mode 100644 rosetta/file56.clojure create mode 100644 rosetta/file56.hs create mode 100644 rosetta/file56.java create mode 100644 rosetta/file56.js create mode 100644 rosetta/file56.ocaml create mode 100644 rosetta/file56.perl create mode 100644 rosetta/file56.php create mode 100644 rosetta/file56.py create mode 100644 rosetta/file56.rb create mode 100644 rosetta/file56.scala create mode 100644 rosetta/file56.ss create mode 100644 rosetta/file56.tcl create mode 100644 rosetta/file57.clojure create mode 100644 rosetta/file57.hs create mode 100644 rosetta/file57.java create mode 100644 rosetta/file57.js create mode 100644 rosetta/file57.ocaml create mode 100644 rosetta/file57.perl create mode 100644 rosetta/file57.php create mode 100644 rosetta/file57.py create mode 100644 rosetta/file57.rb create mode 100644 rosetta/file57.scala create mode 100644 rosetta/file57.ss create mode 100644 rosetta/file57.tcl create mode 100644 rosetta/file58.clojure create mode 100644 rosetta/file58.hs create mode 100644 rosetta/file58.java create mode 100644 rosetta/file58.js create mode 100644 rosetta/file58.ocaml create mode 100644 rosetta/file58.perl create mode 100644 rosetta/file58.php create mode 100644 rosetta/file58.py create mode 100644 rosetta/file58.rb create mode 100644 rosetta/file58.scala create mode 100644 rosetta/file58.ss create mode 100644 rosetta/file58.tcl create mode 100644 rosetta/file59.clojure create mode 100644 rosetta/file59.hs create mode 100644 rosetta/file59.java create mode 100644 rosetta/file59.js create mode 100644 rosetta/file59.ocaml create mode 100644 rosetta/file59.perl create mode 100644 rosetta/file59.php create mode 100644 rosetta/file59.py create mode 100644 rosetta/file59.rb create mode 100644 rosetta/file59.scala create mode 100644 rosetta/file59.ss create mode 100644 rosetta/file59.tcl create mode 100644 rosetta/file6.clojure create mode 100644 rosetta/file6.hs create mode 100644 rosetta/file6.java create mode 100644 rosetta/file6.js create mode 100644 rosetta/file6.ocaml create mode 100644 rosetta/file6.perl create mode 100644 rosetta/file6.php create mode 100644 rosetta/file6.py create mode 100644 rosetta/file6.rb create mode 100644 rosetta/file6.scala create mode 100644 rosetta/file6.ss create mode 100644 rosetta/file6.tcl create mode 100644 rosetta/file60.clojure create mode 100644 rosetta/file60.hs create mode 100644 rosetta/file60.java create mode 100644 rosetta/file60.js create mode 100644 rosetta/file60.ocaml create mode 100644 rosetta/file60.perl create mode 100644 rosetta/file60.php create mode 100644 rosetta/file60.py create mode 100644 rosetta/file60.rb create mode 100644 rosetta/file60.scala create mode 100644 rosetta/file60.ss create mode 100644 rosetta/file60.tcl create mode 100644 rosetta/file7.clojure create mode 100644 rosetta/file7.hs create mode 100644 rosetta/file7.java create mode 100644 rosetta/file7.js create mode 100644 rosetta/file7.ocaml create mode 100644 rosetta/file7.perl create mode 100644 rosetta/file7.php create mode 100644 rosetta/file7.py create mode 100644 rosetta/file7.rb create mode 100644 rosetta/file7.scala create mode 100644 rosetta/file7.ss create mode 100644 rosetta/file7.tcl create mode 100644 rosetta/file8.clojure create mode 100644 rosetta/file8.hs create mode 100644 rosetta/file8.java create mode 100644 rosetta/file8.js create mode 100644 rosetta/file8.ocaml create mode 100644 rosetta/file8.perl create mode 100644 rosetta/file8.php create mode 100644 rosetta/file8.py create mode 100644 rosetta/file8.rb create mode 100644 rosetta/file8.scala create mode 100644 rosetta/file8.ss create mode 100644 rosetta/file8.tcl create mode 100644 rosetta/file9.clojure create mode 100644 rosetta/file9.hs create mode 100644 rosetta/file9.java create mode 100644 rosetta/file9.js create mode 100644 rosetta/file9.ocaml create mode 100644 rosetta/file9.perl create mode 100644 rosetta/file9.php create mode 100644 rosetta/file9.py create mode 100644 rosetta/file9.rb create mode 100644 rosetta/file9.scala create mode 100644 rosetta/file9.ss create mode 100644 rosetta/file9.tcl diff --git a/rosetta/file1.clojure b/rosetta/file1.clojure new file mode 100644 index 0000000..209fe71 --- /dev/null +++ b/rosetta/file1.clojure @@ -0,0 +1 @@ +( ns rosettacode . 24game . solve ( : require [ clojure . math . combinatorics : as c ] [ clojure . walk : as w ] ) )   ( def ^ : private op - maps ( map # ( zipmap [ : o1  : o2  : o3 ] % ) ( c / selections ' ( * + - / ) 3 ) ) )   ( def ^ : private patterns ' ( ( : o1 ( : o2  : n1  : n2 ) ( : o3  : n3  : n4 ) ) ( : o1  : n1 ( : o2  : n2 ( : o3  : n3  : n4 ) ) ) ( : o1 ( : o2 ( : o3  : n1  : n2 )  : n3 )  : n4 ) ) )   ( defn play24 [ & digits ] { : pre ( and ( every? # ( not = 0 % ) digits ) ( = ( count digits ) 4 ) ) } ( ->> ( for [ : let [ digit - maps ( ->> digits sort c / permutations ( map # ( zipmap [ : n1  : n2  : n3  : n4 ] % ) ) ) ] om op - maps, dm digit - maps ] ( w / prewalk - replace dm ( w / prewalk - replace om patterns ) ) ) ( filter # ( = ( eval % ) 24 ) ) ( map println ) doall count ) ) \ No newline at end of file diff --git a/rosetta/file1.hs b/rosetta/file1.hs new file mode 100644 index 0000000..b270548 --- /dev/null +++ b/rosetta/file1.hs @@ -0,0 +1 @@ +ack 0 n = n + 1 ack m 0 = ack ( m - 1 ) 1 ack m n = ack ( m - 1 ) ( ack m ( n - 1 ) ) \ No newline at end of file diff --git a/rosetta/file1.java b/rosetta/file1.java new file mode 100644 index 0000000..8925bad --- /dev/null +++ b/rosetta/file1.java @@ -0,0 +1 @@ +import java.util.* ;   public class Game24Player { final String [ ] patterns = { "nnonnoo" , "nnonono" , "nnnoono" , "nnnonoo" , "nnnnooo" } ; final String ops = "+-*/^" ;   String solution ; List < Integer > digits ;   public static void main ( String [ ] args ) { new Game24Player ( ) . play ( ) ; }   void play ( ) { digits = getSolvableDigits ( ) ;   Scanner in = new Scanner ( System . in ) ; while ( true ) { System . out . print ( "Make 24 using these digits: " ) ; System . out . println ( digits ) ; System . out . println ( "(Enter 'q' to quit, 's' for a solution)" ) ; System . out . print ( "> " ) ;   String line = in. nextLine ( ) ; if ( line. equalsIgnoreCase ( "q" ) ) { System . out . println ( " \n Thanks for playing" ) ; return ; }   if ( line. equalsIgnoreCase ( "s" ) ) { System . out . println ( solution ) ; digits = getSolvableDigits ( ) ; continue ; }   char [ ] entry = line. replaceAll ( "[^*+-/)( \\ d]" , "" ) . toCharArray ( ) ;   try { validate ( entry ) ;   if ( evaluate ( infixToPostfix ( entry ) ) ) { System . out . println ( " \n Correct! Want to try another? " ) ; digits = getSolvableDigits ( ) ; } else { System . out . println ( " \n Not correct." ) ; }   } catch ( Exception e ) { System . out . printf ( "%n%s Try again.%n" , e. getMessage ( ) ) ; } } }   void validate ( char [ ] input ) throws Exception { int total1 = 0 , parens = 0 , opsCount = 0 ;   for ( char c : input ) { if ( Character . isDigit ( c ) ) total1 += 1 << ( c - '0' ) * 4 ; else if ( c == '(' ) parens ++; else if ( c == ')' ) parens --; else if ( ops. indexOf ( c ) != - 1 ) opsCount ++; if ( parens < 0 ) throw new Exception ( "Parentheses mismatch." ) ; }   if ( parens != 0 ) throw new Exception ( "Parentheses mismatch." ) ;   if ( opsCount != 3 ) throw new Exception ( "Wrong number of operators." ) ;   int total2 = 0 ; for ( int d : digits ) total2 += 1 << d * 4 ;   if ( total1 != total2 ) throw new Exception ( "Not the same digits." ) ; }   boolean evaluate ( char [ ] line ) throws Exception { Stack < Float > s = new Stack <> ( ) ; try { for ( char c : line ) { if ( '0' <= c && c <= '9' ) s. push ( ( float ) c - '0' ) ; else s. push ( applyOperator ( s. pop ( ) , s. pop ( ) , c ) ) ; } } catch ( EmptyStackException e ) { throw new Exception ( "Invalid entry." ) ; } return ( Math . abs ( 24 - s. peek ( ) ) < 0.001F ) ; }   float applyOperator ( float a, float b, char c ) { switch ( c ) { case '+' : return a + b ; case '-' : return b - a ; case '*' : return a * b ; case '/' : return b / a ; default : return Float . NaN ; } }   List < Integer > randomDigits ( ) { Random r = new Random ( ) ; List < Integer > result = new ArrayList <> ( 4 ) ; for ( int i = 0 ; i < 4 ; i ++ ) result. add ( r. nextInt ( 9 ) + 1 ) ; return result ; }   List < Integer > getSolvableDigits ( ) { List < Integer > result ; do { result = randomDigits ( ) ; } while ( ! isSolvable ( result ) ) ; return result ; }   boolean isSolvable ( List < Integer > digits ) { Set < List < Integer >> dPerms = new HashSet <> ( 4 * 3 * 2 ) ; permute ( digits, dPerms, 0 ) ;   int total = 4 * 4 * 4 ; List < List < Integer >> oPerms = new ArrayList <> ( total ) ; permuteOperators ( oPerms, 4 , total ) ;   StringBuilder sb = new StringBuilder ( 4 + 3 ) ;   for ( String pattern : patterns ) { char [ ] patternChars = pattern. toCharArray ( ) ;   for ( List < Integer > dig : dPerms ) { for ( List < Integer > opr : oPerms ) {   int i = 0 , j = 0 ; for ( char c : patternChars ) { if ( c == 'n' ) sb. append ( dig. get ( i ++ ) ) ; else sb. append ( ops. charAt ( opr. get ( j ++ ) ) ) ; }   String candidate = sb. toString ( ) ; try { if ( evaluate ( candidate. toCharArray ( ) ) ) { solution = postfixToInfix ( candidate ) ; return true ; } } catch ( Exception ignored ) { } sb. setLength ( 0 ) ; } } } return false ; }   String postfixToInfix ( String postfix ) { class Expression { String op, ex ; int prec = 3 ;   Expression ( String e ) { ex = e ; }   Expression ( String e1, String e2, String o ) { ex = String . format ( "%s %s %s" , e1, o, e2 ) ; op = o ; prec = ops. indexOf ( o ) / 2 ; } }   Stack < Expression > expr = new Stack <> ( ) ;   for ( char c : postfix. toCharArray ( ) ) { int idx = ops. indexOf ( c ) ; if ( idx != - 1 ) {   Expression r = expr. pop ( ) ; Expression l = expr. pop ( ) ;   int opPrec = idx / 2 ;   if ( l. prec < opPrec ) l. ex = '(' + l. ex + ')' ;   if ( r. prec <= opPrec ) r. ex = '(' + r. ex + ')' ;   expr. push ( new Expression ( l. ex , r. ex , "" + c ) ) ; } else { expr. push ( new Expression ( "" + c ) ) ; } } return expr. peek ( ) . ex ; }   char [ ] infixToPostfix ( char [ ] infix ) throws Exception { StringBuilder sb = new StringBuilder ( ) ; Stack < Integer > s = new Stack <> ( ) ; try { for ( char c : infix ) { int idx = ops. indexOf ( c ) ; if ( idx != - 1 ) { if ( s. isEmpty ( ) ) s. push ( idx ) ; else { while ( ! s. isEmpty ( ) ) { int prec2 = s. peek ( ) / 2 ; int prec1 = idx / 2 ; if ( prec2 >= prec1 ) sb. append ( ops. charAt ( s. pop ( ) ) ) ; else break ; } s. push ( idx ) ; } } else if ( c == '(' ) { s. push ( - 2 ) ; } else if ( c == ')' ) { while ( s. peek ( ) != - 2 ) sb. append ( ops. charAt ( s. pop ( ) ) ) ; s. pop ( ) ; } else { sb. append ( c ) ; } } while ( ! s. isEmpty ( ) ) sb. append ( ops. charAt ( s. pop ( ) ) ) ;   } catch ( EmptyStackException e ) { throw new Exception ( "Invalid entry." ) ; } return sb. toString ( ) . toCharArray ( ) ; }   void permute ( List < Integer > lst, Set < List < Integer >> res, int k ) { for ( int i = k ; i < lst. size ( ) ; i ++ ) { Collections . swap ( lst, i, k ) ; permute ( lst, res, k + 1 ) ; Collections . swap ( lst, k, i ) ; } if ( k == lst. size ( ) ) res. add ( new ArrayList <> ( lst ) ) ; }   void permuteOperators ( List < List < Integer >> res, int n, int total ) { for ( int i = 0 , npow = n * n ; i < total ; i ++ ) res. add ( Arrays . asList ( ( i / npow ) , ( i % npow ) / n, i % n ) ) ; } } \ No newline at end of file diff --git a/rosetta/file1.js b/rosetta/file1.js new file mode 100644 index 0000000..b295c99 --- /dev/null +++ b/rosetta/file1.js @@ -0,0 +1 @@ +let characters = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM" ; let blocks = characters. split ( " " ) . map ( pair => pair. split ( "" ) ) ;   function isWordPossible ( word ) { var letters = [ ... word . toUpperCase ( ) ] ; var length = letters. length ; var copy = new Set ( blocks ) ;   for ( let letter of letters ) { for ( let block of copy ) { let index = block. indexOf ( letter ) ;   if ( index !== - 1 ) { length --; copy. delete ( block ) ; break ; } }   } return ! length ; }   [ "A" , "BARK" , "BOOK" , "TREAT" , "COMMON" , "SQUAD" , "CONFUSE" ] . forEach ( word => console. log ( `$ { word } : $ { isWordPossible ( word ) } ` ) ) ;   \ No newline at end of file diff --git a/rosetta/file1.ocaml b/rosetta/file1.ocaml new file mode 100644 index 0000000..21de3c5 --- /dev/null +++ b/rosetta/file1.ocaml @@ -0,0 +1 @@ +let rec a m n = if m = 0 then ( n + 1 ) else if n = 0 then ( a ( m - 1 ) 1 ) else ( a ( m - 1 ) ( a m ( n - 1 ) ) ) \ No newline at end of file diff --git a/rosetta/file1.perl b/rosetta/file1.perl new file mode 100644 index 0000000..67ff242 --- /dev/null +++ b/rosetta/file1.perl @@ -0,0 +1 @@ +  use Net :: LDAP ;   my $ldap = Net :: LDAP -> new ( 'ldap://ldap.example.com' ) or die $@ ; my $mesg = $ldap -> bind ( $bind_dn , password => $bind_pass ) ;   \ No newline at end of file diff --git a/rosetta/file1.php b/rosetta/file1.php new file mode 100644 index 0000000..940c3f6 --- /dev/null +++ b/rosetta/file1.php @@ -0,0 +1 @@ +#!/usr/bin/env php The 24 Game   Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24.   An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwise you are repeatedly asked for an expression until it evaluates to 24   Note: you cannot form multiple digit numbers from the supplied digits, so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.   0 ) { return ; } }   return eval ( "return $expression ;" ) ; } ?> \ No newline at end of file diff --git a/rosetta/file1.py b/rosetta/file1.py new file mode 100644 index 0000000..85c8703 --- /dev/null +++ b/rosetta/file1.py @@ -0,0 +1 @@ +cache = [ [ 1 ] ] def cumu ( n ) : for l in range ( len ( cache ) , n+ 1 ) : r = [ 0 ] for x in range ( 1 , l+ 1 ) : r. append ( r [ - 1 ] + cache [ l-x ] [ min ( x , l-x ) ] ) cache. append ( r ) return cache [ n ]   def row ( n ) : r = cumu ( n ) return [ r [ i+ 1 ] - r [ i ] for i in range ( n ) ]   print "rows:" for x in range ( 1 , 11 ) : print "%2d:" %x , row ( x )     print " \n sums:" for x in [ 23 , 123 , 1234 , 12345 ] : print x , cumu ( x ) [ - 1 ] \ No newline at end of file diff --git a/rosetta/file1.rb b/rosetta/file1.rb new file mode 100644 index 0000000..3878254 --- /dev/null +++ b/rosetta/file1.rb @@ -0,0 +1 @@ +require 'rubygems' require 'net/ldap'   ldap = Net::LDAP . new ( :host => 'hostname' , :base => 'base' ) ldap. authenticate ( 'bind_dn' , 'bind_pass' )   filter = Net::LDAP::Filter . pres ( 'objectclass' ) filter & = Net::LDAP::Filter . eq ( 'sn' , 'Jackman' ) # or filter = Net::LDAP::Filter . construct ( '(&(objectclass=*)(sn=Jackman))' )   results = ldap. search ( :filter => filter ) # returns an array of Net::LDAP::Entry objects   puts results [ 0 ] [ :sn ] # ==> "Jackman" \ No newline at end of file diff --git a/rosetta/file1.scala b/rosetta/file1.scala new file mode 100644 index 0000000..46e0bde --- /dev/null +++ b/rosetta/file1.scala @@ -0,0 +1 @@ +  object Main {   // This is a special class for memoization case class Memo [ A,B ] ( f : A => B ) extends ( A => B ) { private val cache = Map. empty [ A, B ] def apply ( x : A ) = cache getOrElseUpdate ( x, f ( x ) ) }   // Naive, but memoized solution lazy val namesStartingMemo : Memo [ Tuple2 [ Int, Int ] , BigInt ] = Memo { case ( 1 , 1 ) => 1 case ( a, n ) => if ( a > n/ 2 ) namesStartingMemo ( a - 1 , n - 1 ) else if ( n < a ) 0 else if ( n == a ) 1 else ( 1 to a ) . map ( i => namesStartingMemo ( i, n - a ) ) . sum   }   def partitions ( n : Int ) = ( 1 to n ) . map ( namesStartingMemo ( _ , n ) ) . sum   // main method def main ( args : Array [ String ] ) : Unit = { for ( i < - 1 to 25 ) { for ( j < - 1 to i ) { print ( namesStartingMemo ( j, i ) ) ; print ( ' ' ) ; } println ( ) } println ( partitions ( 23 ) ) println ( partitions ( 123 ) ) println ( partitions ( 1234 ) ) println ( partitions ( 12345 ) ) } }   \ No newline at end of file diff --git a/rosetta/file1.ss b/rosetta/file1.ss new file mode 100644 index 0000000..e115460 --- /dev/null +++ b/rosetta/file1.ss @@ -0,0 +1 @@ +#lang scheme ( require srfi / 27 srfi / 1 ) ;; random-integer, every   ( define ( play ) ( let* ( [ numbers ( build - list 4 ( lambda ( n ) ( add1 ( random - integer 9 ) ) ) ) ] [ valid? ( curryr valid? numbers ) ] ) ( printf startup - message numbers ) ( let loop ( [ exp ( read ) ] ) ( with - handlers ( [ exn:fail? ( lambda ( err ) ( printf error - message exp ( exn - message err ) ) ( loop ( read ) ) ) ] ) ( cond [ ( eq? exp ' ! ) ( play ) ]   [ ( or ( eq? exp 'q ) ( eof-object? exp ) ) ( printf quit - message ) ]   [ ( not ( valid? exp ) ) ( printf bad - exp - message exp ) ( loop ( read ) ) ]   [ ( not ( = ( eval exp ) 24 ) ) ( printf bad - result - message exp ( eval exp ) ) ( loop ( read ) ) ]   [ else ( printf winning - message ) ] ) ) ) ) )   ( define ( valid? exp numbers ) ;; must contain each number exactly once and only valid symbols ( define ( valid - symbol? sym ) ;; only +, -, *, and / are valid ( case sym [ ( + - * / ) #t ] [ else #f ] ) )   ( let* ( [ ls ( flatten exp ) ] [ numbers * ( filter number? ls ) ] [ symbols ( remove number? ls ) ] ) ( and ( equal? ( sort numbers < ) ( sort numbers * < ) ) ( every valid - symbol? symbols ) ) ) )   ( define startup - message " Write a lisp expression that evaluates to 24 using only (, ), +, -, *, / and these four numbers: ~a   or '!' to get a new set of numbers or 'q' to quit" )   ( define error - message " Your expression ~a raised an exception:   \" ~a \"   Please try again" )   ( define bad - exp - message "Sorry, ~a is a bad expression." ) ( define bad - result - message "Sorry, ~a evaluates to ~a, not 24." ) ( define quit - message "Thanks for playing..." ) ( define winning - message "You win!" )   ( provide play )   \ No newline at end of file diff --git a/rosetta/file1.tcl b/rosetta/file1.tcl new file mode 100644 index 0000000..e4ab870 --- /dev/null +++ b/rosetta/file1.tcl @@ -0,0 +1 @@ +set cache 1 proc cumu { n } { global cache for { set l [ llength $cache ] } { $l < = $n } { incr l } { set r 0 for { set x 1 ; set y [ expr { $l - 1 } ] } { $y > = 0 } { incr x ; incr y - 1 } { lappend r [ expr { [ lindex $r end ] + [ lindex $cache $y [ expr { min ( $x , $y ) } ] ] } ] } lappend cache $r } return [ lindex $cache $n ] } proc row { n } { set r [ cumu $n ] for { set i 0 ; set j 1 } { $j < [ llength $r ] } { incr i ; incr j } { lappend result [ expr { [ lindex $r $j ] - [ lindex $r $i ] } ] } return $result }   puts "rows:" foreach x { 1 2 3 4 5 6 7 8 9 10 } { puts "${x}: \[ [join [row $x] {, }] \] " } puts " \n sums:" foreach x { 23 123 1234 12345 } { puts "${x}: [lindex [cumu $x] end]" } \ No newline at end of file diff --git a/rosetta/file10.clojure b/rosetta/file10.clojure new file mode 100644 index 0000000..de0274e --- /dev/null +++ b/rosetta/file10.clojure @@ -0,0 +1 @@ +( ns amb ( : use clojure . contrib . monads ) )   ( defn amb [ wss ] ( let [ valid - word ( fn [ w1 w2 ] ( if ( and w1 ( = ( last w1 ) ( first w2 ) ) ) ( str w1 " " w2 ) ) ) ] ( filter # ( reduce valid - word % ) ( with - monad sequence - m ( m - seq wss ) ) ) ) )   amb > ( amb ' ( ( "the" "that" "a" ) ( "frog" "elephant" "thing" ) ( "walked" "treaded" "grows" ) ( "slowly" "quickly" ) ) ) ( ( "that" "thing" "grows" "slowly" ) )   \ No newline at end of file diff --git a/rosetta/file10.hs b/rosetta/file10.hs new file mode 100644 index 0000000..264adbe --- /dev/null +++ b/rosetta/file10.hs @@ -0,0 +1 @@ +module Circle where   import Data . List   type Point = ( Int , Int )   -- Takes the center of the circle and radius, and returns the circle points generateCirclePoints :: Point -> Int -> [ Point ] generateCirclePoints ( x0 , y0 ) radius -- Four initial points, plus the generated points = ( x0 , y0 + radius )  : ( x0 , y0 - radius )  : ( x0 + radius , y0 )  : ( x0 - radius , y0 )  : points where -- Creates the (x, y) octet offsets, then maps them to absolute points in all octets. points = concatMap generatePoints $ unfoldr step initialValues generatePoints ( x , y ) = [ ( xop x0 x ', yop y0 y' ) | ( x ', y' ) <- [ ( x , y ) , ( y , x ) ] , xop <- [ ( + ) , ( - ) ] , yop <- [ ( + ) , ( - ) ] ]   -- The initial values for the loop initialValues = ( 1 - radius , 1 , ( - 2 ) * radius , 0 , radius )   -- One step of the loop. The loop itself stops at Nothing. step ( f , ddf _ x , ddf _ y , x , y ) | x >= y = Nothing | otherwise = Just ( ( x ', y' ) , ( f ', ddf_x' , ddf _ y ', x' , y ')) where (f' , ddf _ y ', y' ) | f >= 0 = ( f + ddf _ y ' + ddf_x' , ddf _ y + 2 , y - 1 ) | otherwise = ( f + ddf _ x , ddf _ y , y ) ddf _ x ' = ddf_x + 2 x' = x + 1   \ No newline at end of file diff --git a/rosetta/file10.java b/rosetta/file10.java new file mode 100644 index 0000000..6a792be --- /dev/null +++ b/rosetta/file10.java @@ -0,0 +1 @@ +import java.io.IOException ; import java.nio.charset.StandardCharsets ; import java.nio.file.Files ; import java.nio.file.Paths ; import java.util.ArrayList ; import java.util.List ;   import org.apache.commons.lang3.StringUtils ;   /** * Aligns fields into columns, separated by "|" */ public class ColumnAligner { private List < String [ ] > words = new ArrayList <> ( ) ; private int columns = 0 ; private List < Integer > columnWidths = new ArrayList <> ( ) ;   /** * Initialize columns aligner from lines in a single string * * @param s * lines in a single string. Empty string does form a column. */ public ColumnAligner ( String s ) { String [ ] lines = s. split ( " \\ n" ) ; for ( String line : lines ) { processInputLine ( line ) ; } }   /** * Initialize columns aligner from lines in a list of strings * * @param lines * lines in a single string. Empty string does form a column. */ public ColumnAligner ( List < String > lines ) { for ( String line : lines ) { processInputLine ( line ) ; } }   private void processInputLine ( String line ) { String [ ] lineWords = line. split ( " \\ $" ) ; words. add ( lineWords ) ; columns = Math . max ( columns, lineWords. length ) ; for ( int i = 0 ; i < lineWords. length ; i ++ ) { String word = lineWords [ i ] ; if ( i >= columnWidths. size ( ) ) { columnWidths. add ( word. length ( ) ) ; } else { columnWidths. set ( i, Math . max ( columnWidths. get ( i ) , word. length ( ) ) ) ; } } }   interface AlignFunction { String align ( String s, int length ) ; }   /** * Left-align all columns * * @return Lines, terminated by "\n" of columns, separated by "|" */ public String alignLeft ( ) { return align ( new AlignFunction ( ) { @Override public String align ( String s, int length ) { return StringUtils. rightPad ( s, length ) ; } } ) ; }   /** * Right-align all columns * * @return Lines, terminated by "\n" of columns, separated by "|" */ public String alignRight ( ) { return align ( new AlignFunction ( ) { @Override public String align ( String s, int length ) { return StringUtils. leftPad ( s, length ) ; } } ) ; }   /** * Center-align all columns * * @return Lines, terminated by "\n" of columns, separated by "|" */ public String alignCenter ( ) { return align ( new AlignFunction ( ) { @Override public String align ( String s, int length ) { return StringUtils. center ( s, length ) ; } } ) ; }   private String align ( AlignFunction a ) { StringBuilder result = new StringBuilder ( ) ; for ( String [ ] lineWords : words ) { for ( int i = 0 ; i < lineWords. length ; i ++ ) { String word = lineWords [ i ] ; if ( i == 0 ) { result. append ( "|" ) ; } result. append ( a. align ( word, columnWidths. get ( i ) ) + "|" ) ; } result. append ( " \n " ) ; } return result. toString ( ) ; }   public static void main ( String args [ ] ) throws IOException { if ( args. length < 1 ) { System . out . println ( "Usage: ColumnAligner file [left|right|center]" ) ; return ; } String filePath = args [ 0 ] ; String alignment = "left" ; if ( args. length >= 2 ) { alignment = args [ 1 ] ; } ColumnAligner ca = new ColumnAligner ( Files. readAllLines ( Paths. get ( filePath ) , StandardCharsets. UTF_8 ) ) ; switch ( alignment ) { case "left" : System . out . print ( ca. alignLeft ( ) ) ; break ; case "right" : System . out . print ( ca. alignRight ( ) ) ; break ; case "center" : System . out . print ( ca. alignCenter ( ) ) ; break ; default : System . err . println ( String . format ( "Error! Unknown alignment: '%s'" , alignment ) ) ; break ; } } } \ No newline at end of file diff --git a/rosetta/file10.js b/rosetta/file10.js new file mode 100644 index 0000000..c59aa4d --- /dev/null +++ b/rosetta/file10.js @@ -0,0 +1 @@ +function map ( a , func ) { var ret = [ ] ; for ( var i = 0 ; i < a. length ; i ++ ) { ret [ i ] = func ( a [ i ] ) ; } return ret ; }   map ( [ 1 , 2 , 3 , 4 , 5 ] , function ( v ) { return v * v ; } ) ; \ No newline at end of file diff --git a/rosetta/file10.ocaml b/rosetta/file10.ocaml new file mode 100644 index 0000000..32ac878 --- /dev/null +++ b/rosetta/file10.ocaml @@ -0,0 +1 @@ +let sort_chars s = let r = String . copy s in for i = 0 to ( String . length r ) - 2 do for j = i + 1 to ( String . length r ) - 1 do if r . [ i ] > r . [ j ] then begin let tmp = r . [ i ] in r . [ i ] <- r . [ j ] ; r . [ j ] <- tmp ; end done done ; ( r )   let deranged ( s1, s2 ) = let len1 = String . length s1 and len2 = String . length s2 in if len1 <> len2 then false else try for i = 0 to pred len1 do if s1 . [ i ] = s2 . [ i ] then raise Exit done ; true with Exit -> false   let pairs_of_list lst = let rec aux acc = function | [ ] -> acc | x :: xs -> aux ( List . fold_left ( fun acc y -> ( x,y ) :: acc ) acc xs ) xs in aux [ ] lst   let ( ) = let h = Hashtbl . create 3571 in let ic = open_in "unixdict.txt" in try while true do let word = input_line ic in let key = sort_chars word in let l = try Hashtbl . find h key with Not_found -> [ ] in Hashtbl . replace h key ( word :: l ) ; done with End_of_file -> close_in ic ; let lst = Hashtbl . fold ( fun _ lw acc -> if List . length lw < 2 then acc else lw :: acc ) h [ ] in let lst = List . fold_left ( fun acc anagrams -> let pairs = pairs_of_list anagrams in ( List . filter deranged pairs ) @ acc ) [ ] lst in let res, _ = List . fold_left ( fun ( res, n ) ( w1, w2 ) -> let len = String . length w1 in match Pervasives . compare len n with | 0 -> ( ( w1, w2 ) :: res, n ) | 1 -> ( [ w1, w2 ] , len ) | _ -> ( res, n ) ) ( [ ] , 0 ) lst in List . iter ( fun ( w1, w2 ) -> Printf . printf "%s, %s\n" w1 w2 ) res \ No newline at end of file diff --git a/rosetta/file10.perl b/rosetta/file10.perl new file mode 100644 index 0000000..04fb642 --- /dev/null +++ b/rosetta/file10.perl @@ -0,0 +1 @@ +#! /usr/bin/perl   use strict ; use Image :: Imlib2 ;   my $img = Image :: Imlib2 -> load ( "Unfilledcirc.jpg" ) ; $img -> set_color ( 0 , 255 , 0 , 255 ) ; $img -> fill ( 100 , 100 ) ; $img -> save ( "filledcirc.jpg" ) ; exit 0 ; \ No newline at end of file diff --git a/rosetta/file10.php b/rosetta/file10.php new file mode 100644 index 0000000..729cd3e --- /dev/null +++ b/rosetta/file10.php @@ -0,0 +1 @@ + STR_PAD_RIGHT , 'R' => STR_PAD_LEFT , 'C' => STR_PAD_BOTH ) ;   /** Justify columns of textual tabular input where the record separator is the newline and the field separator is a 'dollar' character. justification can be L, R, or C; (Left, Right, or Centered).   Return the justified output as a string */ function aligner ( $str , $justification = 'L' ) { global $j2justtype ; assert ( array_key_exists ( $justification , $j2justtype ) ) ; $justtype = $j2justtype [ $justification ] ;   $fieldsbyrow = array ( ) ; foreach ( explode ( " \n " , $str ) as $line ) $fieldsbyrow [ ] = explode ( '$' , $line ) ; $maxfields = max ( array_map ( 'count' , $fieldsbyrow ) ) ;   foreach ( range ( 0 , $maxfields - 1 ) as $col ) { $maxwidth = 0 ; foreach ( $fieldsbyrow as $fields ) $maxwidth = max ( $maxwidth , strlen ( $fields [ $col ] ) ) ; foreach ( $fieldsbyrow as & $fields ) $fields [ $col ] = str_pad ( $fields [ $col ] , $maxwidth , ' ' , $justtype ) ; unset ( $fields ) ; // see http://bugs.php.net/29992 } $result = '' ; foreach ( $fieldsbyrow as $fields ) $result .= implode ( ' ' , $fields ) . " \n " ; return $result ; }   $textinfile = '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 ( array ( 'L' , 'R' , 'C' ) as $j ) echo aligner ( $textinfile , $j ) ;   ?> \ No newline at end of file diff --git a/rosetta/file10.py b/rosetta/file10.py new file mode 100644 index 0000000..efbd517 --- /dev/null +++ b/rosetta/file10.py @@ -0,0 +1 @@ +class MyClass ( object ) : @ classmethod def myClassMethod ( self , x ) : pass @ staticmethod def myStaticMethod ( x ) : pass def myMethod ( self , x ) : return 42 + x   myInstance = MyClass ( )   # Instance method myInstance. myMethod ( someParameter ) # A method can also be retrieved as an attribute from the class, and then explicitly called on an instance: MyClass. myMethod ( myInstance , someParameter )     # Class or static methods MyClass. myClassMethod ( someParameter ) MyClass. myStaticMethod ( someParameter ) # You can also call class or static methods on an instance, which will simply call it on the instance's class myInstance. myClassMethod ( someParameter ) myInstance. myStaticMethod ( someParameter ) \ No newline at end of file diff --git a/rosetta/file10.rb b/rosetta/file10.rb new file mode 100644 index 0000000..a5de4dd --- /dev/null +++ b/rosetta/file10.rb @@ -0,0 +1 @@ +require 'gserver'   class ChatServer < GServer def initialize * args super   #Keep a list for broadcasting messages @chatters = [ ]   #We'll need this for thread safety @mutex = Mutex . new end   #Send message out to everyone but sender def broadcast message, sender = nil #Need to use \r\n for our Windows friends message = message. strip << " \r \n "   #Mutex for safety - GServer uses threads @mutex . synchronize do @chatters . each do | chatter | begin chatter. print message unless chatter == sender rescue @chatters . delete chatter end end end end   #Handle each connection def serve io io. print 'Name: ' name = io. gets   #They might disconnect return if name. nil ?   name. strip !   broadcast "--+ #{name} has joined +--"   #Add to our list of connections @mutex . synchronize do @chatters << io end   #Get and broadcast input until connection returns nil loop do message = io. gets   if message broadcast "#{name}> #{message}" , io else break end end   broadcast "--+ #{name} has left +--" end end   #Start up the server on port 7000 #Accept connections for any IP address #Allow up to 100 connections #Send information to stderr #Turn on informational messages ChatServer. new ( 7000 , '0.0.0.0' , 100 , $stderr , true ) . start . join   \ No newline at end of file diff --git a/rosetta/file10.scala b/rosetta/file10.scala new file mode 100644 index 0000000..e1e346f --- /dev/null +++ b/rosetta/file10.scala @@ -0,0 +1 @@ +def binarySearch [ A <% Ordered [ A ] ] ( a : IndexedSeq [ A ] , v : A ) = { def recurse ( low : Int, high : Int ) : Option [ Int ] = ( low + high ) / 2 match { case _ if high < low => None case mid if a ( mid ) > v => recurse ( low, mid - 1 ) case mid if a ( mid ) < v => recurse ( mid + 1 , high ) case mid => Some ( mid ) } recurse ( 0 , a. size - 1 ) } \ No newline at end of file diff --git a/rosetta/file10.ss b/rosetta/file10.ss new file mode 100644 index 0000000..c506a9b --- /dev/null +++ b/rosetta/file10.ss @@ -0,0 +1 @@ +( define ( A m n ) ( cond ( ( = m 0 ) ( + n 1 ) ) ( ( = n 0 ) ( A ( - m 1 ) 1 ) ) ( else ( A ( - m 1 ) ( A m ( - n 1 ) ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file10.tcl b/rosetta/file10.tcl new file mode 100644 index 0000000..979f66d --- /dev/null +++ b/rosetta/file10.tcl @@ -0,0 +1 @@ +package require Tcl 8.5 package require fileutil   # Parameters to the replacement set from "Goodbye London!" set to "Hello New York!" # Which files to replace set fileList [ list a.txt b.txt c.txt ]   # Make a command fragment that performs the replacement on a supplied string set replacementCmd [ list string map [ list $from $to ] ] # Apply the replacement to the contents of each file foreach filename $fileList { fileutil:: updateInPlace $filename $replacementCmd } \ No newline at end of file diff --git a/rosetta/file11.clojure b/rosetta/file11.clojure new file mode 100644 index 0000000..82f9603 --- /dev/null +++ b/rosetta/file11.clojure @@ -0,0 +1 @@ +  ( defn fib [ n ] ( when ( neg? n ) ( throw ( new IllegalArgumentException "n should be > 0" ) ) ) ( loop [ n n, v1 1 , v2 1 ] ( if ( < n 2 ) v2 ( recur ( dec n ) v2 ( + v1 v2 ) ) ) ) )   \ No newline at end of file diff --git a/rosetta/file11.hs b/rosetta/file11.hs new file mode 100644 index 0000000..65b106f --- /dev/null +++ b/rosetta/file11.hs @@ -0,0 +1 @@ +import Bitmap import Bitmap . RGB import Bitmap . Gray import Bitmap . Netpbm   import Control . Monad import Control . Monad . ST   main = ( readNetpbm "original.ppm" :: IO ( Image RealWorld RGB ) ) >>= stToIO . toGrayImage >>= writeNetpbm "new.pgm" \ No newline at end of file diff --git a/rosetta/file11.java b/rosetta/file11.java new file mode 100644 index 0000000..6a792be --- /dev/null +++ b/rosetta/file11.java @@ -0,0 +1 @@ +import java.io.IOException ; import java.nio.charset.StandardCharsets ; import java.nio.file.Files ; import java.nio.file.Paths ; import java.util.ArrayList ; import java.util.List ;   import org.apache.commons.lang3.StringUtils ;   /** * Aligns fields into columns, separated by "|" */ public class ColumnAligner { private List < String [ ] > words = new ArrayList <> ( ) ; private int columns = 0 ; private List < Integer > columnWidths = new ArrayList <> ( ) ;   /** * Initialize columns aligner from lines in a single string * * @param s * lines in a single string. Empty string does form a column. */ public ColumnAligner ( String s ) { String [ ] lines = s. split ( " \\ n" ) ; for ( String line : lines ) { processInputLine ( line ) ; } }   /** * Initialize columns aligner from lines in a list of strings * * @param lines * lines in a single string. Empty string does form a column. */ public ColumnAligner ( List < String > lines ) { for ( String line : lines ) { processInputLine ( line ) ; } }   private void processInputLine ( String line ) { String [ ] lineWords = line. split ( " \\ $" ) ; words. add ( lineWords ) ; columns = Math . max ( columns, lineWords. length ) ; for ( int i = 0 ; i < lineWords. length ; i ++ ) { String word = lineWords [ i ] ; if ( i >= columnWidths. size ( ) ) { columnWidths. add ( word. length ( ) ) ; } else { columnWidths. set ( i, Math . max ( columnWidths. get ( i ) , word. length ( ) ) ) ; } } }   interface AlignFunction { String align ( String s, int length ) ; }   /** * Left-align all columns * * @return Lines, terminated by "\n" of columns, separated by "|" */ public String alignLeft ( ) { return align ( new AlignFunction ( ) { @Override public String align ( String s, int length ) { return StringUtils. rightPad ( s, length ) ; } } ) ; }   /** * Right-align all columns * * @return Lines, terminated by "\n" of columns, separated by "|" */ public String alignRight ( ) { return align ( new AlignFunction ( ) { @Override public String align ( String s, int length ) { return StringUtils. leftPad ( s, length ) ; } } ) ; }   /** * Center-align all columns * * @return Lines, terminated by "\n" of columns, separated by "|" */ public String alignCenter ( ) { return align ( new AlignFunction ( ) { @Override public String align ( String s, int length ) { return StringUtils. center ( s, length ) ; } } ) ; }   private String align ( AlignFunction a ) { StringBuilder result = new StringBuilder ( ) ; for ( String [ ] lineWords : words ) { for ( int i = 0 ; i < lineWords. length ; i ++ ) { String word = lineWords [ i ] ; if ( i == 0 ) { result. append ( "|" ) ; } result. append ( a. align ( word, columnWidths. get ( i ) ) + "|" ) ; } result. append ( " \n " ) ; } return result. toString ( ) ; }   public static void main ( String args [ ] ) throws IOException { if ( args. length < 1 ) { System . out . println ( "Usage: ColumnAligner file [left|right|center]" ) ; return ; } String filePath = args [ 0 ] ; String alignment = "left" ; if ( args. length >= 2 ) { alignment = args [ 1 ] ; } ColumnAligner ca = new ColumnAligner ( Files. readAllLines ( Paths. get ( filePath ) , StandardCharsets. UTF_8 ) ) ; switch ( alignment ) { case "left" : System . out . print ( ca. alignLeft ( ) ) ; break ; case "right" : System . out . print ( ca. alignRight ( ) ) ; break ; case "center" : System . out . print ( ca. alignCenter ( ) ) ; break ; default : System . err . println ( String . format ( "Error! Unknown alignment: '%s'" , alignment ) ) ; break ; } } } \ No newline at end of file diff --git a/rosetta/file11.js b/rosetta/file11.js new file mode 100644 index 0000000..c59aa4d --- /dev/null +++ b/rosetta/file11.js @@ -0,0 +1 @@ +function map ( a , func ) { var ret = [ ] ; for ( var i = 0 ; i < a. length ; i ++ ) { ret [ i ] = func ( a [ i ] ) ; } return ret ; }   map ( [ 1 , 2 , 3 , 4 , 5 ] , function ( v ) { return v * v ; } ) ; \ No newline at end of file diff --git a/rosetta/file11.ocaml b/rosetta/file11.ocaml new file mode 100644 index 0000000..3c6d93a --- /dev/null +++ b/rosetta/file11.ocaml @@ -0,0 +1 @@ +let fib n = let rec real = function 0 -> 1 | 1 -> 1 | n -> real ( n - 1 ) + real ( n - 2 ) in if n < 0 then None else Some ( real n ) \ No newline at end of file diff --git a/rosetta/file11.perl b/rosetta/file11.perl new file mode 100644 index 0000000..678838c --- /dev/null +++ b/rosetta/file11.perl @@ -0,0 +1 @@ +#! /usr/bin/perl   use strict ; use Image :: Imlib2 ;   my $img = Image :: Imlib2 -> load ( "out0.ppm" ) ;   # let's do something with it now $img -> set_color ( 255 , 255 , 255 , 255 ) ; $img -> draw_line ( 0 , 0 , $img -> width , $img -> height ) ; $img -> image_set_format ( "png" ) ; $img -> save ( "out1.png" ) ;   exit 0 ; \ No newline at end of file diff --git a/rosetta/file11.php b/rosetta/file11.php new file mode 100644 index 0000000..f7d0609 --- /dev/null +++ b/rosetta/file11.php @@ -0,0 +1 @@ += 2 ) { $counts = array ( ) ; foreach ( $words as $word ) { $counts [ $word ] = array ( $word ) ; foreach ( $words as $second_word ) { for ( $i = 0 , $length = strlen ( $word ) ; $i < $length ; $i ++ ) { if ( $word [ $i ] === $second_word [ $i ] ) continue 2 ; } $counts [ $word ] [ ] = $second_word ; } } $max = 0 ; $max_key = '' ; foreach ( $counts as $name => $count ) { if ( count ( $count ) > $max ) { $max = count ( $count ) ; $max_key = $name ; } } if ( $max > 1 ) { $final_words [ ] = $counts [ $max_key ] ; } } } if ( $final_words ) break ; }   foreach ( $final_words as $final_word ) { echo implode ( " " , $final_word ) , " \n " ; } ?> \ No newline at end of file diff --git a/rosetta/file11.py b/rosetta/file11.py new file mode 100644 index 0000000..fc329f3 --- /dev/null +++ b/rosetta/file11.py @@ -0,0 +1 @@ +>>> from operator import add >>> listoflists = [ [ 'the' , 'cat' ] , [ 'sat' , 'on' ] , [ 'the' , 'mat' ] ] >>> help ( reduce ) Help on built- in function reduce in module __builtin__ :   reduce ( ... ) reduce ( function , sequence [ , initial ] ) - > value   Apply a function of two arguments cumulatively to the items of a sequence , from left to right , so as to reduce the sequence to a single value. For example , reduce ( lambda x , y: x+y , [ 1 , 2 , 3 , 4 , 5 ] ) calculates ( ( ( ( 1 + 2 ) + 3 ) + 4 ) + 5 ) . If initial is present , it is placed before the items of the sequence in the calculation , and serves as a default when the sequence is empty.   >>> reduce ( add , listoflists , [ ] ) [ 'the' , 'cat' , 'sat' , 'on' , 'the' , 'mat' ] >>> \ No newline at end of file diff --git a/rosetta/file11.rb b/rosetta/file11.rb new file mode 100644 index 0000000..28ddeaf --- /dev/null +++ b/rosetta/file11.rb @@ -0,0 +1 @@ +module Screen IMPORT_COMMAND = '/usr/bin/import'   # Returns an array with RGB values for the pixel at the given coords def self . pixel ( x, y ) if m = `#{IMPORT_COMMAND} -silent -window root -crop 1x1+#{x.to_i}+#{y.to_i} -depth 8 txt:-` . match ( / \ ( ( \d + ) , ( \d + ) , ( \d + ) \ ) / ) m [ 1 .. 3 ] . map ( & :to_i ) else false end end end \ No newline at end of file diff --git a/rosetta/file11.scala b/rosetta/file11.scala new file mode 100644 index 0000000..e1e346f --- /dev/null +++ b/rosetta/file11.scala @@ -0,0 +1 @@ +def binarySearch [ A <% Ordered [ A ] ] ( a : IndexedSeq [ A ] , v : A ) = { def recurse ( low : Int, high : Int ) : Option [ Int ] = ( low + high ) / 2 match { case _ if high < low => None case mid if a ( mid ) > v => recurse ( low, mid - 1 ) case mid if a ( mid ) < v => recurse ( mid + 1 , high ) case mid => Some ( mid ) } recurse ( 0 , a. size - 1 ) } \ No newline at end of file diff --git a/rosetta/file11.ss b/rosetta/file11.ss new file mode 100644 index 0000000..c506a9b --- /dev/null +++ b/rosetta/file11.ss @@ -0,0 +1 @@ +( define ( A m n ) ( cond ( ( = m 0 ) ( + n 1 ) ) ( ( = n 0 ) ( A ( - m 1 ) 1 ) ) ( else ( A ( - m 1 ) ( A m ( - n 1 ) ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file11.tcl b/rosetta/file11.tcl new file mode 100644 index 0000000..c6c8ee0 --- /dev/null +++ b/rosetta/file11.tcl @@ -0,0 +1 @@ +set hereDocExample { In Tcl, the { curly brace } notation is strictly a here-document style notation as it permits arbitrary content inside it * except * for an unbalanced brace. That is typically not a problem as seen in reality, as almost all content that might be placed in a here-doc is either brace-free or balanced. The content of the braces is not interpreted at all ; no substitutions are performed on it.   The sole exception is that there is limited processing of backslashes ; a single backslash at the end of a line causes the end-of-line plus all whitespace at the start of the next line to be compressed to a single space. } \ No newline at end of file diff --git a/rosetta/file12.clojure b/rosetta/file12.clojure new file mode 100644 index 0000000..82f9603 --- /dev/null +++ b/rosetta/file12.clojure @@ -0,0 +1 @@ +  ( defn fib [ n ] ( when ( neg? n ) ( throw ( new IllegalArgumentException "n should be > 0" ) ) ) ( loop [ n n, v1 1 , v2 1 ] ( if ( < n 2 ) v2 ( recur ( dec n ) v2 ( + v1 v2 ) ) ) ) )   \ No newline at end of file diff --git a/rosetta/file12.hs b/rosetta/file12.hs new file mode 100644 index 0000000..7c4df18 --- /dev/null +++ b/rosetta/file12.hs @@ -0,0 +1 @@ +  import Data . Char import Data . Maybe import Text . Printf   dirs = [ "N" , "NbE" , "N-NE" , "NEbN" , "NE" , "NEbE" , "E-NE" , "EbN" , "E" , "EbS" , "E-SE" , "SEbE" , "SE" , "SEbS" , "S-SE" , "SbE" , "S" , "SbW" , "S-SW" , "SWbS" , "SW" , "SWbW" , "W-SW" , "WbS" , "W" , "WbN" , "W-NW" , "NWbW" , "NW" , "NWbN" , "N-NW" , "NbW" ]   -- Given an index between 0 and 31 return the corresponding compass point name. pointName = capitalize . concatMap ( fromMaybe "?" . fromChar ) . ( dirs !! ) where fromChar c = lookup c [ ( 'N' , "north" ) , ( 'S' , "south" ) , ( 'E' , "east" ) , ( 'W' , "west" ) , ( 'b' , " by " ) , ( '-' , "-" ) ] capitalize ( c:cs ) = toUpper c : cs   -- Convert degrees to a compass point index between 0 and 31. pointIndex d = ( round ( d * 1000 ) + 5625 ) ` mod ` 360000 ` div ` 11250   printPointName d = let deg = read d :: Double idx = pointIndex deg in printf "%2d  %-18s  %6.2f° \n " ( idx + 1 ) ( pointName idx ) deg   main = do input <- getContents mapM_ printPointName $ lines input   \ No newline at end of file diff --git a/rosetta/file12.java b/rosetta/file12.java new file mode 100644 index 0000000..6a792be --- /dev/null +++ b/rosetta/file12.java @@ -0,0 +1 @@ +import java.io.IOException ; import java.nio.charset.StandardCharsets ; import java.nio.file.Files ; import java.nio.file.Paths ; import java.util.ArrayList ; import java.util.List ;   import org.apache.commons.lang3.StringUtils ;   /** * Aligns fields into columns, separated by "|" */ public class ColumnAligner { private List < String [ ] > words = new ArrayList <> ( ) ; private int columns = 0 ; private List < Integer > columnWidths = new ArrayList <> ( ) ;   /** * Initialize columns aligner from lines in a single string * * @param s * lines in a single string. Empty string does form a column. */ public ColumnAligner ( String s ) { String [ ] lines = s. split ( " \\ n" ) ; for ( String line : lines ) { processInputLine ( line ) ; } }   /** * Initialize columns aligner from lines in a list of strings * * @param lines * lines in a single string. Empty string does form a column. */ public ColumnAligner ( List < String > lines ) { for ( String line : lines ) { processInputLine ( line ) ; } }   private void processInputLine ( String line ) { String [ ] lineWords = line. split ( " \\ $" ) ; words. add ( lineWords ) ; columns = Math . max ( columns, lineWords. length ) ; for ( int i = 0 ; i < lineWords. length ; i ++ ) { String word = lineWords [ i ] ; if ( i >= columnWidths. size ( ) ) { columnWidths. add ( word. length ( ) ) ; } else { columnWidths. set ( i, Math . max ( columnWidths. get ( i ) , word. length ( ) ) ) ; } } }   interface AlignFunction { String align ( String s, int length ) ; }   /** * Left-align all columns * * @return Lines, terminated by "\n" of columns, separated by "|" */ public String alignLeft ( ) { return align ( new AlignFunction ( ) { @Override public String align ( String s, int length ) { return StringUtils. rightPad ( s, length ) ; } } ) ; }   /** * Right-align all columns * * @return Lines, terminated by "\n" of columns, separated by "|" */ public String alignRight ( ) { return align ( new AlignFunction ( ) { @Override public String align ( String s, int length ) { return StringUtils. leftPad ( s, length ) ; } } ) ; }   /** * Center-align all columns * * @return Lines, terminated by "\n" of columns, separated by "|" */ public String alignCenter ( ) { return align ( new AlignFunction ( ) { @Override public String align ( String s, int length ) { return StringUtils. center ( s, length ) ; } } ) ; }   private String align ( AlignFunction a ) { StringBuilder result = new StringBuilder ( ) ; for ( String [ ] lineWords : words ) { for ( int i = 0 ; i < lineWords. length ; i ++ ) { String word = lineWords [ i ] ; if ( i == 0 ) { result. append ( "|" ) ; } result. append ( a. align ( word, columnWidths. get ( i ) ) + "|" ) ; } result. append ( " \n " ) ; } return result. toString ( ) ; }   public static void main ( String args [ ] ) throws IOException { if ( args. length < 1 ) { System . out . println ( "Usage: ColumnAligner file [left|right|center]" ) ; return ; } String filePath = args [ 0 ] ; String alignment = "left" ; if ( args. length >= 2 ) { alignment = args [ 1 ] ; } ColumnAligner ca = new ColumnAligner ( Files. readAllLines ( Paths. get ( filePath ) , StandardCharsets. UTF_8 ) ) ; switch ( alignment ) { case "left" : System . out . print ( ca. alignLeft ( ) ) ; break ; case "right" : System . out . print ( ca. alignRight ( ) ) ; break ; case "center" : System . out . print ( ca. alignCenter ( ) ) ; break ; default : System . err . println ( String . format ( "Error! Unknown alignment: '%s'" , alignment ) ) ; break ; } } } \ No newline at end of file diff --git a/rosetta/file12.js b/rosetta/file12.js new file mode 100644 index 0000000..79e4539 --- /dev/null +++ b/rosetta/file12.js @@ -0,0 +1 @@ +function agm ( a0 , g0 ) { var an = ( a0 + g0 ) / 2 , gn = Math . sqrt ( a0 * g0 ) ; while ( Math . abs ( an - gn ) > tolerance ) { an = ( an + gn ) / 2 , gn = Math . sqrt ( an * gn ) } return an ; }   agm ( 1 , 1 / Math . sqrt ( 2 ) ) ; \ No newline at end of file diff --git a/rosetta/file12.ocaml b/rosetta/file12.ocaml new file mode 100644 index 0000000..c58fee1 --- /dev/null +++ b/rosetta/file12.ocaml @@ -0,0 +1 @@ +open Num open Str open String   let ( ) = let answer = ( Int 5 ) **/ ( Int 4 ) **/ ( Int 3 ) **/ ( Int 2 ) in let answer_string = string_of_num answer in Printf . printf "has %d digits: %s ... %s\n" ( length answer_string ) ( first_chars answer_string 20 ) ( last_chars answer_string 20 ) \ No newline at end of file diff --git a/rosetta/file12.perl b/rosetta/file12.perl new file mode 100644 index 0000000..4a3f94a --- /dev/null +++ b/rosetta/file12.perl @@ -0,0 +1 @@ +use utf8 ;   my @names = ( "North" , "North by east" , "North-northeast" , "Northeast by north" , "Northeast" , "Northeast by east" , "East-northeast" , "East by north" , "East" , "East by south" , "East-southeast" , "Southeast by east" , "Southeast" , "Southeast by south" , "South-southeast" , "South by east" , "South" , "South by west" , "South-southwest" , "Southwest by south" , "Southwest" , "Southwest by west" , "West-southwest" , "West by south" , "West" , "West by north" , "West-northwest" , "Northwest by west" , "Northwest" , "Northwest by north" , "North-northwest" , "North by west" , ) ; my @angles = ( 0.0 , 16.87 , 16.88 , 33.75 , 50.62 , 50.63 , 67.5 , 84.37 , 84.38 , 101.25 , 118.12 , 118.13 , 135.0 , 151.87 , 151.88 , 168.75 , 185.62 , 185.63 , 202.5 , 219.37 , 219.38 , 236.25 , 253.12 , 253.13 , 270.0 , 286.87 , 286.88 , 303.75 , 320.62 , 320.63 , 337.5 , 354.37 , 354.38 ) ;   for ( @angles ) { my $i = int ( ( $_ * 32 / 360 ) + . 5 ) % 32 ; printf "%3d %18s %6.2f° \n " , $i + 1 , $names [ $i ] , $_ ; } \ No newline at end of file diff --git a/rosetta/file12.php b/rosetta/file12.php new file mode 100644 index 0000000..f7d0609 --- /dev/null +++ b/rosetta/file12.php @@ -0,0 +1 @@ += 2 ) { $counts = array ( ) ; foreach ( $words as $word ) { $counts [ $word ] = array ( $word ) ; foreach ( $words as $second_word ) { for ( $i = 0 , $length = strlen ( $word ) ; $i < $length ; $i ++ ) { if ( $word [ $i ] === $second_word [ $i ] ) continue 2 ; } $counts [ $word ] [ ] = $second_word ; } } $max = 0 ; $max_key = '' ; foreach ( $counts as $name => $count ) { if ( count ( $count ) > $max ) { $max = count ( $count ) ; $max_key = $name ; } } if ( $max > 1 ) { $final_words [ ] = $counts [ $max_key ] ; } } } if ( $final_words ) break ; }   foreach ( $final_words as $final_word ) { echo implode ( " " , $final_word ) , " \n " ; } ?> \ No newline at end of file diff --git a/rosetta/file12.py b/rosetta/file12.py new file mode 100644 index 0000000..30cace0 --- /dev/null +++ b/rosetta/file12.py @@ -0,0 +1 @@ +import os   os . path . exists ( "input.txt" ) os . path . exists ( "/input.txt" ) os . path . exists ( "docs" ) os . path . exists ( "/docs" ) \ No newline at end of file diff --git a/rosetta/file12.rb b/rosetta/file12.rb new file mode 100644 index 0000000..28ddeaf --- /dev/null +++ b/rosetta/file12.rb @@ -0,0 +1 @@ +module Screen IMPORT_COMMAND = '/usr/bin/import'   # Returns an array with RGB values for the pixel at the given coords def self . pixel ( x, y ) if m = `#{IMPORT_COMMAND} -silent -window root -crop 1x1+#{x.to_i}+#{y.to_i} -depth 8 txt:-` . match ( / \ ( ( \d + ) , ( \d + ) , ( \d + ) \ ) / ) m [ 1 .. 3 ] . map ( & :to_i ) else false end end end \ No newline at end of file diff --git a/rosetta/file12.scala b/rosetta/file12.scala new file mode 100644 index 0000000..9ebae98 --- /dev/null +++ b/rosetta/file12.scala @@ -0,0 +1 @@ +object BitmapOps { def bresenham ( bm : RgbBitmap, x0 : Int, y0 : Int, x1 : Int, y1 : Int, c : Color ) = { val dx = math. abs ( x1-x0 ) val sx = if ( x0 < x1 ) 1 else - 1 val dy = math. abs ( y1-y0 ) val sy = if ( y0 < y1 ) 1 else - 1   def it = new Iterator [ Tuple2 [ Int,Int ] ] { var x = x0 ; var y = y0 var err = ( if ( dx > dy ) dx else -dy ) / 2 def next = { val res = ( x,y ) val e2 = err ; if ( e2 > -dx ) { err- = dy ; x+ = sx } if ( e2 < dy ) { err+ = dx ; y+ = sy } res ; } def hasNext = ( x <= x1 && y <= y1 ) }   for ( ( x,y ) < - it ) bm. setPixel ( x, y, c ) } } \ No newline at end of file diff --git a/rosetta/file12.ss b/rosetta/file12.ss new file mode 100644 index 0000000..c506a9b --- /dev/null +++ b/rosetta/file12.ss @@ -0,0 +1 @@ +( define ( A m n ) ( cond ( ( = m 0 ) ( + n 1 ) ) ( ( = n 0 ) ( A ( - m 1 ) 1 ) ) ( else ( A ( - m 1 ) ( A m ( - n 1 ) ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file12.tcl b/rosetta/file12.tcl new file mode 100644 index 0000000..e77afed --- /dev/null +++ b/rosetta/file12.tcl @@ -0,0 +1 @@ +set hname [ info hostname ] \ No newline at end of file diff --git a/rosetta/file13.clojure b/rosetta/file13.clojure new file mode 100644 index 0000000..57e0083 --- /dev/null +++ b/rosetta/file13.clojure @@ -0,0 +1 @@ +( defn exp [ n k ] ( reduce * ( repeat k n ) ) )   ( def big ( ->> 2 ( exp 3 ) ( exp 4 ) ( exp 5 ) ) ) ( def sbig ( str big ) )   ( assert ( = "62060698786608744707" ( . substring sbig 0 20 ) ) ) ( assert ( = "92256259918212890625" ( . substring sbig ( - ( count sbig ) 20 ) ) ) ) ( println ( count sbig ) "digits" )   ( println ( str ( . substring sbig 0 20 ) ".." ( . substring sbig ( - ( count sbig ) 20 ) ) ) ( str "(" ( count sbig ) " digits)" ) ) \ No newline at end of file diff --git a/rosetta/file13.hs b/rosetta/file13.hs new file mode 100644 index 0000000..ddc1fae --- /dev/null +++ b/rosetta/file13.hs @@ -0,0 +1 @@ +import qualified Data . Text as T import Data . Time import Data . Time . Calendar import Data . Time . Calendar . WeekDate import Data . List . Split ( chunksOf ) import Data . List   data Day = Su | Mo | Tu | We | Th | Fr | Sa deriving ( Show , Eq , Ord , Enum )   data Month = January | February | March | April | May | June | July | August | September | October | November | December deriving ( Show , Eq , Ord , Enum )   monthToInt :: Month -> Int monthToInt = ( + 1 ) . fromEnum   dayFromDate :: Integer -> Month -> Int -> Int dayFromDate year month day = day ' `mod` 7 where (_, _, day' ) = toWeekDate $ fromGregorian year ( monthToInt month ) day   nSpaces :: Int -> T . Text nSpaces n = T . replicate n ( T . pack " " )   space :: T . Text space = nSpaces 1   calMarginWidth = 3   calMargin :: T . Text calMargin = nSpaces calMarginWidth   calWidth = 20   listMonth :: Integer -> Month -> [ T . Text ] listMonth year month = [ monthHeader , weekHeader ] ++ weeks ' where monthHeader = (T.center calWidth ' ') . T.pack $ show month   weekHeader = (T.intercalate space) $ map (T.pack . show) [(Su)..]   monthLength = toInteger $ gregorianMonthLength year $ monthToInt month   firstDay = dayFromDate year month 1   days = replicate firstDay (nSpaces 2) ++ map ((T.justifyRight 2 ' ') . T.pack . show) [1..monthLength]   weeks = map (T.justifyLeft calWidth ' ') $ map (T.intercalate space) $ chunksOf 7 days   weeks' = weeks ++ replicate ( 6 - length weeks ) ( nSpaces calWidth )   listCalendar :: Integer -> Int -> [ [ [ T . Text ] ] ] listCalendar year calColumns = ( chunksOf calColumns ) . ( map ( listMonth year ) ) $ enumFrom January   calColFromCol :: Int -> Int calColFromCol columns = c + if r >= calWidth then 1 else 0 where ( c , r ) = columns ` divMod ` ( calWidth + calMarginWidth )   colFromCalCol :: Int -> Int colFromCalCol calCol = calCol * calWidth + ( ( calCol - 1 ) * calMarginWidth )   center :: Int -> String -> String center i a = T . unpack . ( T . center i ' ' ) $ T . pack a   printCal :: [ [ [ T . Text ] ] ] -> IO ( ) printCal [ ] = return ( ) printCal ( c:cx ) = do mapM_ ( putStrLn . T . unpack ) rows printCal cx where rows = map ( T . intercalate calMargin ) $ transpose c   printCalendar :: Integer -> Int -> IO ( ) printCalendar year columns = if columns < 20 then putStrLn $ "Cannot print less than 20 columns" else do putStrLn $ center columns ' "[Maybe Snoopy]" putStrLn $ center columns' $ show year putStrLn "" printCal $ listCalendar year calcol ' where calcol' = calColFromCol columns   columns ' = colFromCalCol calcol' \ No newline at end of file diff --git a/rosetta/file13.java b/rosetta/file13.java new file mode 100644 index 0000000..6a5d6f4 --- /dev/null +++ b/rosetta/file13.java @@ -0,0 +1 @@ +import java.math.BigInteger ;   class Program { public static void main ( String [ ] args ) { BigInteger x = BigInteger . valueOf ( 5 ) . pow ( BigInteger . valueOf ( 4 ) . pow ( BigInteger . valueOf ( 3 ) . pow ( 2 ) . intValue ( ) ) . intValue ( ) ) ; String y = x. toString ( ) ; int l = y. length ( ) ; System . out . printf ( "5**4**3**2 = %s...%s and has %d digits \n " , y. substring ( 0 , 20 ) , y. substring ( l - 20 ) , l ) ; } } \ No newline at end of file diff --git a/rosetta/file13.js b/rosetta/file13.js new file mode 100644 index 0000000..4a51e18 --- /dev/null +++ b/rosetta/file13.js @@ -0,0 +1 @@ +// Create a new array with length 0 var myArray = new Array ( ) ;   // Create a new array with length 5 var myArray1 = new Array ( 5 ) ;   // Create an array with 2 members (length is 2) var myArray2 = new Array ( "Item1" , "Item2" ) ;   // Create an array with 2 members using an array literal var myArray3 = [ "Item1" , "Item2" ] ;   // Assign a value to member [2] (length is now 3) myArray [ 2 ] = 5 ;   var x = myArray [ 2 ] + myArray. length ; // 8   // Elisions are supported, but are buggy in some implementations var y = [ 0 , 1 ,, ] ; // length 3, or 4 in buggy implementations   \ No newline at end of file diff --git a/rosetta/file13.ocaml b/rosetta/file13.ocaml new file mode 100644 index 0000000..2139187 --- /dev/null +++ b/rosetta/file13.ocaml @@ -0,0 +1 @@ +let rec agm a g tol = if tol > abs_float ( a -. g ) then a else agm ( 0.5 *. ( a +. g ) ) ( sqrt ( a *. g ) ) tol   let _ = Printf . printf "%.16f\n" ( agm 1.0 ( sqrt 0.5 ) 1e - 15 ) \ No newline at end of file diff --git a/rosetta/file13.perl b/rosetta/file13.perl new file mode 100644 index 0000000..ebfaeeb --- /dev/null +++ b/rosetta/file13.perl @@ -0,0 +1 @@ +foo ( ) ; # Call foo on the null list &foo ( ) ; # Ditto foo ( $arg1 , $arg2 ) ; # Call foo on $arg1 and $arg2 &foo ( $arg1 , $arg2 ) ; # Ditto; ignores prototypes \ No newline at end of file diff --git a/rosetta/file13.php b/rosetta/file13.php new file mode 100644 index 0000000..1c03a2b --- /dev/null +++ b/rosetta/file13.php @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/rosetta/file13.py b/rosetta/file13.py new file mode 100644 index 0000000..f0808fa --- /dev/null +++ b/rosetta/file13.py @@ -0,0 +1 @@ +def get_pixel_colour ( i_x , i_y ) : import win32gui i_desktop_window_id = win32gui. GetDesktopWindow ( ) i_desktop_window_dc = win32gui. GetWindowDC ( i_desktop_window_id ) long_colour = win32gui. GetPixel ( i_desktop_window_dc , i_x , i_y ) i_colour = int ( long_colour ) return ( i_colour & 0xff ) , ( ( i_colour >> 8 ) & 0xff ) , ( ( i_colour >> 16 ) & 0xff )   print get_pixel_colour ( 0 , 0 ) \ No newline at end of file diff --git a/rosetta/file13.rb b/rosetta/file13.rb new file mode 100644 index 0000000..28ddeaf --- /dev/null +++ b/rosetta/file13.rb @@ -0,0 +1 @@ +module Screen IMPORT_COMMAND = '/usr/bin/import'   # Returns an array with RGB values for the pixel at the given coords def self . pixel ( x, y ) if m = `#{IMPORT_COMMAND} -silent -window root -crop 1x1+#{x.to_i}+#{y.to_i} -depth 8 txt:-` . match ( / \ ( ( \d + ) , ( \d + ) , ( \d + ) \ ) / ) m [ 1 .. 3 ] . map ( & :to_i ) else false end end end \ No newline at end of file diff --git a/rosetta/file13.scala b/rosetta/file13.scala new file mode 100644 index 0000000..9ebae98 --- /dev/null +++ b/rosetta/file13.scala @@ -0,0 +1 @@ +object BitmapOps { def bresenham ( bm : RgbBitmap, x0 : Int, y0 : Int, x1 : Int, y1 : Int, c : Color ) = { val dx = math. abs ( x1-x0 ) val sx = if ( x0 < x1 ) 1 else - 1 val dy = math. abs ( y1-y0 ) val sy = if ( y0 < y1 ) 1 else - 1   def it = new Iterator [ Tuple2 [ Int,Int ] ] { var x = x0 ; var y = y0 var err = ( if ( dx > dy ) dx else -dy ) / 2 def next = { val res = ( x,y ) val e2 = err ; if ( e2 > -dx ) { err- = dy ; x+ = sx } if ( e2 < dy ) { err+ = dx ; y+ = sy } res ; } def hasNext = ( x <= x1 && y <= y1 ) }   for ( ( x,y ) < - it ) bm. setPixel ( x, y, c ) } } \ No newline at end of file diff --git a/rosetta/file13.ss b/rosetta/file13.ss new file mode 100644 index 0000000..c506a9b --- /dev/null +++ b/rosetta/file13.ss @@ -0,0 +1 @@ +( define ( A m n ) ( cond ( ( = m 0 ) ( + n 1 ) ) ( ( = n 0 ) ( A ( - m 1 ) 1 ) ) ( else ( A ( - m 1 ) ( A m ( - n 1 ) ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file13.tcl b/rosetta/file13.tcl new file mode 100644 index 0000000..c327260 --- /dev/null +++ b/rosetta/file13.tcl @@ -0,0 +1 @@ +package require json set sample { { "foo" : 1 , "bar" : [ 10 , "apples" ] } }   set parsed [ json:: json2dict $sample ] puts $parsed \ No newline at end of file diff --git a/rosetta/file14.clojure b/rosetta/file14.clojure new file mode 100644 index 0000000..ee3bec4 --- /dev/null +++ b/rosetta/file14.clojure @@ -0,0 +1 @@ +( def precedence ' { * 0 , / 0 + 1 , - 1 } )   ( defn order - ops "((A x B) y C) or (A x (B y C)) depending on precedence of x and y" [ [ A x B y C & more ] ] ( let [ ret ( if ( <= ( precedence x ) ( precedence y ) ) ( list ( list A x B ) y C ) ( list A x ( list B y C ) ) ) ] ( if more ( recur ( concat ret more ) ) ret ) ) )   ( defn add - parens "Tree walk to add parens. All lists are length 3 afterwards." [ s ] ( clojure . walk / postwalk # ( if ( seq? % ) ( let [ c ( count % ) ] ( cond ( even? c ) ( throw ( Exception . "Must be an odd number of forms" ) ) ( = c 1 ) ( first % ) ( = c 3 ) % ( >= c 5 ) ( order - ops % ) ) ) % ) s ) )   ( defn make - ast "Parse a string into a list of numbers, ops, and lists" [ s ] ( -> ( format "'(%s)" s ) ( . replaceAll , "([*+-/])" " $1 " ) load - string add - parens ) )   ( def ops { ' * * ' + + ' - - ' / / } )   ( def eval - ast ( partial clojure . walk / postwalk # ( if ( seq? % ) ( let [ [ a o b ] % ] ( ( ops o ) a b ) ) % ) ) )   ( defn evaluate [ s ] "Parse and evaluate an infix arithmetic expression" ( eval - ast ( make - ast s ) ) )   user > ( evaluate "1 + 2*(3 - 2*(3 - 2)*((2 - 4)*5 - 22/(7 + 2*(3 - 1)) - 1)) + 1" ) 60 \ No newline at end of file diff --git a/rosetta/file14.hs b/rosetta/file14.hs new file mode 100644 index 0000000..dcc41d0 --- /dev/null +++ b/rosetta/file14.hs @@ -0,0 +1 @@ +  -- Calling a function with a fixed number of arguments multiply x y = x * y multiply 10 20 -- returns 200   -- Calling a function that requires no arguments -- Normally, you use constant instead of function without arguments: twopi = 6.28 -- But you can also pass special value as the first argument indicating function call: twopi ( ) = 6.28 -- definition twopi :: Num a => ( ) -> a -- its type twopi ( ) -- returns 6.28   -- Partial application and auto-currying is built-in. multiply _ by _ 10 = ( 10 * ) map multiply _ by _ 10 [ 1 , 2 , 3 ] -- [10, 20, 30] multiply _ all _ by _ 10 = map multiply _ by _ 10 multiply _ all _ by _ 10 [ 1 , 2 , 3 ] -- [10, 20, 30]   -- TODO: -- Calling a function with optional arguments -- Calling a function with a variable number of arguments -- Calling a function with named arguments -- Using a function in statement context -- Using a function in first-class context within an expression -- Obtaining the return value of a function -- Distinguishing built-in functions and user-defined functions -- Distinguishing subroutines and functions -- Stating whether arguments are passed by value or by reference   \ No newline at end of file diff --git a/rosetta/file14.java b/rosetta/file14.java new file mode 100644 index 0000000..01f42d8 --- /dev/null +++ b/rosetta/file14.java @@ -0,0 +1,2 @@ +/* +   Arithmetic-Geometric Mean of 1 & 1/sqrt(2)   Brendan Shaklovitz 5/29/12   */   public class ArithmeticMean { public static void agm ( double a, double g ) { double a1 = a ; double g1 = g ; while ( Math . abs ( a1 - g1 ) >= Math . pow ( 10 , - 14 ) ) { double aTemp = ( a1 + g1 ) / 2.0 ; g1 = Math . sqrt ( a1 * g1 ) ; a1 = aTemp ; } System . out . println ( a1 ) ; }   public static void main ( String [ ] args ) { agm ( 1 , 1 / Math . sqrt ( 2 ) ) ; } } \ No newline at end of file diff --git a/rosetta/file14.js b/rosetta/file14.js new file mode 100644 index 0000000..6028fd7 --- /dev/null +++ b/rosetta/file14.js @@ -0,0 +1 @@ +var myhash = { } ; // a new, empty object myhash [ "hello" ] = 3 ; myhash. world = 6 ; // obj.name is equivalent to obj["name"] for certain values of name myhash [ "!" ] = 9 ;   var output = '' , // initialise as string key ; for ( key in myhash ) { if ( myhash. hasOwnProperty ( key ) ) { output += "key is: " + key ; output += " => " ; output += "value is: " + myhash [ key ] ; // cannot use myhash.key, that would be myhash["key"] output += " \n " ; } } \ No newline at end of file diff --git a/rosetta/file14.ocaml b/rosetta/file14.ocaml new file mode 100644 index 0000000..5889950 --- /dev/null +++ b/rosetta/file14.ocaml @@ -0,0 +1 @@ +#!/ usr / bin / env ocaml   let map = [ | ( ' A ' , 1 ) ; ( ' B ' , 2 ) ; ( ' C ' , 3 ) | ] ;;   (* iterate over pairs *) Array . iter ( fun ( k,v ) -> Printf . printf "key: %c - value: %d\n" k v ) map ;;   (* iterate over keys *) Array . iter ( fun ( k,_ ) -> Printf . printf "key: %c\n" k ) map ;;   (* iterate over values *) Array . iter ( fun ( _,v ) -> Printf . printf "value: %d\n" v ) map ;;   (* in functional programming it is often more useful to fold over the elements *) Array . fold_left ( fun acc ( k,v ) -> acc ^ Printf . sprintf "key: %c - value: %d\n" k v ) "Elements:\n" map ;; \ No newline at end of file diff --git a/rosetta/file14.perl b/rosetta/file14.perl new file mode 100644 index 0000000..80f3847 --- /dev/null +++ b/rosetta/file14.perl @@ -0,0 +1 @@ +# Class method MyClass -> classMethod ( $someParameter ) ; # Equivalently using a class name my $foo = 'MyClass' ; $foo -> classMethod ( $someParameter ) ;     # Instance method $myInstance -> method ( $someParameter ) ;   # Calling a method with no parameters $myInstance -> anotherMethod ;   # Class and instance method calls are made behind the scenes by getting the function from # the package and calling it on the class name or object reference explicitly MyClass :: classMethod ( 'MyClass' , $someParameter ) ; MyClass :: method ( $myInstance , $someParameter ) ; \ No newline at end of file diff --git a/rosetta/file14.php b/rosetta/file14.php new file mode 100644 index 0000000..38be5db --- /dev/null +++ b/rosetta/file14.php @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/rosetta/file14.py b/rosetta/file14.py new file mode 100644 index 0000000..4c9278a --- /dev/null +++ b/rosetta/file14.py @@ -0,0 +1 @@ +  #!/usr/bin/env python #vertical coloured stripes in window in Python 2.7.1   from livewires import *   horiz = 640 ; vert = 480 begin_graphics ( width = horiz , height = vert , title = "v_stripes" , background = Colour. black ) NameColors = [ "black" , "red" , "green" , "dark_blue" , "purple" , "blue" , "yellow" , "white" ] stepik = horiz/ len ( NameColors )   for index , each in enumerate ( NameColors ) : ExcStrng = "set_colour(Colour." +each+ ")" exec ExcStrng box ( index*stepik , 0 , ( index+ 1 ) *stepik , vert , filled = 1 )   while keys_pressed ( ) != [ 'x' ] : # press x key to terminate program pass   end_graphics ( )   \ No newline at end of file diff --git a/rosetta/file14.rb b/rosetta/file14.rb new file mode 100644 index 0000000..28ddeaf --- /dev/null +++ b/rosetta/file14.rb @@ -0,0 +1 @@ +module Screen IMPORT_COMMAND = '/usr/bin/import'   # Returns an array with RGB values for the pixel at the given coords def self . pixel ( x, y ) if m = `#{IMPORT_COMMAND} -silent -window root -crop 1x1+#{x.to_i}+#{y.to_i} -depth 8 txt:-` . match ( / \ ( ( \d + ) , ( \d + ) , ( \d + ) \ ) / ) m [ 1 .. 3 ] . map ( & :to_i ) else false end end end \ No newline at end of file diff --git a/rosetta/file14.scala b/rosetta/file14.scala new file mode 100644 index 0000000..07b3fb2 --- /dev/null +++ b/rosetta/file14.scala @@ -0,0 +1 @@ +object BitmapOps { def midpoint ( bm : RgbBitmap, x0 : Int, y0 : Int, radius : Int, c : Color ) = { var f = 1 -radius var ddF _ x = 1 var ddF _ y = - 2 * radius var x = 0 var y = radius   bm. setPixel ( x0, y0+radius, c ) bm. setPixel ( x0, y0-radius, c ) bm. setPixel ( x0+radius, y0, c ) bm. setPixel ( x0-radius, y0, c )   while ( x < y ) { if ( f >= 0 ) { y- = 1 ddF _ y+ = 2 f+ = ddF _ y } x+ = 1 ddF _ x+ = 2 f+ = ddF _ x   bm. setPixel ( x0+x, y0+y, c ) bm. setPixel ( x0-x, y0+y, c ) bm. setPixel ( x0+x, y0-y, c ) bm. setPixel ( x0-x, y0-y, c ) bm. setPixel ( x0+y, y0+x, c ) bm. setPixel ( x0-y, y0+x, c ) bm. setPixel ( x0+y, y0-x, c ) bm. setPixel ( x0-y, y0-x, c ) } } } \ No newline at end of file diff --git a/rosetta/file14.ss b/rosetta/file14.ss new file mode 100644 index 0000000..07e22ec --- /dev/null +++ b/rosetta/file14.ss @@ -0,0 +1 @@ +( define fail ( lambda ( ) ( error "Amb tree exhausted" ) ) )   ( define-syntax amb ( syntax-rules ( ) ( ( AMB ) ( FAIL ) ) ; Two shortcuts. ( ( AMB expression ) expression )   ( ( AMB expression ... ) ( LET ( ( FAIL - SAVE FAIL ) ) ( ( CALL-WITH-CURRENT-CONTINUATION ; Capture a continuation to ( LAMBDA ( K - SUCCESS ) ; which we return possibles. ( CALL-WITH-CURRENT-CONTINUATION ( LAMBDA ( K - FAILURE ) ; K-FAILURE will try the next ( SET! FAIL K - FAILURE ) ; possible expression. ( K - SUCCESS ; Note that the expression is ( LAMBDA ( ) ; evaluated in tail position expression ) ) ) ) ; with respect to AMB. ... ( SET! FAIL FAIL - SAVE ) ; Finally, if this is reached, FAIL - SAVE ) ) ) ) ) ) ) ; we restore the saved FAIL.     ( let ( ( w - 1 ( amb "the" "that" "a" ) ) ( w - 2 ( amb "frog" "elephant" "thing" ) ) ( w - 3 ( amb "walked" "treaded" "grows" ) ) ( w - 4 ( amb "slowly" "quickly" ) ) ) ( define ( joins? left right ) ( equal? ( string-ref left ( - ( string-length left ) 1 ) ) ( string-ref right 0 ) ) ) ( if ( joins? w - 1 w - 2 ) ' ( ) ( amb ) ) ( if ( joins? w - 2 w - 3 ) ' ( ) ( amb ) ) ( if ( joins? w - 3 w - 4 ) ' ( ) ( amb ) ) ( list w - 1 w - 2 w - 3 w - 4 ) ) \ No newline at end of file diff --git a/rosetta/file14.tcl b/rosetta/file14.tcl new file mode 100644 index 0000000..34827d1 --- /dev/null +++ b/rosetta/file14.tcl @@ -0,0 +1 @@ +package require Tcl 8.5   # from http://wiki.tcl.tk/12574 proc lcomp { expression args } { # Check the number of arguments. if { [ llength $args ] < 2 } { error "wrong # args: should be \" lcomp expression var1 list1 \  ?... varN listN? ?condition? \" " }   # Extract condition from $args, or use default. if { [ llength $args ] % 2 == 1 } { set condition [ lindex $args end ] set args [ lrange $args 0 end- 1 ] } else { set condition 1 }   # Collect all var/list pairs and store in reverse order. set varlst [ list ] foreach { var lst } $args { set varlst [ concat [ list $var ] [ list $lst ] $varlst ] }   # Actual command to be executed, repeatedly. set script { lappend result [ subst $expression ] }   # If necessary, make $script conditional. if { $condition ne "1" } { set script [ list if $condition $script ] }   # Apply layers of foreach constructs around $script. foreach { var lst } $varlst { set script [ list foreach $var $lst $script ] }   # Do it! set result [ list ] { * } $script ; # Change to "eval $script" if using Tcl 8.4 or older. return $result }   set range { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 } puts [ lcomp { $x $y $z } x $range y $range z $range { $x < $y && $x ** 2 + $y ** 2 == $z ** 2 } ] \ No newline at end of file diff --git a/rosetta/file15.clojure b/rosetta/file15.clojure new file mode 100644 index 0000000..ee3bec4 --- /dev/null +++ b/rosetta/file15.clojure @@ -0,0 +1 @@ +( def precedence ' { * 0 , / 0 + 1 , - 1 } )   ( defn order - ops "((A x B) y C) or (A x (B y C)) depending on precedence of x and y" [ [ A x B y C & more ] ] ( let [ ret ( if ( <= ( precedence x ) ( precedence y ) ) ( list ( list A x B ) y C ) ( list A x ( list B y C ) ) ) ] ( if more ( recur ( concat ret more ) ) ret ) ) )   ( defn add - parens "Tree walk to add parens. All lists are length 3 afterwards." [ s ] ( clojure . walk / postwalk # ( if ( seq? % ) ( let [ c ( count % ) ] ( cond ( even? c ) ( throw ( Exception . "Must be an odd number of forms" ) ) ( = c 1 ) ( first % ) ( = c 3 ) % ( >= c 5 ) ( order - ops % ) ) ) % ) s ) )   ( defn make - ast "Parse a string into a list of numbers, ops, and lists" [ s ] ( -> ( format "'(%s)" s ) ( . replaceAll , "([*+-/])" " $1 " ) load - string add - parens ) )   ( def ops { ' * * ' + + ' - - ' / / } )   ( def eval - ast ( partial clojure . walk / postwalk # ( if ( seq? % ) ( let [ [ a o b ] % ] ( ( ops o ) a b ) ) % ) ) )   ( defn evaluate [ s ] "Parse and evaluate an infix arithmetic expression" ( eval - ast ( make - ast s ) ) )   user > ( evaluate "1 + 2*(3 - 2*(3 - 2)*((2 - 4)*5 - 22/(7 + 2*(3 - 1)) - 1)) + 1" ) 60 \ No newline at end of file diff --git a/rosetta/file15.hs b/rosetta/file15.hs new file mode 100644 index 0000000..dcc41d0 --- /dev/null +++ b/rosetta/file15.hs @@ -0,0 +1 @@ +  -- Calling a function with a fixed number of arguments multiply x y = x * y multiply 10 20 -- returns 200   -- Calling a function that requires no arguments -- Normally, you use constant instead of function without arguments: twopi = 6.28 -- But you can also pass special value as the first argument indicating function call: twopi ( ) = 6.28 -- definition twopi :: Num a => ( ) -> a -- its type twopi ( ) -- returns 6.28   -- Partial application and auto-currying is built-in. multiply _ by _ 10 = ( 10 * ) map multiply _ by _ 10 [ 1 , 2 , 3 ] -- [10, 20, 30] multiply _ all _ by _ 10 = map multiply _ by _ 10 multiply _ all _ by _ 10 [ 1 , 2 , 3 ] -- [10, 20, 30]   -- TODO: -- Calling a function with optional arguments -- Calling a function with a variable number of arguments -- Calling a function with named arguments -- Using a function in statement context -- Using a function in first-class context within an expression -- Obtaining the return value of a function -- Distinguishing built-in functions and user-defined functions -- Distinguishing subroutines and functions -- Stating whether arguments are passed by value or by reference   \ No newline at end of file diff --git a/rosetta/file15.java b/rosetta/file15.java new file mode 100644 index 0000000..8900661 --- /dev/null +++ b/rosetta/file15.java @@ -0,0 +1 @@ +class BigRationalFindPerfectNumbers { public static void main ( String [ ] args ) { System . out . println ( "Running BigRational built-in tests" ) ; if ( BigRational. testFeatures ( ) ) { int MAX_NUM = ( 1 << 19 ) ; System . out . println ( ) ; System . out . println ( "Searching for perfect numbers in the range [1, " + ( MAX_NUM - 1 ) + "]" ) ; BigRational TWO = BigRational. valueOf ( 2 ) ; for ( int i = 1 ; i < MAX_NUM ; i ++ ) { BigRational reciprocalSum = BigRational. ONE ; if ( i > 1 ) reciprocalSum = reciprocalSum. add ( BigRational. valueOf ( i ) . reciprocal ( ) ) ; int maxDivisor = ( int ) Math . sqrt ( i ) ; if ( maxDivisor >= i ) maxDivisor --; for ( int divisor = 2 ; divisor <= maxDivisor ; divisor ++ ) { if ( ( i % divisor ) == 0 ) { reciprocalSum = reciprocalSum. add ( BigRational. valueOf ( divisor ) . reciprocal ( ) ) ; int dividend = i / divisor ; if ( divisor != dividend ) reciprocalSum = reciprocalSum. add ( BigRational. valueOf ( dividend ) . reciprocal ( ) ) ; } } if ( reciprocalSum. equals ( TWO ) ) System . out . println ( String . valueOf ( i ) + " is a perfect number" ) ; } } return ; } } \ No newline at end of file diff --git a/rosetta/file15.js b/rosetta/file15.js new file mode 100644 index 0000000..6028fd7 --- /dev/null +++ b/rosetta/file15.js @@ -0,0 +1 @@ +var myhash = { } ; // a new, empty object myhash [ "hello" ] = 3 ; myhash. world = 6 ; // obj.name is equivalent to obj["name"] for certain values of name myhash [ "!" ] = 9 ;   var output = '' , // initialise as string key ; for ( key in myhash ) { if ( myhash. hasOwnProperty ( key ) ) { output += "key is: " + key ; output += " => " ; output += "value is: " + myhash [ key ] ; // cannot use myhash.key, that would be myhash["key"] output += " \n " ; } } \ No newline at end of file diff --git a/rosetta/file15.ocaml b/rosetta/file15.ocaml new file mode 100644 index 0000000..5889950 --- /dev/null +++ b/rosetta/file15.ocaml @@ -0,0 +1 @@ +#!/ usr / bin / env ocaml   let map = [ | ( ' A ' , 1 ) ; ( ' B ' , 2 ) ; ( ' C ' , 3 ) | ] ;;   (* iterate over pairs *) Array . iter ( fun ( k,v ) -> Printf . printf "key: %c - value: %d\n" k v ) map ;;   (* iterate over keys *) Array . iter ( fun ( k,_ ) -> Printf . printf "key: %c\n" k ) map ;;   (* iterate over values *) Array . iter ( fun ( _,v ) -> Printf . printf "value: %d\n" v ) map ;;   (* in functional programming it is often more useful to fold over the elements *) Array . fold_left ( fun acc ( k,v ) -> acc ^ Printf . sprintf "key: %c - value: %d\n" k v ) "Elements:\n" map ;; \ No newline at end of file diff --git a/rosetta/file15.perl b/rosetta/file15.perl new file mode 100644 index 0000000..16bc31a --- /dev/null +++ b/rosetta/file15.perl @@ -0,0 +1 @@ +use List :: Util 'reduce' ;   # note the use of the odd $a and $b globals print + ( reduce { $a + $b } 1 .. 10 ) , " \n " ;   # first argument is really an anon function; you could also do this: sub func { $b & 1 ? "$a $b" : "$b $a" } print + ( reduce \&func , 1 .. 10 ) , " \n " \ No newline at end of file diff --git a/rosetta/file15.php b/rosetta/file15.php new file mode 100644 index 0000000..38be5db --- /dev/null +++ b/rosetta/file15.php @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/rosetta/file15.py b/rosetta/file15.py new file mode 100644 index 0000000..4c9278a --- /dev/null +++ b/rosetta/file15.py @@ -0,0 +1 @@ +  #!/usr/bin/env python #vertical coloured stripes in window in Python 2.7.1   from livewires import *   horiz = 640 ; vert = 480 begin_graphics ( width = horiz , height = vert , title = "v_stripes" , background = Colour. black ) NameColors = [ "black" , "red" , "green" , "dark_blue" , "purple" , "blue" , "yellow" , "white" ] stepik = horiz/ len ( NameColors )   for index , each in enumerate ( NameColors ) : ExcStrng = "set_colour(Colour." +each+ ")" exec ExcStrng box ( index*stepik , 0 , ( index+ 1 ) *stepik , vert , filled = 1 )   while keys_pressed ( ) != [ 'x' ] : # press x key to terminate program pass   end_graphics ( )   \ No newline at end of file diff --git a/rosetta/file15.rb b/rosetta/file15.rb new file mode 100644 index 0000000..d64f6bf --- /dev/null +++ b/rosetta/file15.rb @@ -0,0 +1 @@ +x = "code" # I am a comment   =begin hello I a POD documentation comment like Perl =end puts "code" \ No newline at end of file diff --git a/rosetta/file15.scala b/rosetta/file15.scala new file mode 100644 index 0000000..a5e537e --- /dev/null +++ b/rosetta/file15.scala @@ -0,0 +1 @@ +import scala. io . _ import scala. swing . _ import java. io . _ import java. awt . Color import javax. swing . ImageIcon   object Pixmap { private case class PpmHeader ( format : String, width : Int, height : Int, maxColor : Int )   def load ( filename : String ) : Option [ RgbBitmap ] = { implicit val in = new BufferedInputStream ( new FileInputStream ( filename ) ) val header = readHeader if ( header. format == "P6" ) { val bm = new RgbBitmap ( header. width , header. height ) ; for ( y < - 0 until bm. height ; x < - 0 until bm. width ; c = readColor ) bm. setPixel ( x, y, c ) return Some ( bm ) } None }   private def readHeader ( implicit in : InputStream ) = { var format = readLine   var line = readLine while ( line. startsWith ( "#" ) ) //skip comments line = readLine   val parts = line. split ( " \\ s" ) val width = parts ( 0 ) . toInt val height = parts ( 1 ) . toInt val maxColor = readLine. toInt   new PpmHeader ( format, width, height, maxColor ) }   private def readColor ( implicit in : InputStream ) = new Color ( in. read , in. read , in. read )   private def readLine ( implicit in : InputStream ) = { var out = "" var b = in. read while ( b != 0xA ) { out+ = b. toChar ; b = in. read } out } } \ No newline at end of file diff --git a/rosetta/file15.ss b/rosetta/file15.ss new file mode 100644 index 0000000..07e22ec --- /dev/null +++ b/rosetta/file15.ss @@ -0,0 +1 @@ +( define fail ( lambda ( ) ( error "Amb tree exhausted" ) ) )   ( define-syntax amb ( syntax-rules ( ) ( ( AMB ) ( FAIL ) ) ; Two shortcuts. ( ( AMB expression ) expression )   ( ( AMB expression ... ) ( LET ( ( FAIL - SAVE FAIL ) ) ( ( CALL-WITH-CURRENT-CONTINUATION ; Capture a continuation to ( LAMBDA ( K - SUCCESS ) ; which we return possibles. ( CALL-WITH-CURRENT-CONTINUATION ( LAMBDA ( K - FAILURE ) ; K-FAILURE will try the next ( SET! FAIL K - FAILURE ) ; possible expression. ( K - SUCCESS ; Note that the expression is ( LAMBDA ( ) ; evaluated in tail position expression ) ) ) ) ; with respect to AMB. ... ( SET! FAIL FAIL - SAVE ) ; Finally, if this is reached, FAIL - SAVE ) ) ) ) ) ) ) ; we restore the saved FAIL.     ( let ( ( w - 1 ( amb "the" "that" "a" ) ) ( w - 2 ( amb "frog" "elephant" "thing" ) ) ( w - 3 ( amb "walked" "treaded" "grows" ) ) ( w - 4 ( amb "slowly" "quickly" ) ) ) ( define ( joins? left right ) ( equal? ( string-ref left ( - ( string-length left ) 1 ) ) ( string-ref right 0 ) ) ) ( if ( joins? w - 1 w - 2 ) ' ( ) ( amb ) ) ( if ( joins? w - 2 w - 3 ) ' ( ) ( amb ) ) ( if ( joins? w - 3 w - 4 ) ' ( ) ( amb ) ) ( list w - 1 w - 2 w - 3 w - 4 ) ) \ No newline at end of file diff --git a/rosetta/file15.tcl b/rosetta/file15.tcl new file mode 100644 index 0000000..7bec7c2 --- /dev/null +++ b/rosetta/file15.tcl @@ -0,0 +1 @@ +package require Tcl 8.6   puts [ zlib inflate [ binary decode base64 " 7VRNa8MwDL3nV2inXkZ+xDa29taxws5q7NZuPSvYDib/fnJKPxwXBoNCx3KTn56t p6dEC9hbioAWyAgwKHqIisBHNIaiFICwMX1dLUCQnYUDO6oevJIXrMCngbeUTmHr U3pmDAgt64ov/1jEt1pIV1crhQGi09utSbgVsLuIg272KdbWMx1UuvFRCDm8BYGg wdCos7hbN/Gknair904HCbj2HZ9gdaKcCKXihOd6j37cUXfPGOrqFW3T81sc560N 2VItw7nUP23BC23r6jN9ogiK49yCIVuqZTiX+i+sWmo2Y86lv6gLCiLyEwRrPTZt 4JW6Gc5FT+ZemPtGxy53nQ9ArbSMq6RFOSr+zTM915DwXP00jd8sRoqjIoqR0XpM nCtGcDITPI3qxgvc7mWqE4aN5DCknyYy2hfL/MC85lzKjMybxnsP452T83JQNPMg JIpHoA001DH88A0= " ] ] \ No newline at end of file diff --git a/rosetta/file16.clojure b/rosetta/file16.clojure new file mode 100644 index 0000000..cc1574b --- /dev/null +++ b/rosetta/file16.clojure @@ -0,0 +1 @@ +user > 22 / 7 22 / 7 user > 34 / 2 17 user > ( + 37 / 5 42 / 9 ) 181 / 15 \ No newline at end of file diff --git a/rosetta/file16.hs b/rosetta/file16.hs new file mode 100644 index 0000000..dcc41d0 --- /dev/null +++ b/rosetta/file16.hs @@ -0,0 +1 @@ +  -- Calling a function with a fixed number of arguments multiply x y = x * y multiply 10 20 -- returns 200   -- Calling a function that requires no arguments -- Normally, you use constant instead of function without arguments: twopi = 6.28 -- But you can also pass special value as the first argument indicating function call: twopi ( ) = 6.28 -- definition twopi :: Num a => ( ) -> a -- its type twopi ( ) -- returns 6.28   -- Partial application and auto-currying is built-in. multiply _ by _ 10 = ( 10 * ) map multiply _ by _ 10 [ 1 , 2 , 3 ] -- [10, 20, 30] multiply _ all _ by _ 10 = map multiply _ by _ 10 multiply _ all _ by _ 10 [ 1 , 2 , 3 ] -- [10, 20, 30]   -- TODO: -- Calling a function with optional arguments -- Calling a function with a variable number of arguments -- Calling a function with named arguments -- Using a function in statement context -- Using a function in first-class context within an expression -- Obtaining the return value of a function -- Distinguishing built-in functions and user-defined functions -- Distinguishing subroutines and functions -- Stating whether arguments are passed by value or by reference   \ No newline at end of file diff --git a/rosetta/file16.java b/rosetta/file16.java new file mode 100644 index 0000000..bf96770 --- /dev/null +++ b/rosetta/file16.java @@ -0,0 +1 @@ +int [ ] array = new int [ 10 ] ; //optionally, replace "new int[10]" with a braced list of ints like "{1, 2, 3}" array [ 0 ] = 42 ; System . out . println ( array [ 3 ] ) ; \ No newline at end of file diff --git a/rosetta/file16.js b/rosetta/file16.js new file mode 100644 index 0000000..4cc6e65 --- /dev/null +++ b/rosetta/file16.js @@ -0,0 +1 @@ +function mean ( array ) { var sum = 0 , i ; for ( i = 0 ; i < array. length ; i ++ ) { sum += array [ i ] ; } return array. length ? sum / array. length : 0 ; }   alert ( mean ( [ 1 , 2 , 3 , 4 , 5 ] ) ) ; // 3 alert ( mean ( [ ] ) ) ; // 0 \ No newline at end of file diff --git a/rosetta/file16.ocaml b/rosetta/file16.ocaml new file mode 100644 index 0000000..537d42f --- /dev/null +++ b/rosetta/file16.ocaml @@ -0,0 +1 @@ +type btdigit = Pos | Zero | Neg type btern = btdigit list   let to_string n = String . concat "" ( List . rev_map ( function Pos -> "+" | Zero -> "0" | Neg -> "-" ) n )   let from_string s = let sl = ref [ ] in let digit = function '+' -> Pos | '-' -> Neg | ' 0 ' -> Zero | _ -> failwith "invalid digit" in String . iter ( fun c -> sl := ( digit c ) :: ! sl ) s ; ! sl   let rec to_int = function | [ Zero ] | [ ] -> 0 | Pos :: t -> 1 + 3 * to_int t | Neg :: t -> - 1 + 3 * to_int t | Zero :: t -> 3 * to_int t   let rec from_int n = if n = 0 then [ ] else match n mod 3 with | 0 -> Zero :: from_int ( n / 3 ) | 1 | - 2 -> Pos :: from_int ( ( n - 1 ) / 3 ) | 2 | - 1 -> Neg :: from_int ( ( n + 1 ) / 3 )   let rec ( + ~ ) n1 n2 = match ( n1,n2 ) with | ( [ ] , a ) | ( a, [ ] ) -> a | ( Pos :: t1, Neg :: t2 ) | ( Neg :: t1, Pos :: t2 ) | ( Zero :: t1, Zero :: t2 ) -> let sum = t1 + ~ t2 in if sum = [ ] then [ ] else Zero :: sum | ( Pos :: t1, Pos :: t2 ) -> Neg :: t1 + ~ t2 + ~ [ Pos ] | ( Neg :: t1, Neg :: t2 ) -> Pos :: t1 + ~ t2 + ~ [ Neg ] | ( Zero :: t1, h :: t2 ) | ( h :: t1, Zero :: t2 ) -> h :: t1 + ~ t2   let neg = List . map ( function Pos -> Neg | Neg -> Pos | Zero -> Zero ) let ( - ~ ) a b = a + ~ ( neg b )   let rec ( * ~ ) n1 = function | [ ] -> [ ] | [ Pos ] -> n1 | [ Neg ] -> neg n1 | Pos :: t -> ( Zero :: t * ~ n1 ) + ~ n1 | Neg :: t -> ( Zero :: t * ~ n1 ) - ~ n1 | Zero :: t -> Zero :: t * ~ n1   let a = from_string "+-0++0+" let b = from_int ( - 436 ) let c = from_string "+-++-" let d = a * ~ ( b - ~ c ) let _ = Printf . printf "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" ( to_int a ) ( to_int b ) ( to_int c ) ( to_string d ) ( to_int d ) ; \ No newline at end of file diff --git a/rosetta/file16.perl b/rosetta/file16.perl new file mode 100644 index 0000000..9d8773a --- /dev/null +++ b/rosetta/file16.perl @@ -0,0 +1 @@ +print ord ( 'a' ) , " \n " ; # prints "97" print chr ( 97 ) , " \n " ; # prints "a" \ No newline at end of file diff --git a/rosetta/file16.php b/rosetta/file16.php new file mode 100644 index 0000000..4ff9c20 --- /dev/null +++ b/rosetta/file16.php @@ -0,0 +1 @@ +  define ( 'PRECISION' , 13 ) ;   function agm ( $a0 , $g0 , $tolerance = 1e-10 ) { // the bc extension deals in strings and cannot convert // floats in scientific notation by itself - hence // this manual conversion to a string $limit = number_format ( $tolerance , PRECISION , '.' , '' ) ; $an = $a0 ; $gn = $g0 ; do { list ( $an , $gn ) = array ( bcdiv ( bcadd ( $an , $gn ) , 2 ) , bcsqrt ( bcmul ( $an , $gn ) ) , ) ; } while ( bccomp ( bcsub ( $an , $gn ) , $limit ) > 0 ) ;   return $an ; }   bcscale ( PRECISION ) ; echo agm ( 1 , 1 / bcsqrt ( 2 ) ) ;   \ No newline at end of file diff --git a/rosetta/file16.py b/rosetta/file16.py new file mode 100644 index 0000000..749a09c --- /dev/null +++ b/rosetta/file16.py @@ -0,0 +1 @@ +def builtinsort ( x ) : x. sort ( )   def partition ( seq , pivot ) : low , middle , up = [ ] , [ ] , [ ] for x in seq: if x < pivot: low. append ( x ) elif x == pivot: middle. append ( x ) else : up. append ( x ) return low , middle , up import random def qsortranpart ( seq ) : size = len ( seq ) if size < 2 : return seq low , middle , up = partition ( seq , random . choice ( seq ) ) return qsortranpart ( low ) + middle + qsortranpart ( up ) \ No newline at end of file diff --git a/rosetta/file16.rb b/rosetta/file16.rb new file mode 100644 index 0000000..d64f6bf --- /dev/null +++ b/rosetta/file16.rb @@ -0,0 +1 @@ +x = "code" # I am a comment   =begin hello I a POD documentation comment like Perl =end puts "code" \ No newline at end of file diff --git a/rosetta/file16.scala b/rosetta/file16.scala new file mode 100644 index 0000000..79443f0 --- /dev/null +++ b/rosetta/file16.scala @@ -0,0 +1 @@ +object Pixmap { def save ( bm : RgbBitmap, filename : String ) = { val out = new DataOutputStream ( new FileOutputStream ( filename ) )   out. writeBytes ( "P6 \u000a %d %d \u000a %d \u000a " . format ( bm. width , bm. height , 255 ) )   for ( y < - 0 until bm. height ; x < - 0 until bm. width ; c = bm. getPixel ( x, y ) ) { out. writeByte ( c. getRed ) out. writeByte ( c. getGreen ) out. writeByte ( c. getBlue ) } } } \ No newline at end of file diff --git a/rosetta/file16.ss b/rosetta/file16.ss new file mode 100644 index 0000000..07e22ec --- /dev/null +++ b/rosetta/file16.ss @@ -0,0 +1 @@ +( define fail ( lambda ( ) ( error "Amb tree exhausted" ) ) )   ( define-syntax amb ( syntax-rules ( ) ( ( AMB ) ( FAIL ) ) ; Two shortcuts. ( ( AMB expression ) expression )   ( ( AMB expression ... ) ( LET ( ( FAIL - SAVE FAIL ) ) ( ( CALL-WITH-CURRENT-CONTINUATION ; Capture a continuation to ( LAMBDA ( K - SUCCESS ) ; which we return possibles. ( CALL-WITH-CURRENT-CONTINUATION ( LAMBDA ( K - FAILURE ) ; K-FAILURE will try the next ( SET! FAIL K - FAILURE ) ; possible expression. ( K - SUCCESS ; Note that the expression is ( LAMBDA ( ) ; evaluated in tail position expression ) ) ) ) ; with respect to AMB. ... ( SET! FAIL FAIL - SAVE ) ; Finally, if this is reached, FAIL - SAVE ) ) ) ) ) ) ) ; we restore the saved FAIL.     ( let ( ( w - 1 ( amb "the" "that" "a" ) ) ( w - 2 ( amb "frog" "elephant" "thing" ) ) ( w - 3 ( amb "walked" "treaded" "grows" ) ) ( w - 4 ( amb "slowly" "quickly" ) ) ) ( define ( joins? left right ) ( equal? ( string-ref left ( - ( string-length left ) 1 ) ) ( string-ref right 0 ) ) ) ( if ( joins? w - 1 w - 2 ) ' ( ) ( amb ) ) ( if ( joins? w - 2 w - 3 ) ' ( ) ( amb ) ) ( if ( joins? w - 3 w - 4 ) ' ( ) ( amb ) ) ( list w - 1 w - 2 w - 3 w - 4 ) ) \ No newline at end of file diff --git a/rosetta/file16.tcl b/rosetta/file16.tcl new file mode 100644 index 0000000..5269a2d --- /dev/null +++ b/rosetta/file16.tcl @@ -0,0 +1 @@ +package require Tk package require tcl3d   proc resizedWin { win w h } { glViewport 0 0 $w $h glMatrixMode GL_PROJECTION glLoadIdentity glOrtho - 30.0 30.0 - 30.0 30.0 - 30.0 30.0 glMatrixMode GL_MODELVIEW } proc paintShape { win } { glClearColor 0.0 0.0 0.0 0.5 glClear [ expr { $ :: GL_COLOR_BUFFER_BIT + $ :: GL_DEPTH_BUFFER_BIT } ] glShadeModel GL_SMOOTH glLoadIdentity glTranslatef - 15.0 - 15.0 0.0 glBegin GL_TRIANGLES glColor3f 1.0 0.0 0.0 glVertex2f 5.0 5.0 glColor3f 0.0 1.0 0.0 glVertex2f 25.0 5.0 glColor3f 0.0 0.0 1.0 glVertex2f 5.0 25.0 glEnd $win swapbuffers }   togl .surface -width 640 -height 480 -double true -depth true \ -displayproc paintShape -reshapeproc resizedWin pack .surface -fill both -expand 1 \ No newline at end of file diff --git a/rosetta/file17.clojure b/rosetta/file17.clojure new file mode 100644 index 0000000..74dfaa6 --- /dev/null +++ b/rosetta/file17.clojure @@ -0,0 +1 @@ +  ( let [ i 42 ] ( assert ( = i 42 ) ) )   \ No newline at end of file diff --git a/rosetta/file17.hs b/rosetta/file17.hs new file mode 100644 index 0000000..b8b787e --- /dev/null +++ b/rosetta/file17.hs @@ -0,0 +1 @@ +import Text . Printf   main = printf "The three dogs are named %s, %s and %s. \n " dog dOG dOg where dog = "Benjamin" dOG = "Samba" dOg = "Bernie" \ No newline at end of file diff --git a/rosetta/file17.java b/rosetta/file17.java new file mode 100644 index 0000000..bf96770 --- /dev/null +++ b/rosetta/file17.java @@ -0,0 +1 @@ +int [ ] array = new int [ 10 ] ; //optionally, replace "new int[10]" with a braced list of ints like "{1, 2, 3}" array [ 0 ] = 42 ; System . out . println ( array [ 3 ] ) ; \ No newline at end of file diff --git a/rosetta/file17.js b/rosetta/file17.js new file mode 100644 index 0000000..4cc6e65 --- /dev/null +++ b/rosetta/file17.js @@ -0,0 +1 @@ +function mean ( array ) { var sum = 0 , i ; for ( i = 0 ; i < array. length ; i ++ ) { sum += array [ i ] ; } return array. length ? sum / array. length : 0 ; }   alert ( mean ( [ 1 , 2 , 3 , 4 , 5 ] ) ) ; // 3 alert ( mean ( [ ] ) ) ; // 0 \ No newline at end of file diff --git a/rosetta/file17.ocaml b/rosetta/file17.ocaml new file mode 100644 index 0000000..537d42f --- /dev/null +++ b/rosetta/file17.ocaml @@ -0,0 +1 @@ +type btdigit = Pos | Zero | Neg type btern = btdigit list   let to_string n = String . concat "" ( List . rev_map ( function Pos -> "+" | Zero -> "0" | Neg -> "-" ) n )   let from_string s = let sl = ref [ ] in let digit = function '+' -> Pos | '-' -> Neg | ' 0 ' -> Zero | _ -> failwith "invalid digit" in String . iter ( fun c -> sl := ( digit c ) :: ! sl ) s ; ! sl   let rec to_int = function | [ Zero ] | [ ] -> 0 | Pos :: t -> 1 + 3 * to_int t | Neg :: t -> - 1 + 3 * to_int t | Zero :: t -> 3 * to_int t   let rec from_int n = if n = 0 then [ ] else match n mod 3 with | 0 -> Zero :: from_int ( n / 3 ) | 1 | - 2 -> Pos :: from_int ( ( n - 1 ) / 3 ) | 2 | - 1 -> Neg :: from_int ( ( n + 1 ) / 3 )   let rec ( + ~ ) n1 n2 = match ( n1,n2 ) with | ( [ ] , a ) | ( a, [ ] ) -> a | ( Pos :: t1, Neg :: t2 ) | ( Neg :: t1, Pos :: t2 ) | ( Zero :: t1, Zero :: t2 ) -> let sum = t1 + ~ t2 in if sum = [ ] then [ ] else Zero :: sum | ( Pos :: t1, Pos :: t2 ) -> Neg :: t1 + ~ t2 + ~ [ Pos ] | ( Neg :: t1, Neg :: t2 ) -> Pos :: t1 + ~ t2 + ~ [ Neg ] | ( Zero :: t1, h :: t2 ) | ( h :: t1, Zero :: t2 ) -> h :: t1 + ~ t2   let neg = List . map ( function Pos -> Neg | Neg -> Pos | Zero -> Zero ) let ( - ~ ) a b = a + ~ ( neg b )   let rec ( * ~ ) n1 = function | [ ] -> [ ] | [ Pos ] -> n1 | [ Neg ] -> neg n1 | Pos :: t -> ( Zero :: t * ~ n1 ) + ~ n1 | Neg :: t -> ( Zero :: t * ~ n1 ) - ~ n1 | Zero :: t -> Zero :: t * ~ n1   let a = from_string "+-0++0+" let b = from_int ( - 436 ) let c = from_string "+-++-" let d = a * ~ ( b - ~ c ) let _ = Printf . printf "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" ( to_int a ) ( to_int b ) ( to_int c ) ( to_string d ) ( to_int d ) ; \ No newline at end of file diff --git a/rosetta/file17.perl b/rosetta/file17.perl new file mode 100644 index 0000000..2b57994 --- /dev/null +++ b/rosetta/file17.perl @@ -0,0 +1 @@ +sub cholesky { my $matrix = shift ; my $chol = [ map { [ ( 0 ) x @$matrix ] } @$matrix ] ; for my $row ( 0 .. @$matrix - 1 ) { for my $col ( 0 .. $row ) { my $x = $$matrix [ $row ] [ $col ] ; $x -= $$chol [ $row ] [ $_ ] * $$chol [ $col ] [ $_ ] for 0 .. $col ; $$chol [ $row ] [ $col ] = $row == $col ? sqrt $x : $x / $$chol [ $col ] [ $col ] ; } } return $chol ; }   my $example1 = [ [ 25 , 15 , - 5 ] , [ 15 , 18 , 0 ] , [ - 5 , 0 , 11 ] ] ; print "Example 1: \n " ; print + ( map { sprintf "%7.4f \t " , $_ } @ $_ ) , " \n " for @ { cholesky $example1 } ;   my $example2 = [ [ 18 , 22 , 54 , 42 ] , [ 22 , 70 , 86 , 62 ] , [ 54 , 86 , 174 , 134 ] , [ 42 , 62 , 134 , 106 ] ] ; print " \n Example 2: \n " ; print + ( map { sprintf "%7.4f \t " , $_ } @ $_ ) , " \n " for @ { cholesky $example2 } ;   \ No newline at end of file diff --git a/rosetta/file17.php b/rosetta/file17.php new file mode 100644 index 0000000..4ff9c20 --- /dev/null +++ b/rosetta/file17.php @@ -0,0 +1 @@ +  define ( 'PRECISION' , 13 ) ;   function agm ( $a0 , $g0 , $tolerance = 1e-10 ) { // the bc extension deals in strings and cannot convert // floats in scientific notation by itself - hence // this manual conversion to a string $limit = number_format ( $tolerance , PRECISION , '.' , '' ) ; $an = $a0 ; $gn = $g0 ; do { list ( $an , $gn ) = array ( bcdiv ( bcadd ( $an , $gn ) , 2 ) , bcsqrt ( bcmul ( $an , $gn ) ) , ) ; } while ( bccomp ( bcsub ( $an , $gn ) , $limit ) > 0 ) ;   return $an ; }   bcscale ( PRECISION ) ; echo agm ( 1 , 1 / bcsqrt ( 2 ) ) ;   \ No newline at end of file diff --git a/rosetta/file17.py b/rosetta/file17.py new file mode 100644 index 0000000..6eacf95 --- /dev/null +++ b/rosetta/file17.py @@ -0,0 +1 @@ +def conjugate_transpose ( m ) : return tuple ( tuple ( n. conjugate ( ) for n in row ) for row in zip ( *m ) )   def mmul ( ma , mb ) : return tuple ( tuple ( sum ( ea*eb for ea , eb in zip ( a , b ) ) for b in zip ( *mb ) ) for a in ma )   def mi ( size ) : 'Complex Identity matrix' sz = range ( size ) m = [ [ 0 + 0j for i in sz ] for j in sz ] for i in range ( size ) : m [ i ] [ i ] = 1 + 0j return tuple ( tuple ( row ) for row in m )   def __allsame ( vector ) : first , rest = vector [ 0 ] , vector [ 1 : ] return all ( i == first for i in rest )   def __allnearsame ( vector , eps = 1e-14 ) : first , rest = vector [ 0 ] , vector [ 1 : ] return all ( abs ( first. real - i. real ) < eps and abs ( first. imag - i. imag ) < eps for i in rest )   def isequal ( matrices , eps = 1e-14 ) : 'Check any number of matrices for equality within eps' x = [ len ( m ) for m in matrices ] if not __allsame ( x ) : return False y = [ len ( m [ 0 ] ) for m in matrices ] if not __allsame ( y ) : return False for s in range ( x [ 0 ] ) : for t in range ( y [ 0 ] ) : if not __allnearsame ( [ m [ s ] [ t ] for m in matrices ] , eps ) : return False return True     def ishermitian ( m , ct ) : return isequal ( [ m , ct ] )   def isnormal ( m , ct ) : return isequal ( [ mmul ( m , ct ) , mmul ( ct , m ) ] )   def isunitary ( m , ct ) : mct , ctm = mmul ( m , ct ) , mmul ( ct , m ) mctx , mcty , cmx , ctmy = len ( mct ) , len ( mct [ 0 ] ) , len ( ctm ) , len ( ctm [ 0 ] ) ident = mi ( mctx ) return isequal ( [ mct , ctm , ident ] )   def printm ( comment , m ) : print ( comment ) fields = [ [ '%g%+gj'  % ( f. real , f. imag ) for f in row ] for row in m ] width = max ( max ( len ( f ) for f in row ) for row in fields ) lines = ( ', ' . join ( '%*s'  % ( width , f ) for f in row ) for row in fields ) print ( ' \n ' . join ( lines ) )   if __name__ == '__main__' : for matrix in [ ( ( ( 3.000 +0.000j ) , ( + 2.000 +1.000j ) ) , ( ( 2.000 -1.000j ) , ( + 1.000 +0.000j ) ) ) ,   ( ( ( 1.000 +0.000j ) , ( + 1.000 +0.000j ) , ( + 0.000 +0.000j ) ) , ( ( 0.000 +0.000j ) , ( + 1.000 +0.000j ) , ( + 1.000 +0.000j ) ) , ( ( 1.000 +0.000j ) , ( + 0.000 +0.000j ) , ( + 1.000 +0.000j ) ) ) ,   ( ( ( 2 ** 0.5 / 2 +0.000j ) , ( + 2 ** 0.5 / 2 +0.000j ) , ( + 0.000 +0.000j ) ) , ( ( 0.000 + 2 ** 0.5 /2j ) , ( + 0.000 - 2 ** 0.5 /2j ) , ( + 0.000 +0.000j ) ) , ( ( 0.000 +0.000j ) , ( + 0.000 +0.000j ) , ( + 0.000 +1.000j ) ) ) ] : printm ( ' \n Matrix:' , matrix ) ct = conjugate_transpose ( matrix ) printm ( 'Its conjugate transpose:' , ct ) print ( 'Hermitian? %s.'  % ishermitian ( matrix , ct ) ) print ( 'Normal?  %s.'  % isnormal ( matrix , ct ) ) print ( 'Unitary?  %s.'  % isunitary ( matrix , ct ) ) \ No newline at end of file diff --git a/rosetta/file17.rb b/rosetta/file17.rb new file mode 100644 index 0000000..6206ddf --- /dev/null +++ b/rosetta/file17.rb @@ -0,0 +1 @@ +% w { Enjoy Rosetta Code } . map do | x | Thread . new do sleep rand puts x end end . each do | t | t. join end \ No newline at end of file diff --git a/rosetta/file17.scala b/rosetta/file17.scala new file mode 100644 index 0000000..3fa8bea --- /dev/null +++ b/rosetta/file17.scala @@ -0,0 +1 @@ +def bitwise ( a : Int, b : Int ) { println ( "a and b: " + ( a & b ) ) println ( "a or b: " + ( a | b ) ) println ( "a xor b: " + ( a ^ b ) ) println ( "not a: " + ( ~a ) ) println ( "a << b: " + ( a << b ) ) // left shift println ( "a >> b: " + ( a >> b ) ) // arithmetic right shift println ( "a >>> b: " + ( a >>> b ) ) // unsigned right shift println ( "a rot b: " + Integer. rotateLeft ( a, b ) ) // Rotate Left println ( "a rol b: " + Integer. rotateRight ( a, b ) ) // Rotate Right } \ No newline at end of file diff --git a/rosetta/file17.ss b/rosetta/file17.ss new file mode 100644 index 0000000..28fbff3 --- /dev/null +++ b/rosetta/file17.ss @@ -0,0 +1 @@ +# ! r6rs   ;;; R6RS implementation of Pendulum Animation   ( import ( rnrs ) ( lib pstk main ) ; change this for your pstk installation )   ( define PI 3.14159 ) ( define * conv - radians * ( / PI 180 ) ) ( define * theta * 45.0 ) ( define * d - theta * 0.0 ) ( define * length * 150 ) ( define * home - x * 160 ) ( define * home - y * 25 )   ;;; estimates new angle of pendulum ( define ( recompute - angle ) ( define ( avg a b ) ( / ( + a b ) 2 ) ) ( let* ( ( scaling ( / 3000.0 ( * * length * * length * ) ) ) ; first estimate ( first - dd - theta ( - ( * ( sin ( * * theta * * conv - radians * ) ) scaling ) ) ) ( mid - d - theta ( + * d - theta * first - dd - theta ) ) ( mid - theta ( + * theta * ( avg * d - theta * mid - d - theta ) ) ) ; second estimate ( mid - dd - theta ( - ( * ( sin ( * mid - theta * conv - radians * ) ) scaling ) ) ) ( mid - d - theta - 2 ( + * d - theta * ( avg first - dd - theta mid - dd - theta ) ) ) ( mid - theta - 2 ( + * theta * ( avg * d - theta * mid - d - theta - 2 ) ) ) ; again first ( mid - dd - theta - 2 ( - ( * ( sin ( * mid - theta - 2 * conv - radians * ) ) scaling ) ) ) ( last - d - theta ( + mid - d - theta - 2 mid - dd - theta - 2 ) ) ( last - theta ( + mid - theta - 2 ( avg mid - d - theta - 2 last - d - theta ) ) ) ; again second ( last - dd - theta ( - ( * ( sin ( * last - theta * conv - radians * ) ) scaling ) ) ) ( last - d - theta - 2 ( + mid - d - theta - 2 ( avg mid - dd - theta - 2 last - dd - theta ) ) ) ( last - theta - 2 ( + mid - theta - 2 ( avg mid - d - theta - 2 last - d - theta - 2 ) ) ) ) ; put values back in globals ( set! * d - theta * last - d - theta - 2 ) ( set! * theta * last - theta - 2 ) ) )   ;;; The main event loop and graphics context ( let ( ( tk ( tk - start ) ) ) ( tk / wm 'title tk "Pendulum Animation" ) ( let ( ( canvas ( tk 'create - widget 'canvas ) ) )   ;;; redraw the pendulum on canvas ;;; - uses angle and length to compute new (x,y) position of bob ( define ( show - pendulum canvas ) ( let* ( ( pendulum - angle ( * * conv - radians * * theta * ) ) ( x ( + * home - x * ( * * length * ( sin pendulum - angle ) ) ) ) ( y ( + * home - y * ( * * length * ( cos pendulum - angle ) ) ) ) ) ( canvas 'coords 'rod * home - x * * home - y * x y ) ( canvas 'coords 'bob ( - x 15 ) ( - y 15 ) ( + x 15 ) ( + y 15 ) ) ) )   ;;; move the pendulum and repeat after 20ms ( define ( animate ) ( recompute - angle ) ( show - pendulum canvas ) ( tk / after 20 animate ) )   ;; layout the canvas ( tk / grid canvas 'column: 0 'row: 0 ) ( canvas 'create 'line 0 25 320 25 'tags: 'plate 'width: 2 'fill: 'grey50 ) ( canvas 'create 'oval 155 20 165 30 'tags: 'pivot 'outline: "" 'fill: 'grey50 ) ( canvas 'create 'line 1 1 1 1 'tags: 'rod 'width: 3 'fill: 'black ) ( canvas 'create 'oval 1 1 2 2 'tags: 'bob 'outline: 'black 'fill: 'yellow )   ;; get everything started ( show - pendulum canvas ) ( tk / after 500 animate ) ( tk - event - loop tk ) ) )   \ No newline at end of file diff --git a/rosetta/file17.tcl b/rosetta/file17.tcl new file mode 100644 index 0000000..c61797b --- /dev/null +++ b/rosetta/file17.tcl @@ -0,0 +1 @@ +package require Tcl 8.6 package require Thread   # Pooled computation engine; runs event loop internally namespace eval pooled { variable poolSize 3 ; # Needs to be tuned to system size   proc computation { computationDefinition entryPoint values } { variable result variable poolSize # Add communication shim append computationDefinition [ subst -nocommands { proc poolcompute { value target } { set outcome [ $entryPoint \ $value ] set msg [ list set  :: pooled :: result ( \ $value ) \ $outcome ] thread:: send -async \ $target \ $msg } } ]   # Set up the pool set pool [ tpool:: create -initcmd $computationDefinition \ -maxworkers $poolSize ]   # Prepare to receive results unset -nocomplain result array set result { }   # Dispatch the computations foreach value $values { tpool:: post $pool [ list poolcompute $value [ thread:: id ] ] }   # Wait for results while { [ array size result ] < [ llength $values ] } { vwait pooled:: result }   # Dispose of the pool tpool:: release $pool   # Return the results return [ array get result ] } } \ No newline at end of file diff --git a/rosetta/file18.clojure b/rosetta/file18.clojure new file mode 100644 index 0000000..28272fa --- /dev/null +++ b/rosetta/file18.clojure @@ -0,0 +1 @@ +  ( doseq [ [ k v ] { : a 1 , : b 2 , : c 3 } ] ( println k "=" v ) )   ( doseq [ k ( keys { : a 1 , : b 2 , : c 3 } ) ] ( println k ) )   ( doseq [ v ( vals { : a 1 , : b 2 , : c 3 } ) ] ( println v ) )   \ No newline at end of file diff --git a/rosetta/file18.hs b/rosetta/file18.hs new file mode 100644 index 0000000..aa3a445 --- /dev/null +++ b/rosetta/file18.hs @@ -0,0 +1 @@ +-- Three infinite lists, corresponding to the three definitions in the problem -- statement.   cats1 = map ( \n -> product [ n + 2 .. 2 * n ] ` div ` product [ 1 .. n ] ) [ 0 .. ]   cats2 = 1  : map ( \n -> sum $ zipWith ( * ) ( reverse ( take n cats2 ) ) cats2 ) [ 1 .. ]   cats3 = scanl ( \c n -> c * 2 * ( 2 * n - 1 ) ` div ` ( n + 1 ) ) 1 [ 1 .. ]   main = mapM_ ( print . take 15 ) [ cats1 , cats2 , cats3 ] \ No newline at end of file diff --git a/rosetta/file18.java b/rosetta/file18.java new file mode 100644 index 0000000..44ff68b --- /dev/null +++ b/rosetta/file18.java @@ -0,0 +1 @@ +import java.util.Arrays ; import java.util.Random ;   public class AtomicUpdates { public static class Buckets { private final int [ ] data ;   public Buckets ( int [ ] data ) { this . data = data. clone ( ) ; }   public int getBucket ( int index ) { synchronized ( data ) { return data [ index ] ; } }   public int transfer ( int srcBucketIndex, int destBucketIndex, int amount ) { if ( amount == 0 ) return 0 ; // Negative transfers will happen in the opposite direction if ( amount < 0 ) { int tempIndex = srcBucketIndex ; srcBucketIndex = destBucketIndex ; destBucketIndex = tempIndex ; amount = - amount ; } synchronized ( data ) { if ( amount > data [ srcBucketIndex ] ) amount = data [ srcBucketIndex ] ; if ( amount <= 0 ) return 0 ; data [ srcBucketIndex ] -= amount ; data [ destBucketIndex ] += amount ; return amount ; } }   public int [ ] getBuckets ( ) { synchronized ( data ) { return data. clone ( ) ; } } }   public static int getTotal ( int [ ] values ) { int totalValue = 0 ; for ( int i = values. length - 1 ; i >= 0 ; i -- ) totalValue += values [ i ] ; return totalValue ; }   public static void main ( String [ ] args ) { final int NUM_BUCKETS = 10 ; Random rnd = new Random ( ) ; final int [ ] values = new int [ NUM_BUCKETS ] ; for ( int i = 0 ; i < values. length ; i ++ ) values [ i ] = rnd. nextInt ( 10 ) ; System . out . println ( "Initial Array: " + getTotal ( values ) + " " + Arrays . toString ( values ) ) ; final Buckets buckets = new Buckets ( values ) ;   new Thread ( new Runnable ( ) { public void run ( ) { Random r = new Random ( ) ; while ( true ) { int srcBucketIndex = r. nextInt ( NUM_BUCKETS ) ; int destBucketIndex = r. nextInt ( NUM_BUCKETS ) ; int amount = ( buckets. getBucket ( srcBucketIndex ) - buckets. getBucket ( destBucketIndex ) ) >> 1 ; if ( amount != 0 ) buckets. transfer ( srcBucketIndex, destBucketIndex, amount ) ; } } } ) . start ( ) ;   new Thread ( new Runnable ( ) { public void run ( ) { Random r = new Random ( ) ; while ( true ) { int srcBucketIndex = r. nextInt ( NUM_BUCKETS ) ; int destBucketIndex = r. nextInt ( NUM_BUCKETS ) ; int srcBucketAmount = buckets. getBucket ( srcBucketIndex ) ; int destBucketAmount = buckets. getBucket ( destBucketIndex ) ; int amount = r. nextInt ( srcBucketAmount + destBucketAmount + 1 ) - destBucketAmount ; if ( amount != 0 ) buckets. transfer ( srcBucketIndex, destBucketIndex, amount ) ; } } } ) . start ( ) ;   while ( true ) { long nextPrintTime = System . currentTimeMillis ( ) + 3000 ; long curTime ; while ( ( curTime = System . currentTimeMillis ( ) ) < nextPrintTime ) { try { Thread . sleep ( nextPrintTime - curTime ) ; } catch ( InterruptedException e ) { } } int [ ] bucketValues = buckets. getBuckets ( ) ; System . out . println ( "Current values: " + getTotal ( bucketValues ) + " " + Arrays . toString ( bucketValues ) ) ; } } }   \ No newline at end of file diff --git a/rosetta/file18.js b/rosetta/file18.js new file mode 100644 index 0000000..d7403e2 --- /dev/null +++ b/rosetta/file18.js @@ -0,0 +1 @@ +  function createRandomBracketSequence ( maxlen ) { var chars = { '0' : '[' , '1' : ']' } ; function getRandomInteger ( to ) { return Math . floor ( Math . random ( ) * ( to + 1 ) ) ; } var n = getRandomInteger ( maxlen ) ; var result = [ ] ; for ( var i = 0 ; i < n ; i ++ ) { result. push ( chars [ getRandomInteger ( 1 ) ] ) ; } return result. join ( "" ) ; }   function bracketsAreBalanced ( s ) { var open = ( arguments. length > 1 ) ? arguments [ 1 ] : '[' ; var close = ( arguments. length > 2 ) ? arguments [ 2 ] : ']' ; var c = 0 ; for ( var i = 0 ; i < s. length ; i ++ ) { var ch = s. charAt ( i ) ; if ( ch == open ) { c ++; } else if ( ch == close ) { c --; if ( c < 0 ) return false ; } } return c == 0 ; }   var c = 0 ; while ( c < 5 ) { var seq = createRandomBracketSequence ( 8 ) ; alert ( seq + ': \t ' + bracketsAreBalanced ( seq ) ) ; c ++; }   \ No newline at end of file diff --git a/rosetta/file18.ocaml b/rosetta/file18.ocaml new file mode 100644 index 0000000..e6b0863 --- /dev/null +++ b/rosetta/file18.ocaml @@ -0,0 +1 @@ +# String . create 10 ;; - : string = "\000\023\000\000\001\000\000\000\000\000" \ No newline at end of file diff --git a/rosetta/file18.perl b/rosetta/file18.perl new file mode 100644 index 0000000..4d48d5b --- /dev/null +++ b/rosetta/file18.perl @@ -0,0 +1 @@ +use strict ; my @c = ( ) ; # create an empty "array" collection   # fill it push @c , 10 , 11 , 12 ; push @c , 65 ; # print it print join ( " " , @c ) . " \n " ;   # create an empty hash my %h = ( ) ; # add some pair $h { 'one' } = 1 ; $h { 'two' } = 2 ; # print it foreach my $i ( keys %h ) { print $i . " -> " . $h { $i } . " \n " ; } \ No newline at end of file diff --git a/rosetta/file18.php b/rosetta/file18.php new file mode 100644 index 0000000..8438e45 --- /dev/null +++ b/rosetta/file18.php @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/rosetta/file18.py b/rosetta/file18.py new file mode 100644 index 0000000..da23dad --- /dev/null +++ b/rosetta/file18.py @@ -0,0 +1 @@ +class NG: def __init__ ( self , a1 , a , b1 , b ) : self . a1 , self . a , self . b1 , self . b = a1 , a , b1 , b   def ingress ( self , n ) : self . a , self . a1 = self . a1 , self . a + self . a1 * n self . b , self . b1 = self . b1 , self . b + self . b1 * n   @ property def needterm ( self ) : return ( self . b == 0 or self . b1 == 0 ) or not self . a // self . b == self . a1 // self . b1   @ property def egress ( self ) : n = self . a // self . b self . a , self . b = self . b , self . a - self . b * n self . a1 , self . b1 = self . b1 , self . a1 - self . b1 * n return n   @ property def egress_done ( self ) : if self . needterm : self . a , self . b = self . a1 , self . b1 return self . egress   @ property def done ( self ) : return self . b == 0 and self . b1 == 0 \ No newline at end of file diff --git a/rosetta/file18.rb b/rosetta/file18.rb new file mode 100644 index 0000000..d69dd87 --- /dev/null +++ b/rosetta/file18.rb @@ -0,0 +1 @@ +require 'matrix'   # Start with some matrix. i = Complex ::I matrix = Matrix [ [ i, 0 , 0 ] , [ 0 , i, 0 ] , [ 0 , 0 , i ] ]   # Find the conjugate transpose. # Matrix#conjugate appeared in Ruby 1.9.2. conjt = matrix. conj . t # aliases for matrix.conjugate.tranpose print 'conjugate tranpose: ' ; puts conjt   if matrix. square ? # These predicates appeared in Ruby 1.9.3. print 'Hermitian? ' ; puts matrix. hermitian ? print ' normal? ' ; puts matrix. normal ? print ' unitary? ' ; puts matrix. unitary ? else # Matrix is not square. These predicates would # raise ExceptionForMatrix::ErrDimensionMismatch. print 'Hermitian? false' print ' normal? false' print ' unitary? false' end \ No newline at end of file diff --git a/rosetta/file18.scala b/rosetta/file18.scala new file mode 100644 index 0000000..76c913f --- /dev/null +++ b/rosetta/file18.scala @@ -0,0 +1 @@ +class Example { private var _ name : String = null   def this ( name : String ) { this ( ) _ name = name }   override def toString = "Hello, I am " + _ name }   object BreakPrivacy extends App { val foo : Example = new Example ( "Erik" ) for ( f < - classOf [ Example ] . getDeclaredFields if f. getName == "_name" ) { f. setAccessible ( true ) println ( f. get ( foo ) ) f. set ( foo, "Edith" ) println ( foo ) } } \ No newline at end of file diff --git a/rosetta/file18.ss b/rosetta/file18.ss new file mode 100644 index 0000000..9e6c216 --- /dev/null +++ b/rosetta/file18.ss @@ -0,0 +1 @@ +( define ( fibonacci n ) ( if ( > 0 n ) "Error: argument must not be negative." ( let aux ( ( a 1 ) ( b 0 ) ( count n ) ) ( if ( = count 0 ) b ( aux ( + a b ) a ( - count 1 ) ) ) ) ) )   ( map fibonacci ' ( 1 2 3 4 5 6 7 8 9 10 ) ) \ No newline at end of file diff --git a/rosetta/file18.tcl b/rosetta/file18.tcl new file mode 100644 index 0000000..11ba2a3 --- /dev/null +++ b/rosetta/file18.tcl @@ -0,0 +1 @@ +proc subsets { l } { set res [ list [ list ] ] foreach e $l { foreach subset $res { lappend res [ lappend subset $e ] } } return $res } puts [ subsets { a b c d } ] \ No newline at end of file diff --git a/rosetta/file19.clojure b/rosetta/file19.clojure new file mode 100644 index 0000000..28272fa --- /dev/null +++ b/rosetta/file19.clojure @@ -0,0 +1 @@ +  ( doseq [ [ k v ] { : a 1 , : b 2 , : c 3 } ] ( println k "=" v ) )   ( doseq [ k ( keys { : a 1 , : b 2 , : c 3 } ) ] ( println k ) )   ( doseq [ v ( vals { : a 1 , : b 2 , : c 3 } ) ] ( println v ) )   \ No newline at end of file diff --git a/rosetta/file19.hs b/rosetta/file19.hs new file mode 100644 index 0000000..b7eb252 --- /dev/null +++ b/rosetta/file19.hs @@ -0,0 +1 @@ +nums = [ 1 .. 10 ]   summation = foldl ( + ) 0 nums product = foldl ( * ) 1 nums concatenation = foldr ( \num s -> show num ++ s ) "" nums \ No newline at end of file diff --git a/rosetta/file19.java b/rosetta/file19.java new file mode 100644 index 0000000..44ff68b --- /dev/null +++ b/rosetta/file19.java @@ -0,0 +1 @@ +import java.util.Arrays ; import java.util.Random ;   public class AtomicUpdates { public static class Buckets { private final int [ ] data ;   public Buckets ( int [ ] data ) { this . data = data. clone ( ) ; }   public int getBucket ( int index ) { synchronized ( data ) { return data [ index ] ; } }   public int transfer ( int srcBucketIndex, int destBucketIndex, int amount ) { if ( amount == 0 ) return 0 ; // Negative transfers will happen in the opposite direction if ( amount < 0 ) { int tempIndex = srcBucketIndex ; srcBucketIndex = destBucketIndex ; destBucketIndex = tempIndex ; amount = - amount ; } synchronized ( data ) { if ( amount > data [ srcBucketIndex ] ) amount = data [ srcBucketIndex ] ; if ( amount <= 0 ) return 0 ; data [ srcBucketIndex ] -= amount ; data [ destBucketIndex ] += amount ; return amount ; } }   public int [ ] getBuckets ( ) { synchronized ( data ) { return data. clone ( ) ; } } }   public static int getTotal ( int [ ] values ) { int totalValue = 0 ; for ( int i = values. length - 1 ; i >= 0 ; i -- ) totalValue += values [ i ] ; return totalValue ; }   public static void main ( String [ ] args ) { final int NUM_BUCKETS = 10 ; Random rnd = new Random ( ) ; final int [ ] values = new int [ NUM_BUCKETS ] ; for ( int i = 0 ; i < values. length ; i ++ ) values [ i ] = rnd. nextInt ( 10 ) ; System . out . println ( "Initial Array: " + getTotal ( values ) + " " + Arrays . toString ( values ) ) ; final Buckets buckets = new Buckets ( values ) ;   new Thread ( new Runnable ( ) { public void run ( ) { Random r = new Random ( ) ; while ( true ) { int srcBucketIndex = r. nextInt ( NUM_BUCKETS ) ; int destBucketIndex = r. nextInt ( NUM_BUCKETS ) ; int amount = ( buckets. getBucket ( srcBucketIndex ) - buckets. getBucket ( destBucketIndex ) ) >> 1 ; if ( amount != 0 ) buckets. transfer ( srcBucketIndex, destBucketIndex, amount ) ; } } } ) . start ( ) ;   new Thread ( new Runnable ( ) { public void run ( ) { Random r = new Random ( ) ; while ( true ) { int srcBucketIndex = r. nextInt ( NUM_BUCKETS ) ; int destBucketIndex = r. nextInt ( NUM_BUCKETS ) ; int srcBucketAmount = buckets. getBucket ( srcBucketIndex ) ; int destBucketAmount = buckets. getBucket ( destBucketIndex ) ; int amount = r. nextInt ( srcBucketAmount + destBucketAmount + 1 ) - destBucketAmount ; if ( amount != 0 ) buckets. transfer ( srcBucketIndex, destBucketIndex, amount ) ; } } } ) . start ( ) ;   while ( true ) { long nextPrintTime = System . currentTimeMillis ( ) + 3000 ; long curTime ; while ( ( curTime = System . currentTimeMillis ( ) ) < nextPrintTime ) { try { Thread . sleep ( nextPrintTime - curTime ) ; } catch ( InterruptedException e ) { } } int [ ] bucketValues = buckets. getBuckets ( ) ; System . out . println ( "Current values: " + getTotal ( bucketValues ) + " " + Arrays . toString ( bucketValues ) ) ; } } }   \ No newline at end of file diff --git a/rosetta/file19.js b/rosetta/file19.js new file mode 100644 index 0000000..d7403e2 --- /dev/null +++ b/rosetta/file19.js @@ -0,0 +1 @@ +  function createRandomBracketSequence ( maxlen ) { var chars = { '0' : '[' , '1' : ']' } ; function getRandomInteger ( to ) { return Math . floor ( Math . random ( ) * ( to + 1 ) ) ; } var n = getRandomInteger ( maxlen ) ; var result = [ ] ; for ( var i = 0 ; i < n ; i ++ ) { result. push ( chars [ getRandomInteger ( 1 ) ] ) ; } return result. join ( "" ) ; }   function bracketsAreBalanced ( s ) { var open = ( arguments. length > 1 ) ? arguments [ 1 ] : '[' ; var close = ( arguments. length > 2 ) ? arguments [ 2 ] : ']' ; var c = 0 ; for ( var i = 0 ; i < s. length ; i ++ ) { var ch = s. charAt ( i ) ; if ( ch == open ) { c ++; } else if ( ch == close ) { c --; if ( c < 0 ) return false ; } } return c == 0 ; }   var c = 0 ; while ( c < 5 ) { var seq = createRandomBracketSequence ( 8 ) ; alert ( seq + ': \t ' + bracketsAreBalanced ( seq ) ) ; c ++; }   \ No newline at end of file diff --git a/rosetta/file19.ocaml b/rosetta/file19.ocaml new file mode 100644 index 0000000..e6b0863 --- /dev/null +++ b/rosetta/file19.ocaml @@ -0,0 +1 @@ +# String . create 10 ;; - : string = "\000\023\000\000\001\000\000\000\000\000" \ No newline at end of file diff --git a/rosetta/file19.perl b/rosetta/file19.perl new file mode 100644 index 0000000..4d48d5b --- /dev/null +++ b/rosetta/file19.perl @@ -0,0 +1 @@ +use strict ; my @c = ( ) ; # create an empty "array" collection   # fill it push @c , 10 , 11 , 12 ; push @c , 65 ; # print it print join ( " " , @c ) . " \n " ;   # create an empty hash my %h = ( ) ; # add some pair $h { 'one' } = 1 ; $h { 'two' } = 2 ; # print it foreach my $i ( keys %h ) { print $i . " -> " . $h { $i } . " \n " ; } \ No newline at end of file diff --git a/rosetta/file19.php b/rosetta/file19.php new file mode 100644 index 0000000..6140beb --- /dev/null +++ b/rosetta/file19.php @@ -0,0 +1 @@ + 1 , "world" => 2 , "!" => 3 ) ;   // iterate over key-value pairs foreach ( $pairs as $k => $v ) { echo "(k,v) = ( $k , $v ) \n " ; }   // iterate over keys foreach ( array_keys ( $pairs ) as $key ) { echo "key = $key , value = $pairs [ $key ] \n " ; }   // iterate over values foreach ( $pairs as $value ) { echo "values = $value \n " ; } ?> \ No newline at end of file diff --git a/rosetta/file19.py b/rosetta/file19.py new file mode 100644 index 0000000..7995c02 --- /dev/null +++ b/rosetta/file19.py @@ -0,0 +1 @@ +  import random   def rand9999 ( ) : return random . randint ( 1000 , 9999 )   def tag ( attr = '' , **kwargs ) : for tag , txt in kwargs. items ( ) : return '<{tag}{attr}>{txt}' . format ( ** locals ( ) )   if __name__ == '__main__' : header = tag ( tr = '' . join ( tag ( th = txt ) for txt in ',X,Y,Z' . split ( ',' ) ) ) + ' \n ' rows = ' \n ' . join ( tag ( tr = '' . join ( tag ( ' style="font-weight: bold;"' , td = i ) + '' . join ( tag ( td = rand9999 ( ) ) for j in range ( 3 ) ) ) ) for i in range ( 1 , 6 ) ) table = tag ( table = ' \n ' + header + rows + ' \n ' ) print ( table ) \ No newline at end of file diff --git a/rosetta/file19.rb b/rosetta/file19.rb new file mode 100644 index 0000000..a3f3a51 --- /dev/null +++ b/rosetta/file19.rb @@ -0,0 +1 @@ +# I define a class to implement baby NG class NG def initialize ( a1, a, b1, b ) @a1 , @a , @b1 , @b = a1, a, b1, b end def ingress ( n ) @a , @a1 = @a1 , @a + @a1 * n @b , @b1 = @b1 , @b + @b1 * n end def needterm? return true if @b == 0 or @b1 == 0 return true unless @a / @b == @a1 / @b1 false end def egress n = @a / @b @a , @b = @b , @a - @b * n @a1 , @b1 = @b1 , @a1 - @b1 * n n end def egress_done @a , @b = @a1 , @b1 if needterm? egress end def done? @b == 0 and @b1 == 0 end end \ No newline at end of file diff --git a/rosetta/file19.scala b/rosetta/file19.scala new file mode 100644 index 0000000..f0f4316 --- /dev/null +++ b/rosetta/file19.scala @@ -0,0 +1 @@ +import java. util . { Calendar, GregorianCalendar } import language. postfixOps import collection. mutable . ListBuffer   object CalendarPrint extends App { val locd = java. util . Locale . getDefault ( ) val cal = new GregorianCalendar val monthsMax = cal. getMaximum ( Calendar. MONTH )   def JDKweekDaysToISO ( dn : Int ) = { val nday = dn - Calendar. MONDAY if ( nday < 0 ) ( dn + Calendar. THURSDAY ) else nday }   def daysInMonth ( year : Int, monthMinusOne : Int ) : Int = { cal. set ( year, monthMinusOne, 1 ) cal. getActualMaximum ( Calendar. DAY_OF_MONTH ) }   def namesOfMonths ( ) = { def f1 ( i : Int ) : String = { cal. set ( 2013 , i, 1 ) cal. getDisplayName ( Calendar. MONTH , Calendar. LONG , locd ) } ( 0 to monthsMax ) map f1 }   def offsets ( year : Int ) : List [ Int ] = { val months = cal. getMaximum ( Calendar. MONTH ) def get1stDayOfWeek ( i : Int ) = { cal. set ( year, i, 1 ) cal. get ( Calendar. DAY_OF_WEEK ) } ( 0 to monthsMax ) . toList map get1stDayOfWeek map { i => JDKweekDaysToISO ( i ) } }   def headerNameOfDays ( ) = { val mdow = cal. getDisplayNames ( Calendar. DAY_OF_WEEK , Calendar. SHORT , locd ) // map days of week val it = mdow. keySet . iterator val keySet = new ListBuffer [ String ] while ( it. hasNext ) keySet + = it. next ( keySet. map { key => ( JDKweekDaysToISO ( mdow. get ( key ) ) , key. take ( 2 ) ) } . sortWith ( _ . _ 1 < _ . _ 1 ) map ( _ . _ 2 ) ) . mkString ( " " ) }   def getGregCal ( year : Int ) = { {   def dayOfMonth ( month : Int ) = new Iterator [ ( Int, Int ) ] { cal. set ( year, month, 1 ) var ldom = 0   def next ( ) = { val res = ( cal. get ( Calendar. MONTH ) , cal. get ( Calendar. DAY_OF_MONTH ) ) ldom = res. _ 2 cal. roll ( Calendar. DAY_OF_MONTH , true ) res }   def hasNext ( ) = ( cal. get ( Calendar. DAY_OF_MONTH ) > ldom ) } var ret : List [ ( Int, Int ) ] = Nil for ( i < - 0 to monthsMax ) ret = ret ++ ( dayOfMonth ( i ) . toSeq ) ( ret, offsets ( year ) ) } }   def printCalendar ( calendar : ( List [ ( Int, Int ) ] , List [ Int ] ) , headerList : List [ String ] = Nil, printerWidth : Int = 80 ) = { val mw = 20 // month width val gwf = 2 // gap width fixed val gwm = 2 // gap width minimum val fgw = true   val arr = Array. ofDim [ String ] ( 6 , 7 )   def limits ( printerWidth : Int ) : ( Int, Int, Int, Int, Int ) = { val pw = if ( printerWidth < 20 ) 20 else if ( printerWidth > 300 ) 300 else printerWidth   // months side by side, gaps sum minimum val ( msbs, gsm ) = { val x1 = { val c = if ( pw / mw > 12 ) 12 else pw / mw val a = ( c - 1 ) if ( c * mw + a * gwm <= pw ) c else a } match { case 5 => 4 case a if ( a > 6 && a < 12 ) => 6 case other => other } ( x1, ( x1 - 1 ) * gwm ) }   def getFGW ( msbs : Int, gsm : Int ) = { val r = ( pw - msbs * mw - gsm ) / 2 ; ( r, gwf, r ) } // fixed gap width def getVGW ( msbs : Int, gsm : Int ) = pw - msbs * mw - gsm match { // variable gap width case a if ( a < 2 * gwm ) => ( a / 2 , gwm, a / 2 ) case b => { val x = ( b + gsm ) / ( msbs + 1 ) ; ( x, x, x ) } }   // left margin, gap width, right margin val ( lm, gw, rm ) = if ( fgw ) getFGW ( msbs, gsm ) else getVGW ( msbs, gsm ) ( pw, msbs, lm, gw, rm ) } // def limits(   val ( pw, msbs, lm, gw, rm ) = limits ( printerWidth ) val monthsList = ( 0 to monthsMax ) . map { m => calendar. _ 1. filter { _ . _ 1 == m } } val nom = namesOfMonths ( ) val hnod = headerNameOfDays   def fsplit ( list : List [ ( Int, Int ) ] ) : List [ String ] = { def fap ( p : Int ) = ( p / 7 , p % 7 ) for ( i < - 0 until 6 ) for ( j < - 0 until 7 ) arr ( i ) ( j ) = " " for ( i < - 0 until list. size ) arr ( fap ( i + calendar. _ 2 ( list ( i ) . _ 1 ) ) . _ 1 ) ( fap ( i + calendar. _ 2 ( list ( i ) . _ 1 ) ) . _ 2 ) = f "${(list(i)._2)}%2d" arr. toList . map ( _ . foldRight ( "" ) ( _ + " " + _ ) ) } val monthsRows = monthsList. map ( fsplit )   def center ( s : String, l : Int ) : String = { ( if ( s. size >= l ) s else " " * ( ( l - s. size ) / 2 ) + s + " " * ( ( l - s. size ) / 2 ) + " " ) . substring ( 0 , l ) }   val maxMonths = monthsMax + 1   val rowblocks = ( 1 to maxMonths / msbs ) . map { i => ( 0 to 5 ) . map { j => val lb = new ListBuffer [ String ] val k = ( i - 1 ) * msbs ( k to k + msbs - 1 ) . map { l => lb + = monthsRows ( l ) ( j ) } lb } }   val mheaders = ( 1 to maxMonths / msbs ) . map { i => ( 0 to msbs - 1 ) . map { j => center ( nom ( j + ( i - 1 ) * msbs ) , 20 ) } } val dowheaders = ( 1 to maxMonths / msbs ) . map { i => ( 0 to msbs - 1 ) . map { j => center ( hnod, 20 ) } }   headerList. foreach ( xs => println ( center ( xs + ' \n ' , pw ) ) ) ( 1 to 12 / msbs ) . foreach { i => println ( " " * lm + mheaders ( i - 1 ) . foldRight ( "" ) ( _ + " " * gw + _ ) ) println ( " " * lm + dowheaders ( i - 1 ) . foldRight ( "" ) ( _ + " " * gw + _ ) ) rowblocks ( i - 1 ) . foreach { xs => println ( " " * lm + xs. foldRight ( "" ) ( _ + " " * ( gw - 1 ) + _ ) ) } println } } // def printCal(   printCalendar ( getGregCal ( 1969 ) , List ( "[Snoopy Picture]" , "1969" ) ) printCalendar ( getGregCal ( 1582 ) , List ( "[Snoopy Picture]" , "1582" ) , printerWidth = 132 ) } \ No newline at end of file diff --git a/rosetta/file19.ss b/rosetta/file19.ss new file mode 100644 index 0000000..db32120 --- /dev/null +++ b/rosetta/file19.ss @@ -0,0 +1 @@ +( define x ( expt 5 ( expt 4 ( expt 3 2 ) ) ) ) ( define y ( number -> string x ) ) ( define l ( string-length y ) ) ( display ( string-append "5**4**3**2 = " ( substring y 0 20 ) "..." ( substring y ( - l 20 ) l ) " and has " ( number -> string l ) " digits" ) ) ( newline ) \ No newline at end of file diff --git a/rosetta/file19.tcl b/rosetta/file19.tcl new file mode 100644 index 0000000..87f4d68 --- /dev/null +++ b/rosetta/file19.tcl @@ -0,0 +1 @@ +package require Tcl 8.5   # Allow override of device name proc systemRandomInteger { { device "/dev/random" } } { set f [ open $device "rb" ] binary scan [ read $f 4 ] "I" x close $f return $x } \ No newline at end of file diff --git a/rosetta/file2.clojure b/rosetta/file2.clojure new file mode 100644 index 0000000..00b2a4a --- /dev/null +++ b/rosetta/file2.clojure @@ -0,0 +1 @@ +  ( def blocks ( -> "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM" ( . split " " ) vec ) )   ( defn omit "return bs with (one instance of) b omitted" [ bs b ] ( let [ [ before after ] ( split-with # ( not = b % ) bs ) ] ( concat before ( rest after ) ) ) )   ( defn abc "return lazy sequence of solutions (i.e. block lists)" [ blocks [ c & cs ] ] ( if - some c ( for [ b blocks : when ( some # ( = c % ) b ) bs ( abc ( omit blocks b ) cs ) ] ( cons b bs ) ) [ [ ] ] ) )     ( doseq [ word [ "A" "BARK" "Book" "treat" "COMMON" "SQUAD" "CONFUSE" ] ] ( ->> word . toUpperCase ( abc blocks ) first ( printf "%s: %b \n " word ) ) ) \ No newline at end of file diff --git a/rosetta/file2.hs b/rosetta/file2.hs new file mode 100644 index 0000000..b270548 --- /dev/null +++ b/rosetta/file2.hs @@ -0,0 +1 @@ +ack 0 n = n + 1 ack m 0 = ack ( m - 1 ) 1 ack m n = ack ( m - 1 ) ( ack m ( n - 1 ) ) \ No newline at end of file diff --git a/rosetta/file2.java b/rosetta/file2.java new file mode 100644 index 0000000..0d2011b --- /dev/null +++ b/rosetta/file2.java @@ -0,0 +1 @@ +import java.util.* ;   public class Sum2 { public static void main ( String [ ] args ) { Scanner in = new Scanner ( System . in ) ; // Standard input System . out . println ( in. nextInt ( ) + in. nextInt ( ) ) ; // Standard output } } \ No newline at end of file diff --git a/rosetta/file2.js b/rosetta/file2.js new file mode 100644 index 0000000..b295c99 --- /dev/null +++ b/rosetta/file2.js @@ -0,0 +1 @@ +let characters = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM" ; let blocks = characters. split ( " " ) . map ( pair => pair. split ( "" ) ) ;   function isWordPossible ( word ) { var letters = [ ... word . toUpperCase ( ) ] ; var length = letters. length ; var copy = new Set ( blocks ) ;   for ( let letter of letters ) { for ( let block of copy ) { let index = block. indexOf ( letter ) ;   if ( index !== - 1 ) { length --; copy. delete ( block ) ; break ; } }   } return ! length ; }   [ "A" , "BARK" , "BOOK" , "TREAT" , "COMMON" , "SQUAD" , "CONFUSE" ] . forEach ( word => console. log ( `$ { word } : $ { isWordPossible ( word ) } ` ) ) ;   \ No newline at end of file diff --git a/rosetta/file2.ocaml b/rosetta/file2.ocaml new file mode 100644 index 0000000..21de3c5 --- /dev/null +++ b/rosetta/file2.ocaml @@ -0,0 +1 @@ +let rec a m n = if m = 0 then ( n + 1 ) else if n = 0 then ( a ( m - 1 ) 1 ) else ( a ( m - 1 ) ( a m ( n - 1 ) ) ) \ No newline at end of file diff --git a/rosetta/file2.perl b/rosetta/file2.perl new file mode 100644 index 0000000..9eaacf0 --- /dev/null +++ b/rosetta/file2.perl @@ -0,0 +1 @@ +use Math :: BigInt ; my $x = Math :: BigInt -> new ( '5' ) ** Math :: BigInt -> new ( '4' ) ** Math :: BigInt -> new ( '3' ) ** Math :: BigInt -> new ( '2' ) ; my $y = "$x" ; printf ( "5**4**3**2 = %s...%s and has %i digits \n " , substr ( $y , 0 , 20 ) , substr ( $y ,- 20 ) , length ( $y ) ) ; \ No newline at end of file diff --git a/rosetta/file2.php b/rosetta/file2.php new file mode 100644 index 0000000..940c3f6 --- /dev/null +++ b/rosetta/file2.php @@ -0,0 +1 @@ +#!/usr/bin/env php The 24 Game   Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24.   An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwise you are repeatedly asked for an expression until it evaluates to 24   Note: you cannot form multiple digit numbers from the supplied digits, so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.   0 ) { return ; } }   return eval ( "return $expression ;" ) ; } ?> \ No newline at end of file diff --git a/rosetta/file2.py b/rosetta/file2.py new file mode 100644 index 0000000..b9a3c3f --- /dev/null +++ b/rosetta/file2.py @@ -0,0 +1 @@ +>>> y = str ( 5 ** 4 ** 3 ** 2 ) >>> print ( "5**4**3**2 = %s...%s and has %i digits"  % ( y [ : 20 ] , y [ - 20 : ] , len ( y ) ) ) 5 ** 4 ** 3 ** 2 = 62060698786608744707 ... 92256259918212890625 and has 183231 digits \ No newline at end of file diff --git a/rosetta/file2.rb b/rosetta/file2.rb new file mode 100644 index 0000000..f47ee7f --- /dev/null +++ b/rosetta/file2.rb @@ -0,0 +1 @@ +irb ( main ) :001: 0 > y = ( 5 ** 4 ** 3 ** 2 ) . to_s ; puts "5**4**3**2 = #{y[0..19]}...#{y[-20..-1]} and has #{y.length} digits" 5 ** 4 ** 3 ** 2 = 62060698786608744707 ... 92256259918212890625 and has 183231 digits \ No newline at end of file diff --git a/rosetta/file2.scala b/rosetta/file2.scala new file mode 100644 index 0000000..5d9bc2c --- /dev/null +++ b/rosetta/file2.scala @@ -0,0 +1 @@ +def ack ( m : BigInt, n : BigInt ) : BigInt = { if ( m == 0 ) n+ 1 else if ( n == 0 ) ack ( m- 1 , 1 ) else ack ( m- 1 , ack ( m, n- 1 ) ) } \ No newline at end of file diff --git a/rosetta/file2.ss b/rosetta/file2.ss new file mode 100644 index 0000000..4d53f4c --- /dev/null +++ b/rosetta/file2.ss @@ -0,0 +1 @@ +( display ( + ( read ) ( read ) ) ) \ No newline at end of file diff --git a/rosetta/file2.tcl b/rosetta/file2.tcl new file mode 100644 index 0000000..91f5d3a --- /dev/null +++ b/rosetta/file2.tcl @@ -0,0 +1 @@ +oo:: class create AbstractQueue { method enqueue item { error "not implemented" } method dequeue { } { error "not implemented" } self unexport create new } \ No newline at end of file diff --git a/rosetta/file20.clojure b/rosetta/file20.clojure new file mode 100644 index 0000000..28272fa --- /dev/null +++ b/rosetta/file20.clojure @@ -0,0 +1 @@ +  ( doseq [ [ k v ] { : a 1 , : b 2 , : c 3 } ] ( println k "=" v ) )   ( doseq [ k ( keys { : a 1 , : b 2 , : c 3 } ) ] ( println k ) )   ( doseq [ v ( vals { : a 1 , : b 2 , : c 3 } ) ] ( println v ) )   \ No newline at end of file diff --git a/rosetta/file20.hs b/rosetta/file20.hs new file mode 100644 index 0000000..12312b8 --- /dev/null +++ b/rosetta/file20.hs @@ -0,0 +1 @@ +[ 1 , 2 , 3 , 4 , 5 ] \ No newline at end of file diff --git a/rosetta/file20.java b/rosetta/file20.java new file mode 100644 index 0000000..44ff68b --- /dev/null +++ b/rosetta/file20.java @@ -0,0 +1 @@ +import java.util.Arrays ; import java.util.Random ;   public class AtomicUpdates { public static class Buckets { private final int [ ] data ;   public Buckets ( int [ ] data ) { this . data = data. clone ( ) ; }   public int getBucket ( int index ) { synchronized ( data ) { return data [ index ] ; } }   public int transfer ( int srcBucketIndex, int destBucketIndex, int amount ) { if ( amount == 0 ) return 0 ; // Negative transfers will happen in the opposite direction if ( amount < 0 ) { int tempIndex = srcBucketIndex ; srcBucketIndex = destBucketIndex ; destBucketIndex = tempIndex ; amount = - amount ; } synchronized ( data ) { if ( amount > data [ srcBucketIndex ] ) amount = data [ srcBucketIndex ] ; if ( amount <= 0 ) return 0 ; data [ srcBucketIndex ] -= amount ; data [ destBucketIndex ] += amount ; return amount ; } }   public int [ ] getBuckets ( ) { synchronized ( data ) { return data. clone ( ) ; } } }   public static int getTotal ( int [ ] values ) { int totalValue = 0 ; for ( int i = values. length - 1 ; i >= 0 ; i -- ) totalValue += values [ i ] ; return totalValue ; }   public static void main ( String [ ] args ) { final int NUM_BUCKETS = 10 ; Random rnd = new Random ( ) ; final int [ ] values = new int [ NUM_BUCKETS ] ; for ( int i = 0 ; i < values. length ; i ++ ) values [ i ] = rnd. nextInt ( 10 ) ; System . out . println ( "Initial Array: " + getTotal ( values ) + " " + Arrays . toString ( values ) ) ; final Buckets buckets = new Buckets ( values ) ;   new Thread ( new Runnable ( ) { public void run ( ) { Random r = new Random ( ) ; while ( true ) { int srcBucketIndex = r. nextInt ( NUM_BUCKETS ) ; int destBucketIndex = r. nextInt ( NUM_BUCKETS ) ; int amount = ( buckets. getBucket ( srcBucketIndex ) - buckets. getBucket ( destBucketIndex ) ) >> 1 ; if ( amount != 0 ) buckets. transfer ( srcBucketIndex, destBucketIndex, amount ) ; } } } ) . start ( ) ;   new Thread ( new Runnable ( ) { public void run ( ) { Random r = new Random ( ) ; while ( true ) { int srcBucketIndex = r. nextInt ( NUM_BUCKETS ) ; int destBucketIndex = r. nextInt ( NUM_BUCKETS ) ; int srcBucketAmount = buckets. getBucket ( srcBucketIndex ) ; int destBucketAmount = buckets. getBucket ( destBucketIndex ) ; int amount = r. nextInt ( srcBucketAmount + destBucketAmount + 1 ) - destBucketAmount ; if ( amount != 0 ) buckets. transfer ( srcBucketIndex, destBucketIndex, amount ) ; } } } ) . start ( ) ;   while ( true ) { long nextPrintTime = System . currentTimeMillis ( ) + 3000 ; long curTime ; while ( ( curTime = System . currentTimeMillis ( ) ) < nextPrintTime ) { try { Thread . sleep ( nextPrintTime - curTime ) ; } catch ( InterruptedException e ) { } } int [ ] bucketValues = buckets. getBuckets ( ) ; System . out . println ( "Current values: " + getTotal ( bucketValues ) + " " + Arrays . toString ( bucketValues ) ) ; } } }   \ No newline at end of file diff --git a/rosetta/file20.js b/rosetta/file20.js new file mode 100644 index 0000000..d7403e2 --- /dev/null +++ b/rosetta/file20.js @@ -0,0 +1 @@ +  function createRandomBracketSequence ( maxlen ) { var chars = { '0' : '[' , '1' : ']' } ; function getRandomInteger ( to ) { return Math . floor ( Math . random ( ) * ( to + 1 ) ) ; } var n = getRandomInteger ( maxlen ) ; var result = [ ] ; for ( var i = 0 ; i < n ; i ++ ) { result. push ( chars [ getRandomInteger ( 1 ) ] ) ; } return result. join ( "" ) ; }   function bracketsAreBalanced ( s ) { var open = ( arguments. length > 1 ) ? arguments [ 1 ] : '[' ; var close = ( arguments. length > 2 ) ? arguments [ 2 ] : ']' ; var c = 0 ; for ( var i = 0 ; i < s. length ; i ++ ) { var ch = s. charAt ( i ) ; if ( ch == open ) { c ++; } else if ( ch == close ) { c --; if ( c < 0 ) return false ; } } return c == 0 ; }   var c = 0 ; while ( c < 5 ) { var seq = createRandomBracketSequence ( 8 ) ; alert ( seq + ': \t ' + bracketsAreBalanced ( seq ) ) ; c ++; }   \ No newline at end of file diff --git a/rosetta/file20.ocaml b/rosetta/file20.ocaml new file mode 100644 index 0000000..0e6ab77 --- /dev/null +++ b/rosetta/file20.ocaml @@ -0,0 +1 @@ +let quad_bezier ~img ~color ~p1 : ( _x1, _y1 ) ~p2 : ( _x2, _y2 ) ~p3 : ( _x3, _y3 ) = let ( x1, y1, x2, y2, x3, y3 ) = ( float _x1, float _y1, float _x2, float _y2, float _x3, float _y3 ) in let bz t = let a = ( 1.0 -. t ) ** 2.0 and b = 2.0 *. t *. ( 1.0 -. t ) and c = t ** 2.0 in let x = a *. x1 +. b *. x2 +. c *. x3 and y = a *. y1 +. b *. y2 +. c *. y3 in ( int_of_float x, int_of_float y ) in let rec loop _t acc = if _t > 20 then acc else begin let t = ( float _t ) /. 20.0 in let x, y = bz t in loop ( succ _t ) ( ( x,y ) :: acc ) end in let pts = loop 0 [ ] in   (* (* draw only points *) List.iter (fun (x, y) -> put_pixel img color x y) pts; *)   (* draw segments *) let line = draw_line ~img ~color in let by_pair li f = ignore ( List . fold_left ( fun prev x -> f prev x ; x ) ( List . hd li ) ( List . tl li ) ) in by_pair pts ( fun p0 p1 -> line ~p0 ~p1 ) ; ;; \ No newline at end of file diff --git a/rosetta/file20.perl b/rosetta/file20.perl new file mode 100644 index 0000000..8d6e6d8 --- /dev/null +++ b/rosetta/file20.perl @@ -0,0 +1 @@ +#!/usr/bin/perl -w use strict ; use GD ;   my $image = new GD :: Image ( 320 , 240 ) ; my %colors = ( "white" => [ 255 , 255 , 255 ] , "red" => [ 255 , 0 , 0 ] , "green" => [ 0 , 255 , 0 ] , "blue" => [ 0 , 0 , 255 ] , "magenta" => [ 255 , 0 , 255 ] , "yellow" => [ 255 , 255 , 0 ] , "cyan" => [ 0 , 255 , 255 ] , "black" => [ 0 , 0 , 0 ] ) ; my @paintcolors ; foreach my $color ( keys %colors ) { my $paintcolor = $image -> colorAllocate ( @ { $colors { $color } } ) ; push @paintcolors , $paintcolor ; } my $startx = 0 ; my $starty = 0 ; my $run = 0 ; my $barheight = 240 / 4 ; my $colorindex = 0 ; while ( $run < 4 ) { my $barwidth = $run + 1 ; while ( $startx + $barwidth < 320 ) { $image -> filledRectangle ( $startx , $starty , $startx + $barwidth , $starty + $barheight - 1 , $paintcolors [ $colorindex % 8 ] ) ; $startx += $barwidth ; $colorindex ++ ; } $starty += $barheight ; $startx = 0 ; $colorindex = 0 ; $run ++ ; } open ( DISPLAY , ">" , "pinstripes.png" ) || die ; binmode DISPLAY ; print DISPLAY $image -> png ; close DISPLAY ; \ No newline at end of file diff --git a/rosetta/file20.php b/rosetta/file20.php new file mode 100644 index 0000000..6140beb --- /dev/null +++ b/rosetta/file20.php @@ -0,0 +1 @@ + 1 , "world" => 2 , "!" => 3 ) ;   // iterate over key-value pairs foreach ( $pairs as $k => $v ) { echo "(k,v) = ( $k , $v ) \n " ; }   // iterate over keys foreach ( array_keys ( $pairs ) as $key ) { echo "key = $key , value = $pairs [ $key ] \n " ; }   // iterate over values foreach ( $pairs as $value ) { echo "values = $value \n " ; } ?> \ No newline at end of file diff --git a/rosetta/file20.py b/rosetta/file20.py new file mode 100644 index 0000000..47ab033 --- /dev/null +++ b/rosetta/file20.py @@ -0,0 +1 @@ +def ToReducedRowEchelonForm ( M ) : if not M: return lead = 0 rowCount = len ( M ) columnCount = len ( M [ 0 ] ) for r in range ( rowCount ) : if lead >= columnCount: return i = r while M [ i ] [ lead ] == 0 : i + = 1 if i == rowCount: i = r lead + = 1 if columnCount == lead: return M [ i ] , M [ r ] = M [ r ] , M [ i ] lv = M [ r ] [ lead ] M [ r ] = [ mrx / lv for mrx in M [ r ] ] for i in range ( rowCount ) : if i != r: lv = M [ i ] [ lead ] M [ i ] = [ iv - lv*rv for rv , iv in zip ( M [ r ] , M [ i ] ) ] lead + = 1   def pmtx ( mtx ) : print ( ' \n ' . join ( '' . join ( ' %4s'  % col for col in row ) for row in mtx ) )   def convolve ( f , h ) : g = [ 0 ] * ( len ( f ) + len ( h ) - 1 ) for hindex , hval in enumerate ( h ) : for findex , fval in enumerate ( f ) : g [ hindex + findex ] + = fval * hval return g   def deconvolve ( g , f ) : lenh = len ( g ) - len ( f ) + 1 mtx = [ [ 0 for x in range ( lenh+ 1 ) ] for y in g ] for hindex in range ( lenh ) : for findex , fval in enumerate ( f ) : gindex = hindex + findex mtx [ gindex ] [ hindex ] = fval for gindex , gval in enumerate ( g ) : mtx [ gindex ] [ lenh ] = gval ToReducedRowEchelonForm ( mtx ) return [ mtx [ i ] [ lenh ] for i in range ( lenh ) ] # h   if __name__ == '__main__' : h = [ - 8 , - 9 , - 3 , - 1 , - 6 , 7 ] f = [ - 3 , - 6 , - 1 , 8 , - 6 , 3 , - 1 , - 9 , - 9 , 3 , - 2 , 5 , 2 , - 2 , - 7 , - 1 ] g = [ 24 , 75 , 71 , - 34 , 3 , 22 , - 45 , 23 , 245 , 25 , 52 , 25 , - 67 , - 96 , 96 , 31 , 55 , 36 , 29 , - 43 , - 7 ] assert convolve ( f , h ) == g assert deconvolve ( g , f ) == h \ No newline at end of file diff --git a/rosetta/file20.rb b/rosetta/file20.rb new file mode 100644 index 0000000..4f1e608 --- /dev/null +++ b/rosetta/file20.rb @@ -0,0 +1 @@ +[ '/' , './' ] . each { | dir | Dir . mkdir ( dir + 'docs' ) # create '/docs', then './docs' File . open ( dir + 'output.txt' , 'w' ) { } # create empty file /output.txt, then ./output.txt } \ No newline at end of file diff --git a/rosetta/file20.scala b/rosetta/file20.scala new file mode 100644 index 0000000..f0f4316 --- /dev/null +++ b/rosetta/file20.scala @@ -0,0 +1 @@ +import java. util . { Calendar, GregorianCalendar } import language. postfixOps import collection. mutable . ListBuffer   object CalendarPrint extends App { val locd = java. util . Locale . getDefault ( ) val cal = new GregorianCalendar val monthsMax = cal. getMaximum ( Calendar. MONTH )   def JDKweekDaysToISO ( dn : Int ) = { val nday = dn - Calendar. MONDAY if ( nday < 0 ) ( dn + Calendar. THURSDAY ) else nday }   def daysInMonth ( year : Int, monthMinusOne : Int ) : Int = { cal. set ( year, monthMinusOne, 1 ) cal. getActualMaximum ( Calendar. DAY_OF_MONTH ) }   def namesOfMonths ( ) = { def f1 ( i : Int ) : String = { cal. set ( 2013 , i, 1 ) cal. getDisplayName ( Calendar. MONTH , Calendar. LONG , locd ) } ( 0 to monthsMax ) map f1 }   def offsets ( year : Int ) : List [ Int ] = { val months = cal. getMaximum ( Calendar. MONTH ) def get1stDayOfWeek ( i : Int ) = { cal. set ( year, i, 1 ) cal. get ( Calendar. DAY_OF_WEEK ) } ( 0 to monthsMax ) . toList map get1stDayOfWeek map { i => JDKweekDaysToISO ( i ) } }   def headerNameOfDays ( ) = { val mdow = cal. getDisplayNames ( Calendar. DAY_OF_WEEK , Calendar. SHORT , locd ) // map days of week val it = mdow. keySet . iterator val keySet = new ListBuffer [ String ] while ( it. hasNext ) keySet + = it. next ( keySet. map { key => ( JDKweekDaysToISO ( mdow. get ( key ) ) , key. take ( 2 ) ) } . sortWith ( _ . _ 1 < _ . _ 1 ) map ( _ . _ 2 ) ) . mkString ( " " ) }   def getGregCal ( year : Int ) = { {   def dayOfMonth ( month : Int ) = new Iterator [ ( Int, Int ) ] { cal. set ( year, month, 1 ) var ldom = 0   def next ( ) = { val res = ( cal. get ( Calendar. MONTH ) , cal. get ( Calendar. DAY_OF_MONTH ) ) ldom = res. _ 2 cal. roll ( Calendar. DAY_OF_MONTH , true ) res }   def hasNext ( ) = ( cal. get ( Calendar. DAY_OF_MONTH ) > ldom ) } var ret : List [ ( Int, Int ) ] = Nil for ( i < - 0 to monthsMax ) ret = ret ++ ( dayOfMonth ( i ) . toSeq ) ( ret, offsets ( year ) ) } }   def printCalendar ( calendar : ( List [ ( Int, Int ) ] , List [ Int ] ) , headerList : List [ String ] = Nil, printerWidth : Int = 80 ) = { val mw = 20 // month width val gwf = 2 // gap width fixed val gwm = 2 // gap width minimum val fgw = true   val arr = Array. ofDim [ String ] ( 6 , 7 )   def limits ( printerWidth : Int ) : ( Int, Int, Int, Int, Int ) = { val pw = if ( printerWidth < 20 ) 20 else if ( printerWidth > 300 ) 300 else printerWidth   // months side by side, gaps sum minimum val ( msbs, gsm ) = { val x1 = { val c = if ( pw / mw > 12 ) 12 else pw / mw val a = ( c - 1 ) if ( c * mw + a * gwm <= pw ) c else a } match { case 5 => 4 case a if ( a > 6 && a < 12 ) => 6 case other => other } ( x1, ( x1 - 1 ) * gwm ) }   def getFGW ( msbs : Int, gsm : Int ) = { val r = ( pw - msbs * mw - gsm ) / 2 ; ( r, gwf, r ) } // fixed gap width def getVGW ( msbs : Int, gsm : Int ) = pw - msbs * mw - gsm match { // variable gap width case a if ( a < 2 * gwm ) => ( a / 2 , gwm, a / 2 ) case b => { val x = ( b + gsm ) / ( msbs + 1 ) ; ( x, x, x ) } }   // left margin, gap width, right margin val ( lm, gw, rm ) = if ( fgw ) getFGW ( msbs, gsm ) else getVGW ( msbs, gsm ) ( pw, msbs, lm, gw, rm ) } // def limits(   val ( pw, msbs, lm, gw, rm ) = limits ( printerWidth ) val monthsList = ( 0 to monthsMax ) . map { m => calendar. _ 1. filter { _ . _ 1 == m } } val nom = namesOfMonths ( ) val hnod = headerNameOfDays   def fsplit ( list : List [ ( Int, Int ) ] ) : List [ String ] = { def fap ( p : Int ) = ( p / 7 , p % 7 ) for ( i < - 0 until 6 ) for ( j < - 0 until 7 ) arr ( i ) ( j ) = " " for ( i < - 0 until list. size ) arr ( fap ( i + calendar. _ 2 ( list ( i ) . _ 1 ) ) . _ 1 ) ( fap ( i + calendar. _ 2 ( list ( i ) . _ 1 ) ) . _ 2 ) = f "${(list(i)._2)}%2d" arr. toList . map ( _ . foldRight ( "" ) ( _ + " " + _ ) ) } val monthsRows = monthsList. map ( fsplit )   def center ( s : String, l : Int ) : String = { ( if ( s. size >= l ) s else " " * ( ( l - s. size ) / 2 ) + s + " " * ( ( l - s. size ) / 2 ) + " " ) . substring ( 0 , l ) }   val maxMonths = monthsMax + 1   val rowblocks = ( 1 to maxMonths / msbs ) . map { i => ( 0 to 5 ) . map { j => val lb = new ListBuffer [ String ] val k = ( i - 1 ) * msbs ( k to k + msbs - 1 ) . map { l => lb + = monthsRows ( l ) ( j ) } lb } }   val mheaders = ( 1 to maxMonths / msbs ) . map { i => ( 0 to msbs - 1 ) . map { j => center ( nom ( j + ( i - 1 ) * msbs ) , 20 ) } } val dowheaders = ( 1 to maxMonths / msbs ) . map { i => ( 0 to msbs - 1 ) . map { j => center ( hnod, 20 ) } }   headerList. foreach ( xs => println ( center ( xs + ' \n ' , pw ) ) ) ( 1 to 12 / msbs ) . foreach { i => println ( " " * lm + mheaders ( i - 1 ) . foldRight ( "" ) ( _ + " " * gw + _ ) ) println ( " " * lm + dowheaders ( i - 1 ) . foldRight ( "" ) ( _ + " " * gw + _ ) ) rowblocks ( i - 1 ) . foreach { xs => println ( " " * lm + xs. foldRight ( "" ) ( _ + " " * ( gw - 1 ) + _ ) ) } println } } // def printCal(   printCalendar ( getGregCal ( 1969 ) , List ( "[Snoopy Picture]" , "1969" ) ) printCalendar ( getGregCal ( 1582 ) , List ( "[Snoopy Picture]" , "1582" ) , printerWidth = 132 ) } \ No newline at end of file diff --git a/rosetta/file20.ss b/rosetta/file20.ss new file mode 100644 index 0000000..db32120 --- /dev/null +++ b/rosetta/file20.ss @@ -0,0 +1 @@ +( define x ( expt 5 ( expt 4 ( expt 3 2 ) ) ) ) ( define y ( number -> string x ) ) ( define l ( string-length y ) ) ( display ( string-append "5**4**3**2 = " ( substring y 0 20 ) "..." ( substring y ( - l 20 ) l ) " and has " ( number -> string l ) " digits" ) ) ( newline ) \ No newline at end of file diff --git a/rosetta/file20.tcl b/rosetta/file20.tcl new file mode 100644 index 0000000..d11f2fe --- /dev/null +++ b/rosetta/file20.tcl @@ -0,0 +1 @@ +package require Tcl 8.5   proc point_in_polygon { point polygon } { set count 0 foreach side [ sides $polygon ] { if { [ ray_intersects_line $point $side ] } { incr count } } expr { $count % 2 } ; #-- 1 = odd = true, 0 = even = false } proc sides polygon { lassign $polygon x0 y0 foreach { x y } [ lrange [ lappend polygon $x0 $y0 ] 2 end ] { lappend res [ list $x0 $y0 $x $y ] set x0 $x set y0 $y } return $res } proc ray_intersects_line { point line } { lassign $point Px Py lassign $line Ax Ay Bx By # Reverse line direction if necessary if { $By < $Ay } { lassign $line Bx By Ax Ay } # Add epsilon to if { $Py == $Ay || $Py == $By } { set Py [ expr { $Py + abs ( $Py ) /1e6 } ] } # Bounding box checks if { $Py < $Ay || $Py > $By || $Px > max ( $Ax , $Bx ) } { return 0 } elseif { $Px < min ( $Ax , $Bx ) } { return 1 } # Compare dot products to compare (cosines of) angles set mRed [ expr { $Ax ! = $Bx ? ( $By - $Ay ) / ( $Bx - $Ax )  : Inf } ] set mBlu [ expr { $Ax ! = $Px ? ( $Py - $Ay ) / ( $Px - $Ax )  : Inf } ] return [ expr { $mBlu > = $mRed } ] }   foreach { point poly } { { 0 0 } { - 1 - 1 - 1 1 1 1 1 - 1 } { 2 2 } { - 1 - 1 - 1 1 1 1 1 - 1 } { 0 0 } { - 2 - 2 - 2 2 2 2 2 - 2 2 - 1 1 1 - 1 1 - 1 - 1 1 - 1 2 - 1 } { 1.5 1.5 } { - 2 - 2 - 2 2 2 2 2 - 2 2 - 1 1 1 - 1 1 - 1 - 1 1 - 1 2 - 1 } { 5 5 } { 0 0 2.5 2.5 0 10 2.5 7.5 7.5 7.5 10 10 10 0 7.5 0.1 } { 5 8 } { 0 0 2.5 2.5 0 10 2.5 7.5 7.5 7.5 10 10 10 0 7.5 0.1 } { 2 2 } { 0 0 2.5 2.5 0 10 2.5 7.5 7.5 7.5 10 10 10 0 7.5 0.1 } { 0 0 } { 0 0 2.5 2.5 0 10 2.5 7.5 7.5 7.5 10 10 10 0 7.5 0.1 } { 10 10 } { 0 0 2.5 2.5 0 10 2.5 7.5 7.5 7.5 10 10 10 0 7.5 0.1 } { 2.5 2.5 } { 0 0 2.5 2.5 0 10 2.5 7.5 7.5 7.5 10 10 10 0 7.5 0.1 } { - 5 5 } { 3 0 7 0 10 5 7 10 3 10 0 5 } } { puts "$point in $poly = [point_in_polygon $point $poly]" } \ No newline at end of file diff --git a/rosetta/file21.clojure b/rosetta/file21.clojure new file mode 100644 index 0000000..28272fa --- /dev/null +++ b/rosetta/file21.clojure @@ -0,0 +1 @@ +  ( doseq [ [ k v ] { : a 1 , : b 2 , : c 3 } ] ( println k "=" v ) )   ( doseq [ k ( keys { : a 1 , : b 2 , : c 3 } ) ] ( println k ) )   ( doseq [ v ( vals { : a 1 , : b 2 , : c 3 } ) ] ( println v ) )   \ No newline at end of file diff --git a/rosetta/file21.hs b/rosetta/file21.hs new file mode 100644 index 0000000..9b6bdd4 --- /dev/null +++ b/rosetta/file21.hs @@ -0,0 +1 @@ +import qualified Data . ByteString . Lazy as BS import qualified Data . Foldable as Fold import qualified Data . List as List import Data . Ord import qualified Data . Sequence as Seq import Data . Word import System . Environment   import Codec . Picture import Codec . Picture . Types   type Accessor = PixelRGB8 -> Pixel8   -- Getters for pixel components, as the constructor does not -- provide any public ones. red , blue , green :: Accessor red ( PixelRGB8 r _ _ ) = r green ( PixelRGB8 _ g _ ) = g blue ( PixelRGB8 _ _ b ) = b   -- Get all of the pixels in the image in list form. getPixels :: Pixel a => Image a -> [ a ] getPixels image = [ pixelAt image x y | x <- [ 0 .. ( imageWidth image - 1 ) ] , y <- [ 0 .. ( imageHeight image - 1 ) ] ]   -- Compute the color-space extents of a list of pixels. extents :: [ PixelRGB8 ] -> ( PixelRGB8 , PixelRGB8 ) extents pixels = ( extent minimum , extent maximum ) where bound f g = f $ map g pixels extent f = PixelRGB8 ( bound f red ) ( bound f green ) ( bound f blue )   -- Compute the average value of a list of pixels. average :: [ PixelRGB8 ] -> PixelRGB8 average pixels = PixelRGB8 ( avg red ) ( avg green ) ( avg blue ) where len = toInteger $ length pixels avg c = fromIntegral $ ( sum $ map ( toInteger . c ) pixels ) ` div ` len   -- Perform a componentwise pixel operation. compwise :: ( Word8 -> Word8 -> Word8 ) -> PixelRGB8 -> PixelRGB8 -> PixelRGB8 compwise f ( PixelRGB8 ra ga ba ) ( PixelRGB8 rb gb bb ) = PixelRGB8 ( f ra rb ) ( f ga gb ) ( f ba bb )   -- Compute the absolute difference of two pixels. diffPixel :: PixelRGB8 -> PixelRGB8 -> PixelRGB8 diffPixel = compwise ( \x y -> max x y - min x y )   -- Compute the Euclidean distance squared between two pixels. distPixel :: PixelRGB8 -> PixelRGB8 -> Integer distPixel x y = ( rr ^ 2 ) + ( gg ^ 2 ) + ( bb ^ 2 ) where PixelRGB8 r g b = diffPixel x y rr = toInteger r gg = toInteger g bb = toInteger b   -- Determine the dimension of the longest axis of the extents. longestAccessor :: ( PixelRGB8 , PixelRGB8 ) -> Accessor longestAccessor ( l , h ) = snd $ Fold . maximumBy ( comparing fst ) $ zip [ r , g , b ] [ red , green , blue ] where PixelRGB8 r g b = diffPixel h l   -- Find the index of a pixel to its respective palette. nearestIdx :: PixelRGB8 -> [ PixelRGB8 ] -> Int nearestIdx pixel px = ans where Just ans = List . findIndex ( == near ) px near = List . foldl1 comp px comp a b = if distPixel a pixel <= distPixel b pixel then a else b   -- Sort a list of pixels on its longest axis and then split by the mean. -- It is intentional that the mean is chosen by all dimensions -- instead of the given one. meanSplit :: [ PixelRGB8 ] -> Accessor -> ( [ PixelRGB8 ] , [ PixelRGB8 ] ) meanSplit l f = List . splitAt index sorted where sorted = List . sortBy ( comparing f ) l index = nearestIdx ( average l ) sorted   -- Perform the Median Cut algorithm on an image producing -- an index map image and its respective palette. meanCutQuant :: Image PixelRGB8 -> Int -> ( Image Pixel8 , Palette ) meanCutQuant image numRegions = ( indexmap , palette ) where extentsP p = ( p , extents p ) regions = map ( \ ( p , e ) -> ( average p , e ) ) $ search $ Seq . singleton $ extentsP $ getPixels image palette = snd $ generateFoldImage ( \ ( x:xs ) _ _ -> ( xs , x ) ) ( map fst regions ) numRegions 1 indexmap = pixelMap ( \pixel -> fromIntegral $ nearestIdx pixel $ map fst regions ) image search queue = case Seq . viewl queue of ( pixels , extent ) Seq . : < queueB -> let ( left , right ) = meanSplit pixels $ longestAccessor extent queueC = Fold . foldl ( Seq .|> ) queueB $ map extentsP [ left , right ] in if Seq . length queueC >= numRegions then List . take numRegions $ Fold . toList queueC else search queueC Seq . EmptyL -> error "Queue should never be empty."   quantizeIO :: FilePath -> FilePath -> Int -> IO ( ) quantizeIO path outpath numRegions = do dynimage <- readImage path case dynimage of Left err -> putStrLn err Right ( ImageRGB8 image ) -> doImage image Right ( ImageRGBA8 image ) -> doImage ( pixelMap dropTransparency image ) _ -> putStrLn "Expecting RGB8 or RGBA8 image" where doImage image = do let ( indexmap , palette ) = meanCutQuant image numRegions case encodePalettedPng palette indexmap of Left err -> putStrLn err Right bstring -> BS . writeFile outpath bstring   main :: IO ( ) main = do args <- getArgs prog <- getProgName case args of [ path , outpath ] -> quantizeIO path outpath 16 _ -> putStrLn $ "Usage: " ++ prog ++ " " \ No newline at end of file diff --git a/rosetta/file21.java b/rosetta/file21.java new file mode 100644 index 0000000..44ff68b --- /dev/null +++ b/rosetta/file21.java @@ -0,0 +1 @@ +import java.util.Arrays ; import java.util.Random ;   public class AtomicUpdates { public static class Buckets { private final int [ ] data ;   public Buckets ( int [ ] data ) { this . data = data. clone ( ) ; }   public int getBucket ( int index ) { synchronized ( data ) { return data [ index ] ; } }   public int transfer ( int srcBucketIndex, int destBucketIndex, int amount ) { if ( amount == 0 ) return 0 ; // Negative transfers will happen in the opposite direction if ( amount < 0 ) { int tempIndex = srcBucketIndex ; srcBucketIndex = destBucketIndex ; destBucketIndex = tempIndex ; amount = - amount ; } synchronized ( data ) { if ( amount > data [ srcBucketIndex ] ) amount = data [ srcBucketIndex ] ; if ( amount <= 0 ) return 0 ; data [ srcBucketIndex ] -= amount ; data [ destBucketIndex ] += amount ; return amount ; } }   public int [ ] getBuckets ( ) { synchronized ( data ) { return data. clone ( ) ; } } }   public static int getTotal ( int [ ] values ) { int totalValue = 0 ; for ( int i = values. length - 1 ; i >= 0 ; i -- ) totalValue += values [ i ] ; return totalValue ; }   public static void main ( String [ ] args ) { final int NUM_BUCKETS = 10 ; Random rnd = new Random ( ) ; final int [ ] values = new int [ NUM_BUCKETS ] ; for ( int i = 0 ; i < values. length ; i ++ ) values [ i ] = rnd. nextInt ( 10 ) ; System . out . println ( "Initial Array: " + getTotal ( values ) + " " + Arrays . toString ( values ) ) ; final Buckets buckets = new Buckets ( values ) ;   new Thread ( new Runnable ( ) { public void run ( ) { Random r = new Random ( ) ; while ( true ) { int srcBucketIndex = r. nextInt ( NUM_BUCKETS ) ; int destBucketIndex = r. nextInt ( NUM_BUCKETS ) ; int amount = ( buckets. getBucket ( srcBucketIndex ) - buckets. getBucket ( destBucketIndex ) ) >> 1 ; if ( amount != 0 ) buckets. transfer ( srcBucketIndex, destBucketIndex, amount ) ; } } } ) . start ( ) ;   new Thread ( new Runnable ( ) { public void run ( ) { Random r = new Random ( ) ; while ( true ) { int srcBucketIndex = r. nextInt ( NUM_BUCKETS ) ; int destBucketIndex = r. nextInt ( NUM_BUCKETS ) ; int srcBucketAmount = buckets. getBucket ( srcBucketIndex ) ; int destBucketAmount = buckets. getBucket ( destBucketIndex ) ; int amount = r. nextInt ( srcBucketAmount + destBucketAmount + 1 ) - destBucketAmount ; if ( amount != 0 ) buckets. transfer ( srcBucketIndex, destBucketIndex, amount ) ; } } } ) . start ( ) ;   while ( true ) { long nextPrintTime = System . currentTimeMillis ( ) + 3000 ; long curTime ; while ( ( curTime = System . currentTimeMillis ( ) ) < nextPrintTime ) { try { Thread . sleep ( nextPrintTime - curTime ) ; } catch ( InterruptedException e ) { } } int [ ] bucketValues = buckets. getBuckets ( ) ; System . out . println ( "Current values: " + getTotal ( bucketValues ) + " " + Arrays . toString ( bucketValues ) ) ; } } }   \ No newline at end of file diff --git a/rosetta/file21.js b/rosetta/file21.js new file mode 100644 index 0000000..1994a8c --- /dev/null +++ b/rosetta/file21.js @@ -0,0 +1 @@ +//String creation var str = '' ; //or str2 = new String ( ) ;     //String assignment str = "Hello" ; //or str2 = ', Hey there' ; //can use " or ' str = str + str2 ; //concantenates //string deletion delete str2 ; //this will return true or false, true when it has been successfully deleted, it shouldn't/won't work when the variable has been declared with the keyword 'var', you don't have to initialize variables with the var keyword in JavaScript, but when you do, you cannot 'delete' them. However JavaScript garbage collects, so when the function returns, the variable declared on the function is erased.   //String comparison str !== "Hello" ; //!== not equal-> returns true there's also !=== str == "Hello, Hey there" ; //returns true //compares 'byte' by 'byte' "Character Z" > "Character A" ; //returns true, when using > or < operators it converts the string to an array and evalues the first index that is higher than another. (using unicode values) in this case 'Z' char code is 90 (decimal) and 'A' char code is 65, therefore making one string "larger" than the other.   //String cloning and copying string = str ; //Strings are immutable therefore when you assign a string to a variable another one is created. So for two variables to have the 'same' string you have to add that string to an object, and get/set the string from that object   //Check if a string is empty Boolean ( '' ) ; //returns false '' [ 0 ] ; //returns undefined '' . charCodeAt ( ) ; //returns NaN '' == 0 ; //returns true '' === 0 ; //returns false '' == false ; //returns true   //Append byte to String str += " \x 40" ; //using + operator before the equal sign on a string makes it equal to str=str+"\x40"   //Extract a substring from a string //str is "Hello, Hey there@" str. substr ( 3 ) ; //returns "lo, Hey there@" str. substr ( - 5 ) ; //returns "here@" negative values just go to the end str. substr ( 7 , 9 ) ; //returns "Hey there" index of 7 + 9 characters after the 7 str. substring ( 3 ) ; //same as substr str. substring ( - 5 ) ; //negative values don't work on substring same as substr(0) str. substring ( 7 , 9 ) ; //returns "He" that is, whatever is between index 7 and index 9, same as substring(9,7)   //Replace every occurence of x byte with another string str3 = "url,url,url,url,url" ; str3. replace ( /,/g , ' \n ' ) //Regex ,returns the same string with the , replaced by \n str4 = str3. replace ( /./g , function ( index ) { //it also supports callback functions, the function will be called when a match has been found.. return index == ',' ? ' \n ' : index ; //returns replacement } )   //Join Strings [ str , " " , str3 ] . join ( " " /*this is the character that will glue the strings*/ ) //we can join an array of strings str3 + str4 ; str. concat ( ' \n ' , str4 ) ; //concantenate them \ No newline at end of file diff --git a/rosetta/file21.ocaml b/rosetta/file21.ocaml new file mode 100644 index 0000000..3f51bac --- /dev/null +++ b/rosetta/file21.ocaml @@ -0,0 +1 @@ +  let test_cases = [ 0.0 ; 16.87 ; 16.88 ; 33.75 ; 50.62 ; 50.63 ; 67.5 ; 84.37 ; 84.38 ; 101.25 ; 118.12 ; 118.13 ; 135.0 ; 151.87 ; 151.88 ; 168.75 ; 185.62 ; 185.63 ; 202.5 ; 219.37 ; 219.38 ; 236.25 ; 253.12 ; 253.13 ; 270.0 ; 286.87 ; 286.88 ; 303.75 ; 320.62 ; 320.63 ; 337.5 ; 354.37 ; 354.38 ] ;;   let directions = [ "North" ; "North by East" ; "North-Northeast" ; "Northeast by North" ; "Northeast" ; "Northeast by East" ; "East-Northeast" ; "East by North" ; "East" ; "East by South" ; "East-Southeast" ; "Southeast by East" ; "Southeast" ; "Southeast by South" ; "South-Southeast" ; "South by East" ; "South" ; "South by West" ; "South-Southwest" ; "Southwest by South" ; "Southwest" ; "Southwest by West" ; "West-Southwest" ; "West by South" ; "West" ; "West by North" ; "West-Northwest" ; "Northwest by West" ; "Northwest" ; "Northwest by North" ; "North-Northwest" ; "North by West" ; ] ;;   let get_direction_index input = let shifted = ( input +. 5.6201 ) in let shifted = if shifted > 360 . then shifted -. 360 . else shifted in int_of_float ( shifted /. 11.25 ) ;;   let print_direction input = let index = get_direction_index input in let direction = List . nth directions index in let test = Printf . printf "%3d %-20s %.2f\n" ( index + 1 ) direction in test input ;;   List . iter ( print_direction ) test_cases ;;     \ No newline at end of file diff --git a/rosetta/file21.perl b/rosetta/file21.perl new file mode 100644 index 0000000..d119956 --- /dev/null +++ b/rosetta/file21.perl @@ -0,0 +1 @@ +# this is commented \ No newline at end of file diff --git a/rosetta/file21.php b/rosetta/file21.php new file mode 100644 index 0000000..238dc4b --- /dev/null +++ b/rosetta/file21.php @@ -0,0 +1 @@ + array ( 350 , 10 ) , '2nd' => array ( 90 , 180 , 270 , 360 ) , '3rd' => array ( 10 , 20 , 30 ) ) ;   foreach ( $samples as $key => $sample ) { echo 'Mean angle for ' . $key . ' sample: ' . meanAngle ( $sample ) . ' degrees.' . PHP_EOL ; }   function meanAngle ( $angles ) { $y_part = $x_part = 0 ; $size = count ( $angles ) ; for ( $i = 0 ; $i < $size ; $i ++ ) { $x_part += cos ( deg2rad ( $angles [ $i ] ) ) ; $y_part += sin ( deg2rad ( $angles [ $i ] ) ) ; } $x_part /= $size ; $y_part /= $size ; return rad2deg ( atan2 ( $y_part , $x_part ) ) ; } ?> \ No newline at end of file diff --git a/rosetta/file21.py b/rosetta/file21.py new file mode 100644 index 0000000..0bd56bf --- /dev/null +++ b/rosetta/file21.py @@ -0,0 +1 @@ +def dotp ( a , b ) : assert len ( a ) == len ( b ) , 'Vector sizes must match' return sum ( aterm * bterm for aterm , bterm in zip ( a , b ) )   if __name__ == '__main__' : a , b = [ 1 , 3 , - 5 ] , [ 4 , - 2 , - 1 ] assert dotp ( a , b ) == 3 \ No newline at end of file diff --git a/rosetta/file21.rb b/rosetta/file21.rb new file mode 100644 index 0000000..472e1f0 --- /dev/null +++ b/rosetta/file21.rb @@ -0,0 +1 @@ +  def r rand ( 10000 ) end   STDOUT << "" . tap do | html | html << "" [ [ 'X' , 'Y' , 'Z' ] , [ r ,r ,r ] , [ r ,r ,r ] , [ r ,r ,r ] , [ r ,r ,r ]   ] . each_with_index do | row, index | html << "" html << "" html << row. map { | e | "" } . join html << "" end   html << "
#{index > 0 ? index : nil }#{e}
" end   \ No newline at end of file diff --git a/rosetta/file21.scala b/rosetta/file21.scala new file mode 100644 index 0000000..4261365 --- /dev/null +++ b/rosetta/file21.scala @@ -0,0 +1,2 @@ +/* This class implicitly includes a constructor which accepts an Int and + * creates "val variable1: Int" with that value. */ class MyClass ( val memberVal : Int ) { // Acts like a getter, getter automatically generated. var variable2 = "asdf" // Another instance variable; a public mutable this time def this ( ) = this ( 0 ) // An auxilliary constructor that instantiates with a default value }   object HelloObject { val s = "Hello" // Not private, so getter auto-generated }   /** Demonstrate use of our example class. */ object Call _ an _ object _ method extends App { val s = "Hello" val m = new MyClass val n = new MyClass ( 3 )   assert ( HelloObject. s == "Hello" ) // "Hello" by object getterHelloObject assert ( m. memberVal == 0 ) assert ( n. memberVal == 3 ) println ( "Successfully completed without error." ) } \ No newline at end of file diff --git a/rosetta/file21.ss b/rosetta/file21.ss new file mode 100644 index 0000000..db32120 --- /dev/null +++ b/rosetta/file21.ss @@ -0,0 +1 @@ +( define x ( expt 5 ( expt 4 ( expt 3 2 ) ) ) ) ( define y ( number -> string x ) ) ( define l ( string-length y ) ) ( display ( string-append "5**4**3**2 = " ( substring y 0 20 ) "..." ( substring y ( - l 20 ) l ) " and has " ( number -> string l ) " digits" ) ) ( newline ) \ No newline at end of file diff --git a/rosetta/file21.tcl b/rosetta/file21.tcl new file mode 100644 index 0000000..7b09b5b --- /dev/null +++ b/rosetta/file21.tcl @@ -0,0 +1 @@ +package require sha256   puts [ sha2:: sha256 -hex "Rosetta code" ] \ No newline at end of file diff --git a/rosetta/file22.clojure b/rosetta/file22.clojure new file mode 100644 index 0000000..28272fa --- /dev/null +++ b/rosetta/file22.clojure @@ -0,0 +1 @@ +  ( doseq [ [ k v ] { : a 1 , : b 2 , : c 3 } ] ( println k "=" v ) )   ( doseq [ k ( keys { : a 1 , : b 2 , : c 3 } ) ] ( println k ) )   ( doseq [ v ( vals { : a 1 , : b 2 , : c 3 } ) ] ( println v ) )   \ No newline at end of file diff --git a/rosetta/file22.hs b/rosetta/file22.hs new file mode 100644 index 0000000..9b6bdd4 --- /dev/null +++ b/rosetta/file22.hs @@ -0,0 +1 @@ +import qualified Data . ByteString . Lazy as BS import qualified Data . Foldable as Fold import qualified Data . List as List import Data . Ord import qualified Data . Sequence as Seq import Data . Word import System . Environment   import Codec . Picture import Codec . Picture . Types   type Accessor = PixelRGB8 -> Pixel8   -- Getters for pixel components, as the constructor does not -- provide any public ones. red , blue , green :: Accessor red ( PixelRGB8 r _ _ ) = r green ( PixelRGB8 _ g _ ) = g blue ( PixelRGB8 _ _ b ) = b   -- Get all of the pixels in the image in list form. getPixels :: Pixel a => Image a -> [ a ] getPixels image = [ pixelAt image x y | x <- [ 0 .. ( imageWidth image - 1 ) ] , y <- [ 0 .. ( imageHeight image - 1 ) ] ]   -- Compute the color-space extents of a list of pixels. extents :: [ PixelRGB8 ] -> ( PixelRGB8 , PixelRGB8 ) extents pixels = ( extent minimum , extent maximum ) where bound f g = f $ map g pixels extent f = PixelRGB8 ( bound f red ) ( bound f green ) ( bound f blue )   -- Compute the average value of a list of pixels. average :: [ PixelRGB8 ] -> PixelRGB8 average pixels = PixelRGB8 ( avg red ) ( avg green ) ( avg blue ) where len = toInteger $ length pixels avg c = fromIntegral $ ( sum $ map ( toInteger . c ) pixels ) ` div ` len   -- Perform a componentwise pixel operation. compwise :: ( Word8 -> Word8 -> Word8 ) -> PixelRGB8 -> PixelRGB8 -> PixelRGB8 compwise f ( PixelRGB8 ra ga ba ) ( PixelRGB8 rb gb bb ) = PixelRGB8 ( f ra rb ) ( f ga gb ) ( f ba bb )   -- Compute the absolute difference of two pixels. diffPixel :: PixelRGB8 -> PixelRGB8 -> PixelRGB8 diffPixel = compwise ( \x y -> max x y - min x y )   -- Compute the Euclidean distance squared between two pixels. distPixel :: PixelRGB8 -> PixelRGB8 -> Integer distPixel x y = ( rr ^ 2 ) + ( gg ^ 2 ) + ( bb ^ 2 ) where PixelRGB8 r g b = diffPixel x y rr = toInteger r gg = toInteger g bb = toInteger b   -- Determine the dimension of the longest axis of the extents. longestAccessor :: ( PixelRGB8 , PixelRGB8 ) -> Accessor longestAccessor ( l , h ) = snd $ Fold . maximumBy ( comparing fst ) $ zip [ r , g , b ] [ red , green , blue ] where PixelRGB8 r g b = diffPixel h l   -- Find the index of a pixel to its respective palette. nearestIdx :: PixelRGB8 -> [ PixelRGB8 ] -> Int nearestIdx pixel px = ans where Just ans = List . findIndex ( == near ) px near = List . foldl1 comp px comp a b = if distPixel a pixel <= distPixel b pixel then a else b   -- Sort a list of pixels on its longest axis and then split by the mean. -- It is intentional that the mean is chosen by all dimensions -- instead of the given one. meanSplit :: [ PixelRGB8 ] -> Accessor -> ( [ PixelRGB8 ] , [ PixelRGB8 ] ) meanSplit l f = List . splitAt index sorted where sorted = List . sortBy ( comparing f ) l index = nearestIdx ( average l ) sorted   -- Perform the Median Cut algorithm on an image producing -- an index map image and its respective palette. meanCutQuant :: Image PixelRGB8 -> Int -> ( Image Pixel8 , Palette ) meanCutQuant image numRegions = ( indexmap , palette ) where extentsP p = ( p , extents p ) regions = map ( \ ( p , e ) -> ( average p , e ) ) $ search $ Seq . singleton $ extentsP $ getPixels image palette = snd $ generateFoldImage ( \ ( x:xs ) _ _ -> ( xs , x ) ) ( map fst regions ) numRegions 1 indexmap = pixelMap ( \pixel -> fromIntegral $ nearestIdx pixel $ map fst regions ) image search queue = case Seq . viewl queue of ( pixels , extent ) Seq . : < queueB -> let ( left , right ) = meanSplit pixels $ longestAccessor extent queueC = Fold . foldl ( Seq .|> ) queueB $ map extentsP [ left , right ] in if Seq . length queueC >= numRegions then List . take numRegions $ Fold . toList queueC else search queueC Seq . EmptyL -> error "Queue should never be empty."   quantizeIO :: FilePath -> FilePath -> Int -> IO ( ) quantizeIO path outpath numRegions = do dynimage <- readImage path case dynimage of Left err -> putStrLn err Right ( ImageRGB8 image ) -> doImage image Right ( ImageRGBA8 image ) -> doImage ( pixelMap dropTransparency image ) _ -> putStrLn "Expecting RGB8 or RGBA8 image" where doImage image = do let ( indexmap , palette ) = meanCutQuant image numRegions case encodePalettedPng palette indexmap of Left err -> putStrLn err Right bstring -> BS . writeFile outpath bstring   main :: IO ( ) main = do args <- getArgs prog <- getProgName case args of [ path , outpath ] -> quantizeIO path outpath 16 _ -> putStrLn $ "Usage: " ++ prog ++ " " \ No newline at end of file diff --git a/rosetta/file22.java b/rosetta/file22.java new file mode 100644 index 0000000..44ff68b --- /dev/null +++ b/rosetta/file22.java @@ -0,0 +1 @@ +import java.util.Arrays ; import java.util.Random ;   public class AtomicUpdates { public static class Buckets { private final int [ ] data ;   public Buckets ( int [ ] data ) { this . data = data. clone ( ) ; }   public int getBucket ( int index ) { synchronized ( data ) { return data [ index ] ; } }   public int transfer ( int srcBucketIndex, int destBucketIndex, int amount ) { if ( amount == 0 ) return 0 ; // Negative transfers will happen in the opposite direction if ( amount < 0 ) { int tempIndex = srcBucketIndex ; srcBucketIndex = destBucketIndex ; destBucketIndex = tempIndex ; amount = - amount ; } synchronized ( data ) { if ( amount > data [ srcBucketIndex ] ) amount = data [ srcBucketIndex ] ; if ( amount <= 0 ) return 0 ; data [ srcBucketIndex ] -= amount ; data [ destBucketIndex ] += amount ; return amount ; } }   public int [ ] getBuckets ( ) { synchronized ( data ) { return data. clone ( ) ; } } }   public static int getTotal ( int [ ] values ) { int totalValue = 0 ; for ( int i = values. length - 1 ; i >= 0 ; i -- ) totalValue += values [ i ] ; return totalValue ; }   public static void main ( String [ ] args ) { final int NUM_BUCKETS = 10 ; Random rnd = new Random ( ) ; final int [ ] values = new int [ NUM_BUCKETS ] ; for ( int i = 0 ; i < values. length ; i ++ ) values [ i ] = rnd. nextInt ( 10 ) ; System . out . println ( "Initial Array: " + getTotal ( values ) + " " + Arrays . toString ( values ) ) ; final Buckets buckets = new Buckets ( values ) ;   new Thread ( new Runnable ( ) { public void run ( ) { Random r = new Random ( ) ; while ( true ) { int srcBucketIndex = r. nextInt ( NUM_BUCKETS ) ; int destBucketIndex = r. nextInt ( NUM_BUCKETS ) ; int amount = ( buckets. getBucket ( srcBucketIndex ) - buckets. getBucket ( destBucketIndex ) ) >> 1 ; if ( amount != 0 ) buckets. transfer ( srcBucketIndex, destBucketIndex, amount ) ; } } } ) . start ( ) ;   new Thread ( new Runnable ( ) { public void run ( ) { Random r = new Random ( ) ; while ( true ) { int srcBucketIndex = r. nextInt ( NUM_BUCKETS ) ; int destBucketIndex = r. nextInt ( NUM_BUCKETS ) ; int srcBucketAmount = buckets. getBucket ( srcBucketIndex ) ; int destBucketAmount = buckets. getBucket ( destBucketIndex ) ; int amount = r. nextInt ( srcBucketAmount + destBucketAmount + 1 ) - destBucketAmount ; if ( amount != 0 ) buckets. transfer ( srcBucketIndex, destBucketIndex, amount ) ; } } } ) . start ( ) ;   while ( true ) { long nextPrintTime = System . currentTimeMillis ( ) + 3000 ; long curTime ; while ( ( curTime = System . currentTimeMillis ( ) ) < nextPrintTime ) { try { Thread . sleep ( nextPrintTime - curTime ) ; } catch ( InterruptedException e ) { } } int [ ] bucketValues = buckets. getBuckets ( ) ; System . out . println ( "Current values: " + getTotal ( bucketValues ) + " " + Arrays . toString ( bucketValues ) ) ; } } }   \ No newline at end of file diff --git a/rosetta/file22.js b/rosetta/file22.js new file mode 100644 index 0000000..1994a8c --- /dev/null +++ b/rosetta/file22.js @@ -0,0 +1 @@ +//String creation var str = '' ; //or str2 = new String ( ) ;     //String assignment str = "Hello" ; //or str2 = ', Hey there' ; //can use " or ' str = str + str2 ; //concantenates //string deletion delete str2 ; //this will return true or false, true when it has been successfully deleted, it shouldn't/won't work when the variable has been declared with the keyword 'var', you don't have to initialize variables with the var keyword in JavaScript, but when you do, you cannot 'delete' them. However JavaScript garbage collects, so when the function returns, the variable declared on the function is erased.   //String comparison str !== "Hello" ; //!== not equal-> returns true there's also !=== str == "Hello, Hey there" ; //returns true //compares 'byte' by 'byte' "Character Z" > "Character A" ; //returns true, when using > or < operators it converts the string to an array and evalues the first index that is higher than another. (using unicode values) in this case 'Z' char code is 90 (decimal) and 'A' char code is 65, therefore making one string "larger" than the other.   //String cloning and copying string = str ; //Strings are immutable therefore when you assign a string to a variable another one is created. So for two variables to have the 'same' string you have to add that string to an object, and get/set the string from that object   //Check if a string is empty Boolean ( '' ) ; //returns false '' [ 0 ] ; //returns undefined '' . charCodeAt ( ) ; //returns NaN '' == 0 ; //returns true '' === 0 ; //returns false '' == false ; //returns true   //Append byte to String str += " \x 40" ; //using + operator before the equal sign on a string makes it equal to str=str+"\x40"   //Extract a substring from a string //str is "Hello, Hey there@" str. substr ( 3 ) ; //returns "lo, Hey there@" str. substr ( - 5 ) ; //returns "here@" negative values just go to the end str. substr ( 7 , 9 ) ; //returns "Hey there" index of 7 + 9 characters after the 7 str. substring ( 3 ) ; //same as substr str. substring ( - 5 ) ; //negative values don't work on substring same as substr(0) str. substring ( 7 , 9 ) ; //returns "He" that is, whatever is between index 7 and index 9, same as substring(9,7)   //Replace every occurence of x byte with another string str3 = "url,url,url,url,url" ; str3. replace ( /,/g , ' \n ' ) //Regex ,returns the same string with the , replaced by \n str4 = str3. replace ( /./g , function ( index ) { //it also supports callback functions, the function will be called when a match has been found.. return index == ',' ? ' \n ' : index ; //returns replacement } )   //Join Strings [ str , " " , str3 ] . join ( " " /*this is the character that will glue the strings*/ ) //we can join an array of strings str3 + str4 ; str. concat ( ' \n ' , str4 ) ; //concantenate them \ No newline at end of file diff --git a/rosetta/file22.ocaml b/rosetta/file22.ocaml new file mode 100644 index 0000000..3797072 --- /dev/null +++ b/rosetta/file22.ocaml @@ -0,0 +1 @@ +let rec input ( ) = let s = read_line ( ) in try if String . length s <> 4 then raise Exit ; String . iter ( function | ' 1 '..' 9 ' -> ( ) | _ -> raise Exit ) s ; let t = [ s . [ 0 ] ; s . [ 1 ] ; s . [ 2 ] ; s . [ 3 ] ] in let _ = List . fold_left (* reject entry with duplication *) ( fun ac b -> if List . mem b ac then raise Exit ; ( b :: ac ) ) [ ] t in List . map ( fun c -> int_of_string ( String . make 1 c ) ) t with Exit -> prerr_endline "That is an invalid entry. Please try again." ; input ( ) ;;   let print_score g t = let bull = ref 0 in List . iter2 ( fun x y -> if x = y then incr bull ) g t ; let cow = ref 0 in List . iter ( fun x -> if List . mem x t then incr cow ) g ; cow := ! cow - ! bull ; Printf . printf "%d bulls, %d cows\n%!" ! bull ! cow ;;   let ( ) = Random . self_init ( ) ; let rec mkgoal acc = function 4 -> acc | i -> let n = succ ( Random . int 9 ) in if List . mem n acc then mkgoal acc i else mkgoal ( n :: acc ) ( succ i ) in let g = mkgoal [ ] 0 in let found = ref false in while not ! found do let t = input ( ) in if t = g then found := true else print_score g t done ; print_endline "Congratulations you guessed correctly" ; ;; \ No newline at end of file diff --git a/rosetta/file22.perl b/rosetta/file22.perl new file mode 100644 index 0000000..7d413a6 --- /dev/null +++ b/rosetta/file22.perl @@ -0,0 +1 @@ +use feature "switch" ; given ( $input ) { when ( 0 ) { print 'input == 0' ; } when ( 'coffee' ) { print 'input equal coffee' ; } when ( [ 1 .. 9 ] ) { print 'input between 1 and 9' ; } when ( /rats/ ) { print 'input matches rats' ; } default { do_fallback ; } } \ No newline at end of file diff --git a/rosetta/file22.php b/rosetta/file22.php new file mode 100644 index 0000000..d7ba7ab --- /dev/null +++ b/rosetta/file22.php @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/rosetta/file22.py b/rosetta/file22.py new file mode 100644 index 0000000..8a3e01a --- /dev/null +++ b/rosetta/file22.py @@ -0,0 +1 @@ +import os ; if os . listdir ( raw_input ( "directory" ) ) : print "not empty" else : print "empty"   \ No newline at end of file diff --git a/rosetta/file22.rb b/rosetta/file22.rb new file mode 100644 index 0000000..89da294 --- /dev/null +++ b/rosetta/file22.rb @@ -0,0 +1 @@ +# Deal cards for FreeCell. # http://rosettacode.org/wiki/Deal_cards_for_FreeCell   require 'optparse'   # Parse command-line arguments. # games = ARGV converted to Integer # No arguments? Pick any of first 32000 games. games = nil OptionParser. new do | o | begin o. banner = "Usage: #{o.program_name} number..." o. parse ! games = ARGV. map { | s | Integer ( s ) } games. empty ? and games = [ rand ( 32000 ) ] rescue => e $stderr . puts e, o abort end end   # Define methods for old Ruby versions. # Enumerable#each_slice appeared in Ruby 1.8.7. # Enumerable#flat_map appeared in Ruby 1.9.2. module Enumerable unless method_defined? :each_slice def each_slice ( count ) block_given? or return enum_for ( :each_slice , count ) ary = [ ] each { | e | ary << e ary. length == count and ( yield ary. dup ; ary. clear ) } ary. empty ? or yield ary. dup nil end end   unless method_defined? :flat_map def flat_map block_given? or return enum_for ( :flat_map ) ary = [ ] each { | e | y = yield e ary. concat ( y ) rescue ary. push ( y ) } ary end end end   # Create original deck of 52 cards, not yet shuffled. orig_deck = % w { A 2 3 4 5 6 7 8 9 T J Q K } . flat_map { | rank | % w { C D H S } . map { | suit | "#{rank}#{suit}" } }   games. each do | seed | deck = orig_deck. dup   # Shuffle deck with random index from linear congruential # generator like Microsoft. state = seed 52 . downto ( 2 ) do | len | state = ( ( 214013 * state ) + 2531011 ) & 0x7fff_ffff index = ( state >> 16 ) % len last = len - 1 deck [ index ] , deck [ last ] = deck [ last ] , deck [ index ] end   deck. reverse ! # Shuffle did reverse deck. Do reverse again.   # Deal cards. puts "Game ##{seed}" deck. each_slice ( 8 ) { | row | puts " " + row. join ( " " ) } end \ No newline at end of file diff --git a/rosetta/file22.scala b/rosetta/file22.scala new file mode 100644 index 0000000..4261365 --- /dev/null +++ b/rosetta/file22.scala @@ -0,0 +1,2 @@ +/* This class implicitly includes a constructor which accepts an Int and + * creates "val variable1: Int" with that value. */ class MyClass ( val memberVal : Int ) { // Acts like a getter, getter automatically generated. var variable2 = "asdf" // Another instance variable; a public mutable this time def this ( ) = this ( 0 ) // An auxilliary constructor that instantiates with a default value }   object HelloObject { val s = "Hello" // Not private, so getter auto-generated }   /** Demonstrate use of our example class. */ object Call _ an _ object _ method extends App { val s = "Hello" val m = new MyClass val n = new MyClass ( 3 )   assert ( HelloObject. s == "Hello" ) // "Hello" by object getterHelloObject assert ( m. memberVal == 0 ) assert ( n. memberVal == 3 ) println ( "Successfully completed without error." ) } \ No newline at end of file diff --git a/rosetta/file22.ss b/rosetta/file22.ss new file mode 100644 index 0000000..db32120 --- /dev/null +++ b/rosetta/file22.ss @@ -0,0 +1 @@ +( define x ( expt 5 ( expt 4 ( expt 3 2 ) ) ) ) ( define y ( number -> string x ) ) ( define l ( string-length y ) ) ( display ( string-append "5**4**3**2 = " ( substring y 0 20 ) "..." ( substring y ( - l 20 ) l ) " and has " ( number -> string l ) " digits" ) ) ( newline ) \ No newline at end of file diff --git a/rosetta/file22.tcl b/rosetta/file22.tcl new file mode 100644 index 0000000..7cc62af --- /dev/null +++ b/rosetta/file22.tcl @@ -0,0 +1 @@ +package require Tcl 8.6   oo:: class create HopidoSolver { variable grid start limit constructor { puzzle } { set grid $puzzle for { set y 0 } { $y < [ llength $grid ] } { incr y } { for { set x 0 } { $x < [ llength [ lindex $grid $y ] ] } { incr x } { if { [ set cell [ lindex $grid $y $x ] ] == 1 } { set start [ list $y $x ] } incr limit [ expr { $cell > = 0 } ] } } if { ! [ info exist start ] } { return -code error "no starting position found" } } method moves { } { return { 0 - 3 - 2 - 2 - 2 2 - 3 0 3 0 - 2 2 2 2 0 3 } } method Moves { g r c } { set valid { } foreach { dr dc } [ my moves ] { set R [ expr { $r + $dr } ] set C [ expr { $c + $dc } ] if { [ lindex $g $R $C ] == 0 } { lappend valid $R $C } } return $valid }   method Solve { g r c v } { lset g $r $c [ incr v ] if { $v > = $limit } { return $g } foreach { r c } [ my Moves $g $r $c ] { return [ my Solve $g $r $c $v ] } return -code continue }   method solve { } { while { [ incr i ] == 1 } { set grid [ my Solve $grid { * } $start 0 ] return } return -code error "solution not possible" } method solution { } { return $grid } }   proc parsePuzzle { str } { foreach line [ split $str " \n " ] { if { [ string trim $line ] eq "" } continue lappend rows [ lmap { - c } [ regexp -all -inline { ( . ) \s ? } $line ] { string map { " " - 1 "." - 1 } $c } ] } set len [ tcl:: mathfunc :: max { * } [ lmap r $rows { llength $r } ] ] for { set i 0 } { $i < [ llength $rows ] } { incr i } { while { [ llength [ lindex $rows $i ] ] < $len } { lset rows $i end+ 1 - 1 } } return $rows } proc showPuzzle { grid name } { foreach row $grid { foreach cell $row { incr c [ expr { $cell > = 0 } ] } } set len [ string length $c ] set u [ string repeat "_" $len ] puts "$name with $c cells" foreach row $grid { puts [ format "  %s" [ join [ lmap c $row { format "%*s" $len [ if { $c ==- 1 } list elseif { $c == 0 } { set u } { set c } ] } ] ] ] } } set puzzle [ parsePuzzle { . 0 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . 0 0 0 0 0 . . . 0 0 0 . . . . . 1 . . . } ] showPuzzle $puzzle "Input" HopidoSolver create hop $puzzle hop solve showPuzzle [ hop solution ] "Output" \ No newline at end of file diff --git a/rosetta/file23.clojure b/rosetta/file23.clojure new file mode 100644 index 0000000..28272fa --- /dev/null +++ b/rosetta/file23.clojure @@ -0,0 +1 @@ +  ( doseq [ [ k v ] { : a 1 , : b 2 , : c 3 } ] ( println k "=" v ) )   ( doseq [ k ( keys { : a 1 , : b 2 , : c 3 } ) ] ( println k ) )   ( doseq [ v ( vals { : a 1 , : b 2 , : c 3 } ) ] ( println v ) )   \ No newline at end of file diff --git a/rosetta/file23.hs b/rosetta/file23.hs new file mode 100644 index 0000000..9b6bdd4 --- /dev/null +++ b/rosetta/file23.hs @@ -0,0 +1 @@ +import qualified Data . ByteString . Lazy as BS import qualified Data . Foldable as Fold import qualified Data . List as List import Data . Ord import qualified Data . Sequence as Seq import Data . Word import System . Environment   import Codec . Picture import Codec . Picture . Types   type Accessor = PixelRGB8 -> Pixel8   -- Getters for pixel components, as the constructor does not -- provide any public ones. red , blue , green :: Accessor red ( PixelRGB8 r _ _ ) = r green ( PixelRGB8 _ g _ ) = g blue ( PixelRGB8 _ _ b ) = b   -- Get all of the pixels in the image in list form. getPixels :: Pixel a => Image a -> [ a ] getPixels image = [ pixelAt image x y | x <- [ 0 .. ( imageWidth image - 1 ) ] , y <- [ 0 .. ( imageHeight image - 1 ) ] ]   -- Compute the color-space extents of a list of pixels. extents :: [ PixelRGB8 ] -> ( PixelRGB8 , PixelRGB8 ) extents pixels = ( extent minimum , extent maximum ) where bound f g = f $ map g pixels extent f = PixelRGB8 ( bound f red ) ( bound f green ) ( bound f blue )   -- Compute the average value of a list of pixels. average :: [ PixelRGB8 ] -> PixelRGB8 average pixels = PixelRGB8 ( avg red ) ( avg green ) ( avg blue ) where len = toInteger $ length pixels avg c = fromIntegral $ ( sum $ map ( toInteger . c ) pixels ) ` div ` len   -- Perform a componentwise pixel operation. compwise :: ( Word8 -> Word8 -> Word8 ) -> PixelRGB8 -> PixelRGB8 -> PixelRGB8 compwise f ( PixelRGB8 ra ga ba ) ( PixelRGB8 rb gb bb ) = PixelRGB8 ( f ra rb ) ( f ga gb ) ( f ba bb )   -- Compute the absolute difference of two pixels. diffPixel :: PixelRGB8 -> PixelRGB8 -> PixelRGB8 diffPixel = compwise ( \x y -> max x y - min x y )   -- Compute the Euclidean distance squared between two pixels. distPixel :: PixelRGB8 -> PixelRGB8 -> Integer distPixel x y = ( rr ^ 2 ) + ( gg ^ 2 ) + ( bb ^ 2 ) where PixelRGB8 r g b = diffPixel x y rr = toInteger r gg = toInteger g bb = toInteger b   -- Determine the dimension of the longest axis of the extents. longestAccessor :: ( PixelRGB8 , PixelRGB8 ) -> Accessor longestAccessor ( l , h ) = snd $ Fold . maximumBy ( comparing fst ) $ zip [ r , g , b ] [ red , green , blue ] where PixelRGB8 r g b = diffPixel h l   -- Find the index of a pixel to its respective palette. nearestIdx :: PixelRGB8 -> [ PixelRGB8 ] -> Int nearestIdx pixel px = ans where Just ans = List . findIndex ( == near ) px near = List . foldl1 comp px comp a b = if distPixel a pixel <= distPixel b pixel then a else b   -- Sort a list of pixels on its longest axis and then split by the mean. -- It is intentional that the mean is chosen by all dimensions -- instead of the given one. meanSplit :: [ PixelRGB8 ] -> Accessor -> ( [ PixelRGB8 ] , [ PixelRGB8 ] ) meanSplit l f = List . splitAt index sorted where sorted = List . sortBy ( comparing f ) l index = nearestIdx ( average l ) sorted   -- Perform the Median Cut algorithm on an image producing -- an index map image and its respective palette. meanCutQuant :: Image PixelRGB8 -> Int -> ( Image Pixel8 , Palette ) meanCutQuant image numRegions = ( indexmap , palette ) where extentsP p = ( p , extents p ) regions = map ( \ ( p , e ) -> ( average p , e ) ) $ search $ Seq . singleton $ extentsP $ getPixels image palette = snd $ generateFoldImage ( \ ( x:xs ) _ _ -> ( xs , x ) ) ( map fst regions ) numRegions 1 indexmap = pixelMap ( \pixel -> fromIntegral $ nearestIdx pixel $ map fst regions ) image search queue = case Seq . viewl queue of ( pixels , extent ) Seq . : < queueB -> let ( left , right ) = meanSplit pixels $ longestAccessor extent queueC = Fold . foldl ( Seq .|> ) queueB $ map extentsP [ left , right ] in if Seq . length queueC >= numRegions then List . take numRegions $ Fold . toList queueC else search queueC Seq . EmptyL -> error "Queue should never be empty."   quantizeIO :: FilePath -> FilePath -> Int -> IO ( ) quantizeIO path outpath numRegions = do dynimage <- readImage path case dynimage of Left err -> putStrLn err Right ( ImageRGB8 image ) -> doImage image Right ( ImageRGBA8 image ) -> doImage ( pixelMap dropTransparency image ) _ -> putStrLn "Expecting RGB8 or RGBA8 image" where doImage image = do let ( indexmap , palette ) = meanCutQuant image numRegions case encodePalettedPng palette indexmap of Left err -> putStrLn err Right bstring -> BS . writeFile outpath bstring   main :: IO ( ) main = do args <- getArgs prog <- getProgName case args of [ path , outpath ] -> quantizeIO path outpath 16 _ -> putStrLn $ "Usage: " ++ prog ++ " " \ No newline at end of file diff --git a/rosetta/file23.java b/rosetta/file23.java new file mode 100644 index 0000000..6feb8b2 --- /dev/null +++ b/rosetta/file23.java @@ -0,0 +1 @@ +public class RMS { public static double rms ( double [ ] nums ) { double ms = 0 ; for ( int i = 0 ; i < nums. length ; i ++ ) ms += nums [ i ] * nums [ i ] ; ms /= nums. length ; return Math . sqrt ( ms ) ; }   public static void main ( String [ ] args ) { double [ ] nums = { 1.0 , 2.0 , 3.0 , 4.0 , 5.0 , 6.0 , 7.0 , 8.0 , 9.0 , 10.0 } ; System . out . println ( "The RMS of the numbers from 1 to 10 is " + rms ( nums ) ) ; } } \ No newline at end of file diff --git a/rosetta/file23.js b/rosetta/file23.js new file mode 100644 index 0000000..134d9c4 --- /dev/null +++ b/rosetta/file23.js @@ -0,0 +1 @@ +function bline ( x0 , y0 , x1 , y1 ) {   var dx = Math . abs ( x1 - x0 ) , sx = x0 < x1 ? 1 : - 1 ; var dy = Math . abs ( y1 - y0 ) , sy = y0 < y1 ? 1 : - 1 ; var err = ( dx > dy ? dx : - dy ) / 2 ;   while ( true ) { setPixel ( x0 , y0 ) ; if ( x0 === x1 && y0 === y1 ) break ; var e2 = err ; if ( e2 > - dx ) { err -= dy ; x0 += sx ; } if ( e2 < dy ) { err += dx ; y0 += sy ; } } } \ No newline at end of file diff --git a/rosetta/file23.ocaml b/rosetta/file23.ocaml new file mode 100644 index 0000000..d31f119 --- /dev/null +++ b/rosetta/file23.ocaml @@ -0,0 +1 @@ +fun readfile ( ) = readfile [ ] | x = let val ln = readln ( ) in if eof ln then rev x else readfile ` ln :: x end   local val lower_a = ord # "a" ; val lower_z = ord # "z" ; val upper_a = ord # "A" ; val upper_z = ord # "Z" ;   fun which ( c_upper c ) = ( upper_a, upper_z ) | _ = ( lower_a, lower_z ) ;   fun scale ( c, az ) where ( c > # 1 az ) = scale ( ( # 0 az + ( c - # 1 az - 1 ) ) , az ) | ( c, az ) = c   in fun encipher ( [ ] , offset, t ) = implode ` rev t | ( x :: xs, offset, t ) where ( c_alphabetic x ) = encipher ( xs, offset, ( chr ` scale ( ord x + offset, which x ) ) :: t ) | ( x :: xs, offset, t ) = encipher ( xs, offset, x :: t ) | ( s, offset ) = if ( offset < 0 ) then encipher ( explode s, 26 + ( offset rem 26 ) , [ ] ) else encipher ( explode s, offset rem 26 , [ ] ) end   fun default ( false , y ) = y | ( x, _ ) = x   ; map println ` map ( fn s = encipher ( s,ston ` default ( argv 0 , "1" ) ) ) ` readfile ( ) ;   \ No newline at end of file diff --git a/rosetta/file23.perl b/rosetta/file23.perl new file mode 100644 index 0000000..7d413a6 --- /dev/null +++ b/rosetta/file23.perl @@ -0,0 +1 @@ +use feature "switch" ; given ( $input ) { when ( 0 ) { print 'input == 0' ; } when ( 'coffee' ) { print 'input equal coffee' ; } when ( [ 1 .. 9 ] ) { print 'input between 1 and 9' ; } when ( /rats/ ) { print 'input matches rats' ; } default { do_fallback ; } } \ No newline at end of file diff --git a/rosetta/file23.php b/rosetta/file23.php new file mode 100644 index 0000000..d7ba7ab --- /dev/null +++ b/rosetta/file23.php @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/rosetta/file23.py b/rosetta/file23.py new file mode 100644 index 0000000..6049915 --- /dev/null +++ b/rosetta/file23.py @@ -0,0 +1 @@ +>>> def is_odd ( i ) : return bool ( i & 1 )   >>> def is_even ( i ) : return not is_odd ( i )   >>> [ ( j , is_odd ( j ) ) for j in range ( 10 ) ] [ ( 0 , False ) , ( 1 , True ) , ( 2 , False ) , ( 3 , True ) , ( 4 , False ) , ( 5 , True ) , ( 6 , False ) , ( 7 , True ) , ( 8 , False ) , ( 9 , True ) ] >>> [ ( j , is_even ( j ) ) for j in range ( 10 ) ] [ ( 0 , True ) , ( 1 , False ) , ( 2 , True ) , ( 3 , False ) , ( 4 , True ) , ( 5 , False ) , ( 6 , True ) , ( 7 , False ) , ( 8 , True ) , ( 9 , False ) ] >>> \ No newline at end of file diff --git a/rosetta/file23.rb b/rosetta/file23.rb new file mode 100644 index 0000000..89da294 --- /dev/null +++ b/rosetta/file23.rb @@ -0,0 +1 @@ +# Deal cards for FreeCell. # http://rosettacode.org/wiki/Deal_cards_for_FreeCell   require 'optparse'   # Parse command-line arguments. # games = ARGV converted to Integer # No arguments? Pick any of first 32000 games. games = nil OptionParser. new do | o | begin o. banner = "Usage: #{o.program_name} number..." o. parse ! games = ARGV. map { | s | Integer ( s ) } games. empty ? and games = [ rand ( 32000 ) ] rescue => e $stderr . puts e, o abort end end   # Define methods for old Ruby versions. # Enumerable#each_slice appeared in Ruby 1.8.7. # Enumerable#flat_map appeared in Ruby 1.9.2. module Enumerable unless method_defined? :each_slice def each_slice ( count ) block_given? or return enum_for ( :each_slice , count ) ary = [ ] each { | e | ary << e ary. length == count and ( yield ary. dup ; ary. clear ) } ary. empty ? or yield ary. dup nil end end   unless method_defined? :flat_map def flat_map block_given? or return enum_for ( :flat_map ) ary = [ ] each { | e | y = yield e ary. concat ( y ) rescue ary. push ( y ) } ary end end end   # Create original deck of 52 cards, not yet shuffled. orig_deck = % w { A 2 3 4 5 6 7 8 9 T J Q K } . flat_map { | rank | % w { C D H S } . map { | suit | "#{rank}#{suit}" } }   games. each do | seed | deck = orig_deck. dup   # Shuffle deck with random index from linear congruential # generator like Microsoft. state = seed 52 . downto ( 2 ) do | len | state = ( ( 214013 * state ) + 2531011 ) & 0x7fff_ffff index = ( state >> 16 ) % len last = len - 1 deck [ index ] , deck [ last ] = deck [ last ] , deck [ index ] end   deck. reverse ! # Shuffle did reverse deck. Do reverse again.   # Deal cards. puts "Game ##{seed}" deck. each_slice ( 8 ) { | row | puts " " + row. join ( " " ) } end \ No newline at end of file diff --git a/rosetta/file23.scala b/rosetta/file23.scala new file mode 100644 index 0000000..ed0fc93 --- /dev/null +++ b/rosetta/file23.scala @@ -0,0 +1 @@ +val dog = "Benjamin" val Dog = "Samba" val DOG = "Bernie" println ( "There are three dogs named " + dog + ", " + Dog + ", and " + DOG + "." ) \ No newline at end of file diff --git a/rosetta/file23.ss b/rosetta/file23.ss new file mode 100644 index 0000000..0595aa2 --- /dev/null +++ b/rosetta/file23.ss @@ -0,0 +1 @@ +  ;; Create an associative array (hash-table) whose keys are strings: ( define table ( hash - table ' string=? ' ( "hello" . 0 ) ' ( "world" . 22 ) ' ( "!" . 999 ) ) )   ;; Iterate over the table, passing the key and the value of each entry ;; as arguments to a function: ( hash - table - for-each table ;; Create by "partial application" a function that accepts 2 arguments, ;; the key and the value: ( pa$ format #t "Key = ~a, Value = ~a \n " ) ) \ No newline at end of file diff --git a/rosetta/file23.tcl b/rosetta/file23.tcl new file mode 100644 index 0000000..e3a8646 --- /dev/null +++ b/rosetta/file23.tcl @@ -0,0 +1 @@ +package require Tcl 8.5 proc disjointSort { values indices args } { # Ensure that we have a unique list of integers, in order # We assume there are no end-relative indices set indices [ lsort -integer -unique $indices ] # Map from those indices to the values to sort set selected { } foreach i $indices { lappend selected [ lindex $values $i ] } # Sort the values (using any extra options) and write back to the list foreach i $indices v [ lsort { * } $args $selected ] { lset values $i $v } # The updated list is the result return $values } \ No newline at end of file diff --git a/rosetta/file24.clojure b/rosetta/file24.clojure new file mode 100644 index 0000000..91fd623 --- /dev/null +++ b/rosetta/file24.clojure @@ -0,0 +1 @@ +( defn modes [ coll ] ( let [ distrib ( frequencies coll ) [ value freq ] [ first second ] ; name the key/value pairs in the distrib (map) entries sorted ( sort-by ( comp - freq ) distrib ) maxfq ( freq ( first sorted ) ) ] ( map value ( take-while # ( = maxfq ( freq % ) ) sorted ) ) ) ) \ No newline at end of file diff --git a/rosetta/file24.hs b/rosetta/file24.hs new file mode 100644 index 0000000..97b2d7d --- /dev/null +++ b/rosetta/file24.hs @@ -0,0 +1 @@ +comb :: Int -> [ a ] -> [ [ a ] ] comb 0 _ = [ [ ] ] comb _ [ ] = [ ] comb m ( x:xs ) = map ( x: ) ( comb ( m - 1 ) xs ) ++ comb m xs \ No newline at end of file diff --git a/rosetta/file24.java b/rosetta/file24.java new file mode 100644 index 0000000..6feb8b2 --- /dev/null +++ b/rosetta/file24.java @@ -0,0 +1 @@ +public class RMS { public static double rms ( double [ ] nums ) { double ms = 0 ; for ( int i = 0 ; i < nums. length ; i ++ ) ms += nums [ i ] * nums [ i ] ; ms /= nums. length ; return Math . sqrt ( ms ) ; }   public static void main ( String [ ] args ) { double [ ] nums = { 1.0 , 2.0 , 3.0 , 4.0 , 5.0 , 6.0 , 7.0 , 8.0 , 9.0 , 10.0 } ; System . out . println ( "The RMS of the numbers from 1 to 10 is " + rms ( nums ) ) ; } } \ No newline at end of file diff --git a/rosetta/file24.js b/rosetta/file24.js new file mode 100644 index 0000000..134d9c4 --- /dev/null +++ b/rosetta/file24.js @@ -0,0 +1 @@ +function bline ( x0 , y0 , x1 , y1 ) {   var dx = Math . abs ( x1 - x0 ) , sx = x0 < x1 ? 1 : - 1 ; var dy = Math . abs ( y1 - y0 ) , sy = y0 < y1 ? 1 : - 1 ; var err = ( dx > dy ? dx : - dy ) / 2 ;   while ( true ) { setPixel ( x0 , y0 ) ; if ( x0 === x1 && y0 === y1 ) break ; var e2 = err ; if ( e2 > - dx ) { err -= dy ; x0 += sx ; } if ( e2 < dy ) { err += dx ; y0 += sy ; } } } \ No newline at end of file diff --git a/rosetta/file24.ocaml b/rosetta/file24.ocaml new file mode 100644 index 0000000..d31f119 --- /dev/null +++ b/rosetta/file24.ocaml @@ -0,0 +1 @@ +fun readfile ( ) = readfile [ ] | x = let val ln = readln ( ) in if eof ln then rev x else readfile ` ln :: x end   local val lower_a = ord # "a" ; val lower_z = ord # "z" ; val upper_a = ord # "A" ; val upper_z = ord # "Z" ;   fun which ( c_upper c ) = ( upper_a, upper_z ) | _ = ( lower_a, lower_z ) ;   fun scale ( c, az ) where ( c > # 1 az ) = scale ( ( # 0 az + ( c - # 1 az - 1 ) ) , az ) | ( c, az ) = c   in fun encipher ( [ ] , offset, t ) = implode ` rev t | ( x :: xs, offset, t ) where ( c_alphabetic x ) = encipher ( xs, offset, ( chr ` scale ( ord x + offset, which x ) ) :: t ) | ( x :: xs, offset, t ) = encipher ( xs, offset, x :: t ) | ( s, offset ) = if ( offset < 0 ) then encipher ( explode s, 26 + ( offset rem 26 ) , [ ] ) else encipher ( explode s, offset rem 26 , [ ] ) end   fun default ( false , y ) = y | ( x, _ ) = x   ; map println ` map ( fn s = encipher ( s,ston ` default ( argv 0 , "1" ) ) ) ` readfile ( ) ;   \ No newline at end of file diff --git a/rosetta/file24.perl b/rosetta/file24.perl new file mode 100644 index 0000000..c94dac3 --- /dev/null +++ b/rosetta/file24.perl @@ -0,0 +1 @@ +$| = 1 ;   sub rc2f { my ( $num , $den ) = @_ ; return sub { return unless $den ; my $q = int ( $num / $den ) ; ( $num , $den ) = ( $den , $num - $q *$den ) ; $q ; } ; }   sub rcshow { my $sub = shift ; print "[" ; my $n = $sub -> ( ) ; print "$n" if defined $n ; print "; $n" while defined ( $n = $sub -> ( ) ) ; print "] \n " ; }   rcshow ( rc2f ( @ $_ ) ) for ( [ 1 , 2 ] , [ 3 , 1 ] , [ 23 , 8 ] , [ 13 , 11 ] , [ 22 , 7 ] , [ - 151 , 77 ] ) ; print " \n " ; rcshow ( rc2f ( @ $_ ) ) for ( [ 14142 , 10000 ] , [ 141421 , 100000 ] , [ 1414214 , 1000000 ] , [ 14142136 , 10000000 ] ) ; print " \n " ; rcshow ( rc2f ( 314285714 , 100000000 ) ) ; \ No newline at end of file diff --git a/rosetta/file24.php b/rosetta/file24.php new file mode 100644 index 0000000..d7ba7ab --- /dev/null +++ b/rosetta/file24.php @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/rosetta/file24.py b/rosetta/file24.py new file mode 100644 index 0000000..953414c --- /dev/null +++ b/rosetta/file24.py @@ -0,0 +1 @@ +import os exit_code = os . system ( 'ls' ) # Just execute the command, return a success/fail code output = os . popen ( 'ls' ) . read ( ) # If you want to get the output data. Deprecated. \ No newline at end of file diff --git a/rosetta/file24.rb b/rosetta/file24.rb new file mode 100644 index 0000000..89da294 --- /dev/null +++ b/rosetta/file24.rb @@ -0,0 +1 @@ +# Deal cards for FreeCell. # http://rosettacode.org/wiki/Deal_cards_for_FreeCell   require 'optparse'   # Parse command-line arguments. # games = ARGV converted to Integer # No arguments? Pick any of first 32000 games. games = nil OptionParser. new do | o | begin o. banner = "Usage: #{o.program_name} number..." o. parse ! games = ARGV. map { | s | Integer ( s ) } games. empty ? and games = [ rand ( 32000 ) ] rescue => e $stderr . puts e, o abort end end   # Define methods for old Ruby versions. # Enumerable#each_slice appeared in Ruby 1.8.7. # Enumerable#flat_map appeared in Ruby 1.9.2. module Enumerable unless method_defined? :each_slice def each_slice ( count ) block_given? or return enum_for ( :each_slice , count ) ary = [ ] each { | e | ary << e ary. length == count and ( yield ary. dup ; ary. clear ) } ary. empty ? or yield ary. dup nil end end   unless method_defined? :flat_map def flat_map block_given? or return enum_for ( :flat_map ) ary = [ ] each { | e | y = yield e ary. concat ( y ) rescue ary. push ( y ) } ary end end end   # Create original deck of 52 cards, not yet shuffled. orig_deck = % w { A 2 3 4 5 6 7 8 9 T J Q K } . flat_map { | rank | % w { C D H S } . map { | suit | "#{rank}#{suit}" } }   games. each do | seed | deck = orig_deck. dup   # Shuffle deck with random index from linear congruential # generator like Microsoft. state = seed 52 . downto ( 2 ) do | len | state = ( ( 214013 * state ) + 2531011 ) & 0x7fff_ffff index = ( state >> 16 ) % len last = len - 1 deck [ index ] , deck [ last ] = deck [ last ] , deck [ index ] end   deck. reverse ! # Shuffle did reverse deck. Do reverse again.   # Deal cards. puts "Game ##{seed}" deck. each_slice ( 8 ) { | row | puts " " + row. join ( " " ) } end \ No newline at end of file diff --git a/rosetta/file24.scala b/rosetta/file24.scala new file mode 100644 index 0000000..23089c8 --- /dev/null +++ b/rosetta/file24.scala @@ -0,0 +1 @@ +object Catalan { def factorial ( n : BigInt ) = BigInt ( 1 ) . to ( n ) . foldLeft ( BigInt ( 1 ) ) ( _ * _ ) def catalan ( n : BigInt ) = factorial ( 2 * n ) / ( factorial ( n + 1 ) * factorial ( n ) )   def main ( args : Array [ String ] ) { for ( n < - 1 to 15 ) { println ( "catalan(" + n + ") = " + catalan ( n ) ) } } } \ No newline at end of file diff --git a/rosetta/file24.ss b/rosetta/file24.ss new file mode 100644 index 0000000..0595aa2 --- /dev/null +++ b/rosetta/file24.ss @@ -0,0 +1 @@ +  ;; Create an associative array (hash-table) whose keys are strings: ( define table ( hash - table ' string=? ' ( "hello" . 0 ) ' ( "world" . 22 ) ' ( "!" . 999 ) ) )   ;; Iterate over the table, passing the key and the value of each entry ;; as arguments to a function: ( hash - table - for-each table ;; Create by "partial application" a function that accepts 2 arguments, ;; the key and the value: ( pa$ format #t "Key = ~a, Value = ~a \n " ) ) \ No newline at end of file diff --git a/rosetta/file24.tcl b/rosetta/file24.tcl new file mode 100644 index 0000000..1d0f2b0 --- /dev/null +++ b/rosetta/file24.tcl @@ -0,0 +1 @@ +{ ... } ; # group in one word, without substituting content; nests "..." ; # group in one word, with substituting content [ ... ] ; # evaluate content as script, then substitute with its result; nests $foo ; # substitute with content of variable foo $bar ( foo ) ; # substitute with content of element 'foo' of array 'bar' \a ; # audible alert (bell) \b ; # backspace \f ; # form feed \n ; # newline \r ; # carriage return \t ; # Tab \v ; # vertical tab \\ ; # backslash \ooo ; # the Unicode with octal value 'ooo' \xhh ; # the character with hexadecimal value 'hh' \uhhhh ; # the Unicode with hexadecimal value 'hhhh' #  ;# if first character of a word expected to be a command, begin comment ; # (extends till end of line) { * } ; # if first characters of a word, interpret as list of words to substitute, ; # not single word (introduced with Tcl 8.5) \ No newline at end of file diff --git a/rosetta/file25.clojure b/rosetta/file25.clojure new file mode 100644 index 0000000..b5ffa25 --- /dev/null +++ b/rosetta/file25.clojure @@ -0,0 +1 @@ +( defn gen - brackets [ n ] ( ->> ( concat ( repeat n \ [ ) ( repeat n \ ] ) ) shuffle ( apply str , ) ) )   ( defn balanced? [ s ] ( loop [ [ first & coll ] ( seq s ) stack ' ( ) ] ( if first ( if ( = first \ [ ) ( recur coll ( conj stack \ [ ) ) ( when ( = ( peek stack ) \ [ ) ( recur coll ( pop stack ) ) ) ) ( zero? ( count stack ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file25.hs b/rosetta/file25.hs new file mode 100644 index 0000000..08543b0 --- /dev/null +++ b/rosetta/file25.hs @@ -0,0 +1 @@ +i code = True -- I am a comment.   {- I am also a comment. {-comments can be nested-} let u x = x x ( this code not compiled ) Are you ? - }   -- |This is a Haddock documentation comment for the following code i code = True -- ^This is a Haddock documentation comment for the preceding code   {-| This is a Haddock documentation block comment -} i code = True \ No newline at end of file diff --git a/rosetta/file25.java b/rosetta/file25.java new file mode 100644 index 0000000..5693678 --- /dev/null +++ b/rosetta/file25.java @@ -0,0 +1 @@ +import java.math.BigInteger ;   public class Benford { private static interface NumberGenerator { BigInteger [ ] getNumbers ( ) ; }   private static class FibonacciGenerator implements NumberGenerator { public BigInteger [ ] getNumbers ( ) { final BigInteger [ ] fib = new BigInteger [ 1000 ] ; fib [ 0 ] = fib [ 1 ] = BigInteger . ONE ; for ( int i = 2 ; i < fib. length ; i ++ ) fib [ i ] = fib [ i - 2 ] . add ( fib [ i - 1 ] ) ; return fib ; } }   private final int [ ] firstDigits = new int [ 9 ] ; private final int count ;   private Benford ( final NumberGenerator ng ) { final BigInteger [ ] numbers = ng. getNumbers ( ) ; count = numbers. length ; for ( final BigInteger number : numbers ) firstDigits [ Integer . valueOf ( number. toString ( ) . substring ( 0 , 1 ) ) - 1 ] ++; }   public String toString ( ) { final StringBuilder result = new StringBuilder ( ) ; for ( int i = 0 ; i < firstDigits. length ; i ++ ) result. append ( i + 1 ) . append ( ' \t ' ) . append ( firstDigits [ i ] / ( double ) count ) . append ( ' \t ' ) . append ( Math . log10 ( 1 + 1d / ( i + 1 ) ) ) . append ( ' \n ' ) ; return result. toString ( ) ; }   public static void main ( final String [ ] args ) { System . out . println ( new Benford ( new FibonacciGenerator ( ) ) ) ; } } \ No newline at end of file diff --git a/rosetta/file25.js b/rosetta/file25.js new file mode 100644 index 0000000..134d9c4 --- /dev/null +++ b/rosetta/file25.js @@ -0,0 +1 @@ +function bline ( x0 , y0 , x1 , y1 ) {   var dx = Math . abs ( x1 - x0 ) , sx = x0 < x1 ? 1 : - 1 ; var dy = Math . abs ( y1 - y0 ) , sy = y0 < y1 ? 1 : - 1 ; var err = ( dx > dy ? dx : - dy ) / 2 ;   while ( true ) { setPixel ( x0 , y0 ) ; if ( x0 === x1 && y0 === y1 ) break ; var e2 = err ; if ( e2 > - dx ) { err -= dy ; x0 += sx ; } if ( e2 < dy ) { err += dx ; y0 += sy ; } } } \ No newline at end of file diff --git a/rosetta/file25.ocaml b/rosetta/file25.ocaml new file mode 100644 index 0000000..1c55015 --- /dev/null +++ b/rosetta/file25.ocaml @@ -0,0 +1 @@ +my_obj # my_meth params \ No newline at end of file diff --git a/rosetta/file25.perl b/rosetta/file25.perl new file mode 100644 index 0000000..c94dac3 --- /dev/null +++ b/rosetta/file25.perl @@ -0,0 +1 @@ +$| = 1 ;   sub rc2f { my ( $num , $den ) = @_ ; return sub { return unless $den ; my $q = int ( $num / $den ) ; ( $num , $den ) = ( $den , $num - $q *$den ) ; $q ; } ; }   sub rcshow { my $sub = shift ; print "[" ; my $n = $sub -> ( ) ; print "$n" if defined $n ; print "; $n" while defined ( $n = $sub -> ( ) ) ; print "] \n " ; }   rcshow ( rc2f ( @ $_ ) ) for ( [ 1 , 2 ] , [ 3 , 1 ] , [ 23 , 8 ] , [ 13 , 11 ] , [ 22 , 7 ] , [ - 151 , 77 ] ) ; print " \n " ; rcshow ( rc2f ( @ $_ ) ) for ( [ 14142 , 10000 ] , [ 141421 , 100000 ] , [ 1414214 , 1000000 ] , [ 14142136 , 10000000 ] ) ; print " \n " ; rcshow ( rc2f ( 314285714 , 100000000 ) ) ; \ No newline at end of file diff --git a/rosetta/file25.php b/rosetta/file25.php new file mode 100644 index 0000000..d7ba7ab --- /dev/null +++ b/rosetta/file25.php @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/rosetta/file25.py b/rosetta/file25.py new file mode 100644 index 0000000..953414c --- /dev/null +++ b/rosetta/file25.py @@ -0,0 +1 @@ +import os exit_code = os . system ( 'ls' ) # Just execute the command, return a success/fail code output = os . popen ( 'ls' ) . read ( ) # If you want to get the output data. Deprecated. \ No newline at end of file diff --git a/rosetta/file25.rb b/rosetta/file25.rb new file mode 100644 index 0000000..810a539 --- /dev/null +++ b/rosetta/file25.rb @@ -0,0 +1 @@ +irb ( main ) :001: 0 > require 'matrix' => true irb ( main ) :002: 0 > Vector [ 1 , 3 , - 5 ] . inner_product Vector [ 4 , - 2 , - 1 ] => 3 \ No newline at end of file diff --git a/rosetta/file25.scala b/rosetta/file25.scala new file mode 100644 index 0000000..23089c8 --- /dev/null +++ b/rosetta/file25.scala @@ -0,0 +1 @@ +object Catalan { def factorial ( n : BigInt ) = BigInt ( 1 ) . to ( n ) . foldLeft ( BigInt ( 1 ) ) ( _ * _ ) def catalan ( n : BigInt ) = factorial ( 2 * n ) / ( factorial ( n + 1 ) * factorial ( n ) )   def main ( args : Array [ String ] ) { for ( n < - 1 to 15 ) { println ( "catalan(" + n + ") = " + catalan ( n ) ) } } } \ No newline at end of file diff --git a/rosetta/file25.ss b/rosetta/file25.ss new file mode 100644 index 0000000..855d16b --- /dev/null +++ b/rosetta/file25.ss @@ -0,0 +1 @@ +( define ( mean l ) ( if ( null? l ) 0 ( / ( apply + l ) ( length l ) ) ) ) \ No newline at end of file diff --git a/rosetta/file25.tcl b/rosetta/file25.tcl new file mode 100644 index 0000000..42e2ed6 --- /dev/null +++ b/rosetta/file25.tcl @@ -0,0 +1 @@ +oo:: class create SDAccum { variable sum sum2 num constructor { } { set sum 0.0 set sum2 0.0 set num 0 } method value { x } { set sum2 [ expr { $sum2 + $x ** 2 } ] set sum [ expr { $sum + $x } ] incr num return [ my stddev ] } method count { } { return $num } method mean { } { expr { $sum / $num } } method variance { } { expr { $sum2 / $num - [ my mean ] ** 2 } } method stddev { } { expr { sqrt ( [ my variance ] ) } } }   # Demonstration set sdacc [ SDAccum new ] foreach val { 2 4 4 4 5 5 7 9 } { set sd [ $sdacc value $val ] } puts "the standard deviation is: $sd" \ No newline at end of file diff --git a/rosetta/file26.clojure b/rosetta/file26.clojure new file mode 100644 index 0000000..b5ffa25 --- /dev/null +++ b/rosetta/file26.clojure @@ -0,0 +1 @@ +( defn gen - brackets [ n ] ( ->> ( concat ( repeat n \ [ ) ( repeat n \ ] ) ) shuffle ( apply str , ) ) )   ( defn balanced? [ s ] ( loop [ [ first & coll ] ( seq s ) stack ' ( ) ] ( if first ( if ( = first \ [ ) ( recur coll ( conj stack \ [ ) ) ( when ( = ( peek stack ) \ [ ) ( recur coll ( pop stack ) ) ) ) ( zero? ( count stack ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file26.hs b/rosetta/file26.hs new file mode 100644 index 0000000..92ae903 --- /dev/null +++ b/rosetta/file26.hs @@ -0,0 +1 @@ +fac x = if x == 0 then 1 else x * fac ( x - 1 ) \ No newline at end of file diff --git a/rosetta/file26.java b/rosetta/file26.java new file mode 100644 index 0000000..3feaec2 --- /dev/null +++ b/rosetta/file26.java @@ -0,0 +1 @@ +... //check will be the number we are looking for //nums will be the array we are searching through public static int binarySearch ( int [ ] nums, int check ) { int hi = nums. length - 1 ; int lo = 0 ; while ( hi >= lo ) { guess = lo + ( ( hi - lo ) / 2 ) ; if ( nums [ guess ] > check ) { hi = guess - 1 ; } else if ( nums [ guess ] < check ) { lo = guess + 1 ; } else { return guess ; } } return - 1 ; }   public static void main ( String [ ] args ) { int [ ] searchMe ; int someNumber ; ... int index = binarySearch ( searchMe, someNumber ) ; System . out . println ( someNumber + ( ( index == - 1 ) ? " is not in the array" : ( " is at index " + index ) ) ) ; ... } \ No newline at end of file diff --git a/rosetta/file26.js b/rosetta/file26.js new file mode 100644 index 0000000..134d9c4 --- /dev/null +++ b/rosetta/file26.js @@ -0,0 +1 @@ +function bline ( x0 , y0 , x1 , y1 ) {   var dx = Math . abs ( x1 - x0 ) , sx = x0 < x1 ? 1 : - 1 ; var dy = Math . abs ( y1 - y0 ) , sy = y0 < y1 ? 1 : - 1 ; var err = ( dx > dy ? dx : - dy ) / 2 ;   while ( true ) { setPixel ( x0 , y0 ) ; if ( x0 === x1 && y0 === y1 ) break ; var e2 = err ; if ( e2 > - dx ) { err -= dy ; x0 += sx ; } if ( e2 < dy ) { err += dx ; y0 += sy ; } } } \ No newline at end of file diff --git a/rosetta/file26.ocaml b/rosetta/file26.ocaml new file mode 100644 index 0000000..1c55015 --- /dev/null +++ b/rosetta/file26.ocaml @@ -0,0 +1 @@ +my_obj # my_meth params \ No newline at end of file diff --git a/rosetta/file26.perl b/rosetta/file26.perl new file mode 100644 index 0000000..18b3c99 --- /dev/null +++ b/rosetta/file26.perl @@ -0,0 +1 @@ +use File :: Spec :: Functions qw ( catfile rootdir ) ; { # here open my $fh , '>' , 'output.txt' ; mkdir 'docs' ; } ; { # root dir open my $fh , '>' , catfile rootdir , 'output.txt' ; mkdir catfile rootdir , 'docs' ; } ; \ No newline at end of file diff --git a/rosetta/file26.php b/rosetta/file26.php new file mode 100644 index 0000000..d7ba7ab --- /dev/null +++ b/rosetta/file26.php @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/rosetta/file26.py b/rosetta/file26.py new file mode 100644 index 0000000..953414c --- /dev/null +++ b/rosetta/file26.py @@ -0,0 +1 @@ +import os exit_code = os . system ( 'ls' ) # Just execute the command, return a success/fail code output = os . popen ( 'ls' ) . read ( ) # If you want to get the output data. Deprecated. \ No newline at end of file diff --git a/rosetta/file26.rb b/rosetta/file26.rb new file mode 100644 index 0000000..6a11ed8 --- /dev/null +++ b/rosetta/file26.rb @@ -0,0 +1 @@ +print "evens: " p - 5 . upto ( 5 ) . select { | n | n. even ? } print "odds: " p - 5 . upto ( 5 ) . select { | n | n. odd ? } \ No newline at end of file diff --git a/rosetta/file26.scala b/rosetta/file26.scala new file mode 100644 index 0000000..23089c8 --- /dev/null +++ b/rosetta/file26.scala @@ -0,0 +1 @@ +object Catalan { def factorial ( n : BigInt ) = BigInt ( 1 ) . to ( n ) . foldLeft ( BigInt ( 1 ) ) ( _ * _ ) def catalan ( n : BigInt ) = factorial ( 2 * n ) / ( factorial ( n + 1 ) * factorial ( n ) )   def main ( args : Array [ String ] ) { for ( n < - 1 to 15 ) { println ( "catalan(" + n + ") = " + catalan ( n ) ) } } } \ No newline at end of file diff --git a/rosetta/file26.ss b/rosetta/file26.ss new file mode 100644 index 0000000..855d16b --- /dev/null +++ b/rosetta/file26.ss @@ -0,0 +1 @@ +( define ( mean l ) ( if ( null? l ) 0 ( / ( apply + l ) ( length l ) ) ) ) \ No newline at end of file diff --git a/rosetta/file26.tcl b/rosetta/file26.tcl new file mode 100644 index 0000000..855306b --- /dev/null +++ b/rosetta/file26.tcl @@ -0,0 +1 @@ +package require Tcl 8.5   # How to process a single value, adding it to the table mapping stems to # leaves. proc addSLValue { tblName value { splitFactor 10 } } { upvar 1 $tblName tbl # Extract the stem and leaf if { $value < 0 } { set value [ expr { round ( - $value ) } ] set stem - [ expr { $value / $splitFactor } ] } else { set value [ expr { round ( $value ) } ] set stem [ expr { $value / $splitFactor } ] } if { ! [ info exist tbl ] } { dict set tbl min $stem } dict set tbl max $stem set leaf [ expr { $value % $splitFactor } ] dict lappend tbl $stem $leaf }   # How to do the actual output of the stem-and-leaf table, given that we have # already done the splitting into stems and leaves. proc printSLTable { tblName } { upvar 1 $tblName tbl # Get the range of stems set min [ dict get $tbl min ] set max [ dict get $tbl max ] # Work out how much width the stems take so everything lines up set l [ expr { max ( [ string length $min ] , [ string length $max ] ) } ] # Print out the table for { set i $min } { $i < = $max } { incr i } { if { ! [ dict exist $tbl $i ] } { puts [ format " %*d |" $l $i ] } else { puts [ format " %*d | %s" $l $i [ dict get $tbl $i ] ] } } }   # Assemble the parts into a full stem-and-leaf table printer. proc printStemLeaf { dataList { splitFactor 10 } } { foreach value [ lsort -real $dataList ] { addSLValue tbl $value $splitFactor } printSLTable tbl }   # Demo code set data { 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146 } printStemLeaf $data \ No newline at end of file diff --git a/rosetta/file27.clojure b/rosetta/file27.clojure new file mode 100644 index 0000000..b5ffa25 --- /dev/null +++ b/rosetta/file27.clojure @@ -0,0 +1 @@ +( defn gen - brackets [ n ] ( ->> ( concat ( repeat n \ [ ) ( repeat n \ ] ) ) shuffle ( apply str , ) ) )   ( defn balanced? [ s ] ( loop [ [ first & coll ] ( seq s ) stack ' ( ) ] ( if first ( if ( = first \ [ ) ( recur coll ( conj stack \ [ ) ) ( when ( = ( peek stack ) \ [ ) ( recur coll ( pop stack ) ) ) ) ( zero? ( count stack ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file27.hs b/rosetta/file27.hs new file mode 100644 index 0000000..76bd297 --- /dev/null +++ b/rosetta/file27.hs @@ -0,0 +1 @@ +import Data . Ratio ( ( % ) )   real2cf :: ( RealFrac a , Integral b ) => a -> [ b ] real2cf x = i : if f == 0 then [ ] else real2cf ( 1 / f ) where ( i , f ) = properFraction x   main :: IO ( ) main = do print $ real2cf ( 13 % 11 ) -- => [1,5,2] print $ take 20 $ real2cf ( sqrt 2 ) -- => [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2] \ No newline at end of file diff --git a/rosetta/file27.java b/rosetta/file27.java new file mode 100644 index 0000000..3feaec2 --- /dev/null +++ b/rosetta/file27.java @@ -0,0 +1 @@ +... //check will be the number we are looking for //nums will be the array we are searching through public static int binarySearch ( int [ ] nums, int check ) { int hi = nums. length - 1 ; int lo = 0 ; while ( hi >= lo ) { guess = lo + ( ( hi - lo ) / 2 ) ; if ( nums [ guess ] > check ) { hi = guess - 1 ; } else if ( nums [ guess ] < check ) { lo = guess + 1 ; } else { return guess ; } } return - 1 ; }   public static void main ( String [ ] args ) { int [ ] searchMe ; int someNumber ; ... int index = binarySearch ( searchMe, someNumber ) ; System . out . println ( someNumber + ( ( index == - 1 ) ? " is not in the array" : ( " is at index " + index ) ) ) ; ... } \ No newline at end of file diff --git a/rosetta/file27.js b/rosetta/file27.js new file mode 100644 index 0000000..134d9c4 --- /dev/null +++ b/rosetta/file27.js @@ -0,0 +1 @@ +function bline ( x0 , y0 , x1 , y1 ) {   var dx = Math . abs ( x1 - x0 ) , sx = x0 < x1 ? 1 : - 1 ; var dy = Math . abs ( y1 - y0 ) , sy = y0 < y1 ? 1 : - 1 ; var err = ( dx > dy ? dx : - dy ) / 2 ;   while ( true ) { setPixel ( x0 , y0 ) ; if ( x0 === x1 && y0 === y1 ) break ; var e2 = err ; if ( e2 > - dx ) { err -= dy ; x0 += sx ; } if ( e2 < dy ) { err += dx ; y0 += sy ; } } } \ No newline at end of file diff --git a/rosetta/file27.ocaml b/rosetta/file27.ocaml new file mode 100644 index 0000000..b8f20ff --- /dev/null +++ b/rosetta/file27.ocaml @@ -0,0 +1 @@ +let ( ) = let dog = "Benjamin" in let dOG = "Samba" in let dOg = "Bernie" in Printf . printf "The three dogs are named %s, %s and %s.\n" dog dOG dOg \ No newline at end of file diff --git a/rosetta/file27.perl b/rosetta/file27.perl new file mode 100644 index 0000000..b0c3af6 --- /dev/null +++ b/rosetta/file27.perl @@ -0,0 +1 @@ +my @heading = qw ( X Y Z ) ; my $rows = 5 ; print '" } @heading ) , "" ;   for ( 1 .. $rows ) { print "" , ( map { "" } @heading ) , "" ; }   print "
' , ( map { "$_
$_" . int ( rand ( 10000 ) ) . "
" ; \ No newline at end of file diff --git a/rosetta/file27.php b/rosetta/file27.php new file mode 100644 index 0000000..d7ba7ab --- /dev/null +++ b/rosetta/file27.php @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/rosetta/file27.py b/rosetta/file27.py new file mode 100644 index 0000000..702d5c0 --- /dev/null +++ b/rosetta/file27.py @@ -0,0 +1 @@ +>>> import operator >>> class num ( int ) : def __pow__ ( self , b ) : print "Empowered" return operator . __pow__ ( self + 0 , b )     >>> x = num ( 3 ) >>> x** 2 Empowered 9 >>> class num ( float ) : def __pow__ ( self , b ) : print "Empowered" return operator . __pow__ ( self + 0 , b )     >>> x = num ( 2.5 ) >>> x** 2 Empowered 6.25 >>> \ No newline at end of file diff --git a/rosetta/file27.rb b/rosetta/file27.rb new file mode 100644 index 0000000..e0d54ac --- /dev/null +++ b/rosetta/file27.rb @@ -0,0 +1 @@ +var tape_length = 50 _000; var eof_val = - 1 ; var unbalanced_exit_code = 1 ;   var cmd = 0 ; var cell = 0 ; var code = [ ] ; var loops = [ ] ; var tape = tape_length. of ( 0 ) ;   func get_input { static input_buffer = '' ; input_buffer. len || ( input_buffer = STDIN. readline ) ; input_buffer == nil  ? eof_val : ( input_buffer. sub! ( / ^ ( . ) / s ) ; $1. ord ) ; }   func jump { var depth = 0 ; while ( depth > = 0 ) { ++ cmd < code. len || exit ( unbalanced_exit_code ) ; given ( code [ cmd ] ) when ( '[' ) { ++ depth } when ( ']' ) { -- depth } ; } }   var commands = : ( '>' => { ++ cell } , '<' => { -- cell } , '+' => { tape [ cell ] ++ } , '-' => { tape [ cell ] -- } , '.' => { tape [ cell ] chr print } , ',' => { tape [ cell ] = get_input ( ) } , '[' => {  ?tape [ cell ]  ? loops. append ( cmd )  : jump ( ) } , ']' => { cmd = ( loops. pop - 1 ) } , ) ;   code = ARGF. slurp . split ( 1 ) ; var code_len = code. len ;   loop { if ( commands. exists ( code [ cmd ] ) ) { commands [ code [ cmd ] ] . run ; } ; ++ cmd < code_len || break ; } \ No newline at end of file diff --git a/rosetta/file27.scala b/rosetta/file27.scala new file mode 100644 index 0000000..c47e604 --- /dev/null +++ b/rosetta/file27.scala @@ -0,0 +1 @@ +scala > 'a' toInt res2 : Int = 97   scala > 97 toChar res3 : Char = a   scala > ' \u0061 ' res4 : Char = a   scala > " \uD869 \uDEA5 " res5 : String = 𪚥 \ No newline at end of file diff --git a/rosetta/file27.ss b/rosetta/file27.ss new file mode 100644 index 0000000..5473100 --- /dev/null +++ b/rosetta/file27.ss @@ -0,0 +1 @@ +( define ( balanced - brackets string ) ( define ( b chars sum ) ( cond ( ( and ( null? chars ) ( = 0 sum ) ) #t ) ( ( null? chars ) #f ) ( ( char=? #\ [ ( car chars ) ) ( b ( cdr chars ) ( + sum 1 ) ) ) ( ( = sum 0 ) #f ) ( else ( b ( cdr chars ) ( - sum 1 ) ) ) ) ) ( b ( string -> list string ) 0 ) )   ( balanced - brackets "" )   ( balanced - brackets "[]" ) ( balanced - brackets "[][]" ) ( balanced - brackets "[[][]]" )   ( balanced - brackets "][" ) ( balanced - brackets "][][" ) ( balanced - brackets "[]][[]" )   \ No newline at end of file diff --git a/rosetta/file27.tcl b/rosetta/file27.tcl new file mode 100644 index 0000000..228fd14 --- /dev/null +++ b/rosetta/file27.tcl @@ -0,0 +1 @@ +set size "little" puts "Mary had a $size lamb."   proc RandomWord { args } { lindex $args [ expr { int ( rand ( ) * [ llength $args ] ) } ] } puts "Mary had a [RandomWord little big] lamb." \ No newline at end of file diff --git a/rosetta/file28.clojure b/rosetta/file28.clojure new file mode 100644 index 0000000..f34161a --- /dev/null +++ b/rosetta/file28.clojure @@ -0,0 +1 @@ +( defn bsearch ( [ coll t ] ( bsearch coll 0 ( dec ( count coll ) ) t ) ) ( [ coll l u t ] ( if ( > l u ) - 1 ( let [ m ( quot ( + l u ) 2 ) mth ( nth coll m ) ] ( cond ; the middle element is greater than t ; so search the lower half ( > mth t ) ( recur coll l ( dec m ) t ) ; the middle element is less than t ; so search the upper half ( < mth t ) ( recur coll ( inc m ) u t ) ; we've found our target ; so return its index ( = mth t ) m ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file28.hs b/rosetta/file28.hs new file mode 100644 index 0000000..76bd297 --- /dev/null +++ b/rosetta/file28.hs @@ -0,0 +1 @@ +import Data . Ratio ( ( % ) )   real2cf :: ( RealFrac a , Integral b ) => a -> [ b ] real2cf x = i : if f == 0 then [ ] else real2cf ( 1 / f ) where ( i , f ) = properFraction x   main :: IO ( ) main = do print $ real2cf ( 13 % 11 ) -- => [1,5,2] print $ take 20 $ real2cf ( sqrt 2 ) -- => [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2] \ No newline at end of file diff --git a/rosetta/file28.java b/rosetta/file28.java new file mode 100644 index 0000000..3feaec2 --- /dev/null +++ b/rosetta/file28.java @@ -0,0 +1 @@ +... //check will be the number we are looking for //nums will be the array we are searching through public static int binarySearch ( int [ ] nums, int check ) { int hi = nums. length - 1 ; int lo = 0 ; while ( hi >= lo ) { guess = lo + ( ( hi - lo ) / 2 ) ; if ( nums [ guess ] > check ) { hi = guess - 1 ; } else if ( nums [ guess ] < check ) { lo = guess + 1 ; } else { return guess ; } } return - 1 ; }   public static void main ( String [ ] args ) { int [ ] searchMe ; int someNumber ; ... int index = binarySearch ( searchMe, someNumber ) ; System . out . println ( someNumber + ( ( index == - 1 ) ? " is not in the array" : ( " is at index " + index ) ) ) ; ... } \ No newline at end of file diff --git a/rosetta/file28.js b/rosetta/file28.js new file mode 100644 index 0000000..134d9c4 --- /dev/null +++ b/rosetta/file28.js @@ -0,0 +1 @@ +function bline ( x0 , y0 , x1 , y1 ) {   var dx = Math . abs ( x1 - x0 ) , sx = x0 < x1 ? 1 : - 1 ; var dy = Math . abs ( y1 - y0 ) , sy = y0 < y1 ? 1 : - 1 ; var err = ( dx > dy ? dx : - dy ) / 2 ;   while ( true ) { setPixel ( x0 , y0 ) ; if ( x0 === x1 && y0 === y1 ) break ; var e2 = err ; if ( e2 > - dx ) { err -= dy ; x0 += sx ; } if ( e2 < dy ) { err += dx ; y0 += sy ; } } } \ No newline at end of file diff --git a/rosetta/file28.ocaml b/rosetta/file28.ocaml new file mode 100644 index 0000000..b8f20ff --- /dev/null +++ b/rosetta/file28.ocaml @@ -0,0 +1 @@ +let ( ) = let dog = "Benjamin" in let dOG = "Samba" in let dOg = "Bernie" in Printf . printf "The three dogs are named %s, %s and %s.\n" dog dOG dOg \ No newline at end of file diff --git a/rosetta/file28.perl b/rosetta/file28.perl new file mode 100644 index 0000000..0c02d0e --- /dev/null +++ b/rosetta/file28.perl @@ -0,0 +1 @@ +use strict ;   sub sq { my $s = 0 ; $s += $_ ** 2 for @_ ; $s ; }   sub hit { my ( $sph , $x , $y ) = @_ ; $x -= $sph -> [ 0 ] ; $y -= $sph -> [ 1 ] ;   my $z = sq ( $sph -> [ 3 ] ) - sq ( $x , $y ) ; return if $z < 0 ;   $z = sqrt $z ; return $sph -> [ 2 ] - $z , $sph -> [ 2 ] + $z ; }   sub normalize { my $v = shift ; my $n = sqrt sq ( @$v ) ; $_ /= $n for @$v ; $v ; }   sub dot { my ( $x , $y ) = @_ ; my $s = $x -> [ 0 ] * $y -> [ 0 ] + $x -> [ 1 ] * $y -> [ 1 ] + $x -> [ 2 ] * $y -> [ 2 ] ; $s > 0 ? $s : 0 ; }   my $pos = [ 120 , 120 , 0 , 120 ] ; my $neg = [ - 77 , - 33 , - 100 , 190 ] ; my $light = normalize ( [ - 12 , 13 , - 10 ] ) ; sub draw { my ( $k , $amb ) = @_ ; binmode STDOUT , ":raw" ; print "P5 \n " , $pos -> [ 0 ] * 2 + 3 , " " , $pos -> [ 1 ] * 2 + 3 , " \n 255 \n " ; for my $y ( ( $pos -> [ 1 ] - $pos -> [ 3 ] - 1 ) .. ( $pos -> [ 1 ] + $pos -> [ 3 ] + 1 ) ) { my @row = ( ) ; for my $x ( ( $pos -> [ 0 ] - $pos -> [ 3 ] - 1 ) .. ( $pos -> [ 0 ] + $pos -> [ 3 ] + 1 ) ) { my ( $hit , @hs ) = 0 ; my @h = hit ( $pos , $x , $y ) ;   if ( ! @h ) { $hit = 0 } elsif ( ! ( @hs = hit ( $neg , $x , $y ) ) ) { $hit = 1 } elsif ( $hs [ 0 ] > $h [ 0 ] ) { $hit = 1 } elsif ( $hs [ 1 ] > $h [ 0 ] ) { $hit = $hs [ 1 ] > $h [ 1 ] ? 0 : 2 } else { $hit = 1 }   my ( $val , $v ) ; if ( $hit == 0 ) { $val = 0 } elsif ( $hit == 1 ) { $v = [ $x - $pos -> [ 0 ] , $y - $pos -> [ 1 ] , $h [ 0 ] - $pos -> [ 2 ] ] ; } else { $v = [ $neg -> [ 0 ] - $x , $neg -> [ 1 ] - $y , $neg -> [ 2 ] - $hs [ 1 ] ] ; } if ( $v ) { normalize ( $v ) ; $val = int ( ( dot ( $v , $light ) ** $k + $amb ) * 255 ) ; $val = ( $val > 255 ) ? 255 : ( $val < 0 ) ? 0 : $val ; } push @row , $val ; } print pack ( "C*" , @row ) ; } }   draw ( 2 , 0.2 ) ; \ No newline at end of file diff --git a/rosetta/file28.php b/rosetta/file28.php new file mode 100644 index 0000000..d7ba7ab --- /dev/null +++ b/rosetta/file28.php @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/rosetta/file28.py b/rosetta/file28.py new file mode 100644 index 0000000..b000952 --- /dev/null +++ b/rosetta/file28.py @@ -0,0 +1 @@ +import ast   class CallCountingVisitor ( ast. NodeVisitor ) :   def __init__ ( self ) : self . calls = { }   def visit_Call ( self , node ) : if isinstance ( node. func , ast. Name ) : fun_name = node. func . id call_count = self . calls . get ( fun_name , 0 ) self . calls [ fun_name ] = call_count + 1 self . generic_visit ( node )   filename = input ( 'Enter a filename to parse: ' ) with open ( filename , encoding = 'utf-8' ) as f: contents = f. read ( ) root = ast. parse ( contents , filename = filename ) #NOTE: this will throw a SyntaxError if the file isn't valid Python code visitor = CallCountingVisitor ( ) visitor. visit ( root ) top10 = sorted ( visitor. calls . items ( ) , key = lambda x: x [ 1 ] , reverse = True ) [ : 10 ] for name , count in top10: print ( name , 'called' , count , 'times' )   \ No newline at end of file diff --git a/rosetta/file28.rb b/rosetta/file28.rb new file mode 100644 index 0000000..e0d54ac --- /dev/null +++ b/rosetta/file28.rb @@ -0,0 +1 @@ +var tape_length = 50 _000; var eof_val = - 1 ; var unbalanced_exit_code = 1 ;   var cmd = 0 ; var cell = 0 ; var code = [ ] ; var loops = [ ] ; var tape = tape_length. of ( 0 ) ;   func get_input { static input_buffer = '' ; input_buffer. len || ( input_buffer = STDIN. readline ) ; input_buffer == nil  ? eof_val : ( input_buffer. sub! ( / ^ ( . ) / s ) ; $1. ord ) ; }   func jump { var depth = 0 ; while ( depth > = 0 ) { ++ cmd < code. len || exit ( unbalanced_exit_code ) ; given ( code [ cmd ] ) when ( '[' ) { ++ depth } when ( ']' ) { -- depth } ; } }   var commands = : ( '>' => { ++ cell } , '<' => { -- cell } , '+' => { tape [ cell ] ++ } , '-' => { tape [ cell ] -- } , '.' => { tape [ cell ] chr print } , ',' => { tape [ cell ] = get_input ( ) } , '[' => {  ?tape [ cell ]  ? loops. append ( cmd )  : jump ( ) } , ']' => { cmd = ( loops. pop - 1 ) } , ) ;   code = ARGF. slurp . split ( 1 ) ; var code_len = code. len ;   loop { if ( commands. exists ( code [ cmd ] ) ) { commands [ code [ cmd ] ] . run ; } ; ++ cmd < code_len || break ; } \ No newline at end of file diff --git a/rosetta/file28.scala b/rosetta/file28.scala new file mode 100644 index 0000000..c47e604 --- /dev/null +++ b/rosetta/file28.scala @@ -0,0 +1 @@ +scala > 'a' toInt res2 : Int = 97   scala > 97 toChar res3 : Char = a   scala > ' \u0061 ' res4 : Char = a   scala > " \uD869 \uDEA5 " res5 : String = 𪚥 \ No newline at end of file diff --git a/rosetta/file28.ss b/rosetta/file28.ss new file mode 100644 index 0000000..5473100 --- /dev/null +++ b/rosetta/file28.ss @@ -0,0 +1 @@ +( define ( balanced - brackets string ) ( define ( b chars sum ) ( cond ( ( and ( null? chars ) ( = 0 sum ) ) #t ) ( ( null? chars ) #f ) ( ( char=? #\ [ ( car chars ) ) ( b ( cdr chars ) ( + sum 1 ) ) ) ( ( = sum 0 ) #f ) ( else ( b ( cdr chars ) ( - sum 1 ) ) ) ) ) ( b ( string -> list string ) 0 ) )   ( balanced - brackets "" )   ( balanced - brackets "[]" ) ( balanced - brackets "[][]" ) ( balanced - brackets "[[][]]" )   ( balanced - brackets "][" ) ( balanced - brackets "][][" ) ( balanced - brackets "[]][[]" )   \ No newline at end of file diff --git a/rosetta/file28.tcl b/rosetta/file28.tcl new file mode 100644 index 0000000..1a8b7fb --- /dev/null +++ b/rosetta/file28.tcl @@ -0,0 +1 @@ +# Get how the terminal wants to do things... set videoSeq ( reverse ) [ exec tput rev ] set videoSeq ( normal ) [ exec tput rmso ] proc reverseVideo str { global videoSeq return "$videoSeq(reverse)${str}$videoSeq(normal)" }   # The things to print set inReverse "foo" set inNormal "bar"   # Print those words puts "[reverseVideo $inReverse] $inNormal" \ No newline at end of file diff --git a/rosetta/file29.clojure b/rosetta/file29.clojure new file mode 100644 index 0000000..f34161a --- /dev/null +++ b/rosetta/file29.clojure @@ -0,0 +1 @@ +( defn bsearch ( [ coll t ] ( bsearch coll 0 ( dec ( count coll ) ) t ) ) ( [ coll l u t ] ( if ( > l u ) - 1 ( let [ m ( quot ( + l u ) 2 ) mth ( nth coll m ) ] ( cond ; the middle element is greater than t ; so search the lower half ( > mth t ) ( recur coll l ( dec m ) t ) ; the middle element is less than t ; so search the upper half ( < mth t ) ( recur coll ( inc m ) u t ) ; we've found our target ; so return its index ( = mth t ) m ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file29.hs b/rosetta/file29.hs new file mode 100644 index 0000000..017e49b --- /dev/null +++ b/rosetta/file29.hs @@ -0,0 +1 @@ +import Data . Array . Unboxed   type Grid = UArray ( Int , Int ) Bool -- The grid is indexed by (y, x).   life :: Int -> Int -> Grid -> Grid {- Returns the given Grid advanced by one generation. -} life w h old = listArray b ( map f ( range b ) ) where b @ ( ( y1 , x1 ) , ( y2 , x2 ) ) = bounds old f ( y , x ) = ( c && ( n == 2 || n == 3 ) ) || ( not c && n == 3 ) where c = get x y n = count [ get ( x + x ') (y + y' ) | x ' <- [-1, 0, 1], y' <- [ - 1 , 0 , 1 ] , not ( x ' == 0 && y' == 0 ) ]   get x y | x < x1 || x > x2 = False | y < y1 || y > y2 = False | otherwise = old ! ( y , x )   count :: [ Bool ] -> Int count = length . filter id \ No newline at end of file diff --git a/rosetta/file29.java b/rosetta/file29.java new file mode 100644 index 0000000..84d1c79 --- /dev/null +++ b/rosetta/file29.java @@ -0,0 +1 @@ +import java.awt.* ; import javax.swing.* ;   public class Bresenham extends JFrame {   public static void main ( String [ ] args ) { SwingUtilities . invokeLater ( new Runnable ( ) { @Override public void run ( ) { JFrame f = new Bresenham ( ) ; f. setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE ) ; f. setVisible ( true ) ; f. add ( new BresenhamPanel ( ) , BorderLayout . CENTER ) ; f. setTitle ( "Bresenham" ) ; f. setResizable ( false ) ; f. pack ( ) ; f. setLocationRelativeTo ( null ) ; } } ) ; } }   class BresenhamPanel extends JPanel { final int centerX, centerY ;   public BresenhamPanel ( ) { int w = 600 ; int h = 500 ; centerX = w / 2 ; centerY = h / 2 ; setPreferredSize ( new Dimension ( w, h ) ) ; setBackground ( Color . white ) ; }   @Override public void paintComponent ( Graphics g ) { super . paintComponent ( g ) ;   drawLine ( g, 0 , 0 , 8 , 19 ) ; // NNE drawLine ( g, 0 , 0 , 19 , 8 ) ; // ENE drawLine ( g, 0 , 0 , 19 , - 8 ) ; // ESE drawLine ( g, 0 , 0 , 8 , - 19 ) ; // SSE drawLine ( g, 0 , 0 , - 8 , - 19 ) ; // SSW drawLine ( g, 0 , 0 , - 19 , - 8 ) ; // WSW drawLine ( g, 0 , 0 , - 19 , 8 ) ; // WNW drawLine ( g, 0 , 0 , - 8 , 19 ) ; // NNW }   private void plot ( Graphics g, int x, int y ) { g. setColor ( Color . black ) ; g. drawOval ( centerX + ( x * 10 ) , centerY + ( - y * 10 ) , 10 , 10 ) ; }   private void drawLine ( Graphics g, int x1, int y1, int x2, int y2 ) { // delta of exact value and rounded value of the dependant variable int d = 0 ;   int dy = Math . abs ( y2 - y1 ) ; int dx = Math . abs ( x2 - x1 ) ;   int dy2 = ( dy << 1 ) ; // slope scaling factors to avoid floating int dx2 = ( dx << 1 ) ; // point   int ix = x1 < x2 ? 1 : - 1 ; // increment direction int iy = y1 < y2 ? 1 : - 1 ;   if ( dy <= dx ) { for ( ;; ) { plot ( g, x1, y1 ) ; if ( x1 == x2 ) break ; x1 += ix ; d += dy2 ; if ( d > dx ) { y1 += iy ; d -= dx2 ; } } } else { for ( ;; ) { plot ( g, x1, y1 ) ; if ( y1 == y2 ) break ; y1 += iy ; d += dx2 ; if ( d > dy ) { x1 += ix ; d -= dy2 ; } } } } } \ No newline at end of file diff --git a/rosetta/file29.js b/rosetta/file29.js new file mode 100644 index 0000000..134d9c4 --- /dev/null +++ b/rosetta/file29.js @@ -0,0 +1 @@ +function bline ( x0 , y0 , x1 , y1 ) {   var dx = Math . abs ( x1 - x0 ) , sx = x0 < x1 ? 1 : - 1 ; var dy = Math . abs ( y1 - y0 ) , sy = y0 < y1 ? 1 : - 1 ; var err = ( dx > dy ? dx : - dy ) / 2 ;   while ( true ) { setPixel ( x0 , y0 ) ; if ( x0 === x1 && y0 === y1 ) break ; var e2 = err ; if ( e2 > - dx ) { err -= dy ; x0 += sx ; } if ( e2 < dy ) { err += dx ; y0 += sy ; } } } \ No newline at end of file diff --git a/rosetta/file29.ocaml b/rosetta/file29.ocaml new file mode 100644 index 0000000..b8f20ff --- /dev/null +++ b/rosetta/file29.ocaml @@ -0,0 +1 @@ +let ( ) = let dog = "Benjamin" in let dOG = "Samba" in let dOg = "Bernie" in Printf . printf "The three dogs are named %s, %s and %s.\n" dog dOG dOg \ No newline at end of file diff --git a/rosetta/file29.perl b/rosetta/file29.perl new file mode 100644 index 0000000..0c02d0e --- /dev/null +++ b/rosetta/file29.perl @@ -0,0 +1 @@ +use strict ;   sub sq { my $s = 0 ; $s += $_ ** 2 for @_ ; $s ; }   sub hit { my ( $sph , $x , $y ) = @_ ; $x -= $sph -> [ 0 ] ; $y -= $sph -> [ 1 ] ;   my $z = sq ( $sph -> [ 3 ] ) - sq ( $x , $y ) ; return if $z < 0 ;   $z = sqrt $z ; return $sph -> [ 2 ] - $z , $sph -> [ 2 ] + $z ; }   sub normalize { my $v = shift ; my $n = sqrt sq ( @$v ) ; $_ /= $n for @$v ; $v ; }   sub dot { my ( $x , $y ) = @_ ; my $s = $x -> [ 0 ] * $y -> [ 0 ] + $x -> [ 1 ] * $y -> [ 1 ] + $x -> [ 2 ] * $y -> [ 2 ] ; $s > 0 ? $s : 0 ; }   my $pos = [ 120 , 120 , 0 , 120 ] ; my $neg = [ - 77 , - 33 , - 100 , 190 ] ; my $light = normalize ( [ - 12 , 13 , - 10 ] ) ; sub draw { my ( $k , $amb ) = @_ ; binmode STDOUT , ":raw" ; print "P5 \n " , $pos -> [ 0 ] * 2 + 3 , " " , $pos -> [ 1 ] * 2 + 3 , " \n 255 \n " ; for my $y ( ( $pos -> [ 1 ] - $pos -> [ 3 ] - 1 ) .. ( $pos -> [ 1 ] + $pos -> [ 3 ] + 1 ) ) { my @row = ( ) ; for my $x ( ( $pos -> [ 0 ] - $pos -> [ 3 ] - 1 ) .. ( $pos -> [ 0 ] + $pos -> [ 3 ] + 1 ) ) { my ( $hit , @hs ) = 0 ; my @h = hit ( $pos , $x , $y ) ;   if ( ! @h ) { $hit = 0 } elsif ( ! ( @hs = hit ( $neg , $x , $y ) ) ) { $hit = 1 } elsif ( $hs [ 0 ] > $h [ 0 ] ) { $hit = 1 } elsif ( $hs [ 1 ] > $h [ 0 ] ) { $hit = $hs [ 1 ] > $h [ 1 ] ? 0 : 2 } else { $hit = 1 }   my ( $val , $v ) ; if ( $hit == 0 ) { $val = 0 } elsif ( $hit == 1 ) { $v = [ $x - $pos -> [ 0 ] , $y - $pos -> [ 1 ] , $h [ 0 ] - $pos -> [ 2 ] ] ; } else { $v = [ $neg -> [ 0 ] - $x , $neg -> [ 1 ] - $y , $neg -> [ 2 ] - $hs [ 1 ] ] ; } if ( $v ) { normalize ( $v ) ; $val = int ( ( dot ( $v , $light ) ** $k + $amb ) * 255 ) ; $val = ( $val > 255 ) ? 255 : ( $val < 0 ) ? 0 : $val ; } push @row , $val ; } print pack ( "C*" , @row ) ; } }   draw ( 2 , 0.2 ) ; \ No newline at end of file diff --git a/rosetta/file29.php b/rosetta/file29.php new file mode 100644 index 0000000..3495e43 --- /dev/null +++ b/rosetta/file29.php @@ -0,0 +1 @@ +function binary_search ( $array , $secret , $start , $end ) { do { $guess = ( int ) ( $start + ( ( $end - $start ) / 2 ) ) ;   if ( $array [ $guess ] > $secret ) $end = $guess ;   if ( $array [ $guess ] < $secret ) $start = $guess ;   if ( $end < $start ) return - 1 ;   } while ( $array [ $guess ] != $secret ) ;   return $guess ; } \ No newline at end of file diff --git a/rosetta/file29.py b/rosetta/file29.py new file mode 100644 index 0000000..b000952 --- /dev/null +++ b/rosetta/file29.py @@ -0,0 +1 @@ +import ast   class CallCountingVisitor ( ast. NodeVisitor ) :   def __init__ ( self ) : self . calls = { }   def visit_Call ( self , node ) : if isinstance ( node. func , ast. Name ) : fun_name = node. func . id call_count = self . calls . get ( fun_name , 0 ) self . calls [ fun_name ] = call_count + 1 self . generic_visit ( node )   filename = input ( 'Enter a filename to parse: ' ) with open ( filename , encoding = 'utf-8' ) as f: contents = f. read ( ) root = ast. parse ( contents , filename = filename ) #NOTE: this will throw a SyntaxError if the file isn't valid Python code visitor = CallCountingVisitor ( ) visitor. visit ( root ) top10 = sorted ( visitor. calls . items ( ) , key = lambda x: x [ 1 ] , reverse = True ) [ : 10 ] for name , count in top10: print ( name , 'called' , count , 'times' )   \ No newline at end of file diff --git a/rosetta/file29.rb b/rosetta/file29.rb new file mode 100644 index 0000000..7a1cc88 --- /dev/null +++ b/rosetta/file29.rb @@ -0,0 +1 @@ +pid = fork if pid # parent code else # child code end \ No newline at end of file diff --git a/rosetta/file29.scala b/rosetta/file29.scala new file mode 100644 index 0000000..469c36f --- /dev/null +++ b/rosetta/file29.scala @@ -0,0 +1 @@ +import java. nio . file . { Files, FileSystems }   object FileExistsTest extends App {   val defaultFS = FileSystems. getDefault ( ) val separator = defaultFS. getSeparator ( )   def test ( filename : String ) { val path = defaultFS. getPath ( filename )   println ( s "The following ${if (Files.isDirectory(path)) " directory " else " file "} called $filename" + ( if ( Files. exists ( path ) ) " exists." else " not exists." ) ) }   // main List ( "output.txt" , separator + "output.txt" , "docs" , separator + "docs" + separator ) . foreach ( test ) } \ No newline at end of file diff --git a/rosetta/file29.ss b/rosetta/file29.ss new file mode 100644 index 0000000..5473100 --- /dev/null +++ b/rosetta/file29.ss @@ -0,0 +1 @@ +( define ( balanced - brackets string ) ( define ( b chars sum ) ( cond ( ( and ( null? chars ) ( = 0 sum ) ) #t ) ( ( null? chars ) #f ) ( ( char=? #\ [ ( car chars ) ) ( b ( cdr chars ) ( + sum 1 ) ) ) ( ( = sum 0 ) #f ) ( else ( b ( cdr chars ) ( - sum 1 ) ) ) ) ) ( b ( string -> list string ) 0 ) )   ( balanced - brackets "" )   ( balanced - brackets "[]" ) ( balanced - brackets "[][]" ) ( balanced - brackets "[[][]]" )   ( balanced - brackets "][" ) ( balanced - brackets "][][" ) ( balanced - brackets "[]][[]" )   \ No newline at end of file diff --git a/rosetta/file29.tcl b/rosetta/file29.tcl new file mode 100644 index 0000000..44b6b28 --- /dev/null +++ b/rosetta/file29.tcl @@ -0,0 +1 @@ + set out 0 set max_out - 1 set max_times { }   foreach job [ split [ read [ open "mlijobs.txt" "r" ] ] " \n " ] { if { [ lindex $job 1 ] == "OUT" } { incr out } { incr out - 1 } if { $out > $max_out } { set max_out $out set max_times { } } if { $out == $max_out } { lappend max_times [ lindex $job 3 ] } }   puts "Maximum simultaneous license use is $max_out at the following times:" foreach t $max_times { puts " $t" } \ No newline at end of file diff --git a/rosetta/file3.clojure b/rosetta/file3.clojure new file mode 100644 index 0000000..00b2a4a --- /dev/null +++ b/rosetta/file3.clojure @@ -0,0 +1 @@ +  ( def blocks ( -> "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM" ( . split " " ) vec ) )   ( defn omit "return bs with (one instance of) b omitted" [ bs b ] ( let [ [ before after ] ( split-with # ( not = b % ) bs ) ] ( concat before ( rest after ) ) ) )   ( defn abc "return lazy sequence of solutions (i.e. block lists)" [ blocks [ c & cs ] ] ( if - some c ( for [ b blocks : when ( some # ( = c % ) b ) bs ( abc ( omit blocks b ) cs ) ] ( cons b bs ) ) [ [ ] ] ) )     ( doseq [ word [ "A" "BARK" "Book" "treat" "COMMON" "SQUAD" "CONFUSE" ] ] ( ->> word . toUpperCase ( abc blocks ) first ( printf "%s: %b \n " word ) ) ) \ No newline at end of file diff --git a/rosetta/file3.hs b/rosetta/file3.hs new file mode 100644 index 0000000..c240854 --- /dev/null +++ b/rosetta/file3.hs @@ -0,0 +1 @@ +module Integrator ( newIntegrator , input , output , stop , Time , timeInterval ) where import Control . Concurrent ( forkIO , threadDelay ) import Control . Concurrent . MVar ( MVar , newMVar , modifyMVar _, modifyMVar , readMVar ) import Control . Exception ( evaluate ) import Data . Time ( UTCTime ) import Data . Time . Clock ( getCurrentTime , diffUTCTime )   -- RC task main = do let f = 0.5 {- Hz -} t0 <- getCurrentTime i <- newIntegrator input i ( \t -> sin ( 2 * pi * f * timeInterval t0 t ) ) -- task step 1 threadDelay 2000000 {- µs -} -- task step 2 input i ( const 0 ) -- task step 3 threadDelay 500000 {- µs -} -- task step 4 result <- output i stop i print result   ---- Implementation ------------------------------------------------------   -- Utilities for working with the time type type Time = UTCTime type Func a = Time -> a timeInterval t0 t1 = realToFrac $ diffUTCTime t1 t0   -- Type signatures of the module's interface newIntegrator :: Fractional a => IO ( Integrator a ) -- Create an integrator input :: Integrator a -> Func a -> IO ( ) -- Set the input function output :: Integrator a -> IO a -- Get the current value stop :: Integrator a -> IO ( ) -- Stop integration, don't waste CPU   -- Data structures data Integrator a = Integrator ( MVar ( IntState a ) ) -- MVar is a thread-safe mutable cell deriving Eq data IntState a = IntState { func :: Func a , -- The current function run :: Bool , -- Whether to keep going value :: a , -- The current accumulated value time :: Time } -- The time of the previous update   newIntegrator = do now <- getCurrentTime state <- newMVar $ IntState { func = const 0 , run = True , value = 0 , time = now } thread <- forkIO ( intThread state ) -- The state variable is shared between the thread return ( Integrator state ) -- and the client interface object.   input ( Integrator stv ) f = modifyMVar _ stv ( \st -> return st { func = f } ) output ( Integrator stv ) = fmap value $ readMVar stv stop ( Integrator stv ) = modifyMVar _ stv ( \st -> return st { run = False } ) -- modifyMVar_ takes an MVar and replaces its contents according to the provided function. -- a { b = c } is record-update syntax: "the record a, except with field b changed to c"   -- Integration thread intThread :: Fractional a => MVar ( IntState a ) -> IO ( ) intThread stv = whileM $ modifyMVar stv updateAndCheckRun -- modifyMVar is like modifyMVar_ but the function returns a tuple of the new value -- and an arbitrary extra value, which in this case ends up telling whileM whether -- to keep looping. where updateAndCheckRun st = do now <- getCurrentTime let value ' = integrate (func st) (value st) (time st) now evaluate value' -- avoid undesired laziness return ( st { value = value ', time = now }, -- updated state run st) -- whether to continue   integrate :: Fractional a => Func a -> a -> Time -> Time -> a integrate f value t0 t1 = value + (f t0 + f t1)/2 * dt where dt = timeInterval t0 t1   -- Execute ' action ' until it returns false. whileM action = do b <- action; if b then whileM action else return () \ No newline at end of file diff --git a/rosetta/file3.java b/rosetta/file3.java new file mode 100644 index 0000000..542508d --- /dev/null +++ b/rosetta/file3.java @@ -0,0 +1 @@ +public abstract class Abs { abstract public int method1 ( double value ) ; abstract protected int method2 ( String name ) ; int add ( int a, int b ) { return a + b ; } } \ No newline at end of file diff --git a/rosetta/file3.js b/rosetta/file3.js new file mode 100644 index 0000000..13dc519 --- /dev/null +++ b/rosetta/file3.js @@ -0,0 +1 @@ +function ack ( m , n ) { return m === 0 ? n + 1 : ack ( m - 1 , n === 0 ? 1 : ack ( m , n - 1 ) ) ; } \ No newline at end of file diff --git a/rosetta/file3.ocaml b/rosetta/file3.ocaml new file mode 100644 index 0000000..21de3c5 --- /dev/null +++ b/rosetta/file3.ocaml @@ -0,0 +1 @@ +let rec a m n = if m = 0 then ( n + 1 ) else if n = 0 then ( a ( m - 1 ) 1 ) else ( a ( m - 1 ) ( a m ( n - 1 ) ) ) \ No newline at end of file diff --git a/rosetta/file3.perl b/rosetta/file3.perl new file mode 100644 index 0000000..7d1d9e8 --- /dev/null +++ b/rosetta/file3.perl @@ -0,0 +1 @@ +use strict ; use 5 . 10 . 0 ;   use threads 'yield' ; use threads :: shared ;   my @a : shared = ( 100 ) x 10 ; my $stop : shared = 0 ;   sub pick2 { my $i = int ( rand ( 10 ) ) ; my $j ; $j = int ( rand ( 10 ) ) until $j != $i ; ( $i , $j ) }   sub even { lock @a ; my ( $i , $j ) = pick2 ; my $sum = $a [ $i ] + $a [ $j ] ; $a [ $i ] = int ( $sum / 2 ) ; $a [ $j ] = $sum - $a [ $i ] ; }   sub rand_move { lock @a ; my ( $i , $j ) = pick2 ;   my $x = int ( rand $a [ $i ] ) ; $a [ $i ] -= $x ; $a [ $j ] += $x ; }   sub show { lock @a ; my $sum = 0 ; $sum += $_ for ( @a ) ; printf "%4d" , $_ for @a ; print " total $sum \n " ; }   my $t1 = async { even until $stop } my $t2 = async { rand_move until $stop } my $t3 = async { for ( 1 .. 10 ) { show ; sleep ( 1 ) ; } $stop = 1 ; } ;   $t1 -> join ; $t2 -> join ; $t3 -> join ; \ No newline at end of file diff --git a/rosetta/file3.php b/rosetta/file3.php new file mode 100644 index 0000000..64b41d7 --- /dev/null +++ b/rosetta/file3.php @@ -0,0 +1 @@ +abstract class Abs { abstract public function method1 ( $value ) ; abstract protected function method2 ( $name ) ; function add ( $a , $b ) { return a + b ; } } \ No newline at end of file diff --git a/rosetta/file3.py b/rosetta/file3.py new file mode 100644 index 0000000..b1ec695 --- /dev/null +++ b/rosetta/file3.py @@ -0,0 +1 @@ +from hashlib import sha256   digits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'   def decode_base58 ( bc , length ) : n = 0 for char in bc: n = n * 58 + digits58. index ( char ) return n. to_bytes ( length , 'big' )   def check_bc ( bc ) : bcbytes = decode_base58 ( bc , 25 ) return bcbytes [ - 4 : ] == sha256 ( sha256 ( bcbytes [ :- 4 ] ) . digest ( ) ) . digest ( ) [ : 4 ]   if __name__ == '__main__' : bc = '1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i' assert check_bc ( bc ) assert not check_bc ( bc. replace ( 'N' , 'P' , 1 ) ) assert check_bc ( '1111111111111111111114oLvT2' ) assert check_bc ( "17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j" ) \ No newline at end of file diff --git a/rosetta/file3.rb b/rosetta/file3.rb new file mode 100644 index 0000000..6b7ddc2 --- /dev/null +++ b/rosetta/file3.rb @@ -0,0 +1 @@ +class Pixmap def draw_bezier_curve ( points, colour ) # ensure the points are increasing along the x-axis points = points. sort_by { | p | [ p . x , p . y ] } xmin = points [ 0 ] . x xmax = points [ - 1 ] . x increment = 2 prev = points [ 0 ] ( ( xmin + increment ) .. xmax ) . step ( increment ) do | x | t = 1.0 * ( x - xmin ) / ( xmax - xmin ) p = Pixel [ x, bezier ( t, points ) . round ] draw_line ( prev, p , colour ) prev = p end end end   # the generalized n-degree Bezier summation def bezier ( t, points ) n = points. length - 1 points. each_with_index . inject ( 0.0 ) do | sum, ( point, i ) | sum + = n. choose ( i ) * ( 1 - t ) ** ( n - i ) * t ** i * point. y end end   class Fixnum def choose ( k ) self . factorial / ( k. factorial * ( self - k ) . factorial ) end def factorial ( 2 .. self ) . reduce ( 1 , : * ) end end   bitmap = Pixmap. new ( 400 , 400 ) points = [ Pixel [ 40 , 100 ] , Pixel [ 100 , 350 ] , Pixel [ 150 , 50 ] , Pixel [ 150 , 150 ] , Pixel [ 350 , 250 ] , Pixel [ 250 , 250 ] ] points. each { | p | bitmap. draw_circle ( p , 3 , RGBColour::RED ) } bitmap. draw_bezier_curve ( points, RGBColour::BLUE ) \ No newline at end of file diff --git a/rosetta/file3.scala b/rosetta/file3.scala new file mode 100644 index 0000000..5d9bc2c --- /dev/null +++ b/rosetta/file3.scala @@ -0,0 +1 @@ +def ack ( m : BigInt, n : BigInt ) : BigInt = { if ( m == 0 ) n+ 1 else if ( n == 0 ) ack ( m- 1 , 1 ) else ack ( m- 1 , ack ( m, n- 1 ) ) } \ No newline at end of file diff --git a/rosetta/file3.ss b/rosetta/file3.ss new file mode 100644 index 0000000..4d53f4c --- /dev/null +++ b/rosetta/file3.ss @@ -0,0 +1 @@ +( display ( + ( read ) ( read ) ) ) \ No newline at end of file diff --git a/rosetta/file3.tcl b/rosetta/file3.tcl new file mode 100644 index 0000000..41312ed --- /dev/null +++ b/rosetta/file3.tcl @@ -0,0 +1 @@ +package require Tcl 8.5   set text { 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 . }   array set max { } foreach line [ split $text \n ] { set col 0 set thisline [ split $line \ $ ] lappend words $thisline foreach word $thisline { set max ( [ incr col ] ) [ expr { [ info exists max ( $col ) ] ? max ( $max ( $col ) , [ string length $word ] )  : [ string length $word ] } ] } }   proc justify { word position width } { switch -exact -- $position { left { return [ format "%-*s" $width $word ] } center { set lpadw [ expr { ( $width - [ string length $word ] ) / 2 } ] return [ format "%s%-*s" [ string repeat " " $lpadw ] [ incr width - $lpadw ] $word ] } right { return [ format "%*s" $width $word ] } } }   foreach position { left center right } { foreach thisline $words { set col 0 set line "" foreach word $thisline { append line [ justify $word $position $max ( [ incr col ] ) ] " " } puts [ string trimright $line ] } puts "" } \ No newline at end of file diff --git a/rosetta/file30.clojure b/rosetta/file30.clojure new file mode 100644 index 0000000..f34161a --- /dev/null +++ b/rosetta/file30.clojure @@ -0,0 +1 @@ +( defn bsearch ( [ coll t ] ( bsearch coll 0 ( dec ( count coll ) ) t ) ) ( [ coll l u t ] ( if ( > l u ) - 1 ( let [ m ( quot ( + l u ) 2 ) mth ( nth coll m ) ] ( cond ; the middle element is greater than t ; so search the lower half ( > mth t ) ( recur coll l ( dec m ) t ) ; the middle element is less than t ; so search the upper half ( < mth t ) ( recur coll ( inc m ) u t ) ; we've found our target ; so return its index ( = mth t ) m ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file30.hs b/rosetta/file30.hs new file mode 100644 index 0000000..a1180fe --- /dev/null +++ b/rosetta/file30.hs @@ -0,0 +1 @@ +import System . Directory   createFile name = writeFile name ""   main = do createFile "output.txt" createDirectory "docs" createFile "/output.txt" createDirectory "/docs" \ No newline at end of file diff --git a/rosetta/file30.java b/rosetta/file30.java new file mode 100644 index 0000000..84d1c79 --- /dev/null +++ b/rosetta/file30.java @@ -0,0 +1 @@ +import java.awt.* ; import javax.swing.* ;   public class Bresenham extends JFrame {   public static void main ( String [ ] args ) { SwingUtilities . invokeLater ( new Runnable ( ) { @Override public void run ( ) { JFrame f = new Bresenham ( ) ; f. setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE ) ; f. setVisible ( true ) ; f. add ( new BresenhamPanel ( ) , BorderLayout . CENTER ) ; f. setTitle ( "Bresenham" ) ; f. setResizable ( false ) ; f. pack ( ) ; f. setLocationRelativeTo ( null ) ; } } ) ; } }   class BresenhamPanel extends JPanel { final int centerX, centerY ;   public BresenhamPanel ( ) { int w = 600 ; int h = 500 ; centerX = w / 2 ; centerY = h / 2 ; setPreferredSize ( new Dimension ( w, h ) ) ; setBackground ( Color . white ) ; }   @Override public void paintComponent ( Graphics g ) { super . paintComponent ( g ) ;   drawLine ( g, 0 , 0 , 8 , 19 ) ; // NNE drawLine ( g, 0 , 0 , 19 , 8 ) ; // ENE drawLine ( g, 0 , 0 , 19 , - 8 ) ; // ESE drawLine ( g, 0 , 0 , 8 , - 19 ) ; // SSE drawLine ( g, 0 , 0 , - 8 , - 19 ) ; // SSW drawLine ( g, 0 , 0 , - 19 , - 8 ) ; // WSW drawLine ( g, 0 , 0 , - 19 , 8 ) ; // WNW drawLine ( g, 0 , 0 , - 8 , 19 ) ; // NNW }   private void plot ( Graphics g, int x, int y ) { g. setColor ( Color . black ) ; g. drawOval ( centerX + ( x * 10 ) , centerY + ( - y * 10 ) , 10 , 10 ) ; }   private void drawLine ( Graphics g, int x1, int y1, int x2, int y2 ) { // delta of exact value and rounded value of the dependant variable int d = 0 ;   int dy = Math . abs ( y2 - y1 ) ; int dx = Math . abs ( x2 - x1 ) ;   int dy2 = ( dy << 1 ) ; // slope scaling factors to avoid floating int dx2 = ( dx << 1 ) ; // point   int ix = x1 < x2 ? 1 : - 1 ; // increment direction int iy = y1 < y2 ? 1 : - 1 ;   if ( dy <= dx ) { for ( ;; ) { plot ( g, x1, y1 ) ; if ( x1 == x2 ) break ; x1 += ix ; d += dy2 ; if ( d > dx ) { y1 += iy ; d -= dx2 ; } } } else { for ( ;; ) { plot ( g, x1, y1 ) ; if ( y1 == y2 ) break ; y1 += iy ; d += dx2 ; if ( d > dy ) { x1 += ix ; d -= dy2 ; } } } } } \ No newline at end of file diff --git a/rosetta/file30.js b/rosetta/file30.js new file mode 100644 index 0000000..134d9c4 --- /dev/null +++ b/rosetta/file30.js @@ -0,0 +1 @@ +function bline ( x0 , y0 , x1 , y1 ) {   var dx = Math . abs ( x1 - x0 ) , sx = x0 < x1 ? 1 : - 1 ; var dy = Math . abs ( y1 - y0 ) , sy = y0 < y1 ? 1 : - 1 ; var err = ( dx > dy ? dx : - dy ) / 2 ;   while ( true ) { setPixel ( x0 , y0 ) ; if ( x0 === x1 && y0 === y1 ) break ; var e2 = err ; if ( e2 > - dx ) { err -= dy ; x0 += sx ; } if ( e2 < dy ) { err += dx ; y0 += sy ; } } } \ No newline at end of file diff --git a/rosetta/file30.ocaml b/rosetta/file30.ocaml new file mode 100644 index 0000000..69883cc --- /dev/null +++ b/rosetta/file30.ocaml @@ -0,0 +1 @@ +Printf . printf "%d\n" ( int_of_char ' a ' ) ; (* prints "97" *) Printf . printf "%c\n" ( char_of_int 97 ) ; (* prints "a" *) \ No newline at end of file diff --git a/rosetta/file30.perl b/rosetta/file30.perl new file mode 100644 index 0000000..ca21a98 --- /dev/null +++ b/rosetta/file30.perl @@ -0,0 +1 @@ +require 5.014 ; # Older versions can't resolve IPv6 with just core Socket module   use Socket qw ( getaddrinfo getnameinfo ) ; my ( $err , @res ) = getaddrinfo ( "www.kame.net" , 0 , { protocol => Socket :: IPPROTO_TCP } ) ; die "getaddrinfo error: $err" if $err ;   print getnameinfo ( $_ -> { addr } , Socket :: NI_NUMERICHOST ) , " \n " for @res   \ No newline at end of file diff --git a/rosetta/file30.php b/rosetta/file30.php new file mode 100644 index 0000000..3495e43 --- /dev/null +++ b/rosetta/file30.php @@ -0,0 +1 @@ +function binary_search ( $array , $secret , $start , $end ) { do { $guess = ( int ) ( $start + ( ( $end - $start ) / 2 ) ) ;   if ( $array [ $guess ] > $secret ) $end = $guess ;   if ( $array [ $guess ] < $secret ) $start = $guess ;   if ( $end < $start ) return - 1 ;   } while ( $array [ $guess ] != $secret ) ;   return $guess ; } \ No newline at end of file diff --git a/rosetta/file30.py b/rosetta/file30.py new file mode 100644 index 0000000..c21a6b0 --- /dev/null +++ b/rosetta/file30.py @@ -0,0 +1 @@ +import fileinput   for line in fileinput . input ( inplace = True ) : print ( line. replace ( 'Goodbye London!' , 'Hello New York!' ) , end = '' )   \ No newline at end of file diff --git a/rosetta/file30.rb b/rosetta/file30.rb new file mode 100644 index 0000000..026629c --- /dev/null +++ b/rosetta/file30.rb @@ -0,0 +1 @@ +def multiply ( a, b ) a * b end \ No newline at end of file diff --git a/rosetta/file30.scala b/rosetta/file30.scala new file mode 100644 index 0000000..469c36f --- /dev/null +++ b/rosetta/file30.scala @@ -0,0 +1 @@ +import java. nio . file . { Files, FileSystems }   object FileExistsTest extends App {   val defaultFS = FileSystems. getDefault ( ) val separator = defaultFS. getSeparator ( )   def test ( filename : String ) { val path = defaultFS. getPath ( filename )   println ( s "The following ${if (Files.isDirectory(path)) " directory " else " file "} called $filename" + ( if ( Files. exists ( path ) ) " exists." else " not exists." ) ) }   // main List ( "output.txt" , separator + "output.txt" , "docs" , separator + "docs" + separator ) . foreach ( test ) } \ No newline at end of file diff --git a/rosetta/file30.ss b/rosetta/file30.ss new file mode 100644 index 0000000..7d12118 --- /dev/null +++ b/rosetta/file30.ss @@ -0,0 +1 @@ +( define ( binary - search value vector ) ( let helper ( ( low 0 ) ( high ( - ( vector-length vector ) 1 ) ) ) ( if ( < high low ) #f ( let ( ( middle ( quotient ( + low high ) 2 ) ) ) ( cond ( ( > ( vector-ref vector middle ) value ) ( helper low ( - middle 1 ) ) ) ( ( < ( vector-ref vector middle ) value ) ( helper ( + middle 1 ) high ) ) ( else middle ) ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file30.tcl b/rosetta/file30.tcl new file mode 100644 index 0000000..f168a0b --- /dev/null +++ b/rosetta/file30.tcl @@ -0,0 +1 @@ +package require Tcl 8.5   set text { Tyler Bennett,E10297, 32000 ,D101 John Rappl,E21437, 47000 ,D050 George Woltman,E00127, 53500 ,D101 Adam Smith,E63535, 18000 ,D202 Claire Buckman,E39876, 27800 ,D202 David McClellan,E04242, 41500 ,D101 Rich Holcomb,E01234, 49500 ,D202 Nathan Adams,E41298, 21900 ,D050 Richard Potter,E43128, 15900 ,D101 David Motsinger,E27002, 19250 ,D202 Tim Sampair,E03033, 27000 ,D101 Kim Arlich,E10001, 57000 ,D190 Timothy Grove,E16398, 29900 ,D190 }   set data [ dict create ] foreach line [ split $text \n ] { lassign [ split $line , ] name id salary dept dict lappend data $dept [ list $name $id $salary ] }   proc top_n_salaries { n data } { incr n - 1 dict for { dept employees } $data { puts "Department $dept" foreach emp [ lrange [ lsort -integer -decreasing -index 2 $employees ] 0 $n ] { puts [ format "  %-20s %-8s %8d" { * } $emp ] } puts "" } }   top_n_salaries 3 $data \ No newline at end of file diff --git a/rosetta/file31.clojure b/rosetta/file31.clojure new file mode 100644 index 0000000..97cb87d --- /dev/null +++ b/rosetta/file31.clojure @@ -0,0 +1 @@ +    ( defn draw - line "Draw a line from x1,y1 to x2,y2 using Bresenham's, to a java BufferedImage in the colour of pixel." [ buffer x1 y1 x2 y2 pixel ] ( let [ dist - x ( Math / abs ( - x1 x2 ) ) dist - y ( Math / abs ( - y1 y2 ) ) steep ( > dist - y dist - x ) ] ( let [ [ x1 y1 x2 y2 ] ( if steep [ y1 x1 y2 x2 ] [ x1 y1 x2 y2 ] ) ] ( let [ [ x1 y1 x2 y2 ] ( if ( > x1 x2 ) [ x2 y2 x1 y1 ] [ x1 y1 x2 y2 ] ) ] ( let [ delta - x ( - x2 x1 ) delta - y ( Math / abs ( - y1 y2 ) ) y - step ( if ( < y1 y2 ) 1 - 1 ) ]   ( let [ plot ( if steep # ( . setRGB buffer ( int % 1 ) ( int % 2 ) pixel ) # ( . setRGB buffer ( int % 2 ) ( int % 1 ) pixel ) ) ]   ( loop [ x x1 y y1 error ( Math / floor ( / delta - x 2 ) ) ] ( plot x y ) ( if ( < x x2 ) ; Rather then rebind error, test that it is less than delta-y rather than zero ( if ( < error delta - y ) ( recur ( inc x ) ( + y y - step ) ( + error ( - delta - x delta - y ) ) ) ( recur ( inc x ) y ( - error delta - y ) ) ) ) ) ) ) ) ) ) )   \ No newline at end of file diff --git a/rosetta/file31.hs b/rosetta/file31.hs new file mode 100644 index 0000000..3418e27 --- /dev/null +++ b/rosetta/file31.hs @@ -0,0 +1 @@ +# !/ usr / bin / runhaskell   import Control . Monad ( forM _ ) import System . Random import Data . List as L   import Text . Blaze . Html5 import Text . Blaze . Html . Renderer . Pretty   makeTable :: RandomGen g => [ String ] -> Int -> g -> Html makeTable headings nRows gen = table $ do thead $ tr $ forM _ ( L . map toHtml headings ) th tbody $ forM _ ( zip [ 1 .. nRows ] $ unfoldr ( Just . split ) gen ) ( \ ( x , g ) -> tr $ forM _ ( take ( length headings ) ( x:randomRs ( 1000 , 9999 ) g ) ) ( td . toHtml ) )   main = do g <- getStdGen putStrLn $ renderHtml $ makeTable [ "" , "X" , "Y" , "Z" ] 3 g \ No newline at end of file diff --git a/rosetta/file31.java b/rosetta/file31.java new file mode 100644 index 0000000..2b522fb --- /dev/null +++ b/rosetta/file31.java @@ -0,0 +1 @@ +import java.awt.Color ; import java.awt.Point ; import java.awt.image.BufferedImage ; import java.util.Deque ; import java.util.LinkedList ;   public class FloodFill { public void floodFill ( BufferedImage image, Point node, Color targetColor, Color replacementColor ) { int width = image. getWidth ( ) ; int height = image. getHeight ( ) ; int target = targetColor. getRGB ( ) ; int replacement = replacementColor. getRGB ( ) ; if ( target != replacement ) { Deque < Point > queue = new LinkedList < Point > ( ) ; do { int x = node. x ; int y = node. y ; while ( x > 0 && image. getRGB ( x - 1 , y ) == target ) { x --; } boolean spanUp = false ; boolean spanDown = false ; while ( x < width && image. getRGB ( x, y ) == target ) { image. setRGB ( x, y, replacement ) ; if ( ! spanUp && y > 0 && image. getRGB ( x, y - 1 ) == target ) { queue. add ( new Point ( x, y - 1 ) ) ; spanUp = true ; } else if ( spanUp && y > 0 && image. getRGB ( x, y - 1 ) != target ) { spanUp = false ; } if ( ! spanDown && y < height - 1 && image. getRGB ( x, y + 1 ) == target ) { queue. add ( new Point ( x, y + 1 ) ) ; spanDown = true ; } else if ( spanDown && y < height - 1 && image. getRGB ( x, y + 1 ) != target ) { spanDown = false ; } x ++; } } while ( ( node = queue. pollFirst ( ) ) != null ) ; } } } \ No newline at end of file diff --git a/rosetta/file31.js b/rosetta/file31.js new file mode 100644 index 0000000..134d9c4 --- /dev/null +++ b/rosetta/file31.js @@ -0,0 +1 @@ +function bline ( x0 , y0 , x1 , y1 ) {   var dx = Math . abs ( x1 - x0 ) , sx = x0 < x1 ? 1 : - 1 ; var dy = Math . abs ( y1 - y0 ) , sy = y0 < y1 ? 1 : - 1 ; var err = ( dx > dy ? dx : - dy ) / 2 ;   while ( true ) { setPixel ( x0 , y0 ) ; if ( x0 === x1 && y0 === y1 ) break ; var e2 = err ; if ( e2 > - dx ) { err -= dy ; x0 += sx ; } if ( e2 < dy ) { err += dx ; y0 += sy ; } } } \ No newline at end of file diff --git a/rosetta/file31.ocaml b/rosetta/file31.ocaml new file mode 100644 index 0000000..c43bcdf --- /dev/null +++ b/rosetta/file31.ocaml @@ -0,0 +1 @@ +Sys . file_exists "input.txt" ;; Sys . file_exists "docs" ;; Sys . file_exists "/input.txt" ;; Sys . file_exists "/docs" ;; \ No newline at end of file diff --git a/rosetta/file31.perl b/rosetta/file31.perl new file mode 100644 index 0000000..9dd1932 --- /dev/null +++ b/rosetta/file31.perl @@ -0,0 +1 @@ +sub dotprod { my ( $vec_a , $vec_b ) = @_ ; die "they must have the same size \n " unless @$vec_a == @$vec_b ; my $sum = 0 ; $sum += $vec_a -> [ $_ ] * $vec_b -> [ $_ ] for 0 .. $# $vec_a ; return $sum ; }   my @vec_a = ( 1 , 3 ,- 5 ) ; my @vec_b = ( 4 ,- 2 ,- 1 ) ;   print dotprod ( \@vec_a , \@vec_b ) , " \n " ; # 3 \ No newline at end of file diff --git a/rosetta/file31.php b/rosetta/file31.php new file mode 100644 index 0000000..3495e43 --- /dev/null +++ b/rosetta/file31.php @@ -0,0 +1 @@ +function binary_search ( $array , $secret , $start , $end ) { do { $guess = ( int ) ( $start + ( ( $end - $start ) / 2 ) ) ;   if ( $array [ $guess ] > $secret ) $end = $guess ;   if ( $array [ $guess ] < $secret ) $start = $guess ;   if ( $end < $start ) return - 1 ;   } while ( $array [ $guess ] != $secret ) ;   return $guess ; } \ No newline at end of file diff --git a/rosetta/file31.py b/rosetta/file31.py new file mode 100644 index 0000000..80358e0 --- /dev/null +++ b/rosetta/file31.py @@ -0,0 +1 @@ +import random from Tkinter import * import tkMessageBox     class Application ( Frame ) : def __init__ ( self , master ) : Frame. __init__ ( self , master ) self . counter = 0 self . contents = StringVar ( ) self . contents . set ( str ( self . counter ) ) self . pack ( expand = True , fill = 'both' , padx = 10 , pady = 15 ) self . create_widgets ( )   def increment ( self , *args ) : self . counter + = 1 self . update_entry ( )   def random ( self ) : if tkMessageBox. askyesno ( "Confirmation" , "Reset to random value ?" ) : self . counter = random . randint ( 0 , 5000 ) self . update_entry ( )   def entry_updated ( self , event , *args ) : if not event. char : return 'break' if not event. char . isdigit ( ) : tkMessageBox. showerror ( 'Error' , 'Invalid input !' ) return 'break' self . counter = int ( '%s%s'  % ( self . contents . get ( ) , event. char ) )   def update_entry ( self ) : self . contents . set ( str ( self . counter ) ) self . entry [ 'textvariable' ] = self . contents   def create_widgets ( self ) : options = { 'expand' : True , 'fill' : 'x' , 'side' : 'left' , 'padx' : 5 } self . entry = Entry ( self ) self . entry . bind ( '' , self . entry_updated ) self . entry . pack ( **options ) self . update_entry ( ) self . increment_button = Button ( self , text = 'Increment' , command = self . increment ) self . increment_button . pack ( **options ) self . random_button = Button ( self , text = 'Random' , command = self . random ) self . random_button . pack ( **options )     if __name__ == '__main__' : root = Tk ( ) try : app = Application ( master = root ) app. master . title ( "Rosetta code" ) app. mainloop ( ) except KeyboardInterrupt : root. destroy ( ) \ No newline at end of file diff --git a/rosetta/file31.rb b/rosetta/file31.rb new file mode 100644 index 0000000..026629c --- /dev/null +++ b/rosetta/file31.rb @@ -0,0 +1 @@ +def multiply ( a, b ) a * b end \ No newline at end of file diff --git a/rosetta/file31.scala b/rosetta/file31.scala new file mode 100644 index 0000000..f0e9c24 --- /dev/null +++ b/rosetta/file31.scala @@ -0,0 +1 @@ +case class Matrix ( val matrix : Array [ Array [ Double ] ] ) {   // Assuming matrix is positive-definite, symmetric and not empty...   val rows,cols = matrix. size   def getOption ( r : Int, c : Int ) : Option [ Double ] = Pair ( r,c ) match { case ( r,c ) if r < rows && c < rows => Some ( matrix ( r ) ( c ) ) case _ => None }   def isLowerTriangle ( r : Int, c : Int ) : Boolean = { c <= r } def isDiagonal ( r : Int, c : Int ) : Boolean = { r == c }   override def toString = matrix. map ( _ . mkString ( ", " ) ) . mkString ( " \n " )   /** * Perform Cholesky Decomposition of this matrix */ lazy val cholesky : Matrix = {   val l = Array. ofDim [ Double ] ( rows * cols )   for ( i < - ( 0 until rows ) ; j < - ( 0 until cols ) ) yield {   val s = ( for ( k < - ( 0 until j ) ) yield { l ( i * rows+k ) * l ( j * rows+k ) } ) . sum   l ( i * rows+j ) = ( i,j ) match { case ( r,c ) if isDiagonal ( r,c ) => scala. math . sqrt ( matrix ( i ) ( i ) - s ) case ( r,c ) if isLowerTriangle ( r,c ) => ( 1.0 / l ( j * rows+j ) * ( matrix ( i ) ( j ) - s ) ) case _ => 0 } }   val m = Array. ofDim [ Double ] ( rows,cols ) for ( i < - ( 0 until rows ) ; j < - ( 0 until cols ) ) m ( i ) ( j ) = l ( i * rows+j ) Matrix ( m ) } }   // A little test... val a1 = Matrix ( Array [ Array [ Double ] ] ( Array ( 25 , 15 ,- 5 ) ,Array ( 15 , 18 , 0 ) ,Array ( - 5 , 0 , 11 ) ) ) val a2 = Matrix ( Array [ Array [ Double ] ] ( Array ( 18 , 22 , 54 , 42 ) , Array ( 22 , 70 , 86 , 62 ) , Array ( 54 , 86 , 174 , 134 ) , Array ( 42 , 62 , 134 , 106 ) ) )   val l1 = a1. cholesky val l2 = a2. cholesky     // Given test results val r1 = Array [ Double ] ( 5 , 0 , 0 , 3 , 3 , 0 ,- 1 , 1 , 3 ) val r2 = Array [ Double ] ( 4.24264 , 0.00000 , 0.00000 , 0.00000 , 5.18545 , 6.56591 , 0.00000 , 0.00000 , 12.72792 , 3.04604 , 1.64974 , 0.00000 , 9.89949 , 1.62455 , 1.84971 , 1.39262 )   // Verify assertions ( l1. matrix . flatten . zip ( r1 ) ) . foreach { case ( result,test ) => assert ( math. round ( result * 100000 ) * 0.00001 == math. round ( test * 100000 ) * 0.00001 ) }   ( l2. matrix . flatten . zip ( r2 ) ) . foreach { case ( result,test ) => assert ( math. round ( result * 100000 ) * 0.00001 == math. round ( test * 100000 ) * 0.00001 ) } \ No newline at end of file diff --git a/rosetta/file31.ss b/rosetta/file31.ss new file mode 100644 index 0000000..7d12118 --- /dev/null +++ b/rosetta/file31.ss @@ -0,0 +1 @@ +( define ( binary - search value vector ) ( let helper ( ( low 0 ) ( high ( - ( vector-length vector ) 1 ) ) ) ( if ( < high low ) #f ( let ( ( middle ( quotient ( + low high ) 2 ) ) ) ( cond ( ( > ( vector-ref vector middle ) value ) ( helper low ( - middle 1 ) ) ) ( ( < ( vector-ref vector middle ) value ) ( helper ( + middle 1 ) high ) ) ( else middle ) ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file31.tcl b/rosetta/file31.tcl new file mode 100644 index 0000000..ff08d13 --- /dev/null +++ b/rosetta/file31.tcl @@ -0,0 +1 @@ +package require Tcl 8.6   # Function to evaluate the truth of a statement proc tcl:: mathfunc :: S { idx } { upvar 1 state s apply [ lindex $s [ expr { $idx - 1 } ] ] $s } # Procedure to count the number of statements which are true proc S+ args { upvar 1 state state tcl:: mathop ::+ { * } [ lmap i $args { expr { S ( $i ) } } ] } # Turn a list of expressions into a list of lambda terms proc lambdas items { lmap x $items { list state [ list expr $x ] } }   # Find the truth assignment that produces consistency. And those that are # near misses too. proc findTruthMatch { statements } { set n [ llength $statements ] for { set i 0 } { $i < 2 ** $n } { incr i } { set state [ split [ format % 0. * b $n $i ] "" ] set truths [ lmap f $statements { apply $f [ lambdas $state ] } ] set counteq [ tcl:: mathop ::+ { * } [ lmap s $state t $truths { expr { $s == $t } } ] ] if { $counteq == $n } { lappend exact $state } elseif { $counteq == $n - 1 } { set j 0 foreach s $state t $truths { incr j if { $s ! = $t } { lappend differ $state $j break } } } } return [ list $exact $differ ] }   # Rendering code proc renderstate state { return ( [ join [ lmap s $state { incr i expr { $s ? "S($i)"  : " \u 00acS($i)" } } ] " \u 22c0" ] ) }   # The statements, encoded as expressions set statements { { [ llength $state ] == 12 } { [ S+ 7 8 9 10 11 12 ] == 3 } { [ S+ 2 4 6 8 10 12 ] == 2 } { S ( 5 ) ? S ( 6 ) && S ( 7 )  : 1 } { [ S+ 2 3 4 ] == 0 } { [ S+ 1 3 5 7 9 11 ] == 4 } { S ( 2 ) ! = S ( 3 ) } { S ( 7 ) ? S ( 5 ) && S ( 6 )  : 1 } { [ S+ 1 2 3 4 5 6 ] == 3 } { S ( 11 ) && S ( 12 ) } { [ S+ 7 8 9 ] == 1 } { [ S+ 1 2 3 4 5 6 7 8 9 10 11 ] == 4 } } # Find the truth assignment(s) that give consistency lassign [ findTruthMatch [ lambdas $statements ] ] exact differ # Print the results foreach state $exact { puts "exact match \t [renderstate $state ]" } foreach { state j } $differ { puts "almost found \t [renderstate $state] \u 21d2 [expr {[lindex $state $j-1]?" \u00ac ":{}}]S($j)" } \ No newline at end of file diff --git a/rosetta/file32.clojure b/rosetta/file32.clojure new file mode 100644 index 0000000..97cb87d --- /dev/null +++ b/rosetta/file32.clojure @@ -0,0 +1 @@ +    ( defn draw - line "Draw a line from x1,y1 to x2,y2 using Bresenham's, to a java BufferedImage in the colour of pixel." [ buffer x1 y1 x2 y2 pixel ] ( let [ dist - x ( Math / abs ( - x1 x2 ) ) dist - y ( Math / abs ( - y1 y2 ) ) steep ( > dist - y dist - x ) ] ( let [ [ x1 y1 x2 y2 ] ( if steep [ y1 x1 y2 x2 ] [ x1 y1 x2 y2 ] ) ] ( let [ [ x1 y1 x2 y2 ] ( if ( > x1 x2 ) [ x2 y2 x1 y1 ] [ x1 y1 x2 y2 ] ) ] ( let [ delta - x ( - x2 x1 ) delta - y ( Math / abs ( - y1 y2 ) ) y - step ( if ( < y1 y2 ) 1 - 1 ) ]   ( let [ plot ( if steep # ( . setRGB buffer ( int % 1 ) ( int % 2 ) pixel ) # ( . setRGB buffer ( int % 2 ) ( int % 1 ) pixel ) ) ]   ( loop [ x x1 y y1 error ( Math / floor ( / delta - x 2 ) ) ] ( plot x y ) ( if ( < x x2 ) ; Rather then rebind error, test that it is less than delta-y rather than zero ( if ( < error delta - y ) ( recur ( inc x ) ( + y y - step ) ( + error ( - delta - x delta - y ) ) ) ( recur ( inc x ) y ( - error delta - y ) ) ) ) ) ) ) ) ) ) )   \ No newline at end of file diff --git a/rosetta/file32.hs b/rosetta/file32.hs new file mode 100644 index 0000000..186b37d --- /dev/null +++ b/rosetta/file32.hs @@ -0,0 +1 @@ +import Data . Int import Data . Bits import Data . List import Data . Array . ST import Control . Monad import Control . Monad . ST import System . Environment   srnd :: Int32 -> [ Int ] srnd = map ( fromIntegral . flip shiftR 16 ) . tail . iterate ( \x -> ( x * 214013 + 2531011 ) . & . maxBound )   deal :: Int32 -> [ String ] deal s = runST ( do ar <- newListArray ( 0 , 51 ) $ sequence [ "A23456789TJQK" , "CDHS" ] :: ST s ( STArray s Int String ) forM ( zip [ 52 , 51 .. 1 ] rnd ) $ \ ( n , r ) -> do let j = r ` mod ` n vj <- readArray ar j vn <- readArray ar ( n - 1 ) writeArray ar j vn return vj ) where rnd = srnd s   showCards :: [ String ] -> IO ( ) showCards = mapM_ ( putStrLn . unwords ) . takeWhile ( not . null ) . unfoldr ( Just . splitAt 8 )   main :: IO ( ) main = do args <- getArgs let s = read ( head args ) :: Int32 putStrLn $ "Deal " ++ show s ++ ":" let cards = deal s showCards cards \ No newline at end of file diff --git a/rosetta/file32.java b/rosetta/file32.java new file mode 100644 index 0000000..88d3518 --- /dev/null +++ b/rosetta/file32.java @@ -0,0 +1 @@ +  import java.awt.Color ;   public class MidPointCircle { private BasicBitmapStorage image ;   public MidPointCircle ( final int imageWidth, final int imageHeight ) { this . image = new BasicBitmapStorage ( imageWidth, imageHeight ) ; }   private void drawCircle ( final int centerX, final int centerY, final int radius ) { int d = ( 5 - r * 4 ) / 4 ; int x = 0 ; int y = radius ; Color circleColor = Color . white ;   do { image. setPixel ( centerX + x, centerY + y, circleColor ) ; image. setPixel ( centerX + x, centerY - y, circleColor ) ; image. setPixel ( centerX - x, centerY + y, circleColor ) ; image. setPixel ( centerX - x, centerY - y, circleColor ) ; image. setPixel ( centerX + y, centerY + x, circleColor ) ; image. setPixel ( centerX + y, centerY - x, circleColor ) ; image. setPixel ( centerX - y, centerY + x, circleColor ) ; image. setPixel ( centerX - y, centerY - x, circleColor ) ; if ( d < 0 ) { d += 2 * x + 1 ; } else { d += 2 * ( x - y ) + 1 ; y --; } x ++; } while ( x <= y ) ;   } }   \ No newline at end of file diff --git a/rosetta/file32.js b/rosetta/file32.js new file mode 100644 index 0000000..134d9c4 --- /dev/null +++ b/rosetta/file32.js @@ -0,0 +1 @@ +function bline ( x0 , y0 , x1 , y1 ) {   var dx = Math . abs ( x1 - x0 ) , sx = x0 < x1 ? 1 : - 1 ; var dy = Math . abs ( y1 - y0 ) , sy = y0 < y1 ? 1 : - 1 ; var err = ( dx > dy ? dx : - dy ) / 2 ;   while ( true ) { setPixel ( x0 , y0 ) ; if ( x0 === x1 && y0 === y1 ) break ; var e2 = err ; if ( e2 > - dx ) { err -= dy ; x0 += sx ; } if ( e2 < dy ) { err += dx ; y0 += sy ; } } } \ No newline at end of file diff --git a/rosetta/file32.ocaml b/rosetta/file32.ocaml new file mode 100644 index 0000000..a9c5bcf --- /dev/null +++ b/rosetta/file32.ocaml @@ -0,0 +1 @@ +let cholesky inp = let n = Array . length inp in let res = Array . make_matrix n n 0.0 in let factor i k = let rec sum j = if j = k then 0.0 else res . ( i ) . ( j ) *. res . ( k ) . ( j ) +. sum ( j + 1 ) in inp . ( i ) . ( k ) -. sum 0 in for col = 0 to n - 1 do res . ( col ) . ( col ) <- sqrt ( factor col col ) ; for row = col + 1 to n - 1 do res . ( row ) . ( col ) <- ( factor row col ) /. res . ( col ) . ( col ) done done ; res   let pr_vec v = Array . iter ( Printf . printf " %9.5f" ) v ; print_newline ( ) let show = Array . iter pr_vec let test a = print_endline "\nin:" ; show a ; print_endline "out:" ; show ( cholesky a )   let _ = test [ | [ | 25.0 ; 15.0 ; - 5.0 | ] ; [ | 15.0 ; 18.0 ; 0.0 | ] ; [ |- 5.0 ; 0.0 ; 11.0 | ] | ] ; test [ | [ | 18.0 ; 22.0 ; 54.0 ; 42.0 | ] ; [ | 22.0 ; 70.0 ; 86.0 ; 62.0 | ] ; [ | 54.0 ; 86.0 ; 174.0 ; 134.0 | ] ; [ | 42.0 ; 62.0 ; 134.0 ; 106.0 | ] | ] ; \ No newline at end of file diff --git a/rosetta/file32.perl b/rosetta/file32.perl new file mode 100644 index 0000000..18cd89e --- /dev/null +++ b/rosetta/file32.perl @@ -0,0 +1 @@ +my %node_model = ( data => 'something' , prev => undef , next => undef , ) ;   sub insert { my ( $anchor , $newlink ) = @_ ; $newlink -> { next } = $anchor -> { next } ; $newlink -> { prev } = $anchor ; $newlink -> { next } -> { prev } = $newlink ; $anchor -> { next } = $newlink ; }   # create the list {A,B} my $node_a = { %node_model } ; my $node_b = { %node_model } ;   $node_a -> { next } = $node_b ; $node_b -> { prev } = $node_a ;   # insert element C into a list {A,B}, between elements A and B. my $node_c = { %node_model } ; insert ( $node_a , $node_c ) ; \ No newline at end of file diff --git a/rosetta/file32.php b/rosetta/file32.php new file mode 100644 index 0000000..5cc012a --- /dev/null +++ b/rosetta/file32.php @@ -0,0 +1 @@ +class Bitmap { public $data ; public $w ; public $h ; public function __construct ( $w = 16 , $h = 16 ) { $white = array_fill ( 0 , $w , array ( 255 , 255 , 255 ) ) ; $this -> data = array_fill ( 0 , $h , $white ) ; $this -> w = $w ; $this -> h = $h ; } //Fills a rectangle, or the whole image with black by default public function fill ( $x = 0 , $y = 0 , $w = null , $h = null , $color = array ( 0 , 0 , 0 ) ) { if ( is_null ( $w ) ) $w = $this -> w ; if ( is_null ( $h ) ) $h = $this -> h ; $w += $x ; $h += $y ; for ( $i = $y ; $i < $h ; $i ++ ) { for ( $j = $x ; $j < $w ; $j ++ ) { $this -> setPixel ( $j , $i , $color ) ; } } } public function setPixel ( $x , $y , $color = array ( 0 , 0 , 0 ) ) { if ( $x >= $this -> w ) return false ; if ( $x < 0 ) return false ; if ( $y >= $this -> h ) return false ; if ( $y < 0 ) return false ; $this -> data [ $y ] [ $x ] = $color ; } public function getPixel ( $x , $y ) { return $this -> data [ $y ] [ $x ] ; } }   $b = new Bitmap ( 16 , 16 ) ; $b -> fill ( ) ; $b -> fill ( 2 , 2 , 18 , 18 , array ( 240 , 240 , 240 ) ) ; $b -> setPixel ( 0 , 15 , array ( 255 , 0 , 0 ) ) ; print_r ( $b -> getPixel ( 3 , 3 ) ) ; //(240,240,240) \ No newline at end of file diff --git a/rosetta/file32.py b/rosetta/file32.py new file mode 100644 index 0000000..80358e0 --- /dev/null +++ b/rosetta/file32.py @@ -0,0 +1 @@ +import random from Tkinter import * import tkMessageBox     class Application ( Frame ) : def __init__ ( self , master ) : Frame. __init__ ( self , master ) self . counter = 0 self . contents = StringVar ( ) self . contents . set ( str ( self . counter ) ) self . pack ( expand = True , fill = 'both' , padx = 10 , pady = 15 ) self . create_widgets ( )   def increment ( self , *args ) : self . counter + = 1 self . update_entry ( )   def random ( self ) : if tkMessageBox. askyesno ( "Confirmation" , "Reset to random value ?" ) : self . counter = random . randint ( 0 , 5000 ) self . update_entry ( )   def entry_updated ( self , event , *args ) : if not event. char : return 'break' if not event. char . isdigit ( ) : tkMessageBox. showerror ( 'Error' , 'Invalid input !' ) return 'break' self . counter = int ( '%s%s'  % ( self . contents . get ( ) , event. char ) )   def update_entry ( self ) : self . contents . set ( str ( self . counter ) ) self . entry [ 'textvariable' ] = self . contents   def create_widgets ( self ) : options = { 'expand' : True , 'fill' : 'x' , 'side' : 'left' , 'padx' : 5 } self . entry = Entry ( self ) self . entry . bind ( '' , self . entry_updated ) self . entry . pack ( **options ) self . update_entry ( ) self . increment_button = Button ( self , text = 'Increment' , command = self . increment ) self . increment_button . pack ( **options ) self . random_button = Button ( self , text = 'Random' , command = self . random ) self . random_button . pack ( **options )     if __name__ == '__main__' : root = Tk ( ) try : app = Application ( master = root ) app. master . title ( "Rosetta code" ) app. mainloop ( ) except KeyboardInterrupt : root. destroy ( ) \ No newline at end of file diff --git a/rosetta/file32.rb b/rosetta/file32.rb new file mode 100644 index 0000000..5d2e758 --- /dev/null +++ b/rosetta/file32.rb @@ -0,0 +1 @@ +var files = % w ( a. txt b. txt c. txt ) ;   files. map { . toFile } . each { | file | say file. edit { | line | line. gsub ( "Goodbye London!" , "Hello New York!" ) ; } ; } \ No newline at end of file diff --git a/rosetta/file32.scala b/rosetta/file32.scala new file mode 100644 index 0000000..578a2d9 --- /dev/null +++ b/rosetta/file32.scala @@ -0,0 +1 @@ +def getColorAt ( x : Int, y : Int ) : Color = new Robot ( ) . getPixelColor ( x, y ) \ No newline at end of file diff --git a/rosetta/file32.ss b/rosetta/file32.ss new file mode 100644 index 0000000..7d12118 --- /dev/null +++ b/rosetta/file32.ss @@ -0,0 +1 @@ +( define ( binary - search value vector ) ( let helper ( ( low 0 ) ( high ( - ( vector-length vector ) 1 ) ) ) ( if ( < high low ) #f ( let ( ( middle ( quotient ( + low high ) 2 ) ) ) ( cond ( ( > ( vector-ref vector middle ) value ) ( helper low ( - middle 1 ) ) ) ( ( < ( vector-ref vector middle ) value ) ( helper ( + middle 1 ) high ) ) ( else middle ) ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file32.tcl b/rosetta/file32.tcl new file mode 100644 index 0000000..4db7476 --- /dev/null +++ b/rosetta/file32.tcl @@ -0,0 +1 @@ +# Variables are undefined by default and do not need explicit declaration   # Check to see whether it is defined if { ! [ info exists var ] } { puts "var is undefind at first check" }   # Give it a value set var "Screwy Squirrel"   # Check to see whether it is defined if { ! [ info exists var ] } { puts "var is undefind at second check" }   # Remove its value unset var   # Check to see whether it is defined if { ! [ info exists var ] } { puts "var is undefind at third check" }   # Give it a value again set var 12345   # Check to see whether it is defined if { ! [ info exists var ] } { puts "var is undefind at fourth check" }   puts "Done" \ No newline at end of file diff --git a/rosetta/file33.clojure b/rosetta/file33.clojure new file mode 100644 index 0000000..97cb87d --- /dev/null +++ b/rosetta/file33.clojure @@ -0,0 +1 @@ +    ( defn draw - line "Draw a line from x1,y1 to x2,y2 using Bresenham's, to a java BufferedImage in the colour of pixel." [ buffer x1 y1 x2 y2 pixel ] ( let [ dist - x ( Math / abs ( - x1 x2 ) ) dist - y ( Math / abs ( - y1 y2 ) ) steep ( > dist - y dist - x ) ] ( let [ [ x1 y1 x2 y2 ] ( if steep [ y1 x1 y2 x2 ] [ x1 y1 x2 y2 ] ) ] ( let [ [ x1 y1 x2 y2 ] ( if ( > x1 x2 ) [ x2 y2 x1 y1 ] [ x1 y1 x2 y2 ] ) ] ( let [ delta - x ( - x2 x1 ) delta - y ( Math / abs ( - y1 y2 ) ) y - step ( if ( < y1 y2 ) 1 - 1 ) ]   ( let [ plot ( if steep # ( . setRGB buffer ( int % 1 ) ( int % 2 ) pixel ) # ( . setRGB buffer ( int % 2 ) ( int % 1 ) pixel ) ) ]   ( loop [ x x1 y y1 error ( Math / floor ( / delta - x 2 ) ) ] ( plot x y ) ( if ( < x x2 ) ; Rather then rebind error, test that it is less than delta-y rather than zero ( if ( < error delta - y ) ( recur ( inc x ) ( + y y - step ) ( + error ( - delta - x delta - y ) ) ) ( recur ( inc x ) y ( - error delta - y ) ) ) ) ) ) ) ) ) ) )   \ No newline at end of file diff --git a/rosetta/file33.hs b/rosetta/file33.hs new file mode 100644 index 0000000..cdf469d --- /dev/null +++ b/rosetta/file33.hs @@ -0,0 +1 @@ +import Data . List   h , f , g :: [ Double ] h = [ - 8 ,- 9 ,- 3 ,- 1 ,- 6 , 7 ] f = [ - 3 ,- 6 ,- 1 , 8 ,- 6 , 3 ,- 1 ,- 9 ,- 9 , 3 ,- 2 , 5 , 2 ,- 2 ,- 7 ,- 1 ] g = [ 24 , 75 , 71 ,- 34 , 3 , 22 ,- 45 , 23 , 245 , 25 , 52 , 25 ,- 67 ,- 96 , 96 , 31 , 55 , 36 , 29 ,- 43 ,- 7 ]   scale x ys = map ( x * ) ys   deconv1d :: ( Fractional a ) => [ a ] -> [ a ] -> [ a ] deconv1d xs ys = takeWhile ( /= 0 ) $ deconv xs ys where [ ] `deconv` _ = [ ] ( 0 :xs ) `deconv` ( 0 :ys ) = xs `deconv` ys ( x:xs ) `deconv` ( y:ys ) = q : zipWith ( - ) xs ( scale q ys ++ repeat 0 ) `deconv` ( y:ys ) where q = x / y \ No newline at end of file diff --git a/rosetta/file33.java b/rosetta/file33.java new file mode 100644 index 0000000..88d3518 --- /dev/null +++ b/rosetta/file33.java @@ -0,0 +1 @@ +  import java.awt.Color ;   public class MidPointCircle { private BasicBitmapStorage image ;   public MidPointCircle ( final int imageWidth, final int imageHeight ) { this . image = new BasicBitmapStorage ( imageWidth, imageHeight ) ; }   private void drawCircle ( final int centerX, final int centerY, final int radius ) { int d = ( 5 - r * 4 ) / 4 ; int x = 0 ; int y = radius ; Color circleColor = Color . white ;   do { image. setPixel ( centerX + x, centerY + y, circleColor ) ; image. setPixel ( centerX + x, centerY - y, circleColor ) ; image. setPixel ( centerX - x, centerY + y, circleColor ) ; image. setPixel ( centerX - x, centerY - y, circleColor ) ; image. setPixel ( centerX + y, centerY + x, circleColor ) ; image. setPixel ( centerX + y, centerY - x, circleColor ) ; image. setPixel ( centerX - y, centerY + x, circleColor ) ; image. setPixel ( centerX - y, centerY - x, circleColor ) ; if ( d < 0 ) { d += 2 * x + 1 ; } else { d += 2 * ( x - y ) + 1 ; y --; } x ++; } while ( x <= y ) ;   } }   \ No newline at end of file diff --git a/rosetta/file33.js b/rosetta/file33.js new file mode 100644 index 0000000..d4b163d --- /dev/null +++ b/rosetta/file33.js @@ -0,0 +1 @@ +function bitwise ( a , b ) { alert ( "a AND b: " + ( a & b ) ) ; alert ( "a OR b: " + ( a | b ) ) ; alert ( "a XOR b: " + ( a ^ b ) ) ; alert ( "NOT a: " + ~a ) ; alert ( "a << b: " + ( a << b ) ) ; // left shift alert ( "a >> b: " + ( a >> b ) ) ; // arithmetic right shift alert ( "a >>> b: " + ( a >>> b ) ) ; // logical right shift } \ No newline at end of file diff --git a/rosetta/file33.ocaml b/rosetta/file33.ocaml new file mode 100644 index 0000000..dcc0d69 --- /dev/null +++ b/rosetta/file33.ocaml @@ -0,0 +1 @@ +[ 1 ; 2 ; 3 ; 4 ; 5 ] \ No newline at end of file diff --git a/rosetta/file33.perl b/rosetta/file33.perl new file mode 100644 index 0000000..e252f32 --- /dev/null +++ b/rosetta/file33.perl @@ -0,0 +1 @@ +my @results = qx ( ls ) ; # runs command and returns its STDOUT as a string my @results = `ls` ; # ditto, alternative syntax   system "ls" ; # runs command and returns its exit status; its STDOUT gets output to our STDOUT   print `ls` ; #The same, but with back quotes   exec "ls" ; # replace current process with another \ No newline at end of file diff --git a/rosetta/file33.php b/rosetta/file33.php new file mode 100644 index 0000000..de29454 --- /dev/null +++ b/rosetta/file33.php @@ -0,0 +1 @@ + max end end [ max, slice ] end \ No newline at end of file diff --git a/rosetta/file33.scala b/rosetta/file33.scala new file mode 100644 index 0000000..f21e427 --- /dev/null +++ b/rosetta/file33.scala @@ -0,0 +1 @@ +import java. awt . Color import scala. swing . _   class ColorBars extends Component { override def paintComponent ( g : Graphics2D ) = { val colors = List ( Color. BLACK , Color. RED , Color. GREEN , Color. BLUE , Color. MAGENTA , Color. CYAN , Color. YELLOW , Color. WHITE ) val colCount = colors. size val deltaX = size. width . toDouble /colCount for ( x < - 0 until colCount ) { val startX = ( deltaX * x ) . toInt val endX = ( deltaX * ( x+ 1 ) ) . toInt g. setColor ( colors ( x ) ) g. fillRect ( startX, 0 , endX-startX, size. height ) } } } \ No newline at end of file diff --git a/rosetta/file33.ss b/rosetta/file33.ss new file mode 100644 index 0000000..550367e --- /dev/null +++ b/rosetta/file33.ss @@ -0,0 +1 @@ +( define ( make - list length object ) ( if ( = length 0 ) ( list ) ( cons object ( make - list ( - length 1 ) object ) ) ) )   ( define ( list - fill ! list object ) ( if ( not ( null? list ) ) ( begin ( set - car ! list object ) ( list - fill ! ( cdr list ) object ) ) ) )   ( define ( list - set! list element object ) ( if ( = element 1 ) ( set - car ! list object ) ( list - set! ( cdr list ) ( - element 1 ) object ) ) )   ( define ( list - get list element ) ( if ( = element 1 ) ( car list ) ( list - get ( cdr list ) ( - element 1 ) ) ) ) \ No newline at end of file diff --git a/rosetta/file33.tcl b/rosetta/file33.tcl new file mode 100644 index 0000000..bb2bc4c --- /dev/null +++ b/rosetta/file33.tcl @@ -0,0 +1 @@ +proc distcheck { random times { delta 1 } } { for { set i 0 } { $i < $times } { incr i } { incr vals ( [ uplevel 1 $random ] ) } set target [ expr { $times / [ array size vals ] } ] foreach { k v } [ array get vals ] { if { abs ( $v - $target ) > $times * $delta / 100.0 } { error "distribution potentially skewed for $k: expected around $target, got $v" } } foreach k [ lsort -integer [ array names vals ] ] { lappend result $k $vals ( $k ) } return $result } \ No newline at end of file diff --git a/rosetta/file34.clojure b/rosetta/file34.clojure new file mode 100644 index 0000000..97cb87d --- /dev/null +++ b/rosetta/file34.clojure @@ -0,0 +1 @@ +    ( defn draw - line "Draw a line from x1,y1 to x2,y2 using Bresenham's, to a java BufferedImage in the colour of pixel." [ buffer x1 y1 x2 y2 pixel ] ( let [ dist - x ( Math / abs ( - x1 x2 ) ) dist - y ( Math / abs ( - y1 y2 ) ) steep ( > dist - y dist - x ) ] ( let [ [ x1 y1 x2 y2 ] ( if steep [ y1 x1 y2 x2 ] [ x1 y1 x2 y2 ] ) ] ( let [ [ x1 y1 x2 y2 ] ( if ( > x1 x2 ) [ x2 y2 x1 y1 ] [ x1 y1 x2 y2 ] ) ] ( let [ delta - x ( - x2 x1 ) delta - y ( Math / abs ( - y1 y2 ) ) y - step ( if ( < y1 y2 ) 1 - 1 ) ]   ( let [ plot ( if steep # ( . setRGB buffer ( int % 1 ) ( int % 2 ) pixel ) # ( . setRGB buffer ( int % 2 ) ( int % 1 ) pixel ) ) ]   ( loop [ x x1 y y1 error ( Math / floor ( / delta - x 2 ) ) ] ( plot x y ) ( if ( < x x2 ) ; Rather then rebind error, test that it is less than delta-y rather than zero ( if ( < error delta - y ) ( recur ( inc x ) ( + y y - step ) ( + error ( - delta - x delta - y ) ) ) ( recur ( inc x ) y ( - error delta - y ) ) ) ) ) ) ) ) ) ) )   \ No newline at end of file diff --git a/rosetta/file34.hs b/rosetta/file34.hs new file mode 100644 index 0000000..cdf469d --- /dev/null +++ b/rosetta/file34.hs @@ -0,0 +1 @@ +import Data . List   h , f , g :: [ Double ] h = [ - 8 ,- 9 ,- 3 ,- 1 ,- 6 , 7 ] f = [ - 3 ,- 6 ,- 1 , 8 ,- 6 , 3 ,- 1 ,- 9 ,- 9 , 3 ,- 2 , 5 , 2 ,- 2 ,- 7 ,- 1 ] g = [ 24 , 75 , 71 ,- 34 , 3 , 22 ,- 45 , 23 , 245 , 25 , 52 , 25 ,- 67 ,- 96 , 96 , 31 , 55 , 36 , 29 ,- 43 ,- 7 ]   scale x ys = map ( x * ) ys   deconv1d :: ( Fractional a ) => [ a ] -> [ a ] -> [ a ] deconv1d xs ys = takeWhile ( /= 0 ) $ deconv xs ys where [ ] `deconv` _ = [ ] ( 0 :xs ) `deconv` ( 0 :ys ) = xs `deconv` ys ( x:xs ) `deconv` ( y:ys ) = q : zipWith ( - ) xs ( scale q ys ++ repeat 0 ) `deconv` ( y:ys ) where q = x / y \ No newline at end of file diff --git a/rosetta/file34.java b/rosetta/file34.java new file mode 100644 index 0000000..88d3518 --- /dev/null +++ b/rosetta/file34.java @@ -0,0 +1 @@ +  import java.awt.Color ;   public class MidPointCircle { private BasicBitmapStorage image ;   public MidPointCircle ( final int imageWidth, final int imageHeight ) { this . image = new BasicBitmapStorage ( imageWidth, imageHeight ) ; }   private void drawCircle ( final int centerX, final int centerY, final int radius ) { int d = ( 5 - r * 4 ) / 4 ; int x = 0 ; int y = radius ; Color circleColor = Color . white ;   do { image. setPixel ( centerX + x, centerY + y, circleColor ) ; image. setPixel ( centerX + x, centerY - y, circleColor ) ; image. setPixel ( centerX - x, centerY + y, circleColor ) ; image. setPixel ( centerX - x, centerY - y, circleColor ) ; image. setPixel ( centerX + y, centerY + x, circleColor ) ; image. setPixel ( centerX + y, centerY - x, circleColor ) ; image. setPixel ( centerX - y, centerY + x, circleColor ) ; image. setPixel ( centerX - y, centerY - x, circleColor ) ; if ( d < 0 ) { d += 2 * x + 1 ; } else { d += 2 * ( x - y ) + 1 ; y --; } x ++; } while ( x <= y ) ;   } }   \ No newline at end of file diff --git a/rosetta/file34.js b/rosetta/file34.js new file mode 100644 index 0000000..b449ed1 --- /dev/null +++ b/rosetta/file34.js @@ -0,0 +1 @@ +function createRow ( i , point , heading ) { var tr = document. createElement ( 'tr' ) , td ;   td = document. createElement ( 'td' ) ; td. appendChild ( document. createTextNode ( i ) ) ; tr. appendChild ( td ) ;   td = document. createElement ( 'td' ) ; point = point. substr ( 0 , 1 ) . toUpperCase ( ) + point. substr ( 1 ) ; td. appendChild ( document. createTextNode ( point ) ) ; tr. appendChild ( td ) ;   td = document. createElement ( 'td' ) ; td. appendChild ( document. createTextNode ( heading ) ) ; tr. appendChild ( td ) ;   return tr ; }   function getPoint ( i ) { var j = i % 8 , i = Math . floor ( i / 8 ) % 4 , cardinal = [ 'north' , 'east' , 'south' , 'west' ] , pointDesc = [ '1' , '1 by 2' , '1-C' , 'C by 1' , 'C' , 'C by 2' , '2-C' , '2 by 1' ] , str1 , str2 , strC ;   str1 = cardinal [ i ] ; str2 = cardinal [ ( i + 1 ) % 4 ] ; strC = ( str1 === 'north' || str1 === 'south' ) ? str1 + str2 : str2 + str1 ; return pointDesc [ j ] . replace ( '1' , str1 ) . replace ( '2' , str2 ) . replace ( 'C' , strC ) ; }   var i , heading , table = document. createElement ( 'table' ) , tbody = document. createElement ( 'tbody' ) , tr ; for ( i = 0 ; i <= 32 ; i += 1 ) { heading = i * 11.25 + [ 0 , 5.62 , - 5.62 ] [ i % 3 ] ; tr = createRow ( i % 32 + 1 , getPoint ( i ) , heading + '°' ) ; tbody. appendChild ( tr ) ; } table. appendChild ( tbody ) ; document. body . appendChild ( table ) ;   \ No newline at end of file diff --git a/rosetta/file34.ocaml b/rosetta/file34.ocaml new file mode 100644 index 0000000..61893fc --- /dev/null +++ b/rosetta/file34.ocaml @@ -0,0 +1 @@ +open Graphics   let ( ) = open_graph "" ; let width = size_x ( ) and height = size_y ( ) in let colors = [ | black ; red ; green ; blue ; magenta ; cyan ; yellow ; white | ] in let num_colors = Array . length colors in let h = height / 4 in for i = 1 to 4 do let j = 4 - i in for x = 0 to pred width do set_color colors . ( ( x / i ) mod num_colors ) ; moveto x ( j * h ) ; lineto x ( j * h + h ) ; done done ; ignore ( read_key ( ) ) \ No newline at end of file diff --git a/rosetta/file34.perl b/rosetta/file34.perl new file mode 100644 index 0000000..990393e --- /dev/null +++ b/rosetta/file34.perl @@ -0,0 +1 @@ +#!/usr/bin/perl use warnings ; use strict ; use feature qw ( say switch ) ;   my @programme = <> or die "No input. Specify a program file or pipe it to the standard input. \n " ;   for ( @programme ) { for my $char ( split // ) { given ( $char ) { when ( 'H' ) { hello ( ) } when ( 'Q' ) { quinne ( @programme ) } when ( '9' ) { bottles ( ) } default { die "Unknown instruction $char. \n " } # Comment this line to ignore other instructions. } } }   sub hello { print 'Hello World' ; }   sub quinne { print @programme ; }   sub bottles { for my $n ( reverse 0 .. 99 ) { my $before = bottle_count ( $n ) ; my $after = bottle_count ( $n - 1 ) ; my $action = bottle_action ( $n ) ; say " \u $before of beer on the wall, $before of beer." ; say "$action, $after of beer on the wall." ; say q ( ) if $n ; } }   sub bottle_count { my $n = shift ; given ( $n ) { when ( - 1 ) { return '99 bottles' } when ( 0 ) { return 'no more bottles' } when ( 1 ) { return '1 bottle' } default { return "$n bottles" } } }   sub bottle_action { my $n = shift ; return 'Take one down and pass it around' if $n > 0 ; return 'Go to the store and buy some more' ; } \ No newline at end of file diff --git a/rosetta/file34.php b/rosetta/file34.php new file mode 100644 index 0000000..de29454 --- /dev/null +++ b/rosetta/file34.php @@ -0,0 +1 @@ + = 10  ? "disabled"  : nil @decr . state = value. to_i < = 0  ? "disabled"  : nil end   update_controls 0 end \ No newline at end of file diff --git a/rosetta/file34.scala b/rosetta/file34.scala new file mode 100644 index 0000000..f21e427 --- /dev/null +++ b/rosetta/file34.scala @@ -0,0 +1 @@ +import java. awt . Color import scala. swing . _   class ColorBars extends Component { override def paintComponent ( g : Graphics2D ) = { val colors = List ( Color. BLACK , Color. RED , Color. GREEN , Color. BLUE , Color. MAGENTA , Color. CYAN , Color. YELLOW , Color. WHITE ) val colCount = colors. size val deltaX = size. width . toDouble /colCount for ( x < - 0 until colCount ) { val startX = ( deltaX * x ) . toInt val endX = ( deltaX * ( x+ 1 ) ) . toInt g. setColor ( colors ( x ) ) g. fillRect ( startX, 0 , endX-startX, size. height ) } } } \ No newline at end of file diff --git a/rosetta/file34.ss b/rosetta/file34.ss new file mode 100644 index 0000000..550367e --- /dev/null +++ b/rosetta/file34.ss @@ -0,0 +1 @@ +( define ( make - list length object ) ( if ( = length 0 ) ( list ) ( cons object ( make - list ( - length 1 ) object ) ) ) )   ( define ( list - fill ! list object ) ( if ( not ( null? list ) ) ( begin ( set - car ! list object ) ( list - fill ! ( cdr list ) object ) ) ) )   ( define ( list - set! list element object ) ( if ( = element 1 ) ( set - car ! list object ) ( list - set! ( cdr list ) ( - element 1 ) object ) ) )   ( define ( list - get list element ) ( if ( = element 1 ) ( car list ) ( list - get ( cdr list ) ( - element 1 ) ) ) ) \ No newline at end of file diff --git a/rosetta/file34.tcl b/rosetta/file34.tcl new file mode 100644 index 0000000..862fd97 --- /dev/null +++ b/rosetta/file34.tcl @@ -0,0 +1 @@ +package require Tk   # How to open a window proc openWin { } { global win if { [ info exists win ] && [ winfo exists $win ] } { # Already existing; just reset wm deiconify $win wm state $win normal return } catch { destroy $win } ; # Squelch the old one set win [ toplevel .t ] pack [ label $win .label -text "This is the window being manipulated" ] \ -fill both -expand 1 } # How to close a window proc closeWin { } { global win if { [ info exists win ] && [ winfo exists $win ] } { destroy $win } } # How to minimize a window proc minimizeWin { } { global win if { [ info exists win ] && [ winfo exists $win ] } { wm state $win iconic } } # How to maximize a window proc maximizeWin { } { global win if { [ info exists win ] && [ winfo exists $win ] } { wm state $win zoomed catch { wm attribute $win -zoomed 1 } ; # Hack for X11 } } # How to move a window proc moveWin { } { global win if { [ info exists win ] && [ winfo exists $win ] } { scan [ wm geometry $win ] "%dx%d+%d+%d" width height x y wm geometry $win + [ incr x 10 ] + [ incr y 10 ] } } # How to resize a window proc resizeWin { } { global win if { [ info exists win ] && [ winfo exists $win ] } { scan [ wm geometry $win ] "%dx%d+%d+%d" width height x y wm geometry $win [ incr width 10 ] x [ incr height 10 ] } }   grid [ label .l -text "Window handle:" ] [ label .l2 -textvariable win ] grid [ button .b1 -text "Open/Reset" -command openWin ] - grid [ button .b2 -text "Close" -command closeWin ] - grid [ button .b3 -text "Minimize" -command minimizeWin ] - grid [ button .b4 -text "Maximize" -command maximizeWin ] - grid [ button .b5 -text "Move" -command moveWin ] - grid [ button .b6 -text "Resize" -command resizeWin ] - \ No newline at end of file diff --git a/rosetta/file35.clojure b/rosetta/file35.clojure new file mode 100644 index 0000000..97cb87d --- /dev/null +++ b/rosetta/file35.clojure @@ -0,0 +1 @@ +    ( defn draw - line "Draw a line from x1,y1 to x2,y2 using Bresenham's, to a java BufferedImage in the colour of pixel." [ buffer x1 y1 x2 y2 pixel ] ( let [ dist - x ( Math / abs ( - x1 x2 ) ) dist - y ( Math / abs ( - y1 y2 ) ) steep ( > dist - y dist - x ) ] ( let [ [ x1 y1 x2 y2 ] ( if steep [ y1 x1 y2 x2 ] [ x1 y1 x2 y2 ] ) ] ( let [ [ x1 y1 x2 y2 ] ( if ( > x1 x2 ) [ x2 y2 x1 y1 ] [ x1 y1 x2 y2 ] ) ] ( let [ delta - x ( - x2 x1 ) delta - y ( Math / abs ( - y1 y2 ) ) y - step ( if ( < y1 y2 ) 1 - 1 ) ]   ( let [ plot ( if steep # ( . setRGB buffer ( int % 1 ) ( int % 2 ) pixel ) # ( . setRGB buffer ( int % 2 ) ( int % 1 ) pixel ) ) ]   ( loop [ x x1 y y1 error ( Math / floor ( / delta - x 2 ) ) ] ( plot x y ) ( if ( < x x2 ) ; Rather then rebind error, test that it is less than delta-y rather than zero ( if ( < error delta - y ) ( recur ( inc x ) ( + y y - step ) ( + error ( - delta - x delta - y ) ) ) ( recur ( inc x ) y ( - error delta - y ) ) ) ) ) ) ) ) ) ) )   \ No newline at end of file diff --git a/rosetta/file35.hs b/rosetta/file35.hs new file mode 100644 index 0000000..6b720c9 --- /dev/null +++ b/rosetta/file35.hs @@ -0,0 +1 @@ +{-# OPTIONS -fglasgow-exts #-}   data Check a b = Check { unCheck :: b } deriving ( Eq , Ord )   class Checked a b where check :: b -> Check a b   lift f x = f ( unCheck x ) liftc f x = check $ f ( unCheck x )   lift2 f x y = f ( unCheck x ) ( unCheck y ) lift2c f x y = check $ f ( unCheck x ) ( unCheck y ) lift2p f x y = ( check u , check v ) where ( u , v ) = f ( unCheck x ) ( unCheck y )   instance Show b => Show ( Check a b ) where show ( Check x ) = show x showsPrec p ( Check x ) = showsPrec p x   instance ( Enum b , Checked a b ) => Enum ( Check a b ) where succ = liftc succ pred = liftc pred toEnum = check . toEnum fromEnum = lift fromEnum   instance ( Num b , Checked a b ) => Num ( Check a b ) where ( + ) = lift2c ( + ) ( - ) = lift2c ( - ) ( * ) = lift2c ( * ) negate = liftc negate abs = liftc abs signum = liftc signum fromInteger = check . fromInteger   instance ( Real b , Checked a b ) => Real ( Check a b ) where toRational = lift toRational   instance ( Integral b , Checked a b ) => Integral ( Check a b ) where quot = lift2c quot rem = lift2c rem div = lift2c div mod = lift2c mod quotRem = lift2p quotRem divMod = lift2p divMod toInteger = lift toInteger \ No newline at end of file diff --git a/rosetta/file35.java b/rosetta/file35.java new file mode 100644 index 0000000..88d3518 --- /dev/null +++ b/rosetta/file35.java @@ -0,0 +1 @@ +  import java.awt.Color ;   public class MidPointCircle { private BasicBitmapStorage image ;   public MidPointCircle ( final int imageWidth, final int imageHeight ) { this . image = new BasicBitmapStorage ( imageWidth, imageHeight ) ; }   private void drawCircle ( final int centerX, final int centerY, final int radius ) { int d = ( 5 - r * 4 ) / 4 ; int x = 0 ; int y = radius ; Color circleColor = Color . white ;   do { image. setPixel ( centerX + x, centerY + y, circleColor ) ; image. setPixel ( centerX + x, centerY - y, circleColor ) ; image. setPixel ( centerX - x, centerY + y, circleColor ) ; image. setPixel ( centerX - x, centerY - y, circleColor ) ; image. setPixel ( centerX + y, centerY + x, circleColor ) ; image. setPixel ( centerX + y, centerY - x, circleColor ) ; image. setPixel ( centerX - y, centerY + x, circleColor ) ; image. setPixel ( centerX - y, centerY - x, circleColor ) ; if ( d < 0 ) { d += 2 * x + 1 ; } else { d += 2 * ( x - y ) + 1 ; y --; } x ++; } while ( x <= y ) ;   } }   \ No newline at end of file diff --git a/rosetta/file35.js b/rosetta/file35.js new file mode 100644 index 0000000..8737825 --- /dev/null +++ b/rosetta/file35.js @@ -0,0 +1 @@ +# !/ usr / bin / env js   function main ( ) { var len = 4 ; playBullsAndCows ( len ) ; }   function playBullsAndCows ( len ) { var num = pickNum ( len ) ; // print('The secret number is:\n ' + num.join('\n ')); showInstructions ( len ) ; var nGuesses = 0 ; while ( true ) { nGuesses ++; var guess = getGuess ( nGuesses , len ) ; var census = countBovine ( num , guess ) ; showScore ( census. bulls , census. cows ) ; if ( census. bulls == len ) { showFinalResult ( nGuesses ) ; return ; } } }   function showScore ( nBulls , nCows ) { print ( ' Bulls: ' + nBulls + ', cows: ' + nCows ) ; }   function showFinalResult ( guesses ) { print ( 'You win!!! Guesses needed: ' + guesses ) ; }   function countBovine ( num , guess ) { var count = { bulls : 0 , cows : 0 } ; var g = guess. join ( '' ) ; for ( var i = 0 ; i < num. length ; i ++ ) { var digPresent = g. search ( num [ i ] ) != - 1 ; if ( num [ i ] == guess [ i ] ) count. bulls ++; else if ( digPresent ) count. cows ++; } return count ; }   function getGuess ( nGuesses , len ) { while ( true ) { putstr ( 'Your guess #' + nGuesses + ': ' ) ; var guess = readline ( ) ; guess = String ( parseInt ( guess ) ) . split ( '' ) ; if ( guess. length != len ) { print ( ' You must enter a ' + len + ' digit number.' ) ; continue ; } if ( hasDups ( guess ) ) { print ( ' No digits can be duplicated.' ) ; continue ; } return guess ; } }   function hasDups ( ary ) { var t = ary. concat ( ) . sort ( ) ; for ( var i = 1 ; i < t. length ; i ++ ) { if ( t [ i ] == t [ i - 1 ] ) return true ; } return false ; }   function showInstructions ( len ) { print ( ) ; print ( 'Bulls and Cows Game' ) ; print ( '-------------------' ) ; print ( ' You must guess the ' + len + ' digit number I am thinking of.' ) ; print ( ' The number is composed of the digits 1-9.' ) ; print ( ' No digit appears more than once.' ) ; print ( ' After each of your guesses, I will tell you:' ) ; print ( ' The number of bulls (digits in right place)' ) ; print ( ' The number of cows (correct digits, but in the wrong place)' ) ; print ( ) ; }   function pickNum ( len ) { var nums = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] ; nums. sort ( function ( ) { return Math . random ( ) - 0.5 } ) ; return nums. slice ( 0 , len ) ; }   main ( ) ;   \ No newline at end of file diff --git a/rosetta/file35.ocaml b/rosetta/file35.ocaml new file mode 100644 index 0000000..ffb23d1 --- /dev/null +++ b/rosetta/file35.ocaml @@ -0,0 +1 @@ +let rec comb m lst = match m, lst with 0 , _ -> [ [ ] ] | _, [ ] -> [ ] | m, x :: xs -> List . map ( fun y -> x :: y ) ( comb ( pred m ) xs ) @ comb m xs ;; comb 3 [ 0 ; 1 ; 2 ; 3 ; 4 ] ;; \ No newline at end of file diff --git a/rosetta/file35.perl b/rosetta/file35.perl new file mode 100644 index 0000000..c3d10bf --- /dev/null +++ b/rosetta/file35.perl @@ -0,0 +1 @@ +sub multiply { return $_ [ 0 ] * $_ [ 1 ] } \ No newline at end of file diff --git a/rosetta/file35.php b/rosetta/file35.php new file mode 100644 index 0000000..009b20f --- /dev/null +++ b/rosetta/file35.php @@ -0,0 +1 @@ +  define ( 'src_name' , 'input.jpg' ) ; // source image define ( 'dest_name' , 'output.jpg' ) ; // destination image   $img = imagecreatefromjpeg ( src_name ) ; // read image   if ( empty ( $img ) ) { echo 'Image could not be loaded!' ; exit ; }   $black = imagecolorallocate ( $img , 0 , 0 , 0 ) ; $white = imagecolorallocate ( $img , 255 , 255 , 255 ) ; $width = imagesx ( $img ) ; $height = imagesy ( $img ) ;   $array_lum = array ( ) ; // for storage of luminosity of each pixel $sum_lum = 0 ; // total sum of luminosity $average_lum = 0 ; // average luminosity of whole image   for ( $x = 0 ; $x < $width ; $x ++ ) { for ( $y = 0 ; $y < $height ; $y ++ ) { // read pixel value $color = imagecolorat ( $img , $x , $y ) ; $r = ( $color >> 16 ) & 0xFF ; $g = ( $color >> 8 ) & 0xFF ; $b = $color & 0xFF ; // save pixel luminosity in temporary array $array_lum [ $x ] [ $y ] = ( $r + $g + $b ) ; // add pixel luminosity to sum $sum_lum += $array_lum [ $x ] [ $y ] ; } }   // calculate average luminosity $average_lum = $sum_lum / ( $width * $height ) ;   for ( $x = 0 ; $x < $width ; $x ++ ) { for ( $y = 0 ; $y < $height ; $y ++ ) { // pixel is brighter than average -> set white // else -> set black if ( $array_lum [ $x ] [ $y ] > $average_lum ) { imagesetpixel ( $img , $x , $y , $white ) ; } else { imagesetpixel ( $img , $x , $y , $black ) ; } } } // save black and white image to dest_name imagejpeg ( $img , dest_name ) ;   if ( ! file_exists ( dest_name ) ) { echo 'Image not saved! Check permission!' ; }   \ No newline at end of file diff --git a/rosetta/file35.py b/rosetta/file35.py new file mode 100644 index 0000000..9f947c8 --- /dev/null +++ b/rosetta/file35.py @@ -0,0 +1 @@ +# NAME, WEIGHT, VALUE (for this weight) items = [ ( "beef" , 3.8 , 36.0 ) , ( "pork" , 5.4 , 43.0 ) , ( "ham" , 3.6 , 90.0 ) , ( "greaves" , 2.4 , 45.0 ) , ( "flitch" , 4.0 , 30.0 ) , ( "brawn" , 2.5 , 56.0 ) , ( "welt" , 3.7 , 67.0 ) , ( "salami" , 3.0 , 95.0 ) , ( "sausage" , 5.9 , 98.0 ) ]   MAXWT = 15.0   sorted_items = sorted ( ( ( value/amount , amount , name ) for name , amount , value in items ) , reverse = True ) wt = val = 0 bagged = [ ] for unit_value , amount , name in sorted_items: portion = min ( MAXWT - wt , amount ) wt + = portion addval = portion * unit_value val + = addval bagged + = [ ( name , portion , addval ) ] if wt >= MAXWT: break   print ( " ITEM PORTION VALUE" ) print ( " \n " . join ( "%10s %6.2f %6.2f"  % item for item in bagged ) ) print ( " \n TOTAL WEIGHT: %5.2f \n TOTAL VALUE: %5.2f"  % ( wt , val ) ) \ No newline at end of file diff --git a/rosetta/file35.rb b/rosetta/file35.rb new file mode 100644 index 0000000..cbb5695 --- /dev/null +++ b/rosetta/file35.rb @@ -0,0 +1 @@ +open ( "| lpr" , "w" ) { | f | f. puts "Hello World!" } \ No newline at end of file diff --git a/rosetta/file35.scala b/rosetta/file35.scala new file mode 100644 index 0000000..34f920d --- /dev/null +++ b/rosetta/file35.scala @@ -0,0 +1 @@ +implicit def toComb ( m : Int ) = new AnyRef { def comb ( n : Int ) = recurse ( m, List. range ( 0 , n ) ) private def recurse ( m : Int, l : List [ Int ] ) : List [ List [ Int ] ] = ( m, l ) match { case ( 0 , _ ) => List ( Nil ) case ( _ , Nil ) => Nil case _ => ( recurse ( m - 1 , l. tail ) map ( l. head :: _ ) ) ::: recurse ( m, l. tail ) } } \ No newline at end of file diff --git a/rosetta/file35.ss b/rosetta/file35.ss new file mode 100644 index 0000000..550367e --- /dev/null +++ b/rosetta/file35.ss @@ -0,0 +1 @@ +( define ( make - list length object ) ( if ( = length 0 ) ( list ) ( cons object ( make - list ( - length 1 ) object ) ) ) )   ( define ( list - fill ! list object ) ( if ( not ( null? list ) ) ( begin ( set - car ! list object ) ( list - fill ! ( cdr list ) object ) ) ) )   ( define ( list - set! list element object ) ( if ( = element 1 ) ( set - car ! list object ) ( list - set! ( cdr list ) ( - element 1 ) object ) ) )   ( define ( list - get list element ) ( if ( = element 1 ) ( car list ) ( list - get ( cdr list ) ( - element 1 ) ) ) ) \ No newline at end of file diff --git a/rosetta/file35.tcl b/rosetta/file35.tcl new file mode 100644 index 0000000..e0c5ac0 --- /dev/null +++ b/rosetta/file35.tcl @@ -0,0 +1 @@ +# assume $xml holds the XML data package require tdom set doc [ dom parse $xml ] set root [ $doc documentElement ]   set allNames [ $root selectNodes //name ] puts [ llength $allNames ] ; # ==> 4   set firstItem [ lindex [ $root selectNodes //item ] 0 ] puts [ $firstItem @upc ] ; # ==> 123456789   foreach node [ $root selectNodes //price ] { puts [ $node text ] } \ No newline at end of file diff --git a/rosetta/file36.clojure b/rosetta/file36.clojure new file mode 100644 index 0000000..97cb87d --- /dev/null +++ b/rosetta/file36.clojure @@ -0,0 +1 @@ +    ( defn draw - line "Draw a line from x1,y1 to x2,y2 using Bresenham's, to a java BufferedImage in the colour of pixel." [ buffer x1 y1 x2 y2 pixel ] ( let [ dist - x ( Math / abs ( - x1 x2 ) ) dist - y ( Math / abs ( - y1 y2 ) ) steep ( > dist - y dist - x ) ] ( let [ [ x1 y1 x2 y2 ] ( if steep [ y1 x1 y2 x2 ] [ x1 y1 x2 y2 ] ) ] ( let [ [ x1 y1 x2 y2 ] ( if ( > x1 x2 ) [ x2 y2 x1 y1 ] [ x1 y1 x2 y2 ] ) ] ( let [ delta - x ( - x2 x1 ) delta - y ( Math / abs ( - y1 y2 ) ) y - step ( if ( < y1 y2 ) 1 - 1 ) ]   ( let [ plot ( if steep # ( . setRGB buffer ( int % 1 ) ( int % 2 ) pixel ) # ( . setRGB buffer ( int % 2 ) ( int % 1 ) pixel ) ) ]   ( loop [ x x1 y y1 error ( Math / floor ( / delta - x 2 ) ) ] ( plot x y ) ( if ( < x x2 ) ; Rather then rebind error, test that it is less than delta-y rather than zero ( if ( < error delta - y ) ( recur ( inc x ) ( + y y - step ) ( + error ( - delta - x delta - y ) ) ) ( recur ( inc x ) y ( - error delta - y ) ) ) ) ) ) ) ) ) ) )   \ No newline at end of file diff --git a/rosetta/file36.hs b/rosetta/file36.hs new file mode 100644 index 0000000..3093cfe --- /dev/null +++ b/rosetta/file36.hs @@ -0,0 +1 @@ +import Data . List import Data . Time import Data . Time . Calendar . MonthDay   seasons = words "Chaos Discord Confusion Bureaucracy The_Aftermath"   discordianDate ( y , m , d ) = do let doy = monthAndDayToDayOfYear ( isLeapYear y ) m d ( season , dday ) = divMod doy 73 dos = dday - fromEnum ( isLeapYear y && m > 2 ) dDate | isLeapYear y && m == 2 && d == 29 = "St. Tib's Day, " ++ show ( y + 1166 ) ++ " YOLD" | otherwise = seasons !! season ++ " " ++ show dos ++ ", " ++ show ( y + 1166 ) ++ " YOLD" putStrLn dDate \ No newline at end of file diff --git a/rosetta/file36.java b/rosetta/file36.java new file mode 100644 index 0000000..88d3518 --- /dev/null +++ b/rosetta/file36.java @@ -0,0 +1 @@ +  import java.awt.Color ;   public class MidPointCircle { private BasicBitmapStorage image ;   public MidPointCircle ( final int imageWidth, final int imageHeight ) { this . image = new BasicBitmapStorage ( imageWidth, imageHeight ) ; }   private void drawCircle ( final int centerX, final int centerY, final int radius ) { int d = ( 5 - r * 4 ) / 4 ; int x = 0 ; int y = radius ; Color circleColor = Color . white ;   do { image. setPixel ( centerX + x, centerY + y, circleColor ) ; image. setPixel ( centerX + x, centerY - y, circleColor ) ; image. setPixel ( centerX - x, centerY + y, circleColor ) ; image. setPixel ( centerX - x, centerY - y, circleColor ) ; image. setPixel ( centerX + y, centerY + x, circleColor ) ; image. setPixel ( centerX + y, centerY - x, circleColor ) ; image. setPixel ( centerX - y, centerY + x, circleColor ) ; image. setPixel ( centerX - y, centerY - x, circleColor ) ; if ( d < 0 ) { d += 2 * x + 1 ; } else { d += 2 * ( x - y ) + 1 ; y --; } x ++; } while ( x <= y ) ;   } }   \ No newline at end of file diff --git a/rosetta/file36.js b/rosetta/file36.js new file mode 100644 index 0000000..18aa620 --- /dev/null +++ b/rosetta/file36.js @@ -0,0 +1 @@ +< html >< head >< title > Caesar < body >< pre id = 'x' > < script type = "application/javascript" > function disp ( x ) { var e = document. createTextNode ( x + ' \n ' ) ; document. getElementById ( 'x' ) . appendChild ( e ) ; }   function trans ( msg , rot ) { return msg. replace ( /([a-z])/ig , function ( $1 ) { var c = $1. charCodeAt ( 0 ) ; return String . fromCharCode ( c >= 97 ? ( c + rot + 26 - 97 ) % 26 + 97 : ( c + rot + 26 - 65 ) % 26 + 65 ) ; } ) ; }   var msg = "The quick brown f0x Jumped over the lazy Dog 123" ; var enc = trans ( msg , 3 ) ; var dec = trans ( enc , - 3 ) ;   disp ( "Original:" + msg + " \n Encoded: " + enc + " \n Decoded: " + dec ) ; \ No newline at end of file diff --git a/rosetta/file36.ocaml b/rosetta/file36.ocaml new file mode 100644 index 0000000..872a145 --- /dev/null +++ b/rosetta/file36.ocaml @@ -0,0 +1 @@ +let rec combs_with_rep k xxs = match k, xxs with | 0 , _ -> [ [ ] ] | _, [ ] -> [ ] | k, x :: xs -> List . map ( fun ys -> x :: ys ) ( combs_with_rep ( k - 1 ) xxs ) @ combs_with_rep k xs \ No newline at end of file diff --git a/rosetta/file36.perl b/rosetta/file36.perl new file mode 100644 index 0000000..1085f77 --- /dev/null +++ b/rosetta/file36.perl @@ -0,0 +1 @@ +sub noargs ( ) ; # Declare a function with no arguments sub twoargs ( $$ ) ; # Declare a function with two scalar arguments. The two sigils act as argument type placeholders sub noargs : prototype ( ) ; # Using the :attribute syntax instead sub twoargs : prototype ( $$ ) ; \ No newline at end of file diff --git a/rosetta/file36.php b/rosetta/file36.php new file mode 100644 index 0000000..009b20f --- /dev/null +++ b/rosetta/file36.php @@ -0,0 +1 @@ +  define ( 'src_name' , 'input.jpg' ) ; // source image define ( 'dest_name' , 'output.jpg' ) ; // destination image   $img = imagecreatefromjpeg ( src_name ) ; // read image   if ( empty ( $img ) ) { echo 'Image could not be loaded!' ; exit ; }   $black = imagecolorallocate ( $img , 0 , 0 , 0 ) ; $white = imagecolorallocate ( $img , 255 , 255 , 255 ) ; $width = imagesx ( $img ) ; $height = imagesy ( $img ) ;   $array_lum = array ( ) ; // for storage of luminosity of each pixel $sum_lum = 0 ; // total sum of luminosity $average_lum = 0 ; // average luminosity of whole image   for ( $x = 0 ; $x < $width ; $x ++ ) { for ( $y = 0 ; $y < $height ; $y ++ ) { // read pixel value $color = imagecolorat ( $img , $x , $y ) ; $r = ( $color >> 16 ) & 0xFF ; $g = ( $color >> 8 ) & 0xFF ; $b = $color & 0xFF ; // save pixel luminosity in temporary array $array_lum [ $x ] [ $y ] = ( $r + $g + $b ) ; // add pixel luminosity to sum $sum_lum += $array_lum [ $x ] [ $y ] ; } }   // calculate average luminosity $average_lum = $sum_lum / ( $width * $height ) ;   for ( $x = 0 ; $x < $width ; $x ++ ) { for ( $y = 0 ; $y < $height ; $y ++ ) { // pixel is brighter than average -> set white // else -> set black if ( $array_lum [ $x ] [ $y ] > $average_lum ) { imagesetpixel ( $img , $x , $y , $white ) ; } else { imagesetpixel ( $img , $x , $y , $black ) ; } } } // save black and white image to dest_name imagejpeg ( $img , dest_name ) ;   if ( ! file_exists ( dest_name ) ) { echo 'Image not saved! Check permission!' ; }   \ No newline at end of file diff --git a/rosetta/file36.py b/rosetta/file36.py new file mode 100644 index 0000000..03d189a --- /dev/null +++ b/rosetta/file36.py @@ -0,0 +1 @@ +import time import threading   # Only 4 workers can run in the same time sem = threading . Semaphore ( 4 )   workers = [ ] running = 1     def worker ( ) : me = threading . currentThread ( ) while 1 : sem. acquire ( ) try : if not running: break print '%s acquired semaphore'  % me. getName ( ) time . sleep ( 2.0 ) finally : sem. release ( ) time . sleep ( 0.01 ) # Let others acquire   # Start 10 workers for i in range ( 10 ) : t = threading . Thread ( name = str ( i ) , target = worker ) workers. append ( t ) t. start ( )   # Main loop try : while 1 : time . sleep ( 0.1 ) except KeyboardInterrupt : running = 0 for t in workers: t. join ( ) \ No newline at end of file diff --git a/rosetta/file36.rb b/rosetta/file36.rb new file mode 100644 index 0000000..c3269d3 --- /dev/null +++ b/rosetta/file36.rb @@ -0,0 +1 @@ +  require 'net/https' require 'uri' require 'pp'   uri = URI . parse ( 'https://sourceforge.net' ) http = Net::HTTP . new ( uri. host ,uri. port ) http. use_ssl = true http. verify_mode = OpenSSL::SSL::VERIFY_NONE   http. start do content = http. get ( "/" ) p [ content. code , content. message ] pp content. to_hash puts content. body end   \ No newline at end of file diff --git a/rosetta/file36.scala b/rosetta/file36.scala new file mode 100644 index 0000000..6c4defa --- /dev/null +++ b/rosetta/file36.scala @@ -0,0 +1 @@ +// A single line comment   /* A multi-line comment */ \ No newline at end of file diff --git a/rosetta/file36.ss b/rosetta/file36.ss new file mode 100644 index 0000000..550367e --- /dev/null +++ b/rosetta/file36.ss @@ -0,0 +1 @@ +( define ( make - list length object ) ( if ( = length 0 ) ( list ) ( cons object ( make - list ( - length 1 ) object ) ) ) )   ( define ( list - fill ! list object ) ( if ( not ( null? list ) ) ( begin ( set - car ! list object ) ( list - fill ! ( cdr list ) object ) ) ) )   ( define ( list - set! list element object ) ( if ( = element 1 ) ( set - car ! list object ) ( list - set! ( cdr list ) ( - element 1 ) object ) ) )   ( define ( list - get list element ) ( if ( = element 1 ) ( car list ) ( list - get ( cdr list ) ( - element 1 ) ) ) ) \ No newline at end of file diff --git a/rosetta/file36.tcl b/rosetta/file36.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file36.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file37.clojure b/rosetta/file37.clojure new file mode 100644 index 0000000..97cb87d --- /dev/null +++ b/rosetta/file37.clojure @@ -0,0 +1 @@ +    ( defn draw - line "Draw a line from x1,y1 to x2,y2 using Bresenham's, to a java BufferedImage in the colour of pixel." [ buffer x1 y1 x2 y2 pixel ] ( let [ dist - x ( Math / abs ( - x1 x2 ) ) dist - y ( Math / abs ( - y1 y2 ) ) steep ( > dist - y dist - x ) ] ( let [ [ x1 y1 x2 y2 ] ( if steep [ y1 x1 y2 x2 ] [ x1 y1 x2 y2 ] ) ] ( let [ [ x1 y1 x2 y2 ] ( if ( > x1 x2 ) [ x2 y2 x1 y1 ] [ x1 y1 x2 y2 ] ) ] ( let [ delta - x ( - x2 x1 ) delta - y ( Math / abs ( - y1 y2 ) ) y - step ( if ( < y1 y2 ) 1 - 1 ) ]   ( let [ plot ( if steep # ( . setRGB buffer ( int % 1 ) ( int % 2 ) pixel ) # ( . setRGB buffer ( int % 2 ) ( int % 1 ) pixel ) ) ]   ( loop [ x x1 y y1 error ( Math / floor ( / delta - x 2 ) ) ] ( plot x y ) ( if ( < x x2 ) ; Rather then rebind error, test that it is less than delta-y rather than zero ( if ( < error delta - y ) ( recur ( inc x ) ( + y y - step ) ( + error ( - delta - x delta - y ) ) ) ( recur ( inc x ) y ( - error delta - y ) ) ) ) ) ) ) ) ) ) )   \ No newline at end of file diff --git a/rosetta/file37.hs b/rosetta/file37.hs new file mode 100644 index 0000000..5d584cc --- /dev/null +++ b/rosetta/file37.hs @@ -0,0 +1 @@ +import Control . Monad . Error import Control . Monad . Trans ( lift )   -- Our "user-defined exception" tpe data MyError = U0 | U1 | Other deriving ( Eq , Read , Show )   -- Required for any error type instance Error MyError where noMsg = Other strMsg _ = Other   -- Throwing and catching exceptions implies that we are working in a monad. In -- this case, we use ErrorT to support our user-defined exceptions, wrapping -- IO to be able to report the happenings. ('lift' converts ErrorT e IO a -- actions into IO a actions.)   foo = do lift ( putStrLn "foo" ) mapM_ ( \toThrow -> bar toThrow -- the protected call `catchError` \caught -> -- the catch operation -- ↓ what to do with it case caught of U0 -> lift ( putStrLn "foo caught U0" ) _ -> throwError caught ) [ U0 , U1 ] -- the two exceptions to throw     bar toThrow = do lift ( putStrLn " bar" ) baz toThrow   baz toThrow = do lift ( putStrLn " baz" ) throwError toThrow   -- We cannot use exceptions without at some outer level choosing what to do -- if an exception propagates all the way up. Here we just print the exception -- if there was one. main = do result <- runErrorT foo case result of Left e -> putStrLn ( "Caught error at top level: " ++ show e ) Right v -> putStrLn ( "Return value: " ++ show v ) \ No newline at end of file diff --git a/rosetta/file37.java b/rosetta/file37.java new file mode 100644 index 0000000..f12f646 --- /dev/null +++ b/rosetta/file37.java @@ -0,0 +1 @@ +public static void bitwise ( int a, int b ) { System . out . println ( "a AND b: " + ( a & b ) ) ; System . out . println ( "a OR b: " + ( a | b ) ) ; System . out . println ( "a XOR b: " + ( a ^ b ) ) ; System . out . println ( "NOT a: " + ~a ) ; System . out . println ( "a << b: " + ( a << b ) ) ; // left shift System . out . println ( "a >> b: " + ( a >> b ) ) ; // arithmetic right shift System . out . println ( "a >>> b: " + ( a >>> b ) ) ; // logical right shift System . out . println ( "a rol b: " + Integer . rotateLeft ( a, b ) ) ; //rotate left, Java 1.5+ System . out . println ( "a ror b: " + Integer . rotateRight ( a, b ) ) ; //rotate right, Java 1.5+ } \ No newline at end of file diff --git a/rosetta/file37.js b/rosetta/file37.js new file mode 100644 index 0000000..18aa620 --- /dev/null +++ b/rosetta/file37.js @@ -0,0 +1 @@ +< html >< head >< title > Caesar < body >< pre id = 'x' > < script type = "application/javascript" > function disp ( x ) { var e = document. createTextNode ( x + ' \n ' ) ; document. getElementById ( 'x' ) . appendChild ( e ) ; }   function trans ( msg , rot ) { return msg. replace ( /([a-z])/ig , function ( $1 ) { var c = $1. charCodeAt ( 0 ) ; return String . fromCharCode ( c >= 97 ? ( c + rot + 26 - 97 ) % 26 + 97 : ( c + rot + 26 - 65 ) % 26 + 65 ) ; } ) ; }   var msg = "The quick brown f0x Jumped over the lazy Dog 123" ; var enc = trans ( msg , 3 ) ; var dec = trans ( enc , - 3 ) ;   disp ( "Original:" + msg + " \n Encoded: " + enc + " \n Decoded: " + dec ) ; \ No newline at end of file diff --git a/rosetta/file37.ocaml b/rosetta/file37.ocaml new file mode 100644 index 0000000..864083f --- /dev/null +++ b/rosetta/file37.ocaml @@ -0,0 +1,2 @@ +(* This a comment + (* containing nested comment *) *)   (** This an OCamldoc documentation comment *) \ No newline at end of file diff --git a/rosetta/file37.perl b/rosetta/file37.perl new file mode 100644 index 0000000..f47c289 --- /dev/null +++ b/rosetta/file37.perl @@ -0,0 +1 @@ +use strict ; use warnings ; use constant pi => 4 * atan2 ( 1 , 1 ) ; use constant e => exp ( 1 ) ;   # Normally would be: use Math::MPFR # but this will use it if it's installed and ignore otherwise my $have_MPFR = eval { require Math :: MPFR ; Math :: MPFR -> import ( ) ; 1 ; } ;   sub Gamma { my $z = shift ; my $method = shift // 'lanczos' ; if ( $method eq 'lanczos' ) { use constant g => 9 ; $z < . 5 ? pi / sin(pi * $z) / Gamma ( 1 - $z , $method ) : sqrt ( 2 * pi ) * ( $z + g - . 5 ) ** ( $z - . 5 ) * exp ( - ( $z + g - . 5 ) ) * do { my @coeff = qw { 1.000000000000000174663 5716.400188274341379136 - 14815.30426768413909044 14291.49277657478554025 - 6348.160217641458813289 1301.608286058321874105 - 108.1767053514369634679 2.605696505611755827729 - 0 . 7423452510201416151527e - 2 0 . 5384136432509564062961e - 7 - 0 . 4023533141268236372067e - 8 } ; my ( $sum , $i ) = ( shift ( @coeff ) , 0 ) ; $sum += $_ / ( $z + $i ++ ) for @coeff ; $sum ; } } elsif ( $method eq 'taylor' ) { $z < . 5 ? Gamma ( $z + 1 , $method ) / $z : $z > 1.5 ? ( $z - 1 ) *Gamma ( $z - 1 , $method ) : do { my $s = 0 ; ( $s *= $z - 1 ) += $_ for qw { 0.00000000000000000002 - 0.00000000000000000023 0.00000000000000000141 0.00000000000000000119 - 0.00000000000000011813 0.00000000000000122678 - 0.00000000000000534812 - 0.00000000000002058326 0.00000000000051003703 - 0.00000000000369680562 0.00000000000778226344 0.00000000010434267117 - 0.00000000118127457049 0.00000000500200764447 0.00000000611609510448 - 0.00000020563384169776 0.00000113302723198170 - 0.00000125049348214267 - 0.00002013485478078824 0.00012805028238811619 - 0.00021524167411495097 - 0.00116516759185906511 0.00721894324666309954 - 0.00962197152787697356 - 0.04219773455554433675 0.16653861138229148950 - 0.04200263503409523553 - 0.65587807152025388108 0.57721566490153286061 1.00000000000000000000 } ; 1 / $s ; } } elsif ( $method eq 'stirling' ) { no warnings qw ( recursion ) ; $z < 100 ? Gamma ( $z + 1 , $method ) / $z : sqrt ( 2 *pi *$z ) * ( $z / e + 1 / ( 12 *e *$z ) ) * *$z / $z ; } elsif ( $method eq 'MPFR' ) { my $result = Math :: MPFR -> new ( ) ; Math :: MPFR :: Rmpfr_gamma ( $result , Math :: MPFR -> new ( $z ) , 0 ) ; $result ; } else { die "unknown method '$method'" } }   for my $method ( qw ( MPFR lanczos taylor stirling ) ) { next if $method eq 'MPFR' && ! $have_MPFR ; printf "%10s: " , $method ; print join ( ' ' , map { sprintf "%.12f" , Gamma ( $_ / 3 , $method ) } 1 .. 10 ) ; print " \n " ; } \ No newline at end of file diff --git a/rosetta/file37.php b/rosetta/file37.php new file mode 100644 index 0000000..009b20f --- /dev/null +++ b/rosetta/file37.php @@ -0,0 +1 @@ +  define ( 'src_name' , 'input.jpg' ) ; // source image define ( 'dest_name' , 'output.jpg' ) ; // destination image   $img = imagecreatefromjpeg ( src_name ) ; // read image   if ( empty ( $img ) ) { echo 'Image could not be loaded!' ; exit ; }   $black = imagecolorallocate ( $img , 0 , 0 , 0 ) ; $white = imagecolorallocate ( $img , 255 , 255 , 255 ) ; $width = imagesx ( $img ) ; $height = imagesy ( $img ) ;   $array_lum = array ( ) ; // for storage of luminosity of each pixel $sum_lum = 0 ; // total sum of luminosity $average_lum = 0 ; // average luminosity of whole image   for ( $x = 0 ; $x < $width ; $x ++ ) { for ( $y = 0 ; $y < $height ; $y ++ ) { // read pixel value $color = imagecolorat ( $img , $x , $y ) ; $r = ( $color >> 16 ) & 0xFF ; $g = ( $color >> 8 ) & 0xFF ; $b = $color & 0xFF ; // save pixel luminosity in temporary array $array_lum [ $x ] [ $y ] = ( $r + $g + $b ) ; // add pixel luminosity to sum $sum_lum += $array_lum [ $x ] [ $y ] ; } }   // calculate average luminosity $average_lum = $sum_lum / ( $width * $height ) ;   for ( $x = 0 ; $x < $width ; $x ++ ) { for ( $y = 0 ; $y < $height ; $y ++ ) { // pixel is brighter than average -> set white // else -> set black if ( $array_lum [ $x ] [ $y ] > $average_lum ) { imagesetpixel ( $img , $x , $y , $white ) ; } else { imagesetpixel ( $img , $x , $y , $black ) ; } } } // save black and white image to dest_name imagejpeg ( $img , dest_name ) ;   if ( ! file_exists ( dest_name ) ) { echo 'Image not saved! Check permission!' ; }   \ No newline at end of file diff --git a/rosetta/file37.py b/rosetta/file37.py new file mode 100644 index 0000000..c2b831a --- /dev/null +++ b/rosetta/file37.py @@ -0,0 +1 @@ +#-*- coding: utf8 -*-   from OpenGL. GL import * from OpenGL. GLUT import *   def paint ( ) : glClearColor ( 0.3 , 0.3 , 0.3 , 0.0 ) glClear ( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT )   glShadeModel ( GL_SMOOTH )   glLoadIdentity ( ) glTranslatef ( - 15.0 , - 15.0 , 0.0 )   glBegin ( GL_TRIANGLES ) glColor3f ( 1.0 , 0.0 , 0.0 ) glVertex2f ( 0.0 , 0.0 ) glColor3f ( 0.0 , 1.0 , 0.0 ) glVertex2f ( 30.0 , 0.0 ) glColor3f ( 0.0 , 0.0 , 1.0 ) glVertex2f ( 0.0 , 30.0 ) glEnd ( )   glFlush ( )   def reshape ( width , height ) : glViewport ( 0 , 0 , width , height ) glMatrixMode ( GL_PROJECTION ) glLoadIdentity ( ) glOrtho ( - 30.0 , 30.0 , - 30.0 , 30.0 , - 30.0 , 30.0 ) glMatrixMode ( GL_MODELVIEW )   if __name__ == '__main__' : glutInit ( 1 , 1 ) glutInitWindowSize ( 640 , 480 ) glutCreateWindow ( "Triangle" )   glutDisplayFunc ( paint ) glutReshapeFunc ( reshape )   glutMainLoop ( ) \ No newline at end of file diff --git a/rosetta/file37.rb b/rosetta/file37.rb new file mode 100644 index 0000000..c3269d3 --- /dev/null +++ b/rosetta/file37.rb @@ -0,0 +1 @@ +  require 'net/https' require 'uri' require 'pp'   uri = URI . parse ( 'https://sourceforge.net' ) http = Net::HTTP . new ( uri. host ,uri. port ) http. use_ssl = true http. verify_mode = OpenSSL::SSL::VERIFY_NONE   http. start do content = http. get ( "/" ) p [ content. code , content. message ] pp content. to_hash puts content. body end   \ No newline at end of file diff --git a/rosetta/file37.scala b/rosetta/file37.scala new file mode 100644 index 0000000..6c4defa --- /dev/null +++ b/rosetta/file37.scala @@ -0,0 +1 @@ +// A single line comment   /* A multi-line comment */ \ No newline at end of file diff --git a/rosetta/file37.ss b/rosetta/file37.ss new file mode 100644 index 0000000..550367e --- /dev/null +++ b/rosetta/file37.ss @@ -0,0 +1 @@ +( define ( make - list length object ) ( if ( = length 0 ) ( list ) ( cons object ( make - list ( - length 1 ) object ) ) ) )   ( define ( list - fill ! list object ) ( if ( not ( null? list ) ) ( begin ( set - car ! list object ) ( list - fill ! ( cdr list ) object ) ) ) )   ( define ( list - set! list element object ) ( if ( = element 1 ) ( set - car ! list object ) ( list - set! ( cdr list ) ( - element 1 ) object ) ) )   ( define ( list - get list element ) ( if ( = element 1 ) ( car list ) ( list - get ( cdr list ) ( - element 1 ) ) ) ) \ No newline at end of file diff --git a/rosetta/file37.tcl b/rosetta/file37.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file37.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file38.clojure b/rosetta/file38.clojure new file mode 100644 index 0000000..97cb87d --- /dev/null +++ b/rosetta/file38.clojure @@ -0,0 +1 @@ +    ( defn draw - line "Draw a line from x1,y1 to x2,y2 using Bresenham's, to a java BufferedImage in the colour of pixel." [ buffer x1 y1 x2 y2 pixel ] ( let [ dist - x ( Math / abs ( - x1 x2 ) ) dist - y ( Math / abs ( - y1 y2 ) ) steep ( > dist - y dist - x ) ] ( let [ [ x1 y1 x2 y2 ] ( if steep [ y1 x1 y2 x2 ] [ x1 y1 x2 y2 ] ) ] ( let [ [ x1 y1 x2 y2 ] ( if ( > x1 x2 ) [ x2 y2 x1 y1 ] [ x1 y1 x2 y2 ] ) ] ( let [ delta - x ( - x2 x1 ) delta - y ( Math / abs ( - y1 y2 ) ) y - step ( if ( < y1 y2 ) 1 - 1 ) ]   ( let [ plot ( if steep # ( . setRGB buffer ( int % 1 ) ( int % 2 ) pixel ) # ( . setRGB buffer ( int % 2 ) ( int % 1 ) pixel ) ) ]   ( loop [ x x1 y y1 error ( Math / floor ( / delta - x 2 ) ) ] ( plot x y ) ( if ( < x x2 ) ; Rather then rebind error, test that it is less than delta-y rather than zero ( if ( < error delta - y ) ( recur ( inc x ) ( + y y - step ) ( + error ( - delta - x delta - y ) ) ) ( recur ( inc x ) y ( - error delta - y ) ) ) ) ) ) ) ) ) ) )   \ No newline at end of file diff --git a/rosetta/file38.hs b/rosetta/file38.hs new file mode 100644 index 0000000..2b151dd --- /dev/null +++ b/rosetta/file38.hs @@ -0,0 +1 @@ +import System . Cmd   main = system "ls"   \ No newline at end of file diff --git a/rosetta/file38.java b/rosetta/file38.java new file mode 100644 index 0000000..a8c01d9 --- /dev/null +++ b/rosetta/file38.java @@ -0,0 +1 @@ +import java.awt.Graphics ; import java.awt.image.BufferedImage ; import java.util.* ; import javax.swing.JFrame ;   public class BrownianTree extends JFrame implements Runnable {   BufferedImage I ; private List < Particle > particles ; static Random rand = new Random ( ) ;   public BrownianTree ( ) { super ( "Brownian Tree" ) ; setBounds ( 100 , 100 , 400 , 300 ) ; setDefaultCloseOperation ( EXIT_ON_CLOSE ) ; I = new BufferedImage ( getWidth ( ) , getHeight ( ) , BufferedImage . TYPE_INT_RGB ) ; I. setRGB ( I. getWidth ( ) / 2 , I. getHeight ( ) / 2 , 0xff00 ) ; particles = new LinkedList < Particle > ( ) ; }   @Override public void paint ( Graphics g ) { g. drawImage ( I, 0 , 0 , this ) ; }   public void run ( ) { for ( int i = 0 ; i < 20000 ; i ++ ) { particles. add ( new Particle ( ) ) ; } while ( ! particles. isEmpty ( ) ) { for ( Iterator < Particle > it = particles. iterator ( ) ; it. hasNext ( ) ; ) { if ( it. next ( ) . move ( ) ) { it. remove ( ) ; } } repaint ( ) ; } }   public static void main ( String [ ] args ) { BrownianTree b = new BrownianTree ( ) ; b. setVisible ( true ) ; new Thread ( b ) . start ( ) ; }   private class Particle {   private int x, y ;   private Particle ( ) { x = rand. nextInt ( I. getWidth ( ) ) ; y = rand. nextInt ( I. getHeight ( ) ) ; }   /* returns true if either out of bounds or collided with tree */ private boolean move ( ) { int dx = rand. nextInt ( 3 ) - 1 ; int dy = rand. nextInt ( 3 ) - 1 ; if ( ( x + dx < 0 ) || ( y + dy < 0 ) || ( y + dy >= I. getHeight ( ) ) || ( x + dx >= I. getWidth ( ) ) ) { return true ; } x += dx ; y += dy ; if ( ( I. getRGB ( x, y ) & 0xff00 ) == 0xff00 ) { I. setRGB ( x - dx, y - dy, 0xff00 ) ; return true ; } return false ; } } } \ No newline at end of file diff --git a/rosetta/file38.js b/rosetta/file38.js new file mode 100644 index 0000000..18aa620 --- /dev/null +++ b/rosetta/file38.js @@ -0,0 +1 @@ +< html >< head >< title > Caesar < body >< pre id = 'x' > < script type = "application/javascript" > function disp ( x ) { var e = document. createTextNode ( x + ' \n ' ) ; document. getElementById ( 'x' ) . appendChild ( e ) ; }   function trans ( msg , rot ) { return msg. replace ( /([a-z])/ig , function ( $1 ) { var c = $1. charCodeAt ( 0 ) ; return String . fromCharCode ( c >= 97 ? ( c + rot + 26 - 97 ) % 26 + 97 : ( c + rot + 26 - 65 ) % 26 + 65 ) ; } ) ; }   var msg = "The quick brown f0x Jumped over the lazy Dog 123" ; var enc = trans ( msg , 3 ) ; var dec = trans ( enc , - 3 ) ;   disp ( "Original:" + msg + " \n Encoded: " + enc + " \n Decoded: " + dec ) ; \ No newline at end of file diff --git a/rosetta/file38.ocaml b/rosetta/file38.ocaml new file mode 100644 index 0000000..23488fb --- /dev/null +++ b/rosetta/file38.ocaml @@ -0,0 +1 @@ +let condition = true   if condition then 1 (* evaluate something *) else 2 (* evaluate something *) \ No newline at end of file diff --git a/rosetta/file38.perl b/rosetta/file38.perl new file mode 100644 index 0000000..e4e90c4 --- /dev/null +++ b/rosetta/file38.perl @@ -0,0 +1 @@ +( $y , $x ) = ( $x , $y ) ; \ No newline at end of file diff --git a/rosetta/file38.php b/rosetta/file38.php new file mode 100644 index 0000000..009b20f --- /dev/null +++ b/rosetta/file38.php @@ -0,0 +1 @@ +  define ( 'src_name' , 'input.jpg' ) ; // source image define ( 'dest_name' , 'output.jpg' ) ; // destination image   $img = imagecreatefromjpeg ( src_name ) ; // read image   if ( empty ( $img ) ) { echo 'Image could not be loaded!' ; exit ; }   $black = imagecolorallocate ( $img , 0 , 0 , 0 ) ; $white = imagecolorallocate ( $img , 255 , 255 , 255 ) ; $width = imagesx ( $img ) ; $height = imagesy ( $img ) ;   $array_lum = array ( ) ; // for storage of luminosity of each pixel $sum_lum = 0 ; // total sum of luminosity $average_lum = 0 ; // average luminosity of whole image   for ( $x = 0 ; $x < $width ; $x ++ ) { for ( $y = 0 ; $y < $height ; $y ++ ) { // read pixel value $color = imagecolorat ( $img , $x , $y ) ; $r = ( $color >> 16 ) & 0xFF ; $g = ( $color >> 8 ) & 0xFF ; $b = $color & 0xFF ; // save pixel luminosity in temporary array $array_lum [ $x ] [ $y ] = ( $r + $g + $b ) ; // add pixel luminosity to sum $sum_lum += $array_lum [ $x ] [ $y ] ; } }   // calculate average luminosity $average_lum = $sum_lum / ( $width * $height ) ;   for ( $x = 0 ; $x < $width ; $x ++ ) { for ( $y = 0 ; $y < $height ; $y ++ ) { // pixel is brighter than average -> set white // else -> set black if ( $array_lum [ $x ] [ $y ] > $average_lum ) { imagesetpixel ( $img , $x , $y , $white ) ; } else { imagesetpixel ( $img , $x , $y , $black ) ; } } } // save black and white image to dest_name imagejpeg ( $img , dest_name ) ;   if ( ! file_exists ( dest_name ) ) { echo 'Image not saved! Check permission!' ; }   \ No newline at end of file diff --git a/rosetta/file38.py b/rosetta/file38.py new file mode 100644 index 0000000..e222499 --- /dev/null +++ b/rosetta/file38.py @@ -0,0 +1 @@ +from concurrent import futures from math import floor , sqrt   NUMBERS = [ 112272537195293 , 112582718962171 , 112272537095293 , 115280098190773 , 115797840077099 , 1099726829285419 ] # NUMBERS = [33, 44, 55, 275]   def lowest_factor ( n , _start = 3 ) : if n % 2 == 0 : return 2 search_max = int ( floor ( sqrt ( n ) ) ) + 1 for i in range ( _start , search_max , 2 ) : if n % i == 0 : return i return n   def prime_factors ( n , lowest ) : pf = [ ] while n > 1 : pf. append ( lowest ) n // = lowest lowest = lowest_factor ( n , max ( lowest , 3 ) ) return pf   def prime_factors_of_number_with_lowest_prime_factor ( NUMBERS ) : with futures. ProcessPoolExecutor ( ) as executor: low_factor , number = max ( ( l , f ) for l , f in zip ( executor. map ( lowest_factor , NUMBERS ) , NUMBERS ) ) all_factors = prime_factors ( number , low_factor ) return number , all_factors     def main ( ) : print ( 'For these numbers:' ) print ( ' \n ' . join ( str ( p ) for p in NUMBERS ) ) number , all_factors = prime_factors_of_number_with_lowest_prime_factor ( NUMBERS ) print ( ' The one with the largest minimum prime factor is {}:' . format ( number ) ) print ( ' All its prime factors in order are: {}' . format ( all_factors ) )   if __name__ == '__main__' : main ( ) \ No newline at end of file diff --git a/rosetta/file38.rb b/rosetta/file38.rb new file mode 100644 index 0000000..0c54b33 --- /dev/null +++ b/rosetta/file38.rb @@ -0,0 +1 @@ +def main n = ( ARGV [ 0 ] || 41 ) . to_i k = ( ARGV [ 1 ] || 3 ) . to_i puts josephus ( n,k ) end   def josephus ( n, k ) prisoners = ( 0 ... n ) . to_a prisoners. rotate ! ( k - 1 ) . shift while prisoners. length > 1 return prisoners. first end   main \ No newline at end of file diff --git a/rosetta/file38.scala b/rosetta/file38.scala new file mode 100644 index 0000000..6e44db7 --- /dev/null +++ b/rosetta/file38.scala @@ -0,0 +1 @@ + if ( n == 12 ) "twelve" else "not twelve"   today match { case Monday => Compute _ Starting _ Balance ; case Friday => Compute _ Ending _ Balance ; case Tuesday => Accumulate _ Sales case _ => { } } \ No newline at end of file diff --git a/rosetta/file38.ss b/rosetta/file38.ss new file mode 100644 index 0000000..550367e --- /dev/null +++ b/rosetta/file38.ss @@ -0,0 +1 @@ +( define ( make - list length object ) ( if ( = length 0 ) ( list ) ( cons object ( make - list ( - length 1 ) object ) ) ) )   ( define ( list - fill ! list object ) ( if ( not ( null? list ) ) ( begin ( set - car ! list object ) ( list - fill ! ( cdr list ) object ) ) ) )   ( define ( list - set! list element object ) ( if ( = element 1 ) ( set - car ! list object ) ( list - set! ( cdr list ) ( - element 1 ) object ) ) )   ( define ( list - get list element ) ( if ( = element 1 ) ( car list ) ( list - get ( cdr list ) ( - element 1 ) ) ) ) \ No newline at end of file diff --git a/rosetta/file38.tcl b/rosetta/file38.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file38.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file39.clojure b/rosetta/file39.clojure new file mode 100644 index 0000000..97cb87d --- /dev/null +++ b/rosetta/file39.clojure @@ -0,0 +1 @@ +    ( defn draw - line "Draw a line from x1,y1 to x2,y2 using Bresenham's, to a java BufferedImage in the colour of pixel." [ buffer x1 y1 x2 y2 pixel ] ( let [ dist - x ( Math / abs ( - x1 x2 ) ) dist - y ( Math / abs ( - y1 y2 ) ) steep ( > dist - y dist - x ) ] ( let [ [ x1 y1 x2 y2 ] ( if steep [ y1 x1 y2 x2 ] [ x1 y1 x2 y2 ] ) ] ( let [ [ x1 y1 x2 y2 ] ( if ( > x1 x2 ) [ x2 y2 x1 y1 ] [ x1 y1 x2 y2 ] ) ] ( let [ delta - x ( - x2 x1 ) delta - y ( Math / abs ( - y1 y2 ) ) y - step ( if ( < y1 y2 ) 1 - 1 ) ]   ( let [ plot ( if steep # ( . setRGB buffer ( int % 1 ) ( int % 2 ) pixel ) # ( . setRGB buffer ( int % 2 ) ( int % 1 ) pixel ) ) ]   ( loop [ x x1 y y1 error ( Math / floor ( / delta - x 2 ) ) ] ( plot x y ) ( if ( < x x2 ) ; Rather then rebind error, test that it is less than delta-y rather than zero ( if ( < error delta - y ) ( recur ( inc x ) ( + y y - step ) ( + error ( - delta - x delta - y ) ) ) ( recur ( inc x ) y ( - error delta - y ) ) ) ) ) ) ) ) ) ) )   \ No newline at end of file diff --git a/rosetta/file39.hs b/rosetta/file39.hs new file mode 100644 index 0000000..2b151dd --- /dev/null +++ b/rosetta/file39.hs @@ -0,0 +1 @@ +import System . Cmd   main = system "ls"   \ No newline at end of file diff --git a/rosetta/file39.java b/rosetta/file39.java new file mode 100644 index 0000000..a8c01d9 --- /dev/null +++ b/rosetta/file39.java @@ -0,0 +1 @@ +import java.awt.Graphics ; import java.awt.image.BufferedImage ; import java.util.* ; import javax.swing.JFrame ;   public class BrownianTree extends JFrame implements Runnable {   BufferedImage I ; private List < Particle > particles ; static Random rand = new Random ( ) ;   public BrownianTree ( ) { super ( "Brownian Tree" ) ; setBounds ( 100 , 100 , 400 , 300 ) ; setDefaultCloseOperation ( EXIT_ON_CLOSE ) ; I = new BufferedImage ( getWidth ( ) , getHeight ( ) , BufferedImage . TYPE_INT_RGB ) ; I. setRGB ( I. getWidth ( ) / 2 , I. getHeight ( ) / 2 , 0xff00 ) ; particles = new LinkedList < Particle > ( ) ; }   @Override public void paint ( Graphics g ) { g. drawImage ( I, 0 , 0 , this ) ; }   public void run ( ) { for ( int i = 0 ; i < 20000 ; i ++ ) { particles. add ( new Particle ( ) ) ; } while ( ! particles. isEmpty ( ) ) { for ( Iterator < Particle > it = particles. iterator ( ) ; it. hasNext ( ) ; ) { if ( it. next ( ) . move ( ) ) { it. remove ( ) ; } } repaint ( ) ; } }   public static void main ( String [ ] args ) { BrownianTree b = new BrownianTree ( ) ; b. setVisible ( true ) ; new Thread ( b ) . start ( ) ; }   private class Particle {   private int x, y ;   private Particle ( ) { x = rand. nextInt ( I. getWidth ( ) ) ; y = rand. nextInt ( I. getHeight ( ) ) ; }   /* returns true if either out of bounds or collided with tree */ private boolean move ( ) { int dx = rand. nextInt ( 3 ) - 1 ; int dy = rand. nextInt ( 3 ) - 1 ; if ( ( x + dx < 0 ) || ( y + dy < 0 ) || ( y + dy >= I. getHeight ( ) ) || ( x + dx >= I. getWidth ( ) ) ) { return true ; } x += dx ; y += dy ; if ( ( I. getRGB ( x, y ) & 0xff00 ) == 0xff00 ) { I. setRGB ( x - dx, y - dy, 0xff00 ) ; return true ; } return false ; } } } \ No newline at end of file diff --git a/rosetta/file39.js b/rosetta/file39.js new file mode 100644 index 0000000..b128d77 --- /dev/null +++ b/rosetta/file39.js @@ -0,0 +1 @@ +var foo = function ( ) { return arguments. length } ; foo ( ) // 0 foo ( 1 , 2 , 3 ) // 3 \ No newline at end of file diff --git a/rosetta/file39.ocaml b/rosetta/file39.ocaml new file mode 100644 index 0000000..c775162 --- /dev/null +++ b/rosetta/file39.ocaml @@ -0,0 +1 @@ +let pi = 3 , fun n -> ( ( 2 * n - 1 ) * ( 2 * n - 1 ) , 6 ) and nap = 2 , fun n -> ( max 1 ( n - 1 ) , n ) and root2 = 1 , fun n -> ( 1 , 2 ) in   let eval ( i,f ) k = let rec frac n = let a, b = f n in float a /. ( float b +. if n >= k then 0.0 else frac ( n + 1 ) ) in float i +. frac 1 in   Printf . printf "sqrt(2)\t= %.15f\n" ( eval root2 1000 ) ; Printf . printf "e\t= %.15f\n" ( eval nap 1000 ) ; Printf . printf "pi\t= %.15f\n" ( eval pi 1000 ) ; \ No newline at end of file diff --git a/rosetta/file39.perl b/rosetta/file39.perl new file mode 100644 index 0000000..e4e90c4 --- /dev/null +++ b/rosetta/file39.perl @@ -0,0 +1 @@ +( $y , $x ) = ( $x , $y ) ; \ No newline at end of file diff --git a/rosetta/file39.php b/rosetta/file39.php new file mode 100644 index 0000000..32424a1 --- /dev/null +++ b/rosetta/file39.php @@ -0,0 +1 @@ +class Bitmap { public $data ; public $w ; public $h ; public function __construct ( $w = 16 , $h = 16 ) { $white = array_fill ( 0 , $w , array ( 255 , 255 , 255 ) ) ; $this -> data = array_fill ( 0 , $h , $white ) ; $this -> w = $w ; $this -> h = $h ; } //Fills a rectangle, or the whole image with black by default public function fill ( $x = 0 , $y = 0 , $w = null , $h = null , $color = array ( 0 , 0 , 0 ) ) { if ( is_null ( $w ) ) $w = $this -> w ; if ( is_null ( $h ) ) $h = $this -> h ; $w += $x ; $h += $y ; for ( $i = $y ; $i < $h ; $i ++ ) { for ( $j = $x ; $j < $w ; $j ++ ) { $this -> setPixel ( $j , $i , $color ) ; } } } public function setPixel ( $x , $y , $color = array ( 0 , 0 , 0 ) ) { if ( $x >= $this -> w ) return false ; if ( $x < 0 ) return false ; if ( $y >= $this -> h ) return false ; if ( $y < 0 ) return false ; $this -> data [ $y ] [ $x ] = $color ; } public function getPixel ( $x , $y ) { return $this -> data [ $y ] [ $x ] ; } public function writeP6 ( $filename ) { $fh = fopen ( $filename , 'w' ) ; if ( ! $fh ) return false ; fputs ( $fh , "P6 {$this->w} {$this->h} 255 \n " ) ; foreach ( $this -> data as $row ) { foreach ( $row as $pixel ) { fputs ( $fh , pack ( 'C' , $pixel [ 0 ] ) ) ; fputs ( $fh , pack ( 'C' , $pixel [ 1 ] ) ) ; fputs ( $fh , pack ( 'C' , $pixel [ 2 ] ) ) ; } } fclose ( $fh ) ; } }   $b = new Bitmap ( 16 , 16 ) ; $b -> fill ( ) ; $b -> fill ( 2 , 2 , 18 , 18 , array ( 240 , 240 , 240 ) ) ; $b -> setPixel ( 0 , 15 , array ( 255 , 0 , 0 ) ) ; $b -> writeP6 ( 'p6.ppm' ) ; \ No newline at end of file diff --git a/rosetta/file39.py b/rosetta/file39.py new file mode 100644 index 0000000..37cf9cd --- /dev/null +++ b/rosetta/file39.py @@ -0,0 +1 @@ +# Pyramid solver # [151] # [ ] [ ] # [ 40] [ ] [ ] # [ ] [ ] [ ] [ ] #[ X ] [ 11] [ Y ] [ 4 ] [ Z ] # X -Y + Z = 0   def combine ( snl , snr ) :   cl = { } if isinstance ( snl , int ) : cl [ '1' ] = snl elif isinstance ( snl , string ) : cl [ snl ] = 1 else : cl. update ( snl )   if isinstance ( snr , int ) : n = cl. get ( '1' , 0 ) cl [ '1' ] = n + snr elif isinstance ( snr , string ) : n = cl. get ( snr , 0 ) cl [ snr ] = n + 1 else : for k , v in snr. items ( ) : n = cl. get ( k , 0 ) cl [ k ] = n+v return cl     def constrain ( nsum , vn ) : nn = { } nn. update ( vn ) n = nn. get ( '1' , 0 ) nn [ '1' ] = n - nsum return nn   def makeMatrix ( constraints ) : vmap = set ( ) for c in constraints: vmap. update ( c. keys ( ) ) vmap. remove ( '1' ) nvars = len ( vmap ) vmap = sorted ( vmap ) # sort here so output is in sorted order mtx = [ ] for c in constraints: row = [ ] for vv in vmap: row. append ( float ( c. get ( vv , 0 ) ) ) row. append ( - float ( c. get ( '1' , 0 ) ) ) mtx. append ( row )   if len ( constraints ) == nvars: print 'System appears solvable' elif len ( constraints ) < nvars: print 'System is not solvable - needs more constraints.' return mtx , vmap     def SolvePyramid ( vl , cnstr ) :   vl. reverse ( ) constraints = [ cnstr ] lvls = len ( vl ) for lvln in range ( 1 , lvls ) : lvd = vl [ lvln ] for k in range ( lvls - lvln ) : sn = lvd [ k ] ll = vl [ lvln- 1 ] vn = combine ( ll [ k ] , ll [ k+ 1 ] ) if sn is None : lvd [ k ] = vn else : constraints. append ( constrain ( sn , vn ) )   print 'Constraint Equations:' for cstr in constraints: fset = ( '%d*%s' % ( v , k ) for k , v in cstr. items ( ) ) print ' + ' . join ( fset ) , ' = 0'   mtx , vmap = makeMatrix ( constraints )   MtxSolve ( mtx )   d = len ( vmap ) for j in range ( d ) : print vmap [ j ] , '=' , mtx [ j ] [ d ]     def MtxSolve ( mtx ) : # Simple Matrix solver...   mDim = len ( mtx ) # dimension--- for j in range ( mDim ) : rw0 = mtx [ j ] f = 1.0 /rw0 [ j ] for k in range ( j , mDim+ 1 ) : rw0 [ k ] * = f   for l in range ( 1 +j , mDim ) : rwl = mtx [ l ] f = -rwl [ j ] for k in range ( j , mDim+ 1 ) : rwl [ k ] + = f * rw0 [ k ]   # backsolve part --- for j1 in range ( 1 , mDim ) : j = mDim - j1 rw0 = mtx [ j ] for l in range ( 0 , j ) : rwl = mtx [ l ] f = -rwl [ j ] rwl [ j ] + = f * rw0 [ j ] rwl [ mDim ] + = f * rw0 [ mDim ]   return mtx     p = [ [ 151 ] , [ None , None ] , [ 40 , None , None ] , [ None , None , None , None ] , [ 'X' , 11 , 'Y' , 4 , 'Z' ] ] addlConstraint = { 'X' : 1 , 'Y' :- 1 , 'Z' : 1 , '1' : 0 } SolvePyramid ( p , addlConstraint ) \ No newline at end of file diff --git a/rosetta/file39.rb b/rosetta/file39.rb new file mode 100644 index 0000000..8fb2f39 --- /dev/null +++ b/rosetta/file39.rb @@ -0,0 +1 @@ +require 'continuation' unless defined ? Continuation   if a = callcc { | c | [ c, 1 ] } c, i = a c [ nil ] if i > 100   case 0 when i % 3 print "Fizz" case 0 when i % 5 print "Buzz" end when i % 5 print "Buzz" else print i end   puts c [ c, i + 1 ] end \ No newline at end of file diff --git a/rosetta/file39.scala b/rosetta/file39.scala new file mode 100644 index 0000000..d4a340c --- /dev/null +++ b/rosetta/file39.scala @@ -0,0 +1 @@ +object CF extends App { import Stream. _ val sqrt2 = 1 #:: from ( 2 , 0 ) zip from ( 1 , 0 ) val napier = 2 #:: from ( 1 ) zip ( 1 #:: from ( 1 ) ) val pi = 3 #:: from ( 6 , 0 ) zip ( from ( 1 , 2 ) map { x => x * x } )   // reference values, source: wikipedia val refPi = "3.14159265358979323846264338327950288419716939937510" val refNapier = "2.71828182845904523536028747135266249775724709369995" val refSQRT2 = "1.41421356237309504880168872420969807856967187537694"   def calc ( cf : Stream [ ( Int, Int ) ] , numberOfIters : Int = 200 ) : BigDecimal = { ( cf take numberOfIters toList ) . foldRight [ BigDecimal ] ( 1 ) ( ( a, z ) => a. _ 1+a. _ 2/z ) }   def approx ( cfV : BigDecimal, cfRefV : String ) : String = { val p : Pair [ Char,Char ] => Boolean = pair => ( pair. _ 1 == pair. _ 2 ) ( ( cfV. toString + " " * 34 ) . substring ( 0 , 34 ) zip cfRefV. toString . substring ( 0 , 34 ) ) . takeWhile ( p ) . foldRight [ String ] ( "" ) ( ( a : Pair [ Char,Char ] ,z ) => a. _ 1+z ) }   List ( ( "sqrt2" ,sqrt2, 50 ,refSQRT2 ) , ( "napier" ,napier, 50 ,refNapier ) , ( "pi" ,pi, 3000 ,refPi ) ) foreach { t => val ( name,cf,iters,refV ) = t val cfV = calc ( cf,iters ) println ( name+ ":" ) println ( "ref value: " +refV. substring ( 0 , 34 ) ) println ( "cf value: " + ( cfV. toString + " " * 34 ) . substring ( 0 , 34 ) ) println ( "precision: " +approx ( cfV,refV ) ) println ( ) } } \ No newline at end of file diff --git a/rosetta/file39.ss b/rosetta/file39.ss new file mode 100644 index 0000000..550367e --- /dev/null +++ b/rosetta/file39.ss @@ -0,0 +1 @@ +( define ( make - list length object ) ( if ( = length 0 ) ( list ) ( cons object ( make - list ( - length 1 ) object ) ) ) )   ( define ( list - fill ! list object ) ( if ( not ( null? list ) ) ( begin ( set - car ! list object ) ( list - fill ! ( cdr list ) object ) ) ) )   ( define ( list - set! list element object ) ( if ( = element 1 ) ( set - car ! list object ) ( list - set! ( cdr list ) ( - element 1 ) object ) ) )   ( define ( list - get list element ) ( if ( = element 1 ) ( car list ) ( list - get ( cdr list ) ( - element 1 ) ) ) ) \ No newline at end of file diff --git a/rosetta/file39.tcl b/rosetta/file39.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file39.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file4.clojure b/rosetta/file4.clojure new file mode 100644 index 0000000..edf5a6b --- /dev/null +++ b/rosetta/file4.clojure @@ -0,0 +1 @@ +( defn ackermann [ m n ] ( cond ( zero? m ) ( inc n ) ( zero? n ) ( ackermann ( dec m ) 1 )  : else ( ackermann ( dec m ) ( ackermann m ( dec n ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file4.hs b/rosetta/file4.hs new file mode 100644 index 0000000..c240854 --- /dev/null +++ b/rosetta/file4.hs @@ -0,0 +1 @@ +module Integrator ( newIntegrator , input , output , stop , Time , timeInterval ) where import Control . Concurrent ( forkIO , threadDelay ) import Control . Concurrent . MVar ( MVar , newMVar , modifyMVar _, modifyMVar , readMVar ) import Control . Exception ( evaluate ) import Data . Time ( UTCTime ) import Data . Time . Clock ( getCurrentTime , diffUTCTime )   -- RC task main = do let f = 0.5 {- Hz -} t0 <- getCurrentTime i <- newIntegrator input i ( \t -> sin ( 2 * pi * f * timeInterval t0 t ) ) -- task step 1 threadDelay 2000000 {- µs -} -- task step 2 input i ( const 0 ) -- task step 3 threadDelay 500000 {- µs -} -- task step 4 result <- output i stop i print result   ---- Implementation ------------------------------------------------------   -- Utilities for working with the time type type Time = UTCTime type Func a = Time -> a timeInterval t0 t1 = realToFrac $ diffUTCTime t1 t0   -- Type signatures of the module's interface newIntegrator :: Fractional a => IO ( Integrator a ) -- Create an integrator input :: Integrator a -> Func a -> IO ( ) -- Set the input function output :: Integrator a -> IO a -- Get the current value stop :: Integrator a -> IO ( ) -- Stop integration, don't waste CPU   -- Data structures data Integrator a = Integrator ( MVar ( IntState a ) ) -- MVar is a thread-safe mutable cell deriving Eq data IntState a = IntState { func :: Func a , -- The current function run :: Bool , -- Whether to keep going value :: a , -- The current accumulated value time :: Time } -- The time of the previous update   newIntegrator = do now <- getCurrentTime state <- newMVar $ IntState { func = const 0 , run = True , value = 0 , time = now } thread <- forkIO ( intThread state ) -- The state variable is shared between the thread return ( Integrator state ) -- and the client interface object.   input ( Integrator stv ) f = modifyMVar _ stv ( \st -> return st { func = f } ) output ( Integrator stv ) = fmap value $ readMVar stv stop ( Integrator stv ) = modifyMVar _ stv ( \st -> return st { run = False } ) -- modifyMVar_ takes an MVar and replaces its contents according to the provided function. -- a { b = c } is record-update syntax: "the record a, except with field b changed to c"   -- Integration thread intThread :: Fractional a => MVar ( IntState a ) -> IO ( ) intThread stv = whileM $ modifyMVar stv updateAndCheckRun -- modifyMVar is like modifyMVar_ but the function returns a tuple of the new value -- and an arbitrary extra value, which in this case ends up telling whileM whether -- to keep looping. where updateAndCheckRun st = do now <- getCurrentTime let value ' = integrate (func st) (value st) (time st) now evaluate value' -- avoid undesired laziness return ( st { value = value ', time = now }, -- updated state run st) -- whether to continue   integrate :: Fractional a => Func a -> a -> Time -> Time -> a integrate f value t0 t1 = value + (f t0 + f t1)/2 * dt where dt = timeInterval t0 t1   -- Execute ' action ' until it returns false. whileM action = do b <- action; if b then whileM action else return () \ No newline at end of file diff --git a/rosetta/file4.java b/rosetta/file4.java new file mode 100644 index 0000000..5b18f44 --- /dev/null +++ b/rosetta/file4.java @@ -0,0 +1 @@ +import java.io.IOException ; import java.util.Arrays ;   import org.apache.directory.ldap.client.api.LdapConnection ; import org.apache.directory.ldap.client.api.LdapNetworkConnection ; import org.apache.directory.shared.ldap.model.cursor.EntryCursor ; import org.apache.directory.shared.ldap.model.entry.Entry ; import org.apache.directory.shared.ldap.model.exception.LdapException ; import org.apache.directory.shared.ldap.model.message.SearchScope ; import org.slf4j.Logger ; import org.slf4j.LoggerFactory ;     public class RDirectorySearchLDAP {   protected static final Logger log_ ; private static LdapConnection connection ; private static final String ldapHostName ; private static final int ldapPort ; private static final String ldapDnStr ; private static final String ldapCreds ;   static {   log_ = LoggerFactory. getLogger ( RDirectorySearchLDAP. class ) ;   ldapHostName = "localhost" ; ldapPort = 11389 ; ldapDnStr = "uid=admin,ou=system" ; ldapCreds = "********" ; }   public static void main ( String [ ] args ) {   boolean connected = false ;   try { connected = setUp ( ) ; if ( connected ) { search ( "*mil*" ) ; } } finally { if ( connected ) { tearDown ( ) ; } }   return ; }   private static boolean search ( String uid ) {   boolean state ; EntryCursor cursor ; Entry ev ; String baseDn ; String filter ; SearchScope scope ; String attributes [ ] ; int ksearch = 0 ;   state = true ;   baseDn = "ou=users,o=mojo" ; filter = "(&(objectClass=person)(&(uid=" + uid + ")))" ; scope = SearchScope. SUBTREE ; attributes = new java. lang . String [ ] { "dn" , "cn" , "sn" , "uid" } ;   try { if ( log_. isTraceEnabled ( ) ) { log_. trace ( "LDAP search" ) ; } if ( log_. isInfoEnabled ( ) ) { log_. info ( "Begin search" ) ; log_. info ( " search base distinguished name: " + baseDn ) ; log_. info ( " search filter: " + filter ) ; log_. info ( " search attributes: " + ( Arrays . asList ( attributes ) . toString ( ) ) ) ; } cursor = connection. search ( baseDn, filter, scope, attributes ) ; while ( cursor. next ( ) ) { ksearch ++; ev = cursor. get ( ) ; if ( log_. isInfoEnabled ( ) ) { log_. info ( "Search cursor entry count: " + ksearch ) ; } if ( log_. isInfoEnabled ( ) ) { log_. info ( ev. toString ( ) ) ; } } } catch ( LdapException lex ) { state = false ; log_. error ( "LDAP Error in cursor loop: Iteration " + ksearch, lex ) ; } catch ( Exception ex ) { state = false ; log_. error ( "I/O Error in cursor loop: Iteration " + ksearch, ex ) ; }   return state ; }   private static boolean search ( ) {   return search ( "*" ) ; }   private static boolean setUp ( ) {   boolean state = false ;   try { if ( log_. isInfoEnabled ( ) ) { log_. info ( "LDAP Connection to " + ldapHostName + " on port " + ldapPort ) ; } connection = new LdapNetworkConnection ( ldapHostName, ldapPort ) ;   if ( log_. isTraceEnabled ( ) ) { log_. trace ( "LDAP bind" ) ; } connection. bind ( ldapDnStr, ldapCreds ) ;   state = true ; } catch ( LdapException lex ) { state = false ; log_. error ( "LDAP Error" , lex ) ; } catch ( IOException iox ) { state = false ; log_. error ( "I/O Error" , iox ) ; }   return state ; }   private static boolean tearDown ( ) {   boolean state = false ;   try { if ( log_. isTraceEnabled ( ) ) { log_. trace ( "LDAP unbind" ) ; } connection. unBind ( ) ; state = true ; } catch ( LdapException lex ) { state = false ; log_. error ( "LDAP Error" , lex ) ; } finally { try { connection. close ( ) ; } catch ( IOException iox ) { state = false ; log_. error ( "I/O Error on connection.close()" , iox ) ; } }   return state ; } } \ No newline at end of file diff --git a/rosetta/file4.js b/rosetta/file4.js new file mode 100644 index 0000000..13dc519 --- /dev/null +++ b/rosetta/file4.js @@ -0,0 +1 @@ +function ack ( m , n ) { return m === 0 ? n + 1 : ack ( m - 1 , n === 0 ? 1 : ack ( m , n - 1 ) ) ; } \ No newline at end of file diff --git a/rosetta/file4.ocaml b/rosetta/file4.ocaml new file mode 100644 index 0000000..21de3c5 --- /dev/null +++ b/rosetta/file4.ocaml @@ -0,0 +1 @@ +let rec a m n = if m = 0 then ( n + 1 ) else if n = 0 then ( a ( m - 1 ) 1 ) else ( a ( m - 1 ) ( a m ( n - 1 ) ) ) \ No newline at end of file diff --git a/rosetta/file4.perl b/rosetta/file4.perl new file mode 100644 index 0000000..b11b88c --- /dev/null +++ b/rosetta/file4.perl @@ -0,0 +1 @@ +sub Pi ( ) { 3.1415926535897932384626433832795028842 }   sub meanangle { my ( $x , $y ) = ( 0 , 0 ) ; ( $x , $y ) = ( $x + sin ( $_ ) , $y + cos ( $_ ) ) for @_ ; my $atan = atan2 ( $x , $y ) ; $atan += 2 *Pi while $atan < 0 ; # Ghetto fmod $atan -= 2 *Pi while $atan > 2 *Pi ; $atan ; }   sub meandegrees { meanangle ( map { $_ * Pi / 180 } @_ ) * 180 / Pi ; }   print "The mean angle of [@$_] is: " , meandegrees ( @ $_ ) , " degrees \n " for ( [ 350 , 10 ] , [ 90 , 180 , 270 , 360 ] , [ 10 , 20 , 30 ] ) ; \ No newline at end of file diff --git a/rosetta/file4.php b/rosetta/file4.php new file mode 100644 index 0000000..56c2b03 --- /dev/null +++ b/rosetta/file4.php @@ -0,0 +1,2 @@ + */ ' , 'password' ) ;   $base = 'dc=example, dc=com' ; $criteria = '(&(objectClass=user)(sAMAccountName=username))' ; $attributes = array ( 'displayName' , 'company' ) ;   $search = ldap_search ( $l , $base , $criteria , $attributes ) ; $entries = ldap_get_entries ( $l , $search ) ;   var_dump ( $entries ) ; \ No newline at end of file diff --git a/rosetta/file4.py b/rosetta/file4.py new file mode 100644 index 0000000..b1ec695 --- /dev/null +++ b/rosetta/file4.py @@ -0,0 +1 @@ +from hashlib import sha256   digits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'   def decode_base58 ( bc , length ) : n = 0 for char in bc: n = n * 58 + digits58. index ( char ) return n. to_bytes ( length , 'big' )   def check_bc ( bc ) : bcbytes = decode_base58 ( bc , 25 ) return bcbytes [ - 4 : ] == sha256 ( sha256 ( bcbytes [ :- 4 ] ) . digest ( ) ) . digest ( ) [ : 4 ]   if __name__ == '__main__' : bc = '1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i' assert check_bc ( bc ) assert not check_bc ( bc. replace ( 'N' , 'P' , 1 ) ) assert check_bc ( '1111111111111111111114oLvT2' ) assert check_bc ( "17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j" ) \ No newline at end of file diff --git a/rosetta/file4.rb b/rosetta/file4.rb new file mode 100644 index 0000000..9a59863 --- /dev/null +++ b/rosetta/file4.rb @@ -0,0 +1 @@ +def bitwise ( a, b ) form = "%1$7s:%2$6d  %2$016b" puts form % [ "a" , a ] puts form % [ "b" , b ] puts form % [ "a and b" , a & b ] puts form % [ "a or b " , a | b ] puts form % [ "a xor b" , a ^ b ] puts form % [ "not a " , ~a ] puts form % [ "a << b " , a << b ] # left shift puts form % [ "a >> b " , a >> b ] # arithmetic right shift end   bitwise ( 14 , 3 ) \ No newline at end of file diff --git a/rosetta/file4.scala b/rosetta/file4.scala new file mode 100644 index 0000000..a5568d1 --- /dev/null +++ b/rosetta/file4.scala @@ -0,0 +1 @@ +import language. dynamics import scala. collection . mutable . HashMap   class A extends Dynamic { private val map = new HashMap [ String, Any ] def selectDynamic ( name : String ) : Any = { return map ( name ) } def updateDynamic ( name : String ) ( value : Any ) = { map ( name ) = value } } \ No newline at end of file diff --git a/rosetta/file4.ss b/rosetta/file4.ss new file mode 100644 index 0000000..4d53f4c --- /dev/null +++ b/rosetta/file4.ss @@ -0,0 +1 @@ +( display ( + ( read ) ( read ) ) ) \ No newline at end of file diff --git a/rosetta/file4.tcl b/rosetta/file4.tcl new file mode 100644 index 0000000..7a96353 --- /dev/null +++ b/rosetta/file4.tcl @@ -0,0 +1 @@ +package require Tcl 8.5 package require Tk   proc drawBezier { img colour args } { # ensure the points are increasing along the x-axis set points [ lsort -real -index 0 $args ]   set xmin [ x [ lindex $points 0 ] ] set xmax [ x [ lindex $points end ] ] set prev [ lindex $points 0 ] set increment 2 for { set x [ expr { $xmin + $increment } ] } { $x < = $xmax } { incr x $increment } { set t [ expr { 1.0 * ( $x - $xmin ) / ( $xmax - $xmin ) } ] set this [ list $x [ :: tcl :: mathfunc :: round [ bezier $t $points ] ] ] drawLine $img $colour $prev $this set prev $this } }   # the generalized n-degree Bezier summation proc bezier { t points } { set n [ expr { [ llength $points ] - 1 } ] for { set i 0 ; set sum 0.0 } { $i < = $n } { incr i } { set sum [ expr { $sum + [ C $n $i ] * ( 1 - $t ) ** ( $n - $i ) * $t ** $i * [ y [ lindex $points $i ] ] } ] } return $sum }   proc C { n i } { expr { [ ifact $n ] / ( [ ifact $i ] * [ ifact [ expr { $n - $i } ] ] ) } } proc ifact n { for { set i $n ; set sum 1 } { $i > = 2 } { incr i - 1 } { set sum [ expr { $sum * $i } ] } return $sum }   proc x p { lindex $p 0 } proc y p { lindex $p 1 }   proc newbezier { n w } { set size 400 set bezier [ newImage $size $size ] fill $bezier white for { set i 1 } { $i < = $n } { incr i } { set point [ list [ expr { int ( $size * rand ( ) ) } ] [ expr { int ( $size * rand ( ) ) } ] ] lappend points $point drawCircle $bezier red $point 3 } puts $points   drawBezier $bezier blue { * } $points   $w configure -image $bezier }   set degree 4 ; # cubic bezier -- for quadratic, use 3 label .img button .new -command [ list newbezier $degree .img ] -text New button . exit -command exit -text Exit pack .new .img . exit -side top \ No newline at end of file diff --git a/rosetta/file40.clojure b/rosetta/file40.clojure new file mode 100644 index 0000000..97cb87d --- /dev/null +++ b/rosetta/file40.clojure @@ -0,0 +1 @@ +    ( defn draw - line "Draw a line from x1,y1 to x2,y2 using Bresenham's, to a java BufferedImage in the colour of pixel." [ buffer x1 y1 x2 y2 pixel ] ( let [ dist - x ( Math / abs ( - x1 x2 ) ) dist - y ( Math / abs ( - y1 y2 ) ) steep ( > dist - y dist - x ) ] ( let [ [ x1 y1 x2 y2 ] ( if steep [ y1 x1 y2 x2 ] [ x1 y1 x2 y2 ] ) ] ( let [ [ x1 y1 x2 y2 ] ( if ( > x1 x2 ) [ x2 y2 x1 y1 ] [ x1 y1 x2 y2 ] ) ] ( let [ delta - x ( - x2 x1 ) delta - y ( Math / abs ( - y1 y2 ) ) y - step ( if ( < y1 y2 ) 1 - 1 ) ]   ( let [ plot ( if steep # ( . setRGB buffer ( int % 1 ) ( int % 2 ) pixel ) # ( . setRGB buffer ( int % 2 ) ( int % 1 ) pixel ) ) ]   ( loop [ x x1 y y1 error ( Math / floor ( / delta - x 2 ) ) ] ( plot x y ) ( if ( < x x2 ) ; Rather then rebind error, test that it is less than delta-y rather than zero ( if ( < error delta - y ) ( recur ( inc x ) ( + y y - step ) ( + error ( - delta - x delta - y ) ) ) ( recur ( inc x ) y ( - error delta - y ) ) ) ) ) ) ) ) ) ) )   \ No newline at end of file diff --git a/rosetta/file40.hs b/rosetta/file40.hs new file mode 100644 index 0000000..2b151dd --- /dev/null +++ b/rosetta/file40.hs @@ -0,0 +1 @@ +import System . Cmd   main = system "ls"   \ No newline at end of file diff --git a/rosetta/file40.java b/rosetta/file40.java new file mode 100644 index 0000000..a8c01d9 --- /dev/null +++ b/rosetta/file40.java @@ -0,0 +1 @@ +import java.awt.Graphics ; import java.awt.image.BufferedImage ; import java.util.* ; import javax.swing.JFrame ;   public class BrownianTree extends JFrame implements Runnable {   BufferedImage I ; private List < Particle > particles ; static Random rand = new Random ( ) ;   public BrownianTree ( ) { super ( "Brownian Tree" ) ; setBounds ( 100 , 100 , 400 , 300 ) ; setDefaultCloseOperation ( EXIT_ON_CLOSE ) ; I = new BufferedImage ( getWidth ( ) , getHeight ( ) , BufferedImage . TYPE_INT_RGB ) ; I. setRGB ( I. getWidth ( ) / 2 , I. getHeight ( ) / 2 , 0xff00 ) ; particles = new LinkedList < Particle > ( ) ; }   @Override public void paint ( Graphics g ) { g. drawImage ( I, 0 , 0 , this ) ; }   public void run ( ) { for ( int i = 0 ; i < 20000 ; i ++ ) { particles. add ( new Particle ( ) ) ; } while ( ! particles. isEmpty ( ) ) { for ( Iterator < Particle > it = particles. iterator ( ) ; it. hasNext ( ) ; ) { if ( it. next ( ) . move ( ) ) { it. remove ( ) ; } } repaint ( ) ; } }   public static void main ( String [ ] args ) { BrownianTree b = new BrownianTree ( ) ; b. setVisible ( true ) ; new Thread ( b ) . start ( ) ; }   private class Particle {   private int x, y ;   private Particle ( ) { x = rand. nextInt ( I. getWidth ( ) ) ; y = rand. nextInt ( I. getHeight ( ) ) ; }   /* returns true if either out of bounds or collided with tree */ private boolean move ( ) { int dx = rand. nextInt ( 3 ) - 1 ; int dy = rand. nextInt ( 3 ) - 1 ; if ( ( x + dx < 0 ) || ( y + dy < 0 ) || ( y + dy >= I. getHeight ( ) ) || ( x + dx >= I. getWidth ( ) ) ) { return true ; } x += dx ; y += dy ; if ( ( I. getRGB ( x, y ) & 0xff00 ) == 0xff00 ) { I. setRGB ( x - dx, y - dy, 0xff00 ) ; return true ; } return false ; } } } \ No newline at end of file diff --git a/rosetta/file40.js b/rosetta/file40.js new file mode 100644 index 0000000..b128d77 --- /dev/null +++ b/rosetta/file40.js @@ -0,0 +1 @@ +var foo = function ( ) { return arguments. length } ; foo ( ) // 0 foo ( 1 , 2 , 3 ) // 3 \ No newline at end of file diff --git a/rosetta/file40.ocaml b/rosetta/file40.ocaml new file mode 100644 index 0000000..c775162 --- /dev/null +++ b/rosetta/file40.ocaml @@ -0,0 +1 @@ +let pi = 3 , fun n -> ( ( 2 * n - 1 ) * ( 2 * n - 1 ) , 6 ) and nap = 2 , fun n -> ( max 1 ( n - 1 ) , n ) and root2 = 1 , fun n -> ( 1 , 2 ) in   let eval ( i,f ) k = let rec frac n = let a, b = f n in float a /. ( float b +. if n >= k then 0.0 else frac ( n + 1 ) ) in float i +. frac 1 in   Printf . printf "sqrt(2)\t= %.15f\n" ( eval root2 1000 ) ; Printf . printf "e\t= %.15f\n" ( eval nap 1000 ) ; Printf . printf "pi\t= %.15f\n" ( eval pi 1000 ) ; \ No newline at end of file diff --git a/rosetta/file40.perl b/rosetta/file40.perl new file mode 100644 index 0000000..1b0864f --- /dev/null +++ b/rosetta/file40.perl @@ -0,0 +1 @@ +use strict ;   sub max_sub ( \ @ ) { my ( $a , $maxs , $maxe , $s , $sum , $maxsum ) = shift ; foreach ( 0 .. $# $a ) { my $t = $sum + $a -> [ $_ ] ; ( $s , $sum ) = $t > 0 ? ( $s , $t ) : ( $_ + 1 , 0 ) ;   if ( $maxsum < $sum ) { $maxsum = $sum ; ( $maxs , $maxe ) = ( $s , $_ + 1 ) } } @$a [ $maxs .. $maxe - 1 ] }   my @a = map { int ( rand ( 20 ) - 10 ) } 1 .. 10 ; my @b = ( - 1 ) x 10 ;   print "seq: @a \n max: [ @{[max_sub @a]} ] \n " ; print "seq: @b \n max: [ @{[max_sub @b]} ] \n " ; \ No newline at end of file diff --git a/rosetta/file40.php b/rosetta/file40.php new file mode 100644 index 0000000..8f8f4b4 --- /dev/null +++ b/rosetta/file40.php @@ -0,0 +1 @@ +function bitwise ( $a , $b ) { function zerofill ( $a , $b ) { if ( $a >= 0 ) return $a >> $b ; if ( $b == 0 ) return ( ( $a >> 1 ) & 0x7fffffff ) * 2 + ( ( $a >> $b ) & 1 ) ; // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ( ( ~ $a ) >> $b ) ^ ( 0x7fffffff >> ( $b - 1 ) ) ;   echo '$a AND $b: ' . $a & $b . '\n' ; echo '$a OR $b: ' . $a | $b . '\n' ; echo '$a XOR $b: ' . $a ^ $b . '\n' ; echo 'NOT $a: ' . ~ $a . '\n' ; echo '$a << $b: ' . $a << $b . '\n' ; // left shift echo '$a >> $b: ' . $a >> $b . '\n' ; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill ( $a , $b ) . '\n' ; // logical right shift } \ No newline at end of file diff --git a/rosetta/file40.py b/rosetta/file40.py new file mode 100644 index 0000000..6329566 --- /dev/null +++ b/rosetta/file40.py @@ -0,0 +1 @@ +#!/usr/bin/python3   ''' See: http://en.wikipedia.org/wiki/Pig_(dice)   This program scores, throws the dice, and plays for an N player game of Pig.   '''   from random import randint from collections import namedtuple import random from pprint import pprint as pp from collections import Counter     playercount = 2 maxscore = 100 maxgames = 100000     Game = namedtuple ( 'Game' , 'players, maxscore, rounds' ) Round = namedtuple ( 'Round' , 'who, start, scores, safe' )     class Player ( ) : def __init__ ( self , player_index ) : self . player_index = player_index   def __repr__ ( self ) : return '%s(%i)'  % ( self .__class__.__name__ , self . player_index )   def __call__ ( self , safescore , scores , game ) : 'Returns boolean True to roll again' pass   class RandPlay ( Player ) : def __call__ ( self , safe , scores , game ) : 'Returns random boolean choice of whether to roll again' return bool ( random . randint ( 0 , 1 ) )   class RollTo20 ( Player ) : def __call__ ( self , safe , scores , game ) : 'Roll again if this rounds score < 20' return ( ( ( sum ( scores ) + safe [ self . player_index ] ) < maxscore ) # Haven't won yet and ( sum ( scores ) < 20 ) ) # Not at 20 this round   class Desparat ( Player ) : def __call__ ( self , safe , scores , game ) : 'Roll again if this rounds score < 20 or someone is within 20 of winning' return ( ( ( sum ( scores ) + safe [ self . player_index ] ) < maxscore ) # Haven't won yet and ( ( sum ( scores ) < 20 ) # Not at 20 this round or max ( safe ) >= ( maxscore - 20 ) ) ) # Someone's close     def game__str__ ( self ) : 'Pretty printer for Game class' return ( "Game(players=%r, maxscore=%i, \n rounds=[ \n  %s \n ])"  % ( self . players , self . maxscore , ', \n ' . join ( repr ( round ) for round in self . rounds ) ) ) Game. __str__ = game__str__     def winningorder ( players , safescores ) : 'Return (players in winning order, their scores)' return tuple ( zip ( * sorted ( zip ( players , safescores ) , key = lambda x: x [ 1 ] , reverse = True ) ) )   def playpig ( game ) : ''' Plays the game of pig returning the players in winning order and their scores whilst updating argument game with the details of play. ''' players , maxscore , rounds = game playercount = len ( players ) safescore = [ 0 ] * playercount # Safe scores for each player player = 0 # Who plays this round scores = [ ] # Individual scores this round   while max ( safescore ) < maxscore: startscore = safescore [ player ] rolling = players [ player ] ( safescore , scores , game ) if rolling: rolled = randint ( 1 , 6 ) scores. append ( rolled ) if rolled == 1 : # Bust! round = Round ( who = players [ player ] , start = startscore , scores = scores , safe = safescore [ player ] ) rounds. append ( round ) scores , player = [ ] , ( player + 1 )  % playercount else : # Stick safescore [ player ] + = sum ( scores ) round = Round ( who = players [ player ] , start = startscore , scores = scores , safe = safescore [ player ] ) rounds. append ( round ) if safescore [ player ] >= maxscore: break scores , player = [ ] , ( player + 1 )  % playercount   # return players in winning order and all scores return winningorder ( players , safescore )   if __name__ == '__main__' : game = Game ( players = tuple ( RandPlay ( i ) for i in range ( playercount ) ) , maxscore = 20 , rounds = [ ] ) print ( 'ONE GAME' ) print ( 'Winning order: %r; Respective scores: %r \n '  % playpig ( game ) ) print ( game ) game = Game ( players = tuple ( RandPlay ( i ) for i in range ( playercount ) ) , maxscore = maxscore , rounds = [ ] ) algos = ( RollTo20 , RandPlay , Desparat ) print ( ' \n \n MULTIPLE STATISTICS using %r \n for %i GAMES'  % ( ', ' . join ( p.__name__ for p in algos ) , maxgames , ) ) winners = Counter ( repr ( playpig ( game._replace ( players = tuple ( random . choice ( algos ) ( i ) for i in range ( playercount ) ) , rounds = [ ] ) ) [ 0 ] ) for i in range ( maxgames ) ) print ( ' Players(position) winning on left; occurrences on right: \n  %s'  % ', \n ' . join ( str ( w ) for w in winners. most_common ( ) ) ) \ No newline at end of file diff --git a/rosetta/file40.rb b/rosetta/file40.rb new file mode 100644 index 0000000..8fb2f39 --- /dev/null +++ b/rosetta/file40.rb @@ -0,0 +1 @@ +require 'continuation' unless defined ? Continuation   if a = callcc { | c | [ c, 1 ] } c, i = a c [ nil ] if i > 100   case 0 when i % 3 print "Fizz" case 0 when i % 5 print "Buzz" end when i % 5 print "Buzz" else print i end   puts c [ c, i + 1 ] end \ No newline at end of file diff --git a/rosetta/file40.scala b/rosetta/file40.scala new file mode 100644 index 0000000..d4a340c --- /dev/null +++ b/rosetta/file40.scala @@ -0,0 +1 @@ +object CF extends App { import Stream. _ val sqrt2 = 1 #:: from ( 2 , 0 ) zip from ( 1 , 0 ) val napier = 2 #:: from ( 1 ) zip ( 1 #:: from ( 1 ) ) val pi = 3 #:: from ( 6 , 0 ) zip ( from ( 1 , 2 ) map { x => x * x } )   // reference values, source: wikipedia val refPi = "3.14159265358979323846264338327950288419716939937510" val refNapier = "2.71828182845904523536028747135266249775724709369995" val refSQRT2 = "1.41421356237309504880168872420969807856967187537694"   def calc ( cf : Stream [ ( Int, Int ) ] , numberOfIters : Int = 200 ) : BigDecimal = { ( cf take numberOfIters toList ) . foldRight [ BigDecimal ] ( 1 ) ( ( a, z ) => a. _ 1+a. _ 2/z ) }   def approx ( cfV : BigDecimal, cfRefV : String ) : String = { val p : Pair [ Char,Char ] => Boolean = pair => ( pair. _ 1 == pair. _ 2 ) ( ( cfV. toString + " " * 34 ) . substring ( 0 , 34 ) zip cfRefV. toString . substring ( 0 , 34 ) ) . takeWhile ( p ) . foldRight [ String ] ( "" ) ( ( a : Pair [ Char,Char ] ,z ) => a. _ 1+z ) }   List ( ( "sqrt2" ,sqrt2, 50 ,refSQRT2 ) , ( "napier" ,napier, 50 ,refNapier ) , ( "pi" ,pi, 3000 ,refPi ) ) foreach { t => val ( name,cf,iters,refV ) = t val cfV = calc ( cf,iters ) println ( name+ ":" ) println ( "ref value: " +refV. substring ( 0 , 34 ) ) println ( "cf value: " + ( cfV. toString + " " * 34 ) . substring ( 0 , 34 ) ) println ( "precision: " +approx ( cfV,refV ) ) println ( ) } } \ No newline at end of file diff --git a/rosetta/file40.ss b/rosetta/file40.ss new file mode 100644 index 0000000..550367e --- /dev/null +++ b/rosetta/file40.ss @@ -0,0 +1 @@ +( define ( make - list length object ) ( if ( = length 0 ) ( list ) ( cons object ( make - list ( - length 1 ) object ) ) ) )   ( define ( list - fill ! list object ) ( if ( not ( null? list ) ) ( begin ( set - car ! list object ) ( list - fill ! ( cdr list ) object ) ) ) )   ( define ( list - set! list element object ) ( if ( = element 1 ) ( set - car ! list object ) ( list - set! ( cdr list ) ( - element 1 ) object ) ) )   ( define ( list - get list element ) ( if ( = element 1 ) ( car list ) ( list - get ( cdr list ) ( - element 1 ) ) ) ) \ No newline at end of file diff --git a/rosetta/file40.tcl b/rosetta/file40.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file40.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file41.clojure b/rosetta/file41.clojure new file mode 100644 index 0000000..97cb87d --- /dev/null +++ b/rosetta/file41.clojure @@ -0,0 +1 @@ +    ( defn draw - line "Draw a line from x1,y1 to x2,y2 using Bresenham's, to a java BufferedImage in the colour of pixel." [ buffer x1 y1 x2 y2 pixel ] ( let [ dist - x ( Math / abs ( - x1 x2 ) ) dist - y ( Math / abs ( - y1 y2 ) ) steep ( > dist - y dist - x ) ] ( let [ [ x1 y1 x2 y2 ] ( if steep [ y1 x1 y2 x2 ] [ x1 y1 x2 y2 ] ) ] ( let [ [ x1 y1 x2 y2 ] ( if ( > x1 x2 ) [ x2 y2 x1 y1 ] [ x1 y1 x2 y2 ] ) ] ( let [ delta - x ( - x2 x1 ) delta - y ( Math / abs ( - y1 y2 ) ) y - step ( if ( < y1 y2 ) 1 - 1 ) ]   ( let [ plot ( if steep # ( . setRGB buffer ( int % 1 ) ( int % 2 ) pixel ) # ( . setRGB buffer ( int % 2 ) ( int % 1 ) pixel ) ) ]   ( loop [ x x1 y y1 error ( Math / floor ( / delta - x 2 ) ) ] ( plot x y ) ( if ( < x x2 ) ; Rather then rebind error, test that it is less than delta-y rather than zero ( if ( < error delta - y ) ( recur ( inc x ) ( + y y - step ) ( + error ( - delta - x delta - y ) ) ) ( recur ( inc x ) y ( - error delta - y ) ) ) ) ) ) ) ) ) ) )   \ No newline at end of file diff --git a/rosetta/file41.hs b/rosetta/file41.hs new file mode 100644 index 0000000..962538e --- /dev/null +++ b/rosetta/file41.hs @@ -0,0 +1 @@ +# !/ usr / bin / env runghc   import Data . List import Data . Numbers . Primes import System . IO   firstNPrimes :: Integer -> [ Integer ] firstNPrimes n = genericTake n primes   primesBetweenInclusive :: Integer -> Integer -> [ Integer ] primesBetweenInclusive lo hi = dropWhile ( < lo ) $ takeWhile ( <= hi ) primes   nthPrime :: Integer -> Integer nthPrime n = genericIndex primes ( n - 1 ) -- beware 0-based indexing   main = do hSetBuffering stdout NoBuffering putStr "First 20 primes: " print $ firstNPrimes 20 putStr "Primes between 100 and 150: " print $ primesBetweenInclusive 100 150 putStr "Number of primes between 7700 and 8000: " print $ genericLength $ primesBetweenInclusive 7700 8000 putStr "The 10000th prime: " print $ nthPrime 10000 \ No newline at end of file diff --git a/rosetta/file41.java b/rosetta/file41.java new file mode 100644 index 0000000..bb10f9e --- /dev/null +++ b/rosetta/file41.java @@ -0,0 +1 @@ +import java.text.* ; import java.util.* ;   public class CalendarTask {   public static void main ( String [ ] args ) { printCalendar ( 1969 , 3 ) ; }   static void printCalendar ( int year, int nCols ) { if ( nCols < 1 || nCols > 12 ) throw new IllegalArgumentException ( "Illegal column width." ) ;   Calendar date = new GregorianCalendar ( year, 0 , 1 ) ;   int nRows = ( int ) Math . ceil ( 12.0 / nCols ) ; int offs = date. get ( Calendar . DAY_OF_WEEK ) - 1 ; int w = nCols * 24 ;   String [ ] monthNames = new DateFormatSymbols ( Locale . US ) . getMonths ( ) ;   String [ ] [ ] mons = new String [ 12 ] [ 8 ] ; for ( int m = 0 ; m < 12 ; m ++ ) {   String name = monthNames [ m ] ; int len = 11 + name. length ( ) / 2 ; String format = MessageFormat . format ( "%{0}s%{1}s" , len, 21 - len ) ;   mons [ m ] [ 0 ] = String . format ( format, name, "" ) ; mons [ m ] [ 1 ] = " Su Mo Tu We Th Fr Sa" ; int dim = date. getActualMaximum ( Calendar . DAY_OF_MONTH ) ;   for ( int d = 1 ; d < 43 ; d ++ ) { boolean isDay = d > offs && d <= offs + dim ; String entry = isDay ? String . format ( " %2s" , d - offs ) : " " ; if ( d % 7 == 1 ) mons [ m ] [ 2 + ( d - 1 ) / 7 ] = entry ; else mons [ m ] [ 2 + ( d - 1 ) / 7 ] += entry ; } offs = ( offs + dim ) % 7 ; date. add ( Calendar . MONTH , 1 ) ; }   System . out . printf ( "%" + ( w / 2 + 10 ) + "s%n" , "[Snoopy Picture]" ) ; System . out . printf ( "%" + ( w / 2 + 4 ) + "s%n%n" , year ) ;   for ( int r = 0 ; r < nRows ; r ++ ) { for ( int i = 0 ; i < 8 ; i ++ ) { for ( int c = r * nCols ; c < ( r + 1 ) * nCols && c < 12 ; c ++ ) System . out . printf ( "  %s" , mons [ c ] [ i ] ) ; System . out . println ( ) ; } System . out . println ( ) ; } } } \ No newline at end of file diff --git a/rosetta/file41.js b/rosetta/file41.js new file mode 100644 index 0000000..b128d77 --- /dev/null +++ b/rosetta/file41.js @@ -0,0 +1 @@ +var foo = function ( ) { return arguments. length } ; foo ( ) // 0 foo ( 1 , 2 , 3 ) // 3 \ No newline at end of file diff --git a/rosetta/file41.ocaml b/rosetta/file41.ocaml new file mode 100644 index 0000000..c775162 --- /dev/null +++ b/rosetta/file41.ocaml @@ -0,0 +1 @@ +let pi = 3 , fun n -> ( ( 2 * n - 1 ) * ( 2 * n - 1 ) , 6 ) and nap = 2 , fun n -> ( max 1 ( n - 1 ) , n ) and root2 = 1 , fun n -> ( 1 , 2 ) in   let eval ( i,f ) k = let rec frac n = let a, b = f n in float a /. ( float b +. if n >= k then 0.0 else frac ( n + 1 ) ) in float i +. frac 1 in   Printf . printf "sqrt(2)\t= %.15f\n" ( eval root2 1000 ) ; Printf . printf "e\t= %.15f\n" ( eval nap 1000 ) ; Printf . printf "pi\t= %.15f\n" ( eval pi 1000 ) ; \ No newline at end of file diff --git a/rosetta/file41.perl b/rosetta/file41.perl new file mode 100644 index 0000000..1a29ec0 --- /dev/null +++ b/rosetta/file41.perl @@ -0,0 +1 @@ +#!/usr/bin/perl   my $min = 1 ; my $max = 99 ; my $guess = int ( rand $max ) + $min ; my $tries = 0 ;   print "=>> Think of a number between $min and $max and I'll guess it! \n Press when are you ready... " ;   ;   { do {   $tries ++; print " \n =>> My guess is: $guess Is your number higher, lower, or equal? (h/l/e) \n > " ;   my $score = ;   if ( $max <= $min ) { print " \n I give up... \n " and last ; } elsif ( $score =~ /^h/i ) { $min = $guess + 1 ; } elsif ( $score =~ /^l/i ) { $max = $guess ; } elsif ( $score =~ /^e/i ) { print " \n I knew it! It took me only $tries tries. \n " and last ; } else { print "error: invalid score \n " ; }   $guess = int ( ( $max + $min ) / 2 ) ;   } while ( 1 ) ; } \ No newline at end of file diff --git a/rosetta/file41.php b/rosetta/file41.php new file mode 100644 index 0000000..8f8f4b4 --- /dev/null +++ b/rosetta/file41.php @@ -0,0 +1 @@ +function bitwise ( $a , $b ) { function zerofill ( $a , $b ) { if ( $a >= 0 ) return $a >> $b ; if ( $b == 0 ) return ( ( $a >> 1 ) & 0x7fffffff ) * 2 + ( ( $a >> $b ) & 1 ) ; // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ( ( ~ $a ) >> $b ) ^ ( 0x7fffffff >> ( $b - 1 ) ) ;   echo '$a AND $b: ' . $a & $b . '\n' ; echo '$a OR $b: ' . $a | $b . '\n' ; echo '$a XOR $b: ' . $a ^ $b . '\n' ; echo 'NOT $a: ' . ~ $a . '\n' ; echo '$a << $b: ' . $a << $b . '\n' ; // left shift echo '$a >> $b: ' . $a >> $b . '\n' ; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill ( $a , $b ) . '\n' ; // logical right shift } \ No newline at end of file diff --git a/rosetta/file41.py b/rosetta/file41.py new file mode 100644 index 0000000..6329566 --- /dev/null +++ b/rosetta/file41.py @@ -0,0 +1 @@ +#!/usr/bin/python3   ''' See: http://en.wikipedia.org/wiki/Pig_(dice)   This program scores, throws the dice, and plays for an N player game of Pig.   '''   from random import randint from collections import namedtuple import random from pprint import pprint as pp from collections import Counter     playercount = 2 maxscore = 100 maxgames = 100000     Game = namedtuple ( 'Game' , 'players, maxscore, rounds' ) Round = namedtuple ( 'Round' , 'who, start, scores, safe' )     class Player ( ) : def __init__ ( self , player_index ) : self . player_index = player_index   def __repr__ ( self ) : return '%s(%i)'  % ( self .__class__.__name__ , self . player_index )   def __call__ ( self , safescore , scores , game ) : 'Returns boolean True to roll again' pass   class RandPlay ( Player ) : def __call__ ( self , safe , scores , game ) : 'Returns random boolean choice of whether to roll again' return bool ( random . randint ( 0 , 1 ) )   class RollTo20 ( Player ) : def __call__ ( self , safe , scores , game ) : 'Roll again if this rounds score < 20' return ( ( ( sum ( scores ) + safe [ self . player_index ] ) < maxscore ) # Haven't won yet and ( sum ( scores ) < 20 ) ) # Not at 20 this round   class Desparat ( Player ) : def __call__ ( self , safe , scores , game ) : 'Roll again if this rounds score < 20 or someone is within 20 of winning' return ( ( ( sum ( scores ) + safe [ self . player_index ] ) < maxscore ) # Haven't won yet and ( ( sum ( scores ) < 20 ) # Not at 20 this round or max ( safe ) >= ( maxscore - 20 ) ) ) # Someone's close     def game__str__ ( self ) : 'Pretty printer for Game class' return ( "Game(players=%r, maxscore=%i, \n rounds=[ \n  %s \n ])"  % ( self . players , self . maxscore , ', \n ' . join ( repr ( round ) for round in self . rounds ) ) ) Game. __str__ = game__str__     def winningorder ( players , safescores ) : 'Return (players in winning order, their scores)' return tuple ( zip ( * sorted ( zip ( players , safescores ) , key = lambda x: x [ 1 ] , reverse = True ) ) )   def playpig ( game ) : ''' Plays the game of pig returning the players in winning order and their scores whilst updating argument game with the details of play. ''' players , maxscore , rounds = game playercount = len ( players ) safescore = [ 0 ] * playercount # Safe scores for each player player = 0 # Who plays this round scores = [ ] # Individual scores this round   while max ( safescore ) < maxscore: startscore = safescore [ player ] rolling = players [ player ] ( safescore , scores , game ) if rolling: rolled = randint ( 1 , 6 ) scores. append ( rolled ) if rolled == 1 : # Bust! round = Round ( who = players [ player ] , start = startscore , scores = scores , safe = safescore [ player ] ) rounds. append ( round ) scores , player = [ ] , ( player + 1 )  % playercount else : # Stick safescore [ player ] + = sum ( scores ) round = Round ( who = players [ player ] , start = startscore , scores = scores , safe = safescore [ player ] ) rounds. append ( round ) if safescore [ player ] >= maxscore: break scores , player = [ ] , ( player + 1 )  % playercount   # return players in winning order and all scores return winningorder ( players , safescore )   if __name__ == '__main__' : game = Game ( players = tuple ( RandPlay ( i ) for i in range ( playercount ) ) , maxscore = 20 , rounds = [ ] ) print ( 'ONE GAME' ) print ( 'Winning order: %r; Respective scores: %r \n '  % playpig ( game ) ) print ( game ) game = Game ( players = tuple ( RandPlay ( i ) for i in range ( playercount ) ) , maxscore = maxscore , rounds = [ ] ) algos = ( RollTo20 , RandPlay , Desparat ) print ( ' \n \n MULTIPLE STATISTICS using %r \n for %i GAMES'  % ( ', ' . join ( p.__name__ for p in algos ) , maxgames , ) ) winners = Counter ( repr ( playpig ( game._replace ( players = tuple ( random . choice ( algos ) ( i ) for i in range ( playercount ) ) , rounds = [ ] ) ) [ 0 ] ) for i in range ( maxgames ) ) print ( ' Players(position) winning on left; occurrences on right: \n  %s'  % ', \n ' . join ( str ( w ) for w in winners. most_common ( ) ) ) \ No newline at end of file diff --git a/rosetta/file41.rb b/rosetta/file41.rb new file mode 100644 index 0000000..da986d9 --- /dev/null +++ b/rosetta/file41.rb @@ -0,0 +1 @@ +require 'io/console' $stdin . iflush \ No newline at end of file diff --git a/rosetta/file41.scala b/rosetta/file41.scala new file mode 100644 index 0000000..d4a340c --- /dev/null +++ b/rosetta/file41.scala @@ -0,0 +1 @@ +object CF extends App { import Stream. _ val sqrt2 = 1 #:: from ( 2 , 0 ) zip from ( 1 , 0 ) val napier = 2 #:: from ( 1 ) zip ( 1 #:: from ( 1 ) ) val pi = 3 #:: from ( 6 , 0 ) zip ( from ( 1 , 2 ) map { x => x * x } )   // reference values, source: wikipedia val refPi = "3.14159265358979323846264338327950288419716939937510" val refNapier = "2.71828182845904523536028747135266249775724709369995" val refSQRT2 = "1.41421356237309504880168872420969807856967187537694"   def calc ( cf : Stream [ ( Int, Int ) ] , numberOfIters : Int = 200 ) : BigDecimal = { ( cf take numberOfIters toList ) . foldRight [ BigDecimal ] ( 1 ) ( ( a, z ) => a. _ 1+a. _ 2/z ) }   def approx ( cfV : BigDecimal, cfRefV : String ) : String = { val p : Pair [ Char,Char ] => Boolean = pair => ( pair. _ 1 == pair. _ 2 ) ( ( cfV. toString + " " * 34 ) . substring ( 0 , 34 ) zip cfRefV. toString . substring ( 0 , 34 ) ) . takeWhile ( p ) . foldRight [ String ] ( "" ) ( ( a : Pair [ Char,Char ] ,z ) => a. _ 1+z ) }   List ( ( "sqrt2" ,sqrt2, 50 ,refSQRT2 ) , ( "napier" ,napier, 50 ,refNapier ) , ( "pi" ,pi, 3000 ,refPi ) ) foreach { t => val ( name,cf,iters,refV ) = t val cfV = calc ( cf,iters ) println ( name+ ":" ) println ( "ref value: " +refV. substring ( 0 , 34 ) ) println ( "cf value: " + ( cfV. toString + " " * 34 ) . substring ( 0 , 34 ) ) println ( "precision: " +approx ( cfV,refV ) ) println ( ) } } \ No newline at end of file diff --git a/rosetta/file41.ss b/rosetta/file41.ss new file mode 100644 index 0000000..550367e --- /dev/null +++ b/rosetta/file41.ss @@ -0,0 +1 @@ +( define ( make - list length object ) ( if ( = length 0 ) ( list ) ( cons object ( make - list ( - length 1 ) object ) ) ) )   ( define ( list - fill ! list object ) ( if ( not ( null? list ) ) ( begin ( set - car ! list object ) ( list - fill ! ( cdr list ) object ) ) ) )   ( define ( list - set! list element object ) ( if ( = element 1 ) ( set - car ! list object ) ( list - set! ( cdr list ) ( - element 1 ) object ) ) )   ( define ( list - get list element ) ( if ( = element 1 ) ( car list ) ( list - get ( cdr list ) ( - element 1 ) ) ) ) \ No newline at end of file diff --git a/rosetta/file41.tcl b/rosetta/file41.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file41.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file42.clojure b/rosetta/file42.clojure new file mode 100644 index 0000000..97cb87d --- /dev/null +++ b/rosetta/file42.clojure @@ -0,0 +1 @@ +    ( defn draw - line "Draw a line from x1,y1 to x2,y2 using Bresenham's, to a java BufferedImage in the colour of pixel." [ buffer x1 y1 x2 y2 pixel ] ( let [ dist - x ( Math / abs ( - x1 x2 ) ) dist - y ( Math / abs ( - y1 y2 ) ) steep ( > dist - y dist - x ) ] ( let [ [ x1 y1 x2 y2 ] ( if steep [ y1 x1 y2 x2 ] [ x1 y1 x2 y2 ] ) ] ( let [ [ x1 y1 x2 y2 ] ( if ( > x1 x2 ) [ x2 y2 x1 y1 ] [ x1 y1 x2 y2 ] ) ] ( let [ delta - x ( - x2 x1 ) delta - y ( Math / abs ( - y1 y2 ) ) y - step ( if ( < y1 y2 ) 1 - 1 ) ]   ( let [ plot ( if steep # ( . setRGB buffer ( int % 1 ) ( int % 2 ) pixel ) # ( . setRGB buffer ( int % 2 ) ( int % 1 ) pixel ) ) ]   ( loop [ x x1 y y1 error ( Math / floor ( / delta - x 2 ) ) ] ( plot x y ) ( if ( < x x2 ) ; Rather then rebind error, test that it is less than delta-y rather than zero ( if ( < error delta - y ) ( recur ( inc x ) ( + y y - step ) ( + error ( - delta - x delta - y ) ) ) ( recur ( inc x ) y ( - error delta - y ) ) ) ) ) ) ) ) ) ) )   \ No newline at end of file diff --git a/rosetta/file42.hs b/rosetta/file42.hs new file mode 100644 index 0000000..73feba8 --- /dev/null +++ b/rosetta/file42.hs @@ -0,0 +1 @@ +module Main where   import Control . Monad import Data . List import Data . Monoid import Text . Printf   entropy :: ( Ord a ) => [ a ] -> Double entropy = sum . map ( \c -> ( c * ) . logBase 2 $ 1.0 / c ) . ( \cs -> let { sc = sum cs } in map ( / sc ) cs ) . map ( fromIntegral . length ) . group . sort   fibonacci :: ( Monoid m ) => m -> m -> [ m ] fibonacci a b = unfoldr ( \ ( a , b ) -> Just ( a , ( b , a <> b ) ) ) ( a , b )   main :: IO ( ) main = do printf "%2s %10s %17s %s \n " "N" "length" "entropy" "word" zipWithM _ ( \i v -> let { l = length v } in printf "%2d %10d %.15f %s \n " i l ( entropy v ) ( if l > 40 then "..." else v ) ) [ 1 .. 38 :: Int ] ( take 37 $ fibonacci "1" "0" ) \ No newline at end of file diff --git a/rosetta/file42.java b/rosetta/file42.java new file mode 100644 index 0000000..b2e8659 --- /dev/null +++ b/rosetta/file42.java @@ -0,0 +1 @@ +ClassWithStaticMethod. staticMethodName ( argument1, argument2 ) ; //for methods with no arguments, use empty parentheses \ No newline at end of file diff --git a/rosetta/file42.js b/rosetta/file42.js new file mode 100644 index 0000000..b128d77 --- /dev/null +++ b/rosetta/file42.js @@ -0,0 +1 @@ +var foo = function ( ) { return arguments. length } ; foo ( ) // 0 foo ( 1 , 2 , 3 ) // 3 \ No newline at end of file diff --git a/rosetta/file42.ocaml b/rosetta/file42.ocaml new file mode 100644 index 0000000..c775162 --- /dev/null +++ b/rosetta/file42.ocaml @@ -0,0 +1 @@ +let pi = 3 , fun n -> ( ( 2 * n - 1 ) * ( 2 * n - 1 ) , 6 ) and nap = 2 , fun n -> ( max 1 ( n - 1 ) , n ) and root2 = 1 , fun n -> ( 1 , 2 ) in   let eval ( i,f ) k = let rec frac n = let a, b = f n in float a /. ( float b +. if n >= k then 0.0 else frac ( n + 1 ) ) in float i +. frac 1 in   Printf . printf "sqrt(2)\t= %.15f\n" ( eval root2 1000 ) ; Printf . printf "e\t= %.15f\n" ( eval nap 1000 ) ; Printf . printf "pi\t= %.15f\n" ( eval pi 1000 ) ; \ No newline at end of file diff --git a/rosetta/file42.perl b/rosetta/file42.perl new file mode 100644 index 0000000..1a29ec0 --- /dev/null +++ b/rosetta/file42.perl @@ -0,0 +1 @@ +#!/usr/bin/perl   my $min = 1 ; my $max = 99 ; my $guess = int ( rand $max ) + $min ; my $tries = 0 ;   print "=>> Think of a number between $min and $max and I'll guess it! \n Press when are you ready... " ;   ;   { do {   $tries ++; print " \n =>> My guess is: $guess Is your number higher, lower, or equal? (h/l/e) \n > " ;   my $score = ;   if ( $max <= $min ) { print " \n I give up... \n " and last ; } elsif ( $score =~ /^h/i ) { $min = $guess + 1 ; } elsif ( $score =~ /^l/i ) { $max = $guess ; } elsif ( $score =~ /^e/i ) { print " \n I knew it! It took me only $tries tries. \n " and last ; } else { print "error: invalid score \n " ; }   $guess = int ( ( $max + $min ) / 2 ) ;   } while ( 1 ) ; } \ No newline at end of file diff --git a/rosetta/file42.php b/rosetta/file42.php new file mode 100644 index 0000000..3f43cd6 --- /dev/null +++ b/rosetta/file42.php @@ -0,0 +1 @@ + maxperimeter or cc > aa + bb: break if aa + bb == cc: trips. append ( ( a , b , c , gcd ( a , b ) == 1 ) ) return trips   def pytrip ( trip = ( 3 , 4 , 5 ) , perim = 100 , prim = 1 ) : a0 , b0 , c0 = a , b , c = sorted ( trip ) t , firstprim = set ( ) , prim > 0 while a + b + c <= perim: t. add ( ( a , b , c , firstprim > 0 ) ) a , b , c , firstprim = a+a0 , b+b0 , c+c0 , False # t2 = set ( ) for a , b , c , firstprim in t: a2 , a5 , b2 , b5 , c2 , c3 , c7 = a* 2 , a* 5 , b* 2 , b* 5 , c* 2 , c* 3 , c* 7 if a5 - b5 + c7 <= perim: t2 | = pytrip ( ( a - b2 + c2 , a2 - b + c2 , a2 - b2 + c3 ) , perim , firstprim ) if a5 + b5 + c7 <= perim: t2 | = pytrip ( ( a + b2 + c2 , a2 + b + c2 , a2 + b2 + c3 ) , perim , firstprim ) if -a5 + b5 + c7 <= perim: t2 | = pytrip ( ( -a + b2 + c2 , -a2 + b + c2 , -a2 + b2 + c3 ) , perim , firstprim ) return t | t2   def pt2 ( maxperimeter = 100 ) : ''' # Parent/child relationship method: # http://en.wikipedia.org/wiki/Formulas_for_generating_Pythagorean_triples#XI. ''' trips = pytrip ( ( 3 , 4 , 5 ) , maxperimeter , 1 ) return trips   def printit ( maxperimeter = 100 , pt = pt1 ) : trips = pt ( maxperimeter ) print ( " Up to a perimeter of %i there are %i triples, of which %i are primitive"  % ( maxperimeter , len ( trips ) , len ( [ prim for a , b , c , prim in trips if prim ] ) ) )   for algo , mn , mx in ( ( pt1 , 250 , 2500 ) , ( pt2 , 500 , 20000 ) ) : print ( algo.__doc__ ) for maxperimeter in range ( mn , mx+ 1 , mn ) : printit ( maxperimeter , algo )   \ No newline at end of file diff --git a/rosetta/file42.rb b/rosetta/file42.rb new file mode 100644 index 0000000..7917cc0 --- /dev/null +++ b/rosetta/file42.rb @@ -0,0 +1 @@ +KnapsackItem = Struct . new ( :name , :weight , :value ) potential_items = [ KnapsackItem [ 'map' , 9 , 150 ] , KnapsackItem [ 'compass' , 13 , 35 ] , KnapsackItem [ 'water' , 153 , 200 ] , KnapsackItem [ 'sandwich' , 50 , 160 ] , KnapsackItem [ 'glucose' , 15 , 60 ] , KnapsackItem [ 'tin' , 68 , 45 ] , KnapsackItem [ 'banana' , 27 , 60 ] , KnapsackItem [ 'apple' , 39 , 40 ] , KnapsackItem [ 'cheese' , 23 , 30 ] , KnapsackItem [ 'beer' , 52 , 10 ] , KnapsackItem [ 'suntan cream' , 11 , 70 ] , KnapsackItem [ 'camera' , 32 , 30 ] , KnapsackItem [ 't-shirt' , 24 , 15 ] , KnapsackItem [ 'trousers' , 48 , 10 ] , KnapsackItem [ 'umbrella' , 73 , 40 ] , KnapsackItem [ 'waterproof trousers' , 42 , 70 ] , KnapsackItem [ 'waterproof overclothes' , 43 , 75 ] , KnapsackItem [ 'note-case' , 22 , 80 ] , KnapsackItem [ 'sunglasses' , 7 , 20 ] , KnapsackItem [ 'towel' , 18 , 12 ] , KnapsackItem [ 'socks' , 4 , 50 ] , KnapsackItem [ 'book' , 30 , 10 ] , ] knapsack_capacity = 400   class Array # do something for each element of the array's power set def power_set yield [ ] if block_given? self . inject ( [ [ ] ] ) do | ps, elem | ps. each_with_object ( [ ] ) do | i,r | r << i new_subset = i + [ elem ] yield new_subset if block_given? r << new_subset end end end end   maxval, solutions = potential_items. power_set . group_by { | subset | weight = subset. inject ( 0 ) { | w, elem | w + elem. weight } weight > knapsack_capacity ? 0  : subset. inject ( 0 ) { | v, elem | v + elem. value } } . max   puts "value: #{maxval}" solutions. each do | set | wt, items = 0 , [ ] set. each { | elem | wt + = elem. weight ; items << elem. name } puts "weight: #{wt}" puts "items: #{items.join(',')}" end \ No newline at end of file diff --git a/rosetta/file42.scala b/rosetta/file42.scala new file mode 100644 index 0000000..d4a340c --- /dev/null +++ b/rosetta/file42.scala @@ -0,0 +1 @@ +object CF extends App { import Stream. _ val sqrt2 = 1 #:: from ( 2 , 0 ) zip from ( 1 , 0 ) val napier = 2 #:: from ( 1 ) zip ( 1 #:: from ( 1 ) ) val pi = 3 #:: from ( 6 , 0 ) zip ( from ( 1 , 2 ) map { x => x * x } )   // reference values, source: wikipedia val refPi = "3.14159265358979323846264338327950288419716939937510" val refNapier = "2.71828182845904523536028747135266249775724709369995" val refSQRT2 = "1.41421356237309504880168872420969807856967187537694"   def calc ( cf : Stream [ ( Int, Int ) ] , numberOfIters : Int = 200 ) : BigDecimal = { ( cf take numberOfIters toList ) . foldRight [ BigDecimal ] ( 1 ) ( ( a, z ) => a. _ 1+a. _ 2/z ) }   def approx ( cfV : BigDecimal, cfRefV : String ) : String = { val p : Pair [ Char,Char ] => Boolean = pair => ( pair. _ 1 == pair. _ 2 ) ( ( cfV. toString + " " * 34 ) . substring ( 0 , 34 ) zip cfRefV. toString . substring ( 0 , 34 ) ) . takeWhile ( p ) . foldRight [ String ] ( "" ) ( ( a : Pair [ Char,Char ] ,z ) => a. _ 1+z ) }   List ( ( "sqrt2" ,sqrt2, 50 ,refSQRT2 ) , ( "napier" ,napier, 50 ,refNapier ) , ( "pi" ,pi, 3000 ,refPi ) ) foreach { t => val ( name,cf,iters,refV ) = t val cfV = calc ( cf,iters ) println ( name+ ":" ) println ( "ref value: " +refV. substring ( 0 , 34 ) ) println ( "cf value: " + ( cfV. toString + " " * 34 ) . substring ( 0 , 34 ) ) println ( "precision: " +approx ( cfV,refV ) ) println ( ) } } \ No newline at end of file diff --git a/rosetta/file42.ss b/rosetta/file42.ss new file mode 100644 index 0000000..b6042d7 --- /dev/null +++ b/rosetta/file42.ss @@ -0,0 +1 @@ +( define ( write - ppm image file ) ( define ( write - image image ) ( define ( write - row row ) ( define ( write - colour colour ) ( if ( not ( null? colour ) ) ( begin ( write-char ( integer -> char ( car colour ) ) ) ( write - colour ( cdr colour ) ) ) ) ) ( if ( not ( null? row ) ) ( begin ( write - colour ( car row ) ) ( write - row ( cdr row ) ) ) ) ) ( if ( not ( null? image ) ) ( begin ( write - row ( car image ) ) ( write - image ( cdr image ) ) ) ) ) ( with-output-to-file file ( lambda ( ) ( begin ( display "P6" ) ( newline ) ( display ( length ( car image ) ) ) ( display " " ) ( display ( length image ) ) ( newline ) ( display 255 ) ( newline ) ( write - image image ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file42.tcl b/rosetta/file42.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file42.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file43.clojure b/rosetta/file43.clojure new file mode 100644 index 0000000..97cb87d --- /dev/null +++ b/rosetta/file43.clojure @@ -0,0 +1 @@ +    ( defn draw - line "Draw a line from x1,y1 to x2,y2 using Bresenham's, to a java BufferedImage in the colour of pixel." [ buffer x1 y1 x2 y2 pixel ] ( let [ dist - x ( Math / abs ( - x1 x2 ) ) dist - y ( Math / abs ( - y1 y2 ) ) steep ( > dist - y dist - x ) ] ( let [ [ x1 y1 x2 y2 ] ( if steep [ y1 x1 y2 x2 ] [ x1 y1 x2 y2 ] ) ] ( let [ [ x1 y1 x2 y2 ] ( if ( > x1 x2 ) [ x2 y2 x1 y1 ] [ x1 y1 x2 y2 ] ) ] ( let [ delta - x ( - x2 x1 ) delta - y ( Math / abs ( - y1 y2 ) ) y - step ( if ( < y1 y2 ) 1 - 1 ) ]   ( let [ plot ( if steep # ( . setRGB buffer ( int % 1 ) ( int % 2 ) pixel ) # ( . setRGB buffer ( int % 2 ) ( int % 1 ) pixel ) ) ]   ( loop [ x x1 y y1 error ( Math / floor ( / delta - x 2 ) ) ] ( plot x y ) ( if ( < x x2 ) ; Rather then rebind error, test that it is less than delta-y rather than zero ( if ( < error delta - y ) ( recur ( inc x ) ( + y y - step ) ( + error ( - delta - x delta - y ) ) ) ( recur ( inc x ) y ( - error delta - y ) ) ) ) ) ) ) ) ) ) )   \ No newline at end of file diff --git a/rosetta/file43.hs b/rosetta/file43.hs new file mode 100644 index 0000000..21e8a8c --- /dev/null +++ b/rosetta/file43.hs @@ -0,0 +1 @@ +primesTo100 = [ 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 ]   -- (eq. to) find2km (2^k * n) = (k,n) find2km :: Integral a => a -> ( Int , a ) find2km n = f 0 n where f k m | r == 1 = ( k , m ) | otherwise = f ( k + 1 ) q where ( q , r ) = quotRem m 2   -- n is the number to test; a is the (presumably randomly chosen) witness millerRabinPrimality :: Integer -> Integer -> Bool millerRabinPrimality n a | a >= n _ = True | b0 == 1 || b0 == n _ = True | otherwise = iter ( tail b ) where n _ = n - 1 ( k , m ) = find2km n _ b0 = powMod n a m b = take k $ iterate ( squareMod n ) b0 iter [ ] = False iter ( x:xs ) | x == 1 = False | x == n _ = True | otherwise = iter xs   -- (eq. to) pow_ (*) (^2) n k = n^k pow _ :: ( Num a , Integral b ) => ( a -> a -> a ) -> ( a -> a ) -> a -> b -> a pow _ _ _ _ 0 = 1 pow _ mul sq x _ n _ = f x _ n _ 1 where f x n y | n == 1 = x `mul` y | r == 0 = f x2 q y | otherwise = f x2 q ( x `mul` y ) where ( q , r ) = quotRem n 2 x2 = sq x   mulMod :: Integral a => a -> a -> a -> a mulMod a b c = ( b * c ) ` mod ` a squareMod :: Integral a => a -> a -> a squareMod a b = ( b * b ) ` rem ` a   -- (eq. to) powMod m n k = n^k `mod` m powMod :: Integral a => a -> a -> a -> a powMod m = pow _ ( mulMod m ) ( squareMod m )   -- Caller supplies a witness list w, which may be used for MR test. -- Use faster trial division against a small primes list first, to -- weed out more obvious composites. is _ prime w n | n < 100 = n ` elem ` primesTo100 | any ( ( == 0 ) . ( n` mod ` ) ) primesTo100 = False | otherwise = all ( millerRabinPrimality n ) w   -- final result gets a more thorough Miller-Rabin left _ trunc base = head $ filter ( is _ prime primesTo100 ) ( reverse hopeful ) where hopeful = extend base $ takeWhile ( < base ) primesTo100 where extend b x = if null d then x else extend ( b * base ) d where d = concatMap addDigit [ 1 .. base - 1 ] -- we do *one* prime test, which seems good enough in practice addDigit a = filter ( is _ prime [ 3 ] ) $ map ( a * b + ) x   main = mapM_ print $ map ( \x -> ( x , left _ trunc x ) ) [ 3 .. 21 ] \ No newline at end of file diff --git a/rosetta/file43.java b/rosetta/file43.java new file mode 100644 index 0000000..b2e8659 --- /dev/null +++ b/rosetta/file43.java @@ -0,0 +1 @@ +ClassWithStaticMethod. staticMethodName ( argument1, argument2 ) ; //for methods with no arguments, use empty parentheses \ No newline at end of file diff --git a/rosetta/file43.js b/rosetta/file43.js new file mode 100644 index 0000000..c8cedb4 --- /dev/null +++ b/rosetta/file43.js @@ -0,0 +1 @@ +var dog = "Benjamin" ; var Dog = "Samba" ; var DOG = "Bernie" ; document. write ( "The three dogs are named " + dog + ", " + Dog + ", and " + DOG + "." ) ; \ No newline at end of file diff --git a/rosetta/file43.ocaml b/rosetta/file43.ocaml new file mode 100644 index 0000000..95c78d4 --- /dev/null +++ b/rosetta/file43.ocaml @@ -0,0 +1 @@ +# let oc = open_out "output.txt" in close_out oc ;; - : unit = ( )   # Unix . mkdir "docs" 0o750 ;; (* rights 0o750 for rwxr-x--- *) - : unit = ( ) \ No newline at end of file diff --git a/rosetta/file43.perl b/rosetta/file43.perl new file mode 100644 index 0000000..f4e1e92 --- /dev/null +++ b/rosetta/file43.perl @@ -0,0 +1 @@ +use Data :: Dumper qw ( Dumper ) ;   sub hashJoin { my ( $table1 , $index1 , $table2 , $index2 ) = @_ ; my %h ; # hash phase foreach my $s ( @$table1 ) { push @ { $h { $s -> [ $index1 ] } } , $s ; } # join phase map { my $r = $_ ; map [ $_ , $r ] , @ { $h { $r -> [ $index2 ] } } } @$table2 ; }   @table1 = ( [ 27 , "Jonah" ] , [ 18 , "Alan" ] , [ 28 , "Glory" ] , [ 18 , "Popeye" ] , [ 28 , "Alan" ] ) ; @table2 = ( [ "Jonah" , "Whales" ] , [ "Jonah" , "Spiders" ] , [ "Alan" , "Ghosts" ] , [ "Alan" , "Zombies" ] , [ "Glory" , "Buffy" ] ) ;   $Data :: Dumper :: Indent = 0 ; foreach my $row ( hashJoin ( \@table1 , 1 , \@table2 , 0 ) ) { print Dumper ( $row ) , " \n " ; } \ No newline at end of file diff --git a/rosetta/file43.php b/rosetta/file43.php new file mode 100644 index 0000000..7cbfd9d --- /dev/null +++ b/rosetta/file43.php @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/rosetta/file43.py b/rosetta/file43.py new file mode 100644 index 0000000..6234c1c --- /dev/null +++ b/rosetta/file43.py @@ -0,0 +1 @@ +import random rand = random . SystemRandom ( ) rand. randint ( 1 , 10 ) \ No newline at end of file diff --git a/rosetta/file43.rb b/rosetta/file43.rb new file mode 100644 index 0000000..070ab11 --- /dev/null +++ b/rosetta/file43.rb @@ -0,0 +1 @@ +# Compress a string to a list of output symbols. def compress ( uncompressed ) # Build the dictionary. dict_size = 256 dictionary = Hash [ Array . new ( dict_size ) { | i | [ i. chr , i. chr ] } ]   w = "" result = [ ] for c in uncompressed. split ( '' ) wc = w + c if dictionary. has_key ? ( wc ) w = wc else result << dictionary [ w ] # Add wc to the dictionary. dictionary [ wc ] = dict_size dict_size + = 1 w = c end end   # Output the code for w. result << dictionary [ w ] unless w. empty ? result end   # Decompress a list of output ks to a string. def decompress ( compressed ) # Build the dictionary. dict_size = 256 dictionary = Hash [ Array . new ( dict_size ) { | i | [ i. chr , i. chr ] } ]   w = result = compressed. shift for k in compressed if dictionary. has_key ? ( k ) entry = dictionary [ k ] elsif k == dict_size entry = w + w [ 0 , 1 ] else raise 'Bad compressed k: %s' % k end result + = entry   # Add w+entry[0] to the dictionary. dictionary [ dict_size ] = w + entry [ 0 , 1 ] dict_size + = 1   w = entry end result end   # How to use: compressed = compress ( 'TOBEORNOTTOBEORTOBEORNOT' ) p compressed decompressed = decompress ( compressed ) puts decompressed \ No newline at end of file diff --git a/rosetta/file43.scala b/rosetta/file43.scala new file mode 100644 index 0000000..d4a340c --- /dev/null +++ b/rosetta/file43.scala @@ -0,0 +1 @@ +object CF extends App { import Stream. _ val sqrt2 = 1 #:: from ( 2 , 0 ) zip from ( 1 , 0 ) val napier = 2 #:: from ( 1 ) zip ( 1 #:: from ( 1 ) ) val pi = 3 #:: from ( 6 , 0 ) zip ( from ( 1 , 2 ) map { x => x * x } )   // reference values, source: wikipedia val refPi = "3.14159265358979323846264338327950288419716939937510" val refNapier = "2.71828182845904523536028747135266249775724709369995" val refSQRT2 = "1.41421356237309504880168872420969807856967187537694"   def calc ( cf : Stream [ ( Int, Int ) ] , numberOfIters : Int = 200 ) : BigDecimal = { ( cf take numberOfIters toList ) . foldRight [ BigDecimal ] ( 1 ) ( ( a, z ) => a. _ 1+a. _ 2/z ) }   def approx ( cfV : BigDecimal, cfRefV : String ) : String = { val p : Pair [ Char,Char ] => Boolean = pair => ( pair. _ 1 == pair. _ 2 ) ( ( cfV. toString + " " * 34 ) . substring ( 0 , 34 ) zip cfRefV. toString . substring ( 0 , 34 ) ) . takeWhile ( p ) . foldRight [ String ] ( "" ) ( ( a : Pair [ Char,Char ] ,z ) => a. _ 1+z ) }   List ( ( "sqrt2" ,sqrt2, 50 ,refSQRT2 ) , ( "napier" ,napier, 50 ,refNapier ) , ( "pi" ,pi, 3000 ,refPi ) ) foreach { t => val ( name,cf,iters,refV ) = t val cfV = calc ( cf,iters ) println ( name+ ":" ) println ( "ref value: " +refV. substring ( 0 , 34 ) ) println ( "cf value: " + ( cfV. toString + " " * 34 ) . substring ( 0 , 34 ) ) println ( "precision: " +approx ( cfV,refV ) ) println ( ) } } \ No newline at end of file diff --git a/rosetta/file43.ss b/rosetta/file43.ss new file mode 100644 index 0000000..251bf4e --- /dev/null +++ b/rosetta/file43.ss @@ -0,0 +1 @@ +( import ( rnrs arithmetic bitwise ( 6 ) ) )   ( define ( bitwise a b ) ( display ( bitwise - and a b ) ) ( newline ) ( display ( bitwise - ior a b ) ) ( newline ) ( display ( bitwise - xor a b ) ) ( newline ) ( display ( bitwise - not a ) ) ( newline ) ( display ( bitwise - arithmetic - shift - right a b ) ) ( newline ) )   ( bitwise 255 5 ) \ No newline at end of file diff --git a/rosetta/file43.tcl b/rosetta/file43.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file43.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file44.clojure b/rosetta/file44.clojure new file mode 100644 index 0000000..3267562 --- /dev/null +++ b/rosetta/file44.clojure @@ -0,0 +1 @@ +  ( ns a ) ( def ^ : private priv : secret )   ; From REPL, in another namespace 'user': user => @a / priv ; fails with: IllegalStateException: var: a/priv is not public user => @#'a / priv ; succeeds : secret   \ No newline at end of file diff --git a/rosetta/file44.hs b/rosetta/file44.hs new file mode 100644 index 0000000..21e8a8c --- /dev/null +++ b/rosetta/file44.hs @@ -0,0 +1 @@ +primesTo100 = [ 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 ]   -- (eq. to) find2km (2^k * n) = (k,n) find2km :: Integral a => a -> ( Int , a ) find2km n = f 0 n where f k m | r == 1 = ( k , m ) | otherwise = f ( k + 1 ) q where ( q , r ) = quotRem m 2   -- n is the number to test; a is the (presumably randomly chosen) witness millerRabinPrimality :: Integer -> Integer -> Bool millerRabinPrimality n a | a >= n _ = True | b0 == 1 || b0 == n _ = True | otherwise = iter ( tail b ) where n _ = n - 1 ( k , m ) = find2km n _ b0 = powMod n a m b = take k $ iterate ( squareMod n ) b0 iter [ ] = False iter ( x:xs ) | x == 1 = False | x == n _ = True | otherwise = iter xs   -- (eq. to) pow_ (*) (^2) n k = n^k pow _ :: ( Num a , Integral b ) => ( a -> a -> a ) -> ( a -> a ) -> a -> b -> a pow _ _ _ _ 0 = 1 pow _ mul sq x _ n _ = f x _ n _ 1 where f x n y | n == 1 = x `mul` y | r == 0 = f x2 q y | otherwise = f x2 q ( x `mul` y ) where ( q , r ) = quotRem n 2 x2 = sq x   mulMod :: Integral a => a -> a -> a -> a mulMod a b c = ( b * c ) ` mod ` a squareMod :: Integral a => a -> a -> a squareMod a b = ( b * b ) ` rem ` a   -- (eq. to) powMod m n k = n^k `mod` m powMod :: Integral a => a -> a -> a -> a powMod m = pow _ ( mulMod m ) ( squareMod m )   -- Caller supplies a witness list w, which may be used for MR test. -- Use faster trial division against a small primes list first, to -- weed out more obvious composites. is _ prime w n | n < 100 = n ` elem ` primesTo100 | any ( ( == 0 ) . ( n` mod ` ) ) primesTo100 = False | otherwise = all ( millerRabinPrimality n ) w   -- final result gets a more thorough Miller-Rabin left _ trunc base = head $ filter ( is _ prime primesTo100 ) ( reverse hopeful ) where hopeful = extend base $ takeWhile ( < base ) primesTo100 where extend b x = if null d then x else extend ( b * base ) d where d = concatMap addDigit [ 1 .. base - 1 ] -- we do *one* prime test, which seems good enough in practice addDigit a = filter ( is _ prime [ 3 ] ) $ map ( a * b + ) x   main = mapM_ print $ map ( \x -> ( x , left _ trunc x ) ) [ 3 .. 21 ] \ No newline at end of file diff --git a/rosetta/file44.java b/rosetta/file44.java new file mode 100644 index 0000000..cd3af7b --- /dev/null +++ b/rosetta/file44.java @@ -0,0 +1 @@ +String dog = "Benjamin" ; String Dog = "Samba" ; //in general, identifiers that start with capital letters are class names String DOG = "Bernie" ; //in general, identifiers in all caps are constants //the conventions listed in comments here are not enforced by the language System . out . println ( "There are three dogs named " + dog + ", " + Dog + ", and " + DOG + "'" ) ; \ No newline at end of file diff --git a/rosetta/file44.js b/rosetta/file44.js new file mode 100644 index 0000000..f2d20b7 --- /dev/null +++ b/rosetta/file44.js @@ -0,0 +1 @@ +< html >< head >< title > Catalan < body >< pre id = 'x' >< script type = "application/javascript" > function disp ( x ) { var e = document. createTextNode ( x + ' \n ' ) ; document. getElementById ( 'x' ) . appendChild ( e ) ; }   var fc = [ ] , c2 = [ ] , c3 = [ ] ; function fact ( n ) { return fc [ n ] ? fc [ n ] : fc [ n ] = ( n ? n * fact ( n - 1 ) : 1 ) ; } function cata1 ( n ) { return Math . floor ( fact ( 2 * n ) / fact ( n + 1 ) / fact ( n ) + .5 ) ; } function cata2 ( n ) { if ( n == 0 ) return 1 ; if ( ! c2 [ n ] ) { var s = 0 ; for ( var i = 0 ; i < n ; i ++ ) s += cata2 ( i ) * cata2 ( n - i - 1 ) ; c2 [ n ] = s ; } return c2 [ n ] ; } function cata3 ( n ) { if ( n == 0 ) return 1 ; return c3 [ n ] ? c3 [ n ] : c3 [ n ] = ( 4 * n - 2 ) * cata3 ( n - 1 ) / ( n + 1 ) ; }   disp ( " meth1 meth2 meth3" ) ; for ( var i = 0 ; i <= 15 ; i ++ ) disp ( i + ' \t ' + cata1 ( i ) + ' \t ' + cata2 ( i ) + ' \t ' + cata3 ( i ) ) ;   \ No newline at end of file diff --git a/rosetta/file44.ocaml b/rosetta/file44.ocaml new file mode 100644 index 0000000..760e31d --- /dev/null +++ b/rosetta/file44.ocaml @@ -0,0 +1 @@ +let ( ) = let buf = Buffer . create 1 in let s = Buffer . add_string buf in Random . self_init ( ) ; s "" ; s "" ; s "" ; List . iter ( fun v -> s ( "" ) ) [ "X" ; "Y" ; "Z" ] ; s "" ; s "" ; s "" ; for i = 0 to pred 3 do s ( "" ) ; for j = 0 to pred 3 do s ( "" ) ; done ; s "" ; done ; s "" ; s "
" ^ v ^ "
" ^ string_of_int i ^ "" ^ string_of_int ( Random . int 1000 ) ^ "
" ; print_endline ( Buffer . contents buf ) \ No newline at end of file diff --git a/rosetta/file44.perl b/rosetta/file44.perl new file mode 100644 index 0000000..967b004 --- /dev/null +++ b/rosetta/file44.perl @@ -0,0 +1 @@ +#!/usr/bin/perl use warnings ; use strict ;   use Tk ; use List :: Util qw ( shuffle ) ;     sub altitude { sqrt ( 3 / 4 ) * shift ; }     sub polygon_coordinates { my ( $x , $y , $size ) = @_ ; my $alt = altitude ( $size ) ; return ( $x - $size , $y , $x - ( $size / 2 ) , $y - $alt , $x + ( $size / 2 ) , $y - $alt , $x + $size , $y , $x + ( $size / 2 ) , $y + $alt , $x - ( $size / 2 ) , $y + $alt , ) ; }     { my %changed ; sub change { my ( $canvas , $id , $letter_id ) = @_ ; return sub { $canvas -> itemconfigure ( $id , - fill => 'magenta' ) ; $canvas -> itemconfigure ( $letter_id , - fill => 'black' ) ; undef $changed { $id } ;   if ( 20 == keys %changed ) { print "All letters pressed. \n " ; # Simple exit causes a "Font still in cache" segfault # when the last letter is changed with a mouse button. $canvas -> MainWindow -> after ( 10 , sub { exit } ) ; } } } }     { my @letters = ( shuffle ( 'A' .. 'Z' ) ) [ 1 .. 20 ] ; sub comb { my ( $canvas , $fromx , $fromy , $size , $count ) = @_ ; for ( my $x = $fromx ; $x < 3 * $count * $size ; $x += 3 * $size ) { for ( my $y = $fromy ; $y < 7.5 * $size ; $y += 2 * altitude ( $size ) ) { my $id = $canvas -> createPolygon ( polygon_coordinates ( $x , $y , $size ) , - outline => 'black' , - fill => 'yellow' , - width => 2 , ) ; my $letter = shift @letters ; my $letter_id = $canvas -> createText ( $x , $y , - fill => 'red' , - text => $letter , - font => "{sans} " . ( $size * 0.9 ) , ) ; $canvas -> MainWindow -> bind ( 'all' , lc $letter , change ( $canvas , $id , $letter_id ) ) ; $canvas -> bind ( $_ , '' , change ( $canvas , $id , $letter_id ) ) for $id , $letter_id ; } } } }     my $size = 36 ;   my $mw = 'MainWindow' -> new ( - title => "Honeycombs" ) ; my $canvas = $mw -> Canvas ( - width => 8 * $size , - height => 8 * $size , ) -> pack ;   comb ( $canvas , $size , $size , $size , 3 ) ; comb ( $canvas , $size * 2.5 , $size + altitude ( $size ) , $size , 2 ) ;     my $btn = $mw -> Button ( - text => 'Quit' , - underline => 0 , - command => sub { exit } , ) -> pack ; $mw -> bind ( '' , sub { $btn -> invoke } ) ; MainLoop ( ) ; \ No newline at end of file diff --git a/rosetta/file44.php b/rosetta/file44.php new file mode 100644 index 0000000..6c57158 --- /dev/null +++ b/rosetta/file44.php @@ -0,0 +1 @@ += $ascii_a && $char <= $ascii_z ) { $char = ( ( $key + $char - $ascii_a ) % 26 ) + $ascii_a ; } $plaintext = substr ( $plaintext , 1 ) ; $ciphertext .= chr ( $char ) ; } return $ciphertext ; }   echo caesarEncode ( "The quick brown fox Jumped over the lazy Dog" , 12 ) , " \n " ; ?> \ No newline at end of file diff --git a/rosetta/file44.py b/rosetta/file44.py new file mode 100644 index 0000000..3fdc587 --- /dev/null +++ b/rosetta/file44.py @@ -0,0 +1 @@ +from collections import namedtuple from pprint import pprint as pp import sys   Pt = namedtuple ( 'Pt' , 'x, y' ) # Point Edge = namedtuple ( 'Edge' , 'a, b' ) # Polygon edge from a to b Poly = namedtuple ( 'Poly' , 'name, edges' ) # Polygon   _eps = 0.00001 _huge = sys . float_info . max _tiny = sys . float_info . min   def rayintersectseg ( p , edge ) : ''' takes a point p=Pt() and an edge of two endpoints a,b=Pt() of a line segment returns boolean ''' a , b = edge if a. y > b. y : a , b = b , a if p. y == a. y or p. y == b. y : p = Pt ( p. x , p. y + _eps )   intersect = False   if ( p. y > b. y or p. y < a. y ) or ( p. x > max ( a. x , b. x ) ) : return False   if p. x < min ( a. x , b. x ) : intersect = True else : if abs ( a. x - b. x ) > _tiny: m_red = ( b. y - a. y ) / float ( b. x - a. x ) else : m_red = _huge if abs ( a. x - p. x ) > _tiny: m_blue = ( p. y - a. y ) / float ( p. x - a. x ) else : m_blue = _huge intersect = m_blue >= m_red return intersect   def _odd ( x ) : return x% 2 == 1   def ispointinside ( p , poly ) : ln = len ( poly ) return _odd ( sum ( rayintersectseg ( p , edge ) for edge in poly. edges ) )   def polypp ( poly ) : print " \n Polygon(name='%s', edges=("  % poly. name print ' ' , ', \n ' . join ( str ( e ) for e in poly. edges ) + ' \n ))'   if __name__ == '__main__' : polys = [ Poly ( name = 'square' , edges = ( Edge ( a = Pt ( x = 0 , y = 0 ) , b = Pt ( x = 10 , y = 0 ) ) , Edge ( a = Pt ( x = 10 , y = 0 ) , b = Pt ( x = 10 , y = 10 ) ) , Edge ( a = Pt ( x = 10 , y = 10 ) , b = Pt ( x = 0 , y = 10 ) ) , Edge ( a = Pt ( x = 0 , y = 10 ) , b = Pt ( x = 0 , y = 0 ) ) ) ) , Poly ( name = 'square_hole' , edges = ( Edge ( a = Pt ( x = 0 , y = 0 ) , b = Pt ( x = 10 , y = 0 ) ) , Edge ( a = Pt ( x = 10 , y = 0 ) , b = Pt ( x = 10 , y = 10 ) ) , Edge ( a = Pt ( x = 10 , y = 10 ) , b = Pt ( x = 0 , y = 10 ) ) , Edge ( a = Pt ( x = 0 , y = 10 ) , b = Pt ( x = 0 , y = 0 ) ) , Edge ( a = Pt ( x = 2.5 , y = 2.5 ) , b = Pt ( x = 7.5 , y = 2.5 ) ) , Edge ( a = Pt ( x = 7.5 , y = 2.5 ) , b = Pt ( x = 7.5 , y = 7.5 ) ) , Edge ( a = Pt ( x = 7.5 , y = 7.5 ) , b = Pt ( x = 2.5 , y = 7.5 ) ) , Edge ( a = Pt ( x = 2.5 , y = 7.5 ) , b = Pt ( x = 2.5 , y = 2.5 ) ) ) ) , Poly ( name = 'strange' , edges = ( Edge ( a = Pt ( x = 0 , y = 0 ) , b = Pt ( x = 2.5 , y = 2.5 ) ) , Edge ( a = Pt ( x = 2.5 , y = 2.5 ) , b = Pt ( x = 0 , y = 10 ) ) , Edge ( a = Pt ( x = 0 , y = 10 ) , b = Pt ( x = 2.5 , y = 7.5 ) ) , Edge ( a = Pt ( x = 2.5 , y = 7.5 ) , b = Pt ( x = 7.5 , y = 7.5 ) ) , Edge ( a = Pt ( x = 7.5 , y = 7.5 ) , b = Pt ( x = 10 , y = 10 ) ) , Edge ( a = Pt ( x = 10 , y = 10 ) , b = Pt ( x = 10 , y = 0 ) ) , Edge ( a = Pt ( x = 10 , y = 0 ) , b = Pt ( x = 2.5 , y = 2.5 ) ) ) ) , Poly ( name = 'exagon' , edges = ( Edge ( a = Pt ( x = 3 , y = 0 ) , b = Pt ( x = 7 , y = 0 ) ) , Edge ( a = Pt ( x = 7 , y = 0 ) , b = Pt ( x = 10 , y = 5 ) ) , Edge ( a = Pt ( x = 10 , y = 5 ) , b = Pt ( x = 7 , y = 10 ) ) , Edge ( a = Pt ( x = 7 , y = 10 ) , b = Pt ( x = 3 , y = 10 ) ) , Edge ( a = Pt ( x = 3 , y = 10 ) , b = Pt ( x = 0 , y = 5 ) ) , Edge ( a = Pt ( x = 0 , y = 5 ) , b = Pt ( x = 3 , y = 0 ) ) ) ) , ] testpoints = ( Pt ( x = 5 , y = 5 ) , Pt ( x = 5 , y = 8 ) , Pt ( x = - 10 , y = 5 ) , Pt ( x = 0 , y = 5 ) , Pt ( x = 10 , y = 5 ) , Pt ( x = 8 , y = 5 ) , Pt ( x = 10 , y = 10 ) )   print " \n TESTING WHETHER POINTS ARE WITHIN POLYGONS" for poly in polys: polypp ( poly ) print ' ' , ' \t ' . join ( "%s: %s"  % ( p , ispointinside ( p , poly ) ) for p in testpoints [ : 3 ] ) print ' ' , ' \t ' . join ( "%s: %s"  % ( p , ispointinside ( p , poly ) ) for p in testpoints [ 3 : 6 ] ) print ' ' , ' \t ' . join ( "%s: %s"  % ( p , ispointinside ( p , poly ) ) for p in testpoints [ 6 : ] ) \ No newline at end of file diff --git a/rosetta/file44.rb b/rosetta/file44.rb new file mode 100644 index 0000000..166b77f --- /dev/null +++ b/rosetta/file44.rb @@ -0,0 +1 @@ +def odd_magic_square ( n ) raise ArgumentError "Need odd positive number" if n. even ? || n < = 0 n. times . map { | i | n. times . map { | j | n * ( ( i + j + 1 + n / 2 ) % n ) + ( ( i + 2 * j - 5 ) % n ) + 1 } } end   [ 3 , 5 , 9 ] . each do | n | puts " \n Size #{n}, magic sum #{(n*n+1)/2*n}" fmt = "%#{(n*n).to_s.size + 1}d" * n odd_magic_square ( n ) . each { | row | puts fmt % row } end   \ No newline at end of file diff --git a/rosetta/file44.scala b/rosetta/file44.scala new file mode 100644 index 0000000..ad0e2d2 --- /dev/null +++ b/rosetta/file44.scala @@ -0,0 +1 @@ +object TableGenerator extends App { val data = List ( List ( "X" , "Y" , "Z" ) , List ( 11 , 12 , 13 ) , List ( 12 , 22 , 23 ) , List ( 13 , 32 , 33 ) )   def generateTable ( data : List [ List [ Any ] ] ) = { < table > { data. zipWithIndex . map { case ( row, rownum ) => ( if ( rownum == 0 ) Nil else rownum ) + : row } . map ( row => < tr > { row. map ( cell => < td > { cell } < /td > ) } < /tr > ) } < /table > }   println ( generateTable ( data ) ) } \ No newline at end of file diff --git a/rosetta/file44.ss b/rosetta/file44.ss new file mode 100644 index 0000000..251bf4e --- /dev/null +++ b/rosetta/file44.ss @@ -0,0 +1 @@ +( import ( rnrs arithmetic bitwise ( 6 ) ) )   ( define ( bitwise a b ) ( display ( bitwise - and a b ) ) ( newline ) ( display ( bitwise - ior a b ) ) ( newline ) ( display ( bitwise - xor a b ) ) ( newline ) ( display ( bitwise - not a ) ) ( newline ) ( display ( bitwise - arithmetic - shift - right a b ) ) ( newline ) )   ( bitwise 255 5 ) \ No newline at end of file diff --git a/rosetta/file44.tcl b/rosetta/file44.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file44.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file45.clojure b/rosetta/file45.clojure new file mode 100644 index 0000000..1529e3f --- /dev/null +++ b/rosetta/file45.clojure @@ -0,0 +1 @@ +  ( ns bulls - and - cows )   ( defn bulls [ guess solution ] ( count ( filter true? ( map = guess solution ) ) ) )   ( defn cows [ guess solution ] ( - ( count ( filter ( set solution ) guess ) ) ( bulls guess solution ) ) )   ( defn valid - input? "checks whether the string is a 4 digit number with unique digits" [ user - input ] ( if ( re-seq # "^(?!.*( \d ).* \1 ) \d {4}$" user - input ) true false ) )   ( defn enter - guess [ ] "Let the user enter a guess. Verify the input. Repeat until valid. returns a list of digits enters by the user (# # # #)" ( println "Enter your guess: " ) ( let [ guess ( read - line ) ] ( if ( valid - input? guess ) ( map # ( Character / digit % 10 ) guess ) ( recur ) ) ) )   ( defn bulls - and - cows [ ] "generate a random 4 digit number from the list of (1 ... 9): no repeating digits player tries to guess the number with bull and cows rules gameplay" ( let [ solution ( take 4 ( shuffle ( range 1 10 ) ) ) ] ( println "lets play some bulls and cows!" ) ( loop [ guess ( enter - guess ) ] ( println ( bulls guess solution ) " bulls and " ( cows guess solution ) " cows." ) ( if ( not = guess solution ) ( recur ( enter - guess ) ) ( println "You have won!" ) ) ) ) )   ( bulls - and - cows )   \ No newline at end of file diff --git a/rosetta/file45.hs b/rosetta/file45.hs new file mode 100644 index 0000000..5fddc09 --- /dev/null +++ b/rosetta/file45.hs @@ -0,0 +1 @@ +import Data . List import Control . Monad import Control . Arrow   missingPerm :: Eq a => [ [ a ] ] -> [ [ a ] ] missingPerm = ( \\ ) =<< permutations . nub . join   deficientPermsList = [ "ABCD" , "CABD" , "ACDB" , "DACB" , "BCDA" , "ACBD" , "ADCB" , "CDAB" , "DABC" , "BCAD" , "CADB" , "CDBA" , "CBAD" , "ABDC" , "ADBC" , "BDCA" , "DCBA" , "BACD" , "BADC" , "BDAC" , "CBDA" , "DBCA" , "DCAB" ]   main = do print $ missingPerm deficientPermsList \ No newline at end of file diff --git a/rosetta/file45.java b/rosetta/file45.java new file mode 100644 index 0000000..cd3af7b --- /dev/null +++ b/rosetta/file45.java @@ -0,0 +1 @@ +String dog = "Benjamin" ; String Dog = "Samba" ; //in general, identifiers that start with capital letters are class names String DOG = "Bernie" ; //in general, identifiers in all caps are constants //the conventions listed in comments here are not enforced by the language System . out . println ( "There are three dogs named " + dog + ", " + Dog + ", and " + DOG + "'" ) ; \ No newline at end of file diff --git a/rosetta/file45.js b/rosetta/file45.js new file mode 100644 index 0000000..aa030a5 --- /dev/null +++ b/rosetta/file45.js @@ -0,0 +1 @@ +var nums = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] ;   function add ( a , b ) { return a + b ; }   var summation = nums. reduce ( add ) ;   function mul ( a , b ) { return a * b ; }   var product = nums. reduce ( mul , 1 ) ;   var concatenation = nums. reduce ( add , "" ) ;   console. log ( summation , product , concatenation ) ; \ No newline at end of file diff --git a/rosetta/file45.ocaml b/rosetta/file45.ocaml new file mode 100644 index 0000000..760e31d --- /dev/null +++ b/rosetta/file45.ocaml @@ -0,0 +1 @@ +let ( ) = let buf = Buffer . create 1 in let s = Buffer . add_string buf in Random . self_init ( ) ; s "" ; s "" ; s "" ; List . iter ( fun v -> s ( "" ) ) [ "X" ; "Y" ; "Z" ] ; s "" ; s "" ; s "" ; for i = 0 to pred 3 do s ( "" ) ; for j = 0 to pred 3 do s ( "" ) ; done ; s "" ; done ; s "" ; s "
" ^ v ^ "
" ^ string_of_int i ^ "" ^ string_of_int ( Random . int 1000 ) ^ "
" ; print_endline ( Buffer . contents buf ) \ No newline at end of file diff --git a/rosetta/file45.perl b/rosetta/file45.perl new file mode 100644 index 0000000..92a78d0 --- /dev/null +++ b/rosetta/file45.perl @@ -0,0 +1 @@ +use Sys :: Hostname ;   $name = hostname ; \ No newline at end of file diff --git a/rosetta/file45.php b/rosetta/file45.php new file mode 100644 index 0000000..74c4687 --- /dev/null +++ b/rosetta/file45.php @@ -0,0 +1 @@ + < title > CsvToHTML < /title > < style type = "text/css" > td { { background-color :# ddddff ; } } thead td { { background-color :# ddffdd ; text-align : center ; } } < /style > < /head > val csv = "" "Character,Speech |The multitude,The messiah! Show us the messiah! |Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! |The multitude,Who are you? |Brians mother,I'm his mother; that's who! |The multitude,Behold his mother! Behold his mother!" "" . stripMargin   def csv2html ( csv : String, withHead : Boolean ) = {   def processRow ( text : String ) = < tr > { text. split ( ',' ) . map ( s => < td > { s } < /td > ) } < /tr >   val ( first :: rest ) = csv. lines . toList // Separate the header and the rest   def tableHead = if ( withHead ) < thead > { processRow ( first ) } < /thead > else processRow ( first )   < html > { header } < body > < table > { tableHead } { rest. map ( processRow ) } < /table > < /body > < /html > }   println ( csv2html ( csv, true ) ) } \ No newline at end of file diff --git a/rosetta/file45.ss b/rosetta/file45.ss new file mode 100644 index 0000000..251bf4e --- /dev/null +++ b/rosetta/file45.ss @@ -0,0 +1 @@ +( import ( rnrs arithmetic bitwise ( 6 ) ) )   ( define ( bitwise a b ) ( display ( bitwise - and a b ) ) ( newline ) ( display ( bitwise - ior a b ) ) ( newline ) ( display ( bitwise - xor a b ) ) ( newline ) ( display ( bitwise - not a ) ) ( newline ) ( display ( bitwise - arithmetic - shift - right a b ) ) ( newline ) )   ( bitwise 255 5 ) \ No newline at end of file diff --git a/rosetta/file45.tcl b/rosetta/file45.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file45.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file46.clojure b/rosetta/file46.clojure new file mode 100644 index 0000000..9a2fb2f --- /dev/null +++ b/rosetta/file46.clojure @@ -0,0 +1 @@ +( defn encrypt - character [ offset c ] ( if ( Character / isLetter c ) ( let [ v ( int c ) base ( if ( >= v ( int \a ) ) ( int \a ) ( int \A ) ) offset ( mod offset 26 ) ] ;works with negative offsets too! ( char ( + ( mod ( + ( - v base ) offset ) 26 ) base ) ) ) c ) )   ( defn encrypt [ offset text ] ( apply str ( map # ( encrypt - character offset % ) text ) ) )   ( defn decrypt [ offset text ] ( encrypt ( - 26 offset ) text ) )     ( let [ text "The Quick Brown Fox Jumps Over The Lazy Dog." enc ( encrypt - 1 text ) ] ( print "Original text:" text " \n " ) ( print "Encryption:" enc " \n " ) ( print "Decryption:" ( decrypt - 1 enc ) " \n " ) ) \ No newline at end of file diff --git a/rosetta/file46.hs b/rosetta/file46.hs new file mode 100644 index 0000000..2fcc2a7 --- /dev/null +++ b/rosetta/file46.hs @@ -0,0 +1 @@ +multiply x y = x * y \ No newline at end of file diff --git a/rosetta/file46.java b/rosetta/file46.java new file mode 100644 index 0000000..cd3af7b --- /dev/null +++ b/rosetta/file46.java @@ -0,0 +1 @@ +String dog = "Benjamin" ; String Dog = "Samba" ; //in general, identifiers that start with capital letters are class names String DOG = "Bernie" ; //in general, identifiers in all caps are constants //the conventions listed in comments here are not enforced by the language System . out . println ( "There are three dogs named " + dog + ", " + Dog + ", and " + DOG + "'" ) ; \ No newline at end of file diff --git a/rosetta/file46.js b/rosetta/file46.js new file mode 100644 index 0000000..ec2e00a --- /dev/null +++ b/rosetta/file46.js @@ -0,0 +1 @@ +var net = require ( "net" ) ; var sys = require ( "sys" ) ; var EventEmitter = require ( "events" ) . EventEmitter ;   /******************************************************************************* * ChatServer * * Manages connections, users, and chat messages. ******************************************************************************/   function ChatServer ( ) { this . chatters = { } ; this . server = net. createServer ( this . handleConnection . bind ( this ) ) ; this . server . listen ( 1212 , "localhost" ) ; }   ChatServer. prototype . isNicknameLegal = function ( nickname ) { // A nickname may contain letters or numbers only, // and may only be used once. if ( nickname. replace ( /[A-Za-z0-9]*/ , '' ) != "" ) { return false } for ( used_nick in this . chatters ) { if ( used_nick == nickname ) { return false ; } } return true ; } ;   ChatServer. prototype . handleConnection = function ( connection ) { console. log ( "Incoming connection from " + connection. remoteAddress ) ; connection. setEncoding ( "utf8" ) ;   var chatter = new Chatter ( connection , this ) ; chatter. on ( "chat" , this . handleChat . bind ( this ) ) ; chatter. on ( "join" , this . handleJoin . bind ( this ) ) ; chatter. on ( "leave" , this . handleLeave . bind ( this ) ) ; } ;   ChatServer. prototype . handleChat = function ( chatter , message ) { this . sendToEveryChatterExcept ( chatter , chatter. nickname + ": " + message ) ; } ;   ChatServer. prototype . handleJoin = function ( chatter ) { console. log ( chatter. nickname + " has joined the chat." ) ; this . sendToEveryChatter ( chatter. nickname + " has joined the chat." ) ; this . addChatter ( chatter ) ; } ;   ChatServer. prototype . handleLeave = function ( chatter ) { console. log ( chatter. nickname + " has left the chat." ) ; this . removeChatter ( chatter ) ; this . sendToEveryChatter ( chatter. nickname + " has left the chat." ) ; } ;   ChatServer. prototype . addChatter = function ( chatter ) { this . chatters [ chatter. nickname ] = chatter ; } ;   ChatServer. prototype . removeChatter = function ( chatter ) { delete this . chatters [ chatter. nickname ] ; } ;   ChatServer. prototype . sendToEveryChatter = function ( data ) { for ( nickname in this . chatters ) { this . chatters [ nickname ] . send ( data ) ; } } ;   ChatServer. prototype . sendToEveryChatterExcept = function ( chatter , data ) { for ( nickname in this . chatters ) { if ( nickname != chatter. nickname ) { this . chatters [ nickname ] . send ( data ) ; } } } ;   /******************************************************************************* * Chatter * * Represents a single user/connection in the chat server. ******************************************************************************/   function Chatter ( socket , server ) { EventEmitter. call ( this ) ;   this . socket = socket ; this . server = server ; this . nickname = "" ; this . lineBuffer = new SocketLineBuffer ( socket ) ;   this . lineBuffer . on ( "line" , this . handleNickname . bind ( this ) ) ; this . socket . on ( "close" , this . handleDisconnect . bind ( this ) ) ;   this . send ( "Welcome! What is your nickname?" ) ; } ;   sys. inherits ( Chatter , EventEmitter ) ;   Chatter. prototype . handleNickname = function ( nickname ) { if ( server. isNicknameLegal ( nickname ) ) { this . nickname = nickname ; this . lineBuffer . removeAllListeners ( "line" ) ; this . lineBuffer . on ( "line" , this . handleChat . bind ( this ) ) ; this . send ( "Welcome to the chat, " + nickname + "!" ) ; this . emit ( "join" , this ) ; } else { this . send ( "Sorry, but that nickname is not legal or is already in use!" ) ; this . send ( "What is your nickname?" ) ; } } ;   Chatter. prototype . handleChat = function ( line ) { this . emit ( "chat" , this , line ) ; } ;   Chatter. prototype . handleDisconnect = function ( ) { this . emit ( "leave" , this ) ; } ;   Chatter. prototype . send = function ( data ) { this . socket . write ( data + " \r \n " ) ; } ;   /******************************************************************************* * SocketLineBuffer * * Listens for and buffers incoming data on a socket and emits a 'line' event * whenever a complete line is detected. ******************************************************************************/   function SocketLineBuffer ( socket ) { EventEmitter. call ( this ) ;   this . socket = socket ; this . buffer = "" ;   this . socket . on ( "data" , this . handleData . bind ( this ) ) ; } ;   sys. inherits ( SocketLineBuffer , EventEmitter ) ;   SocketLineBuffer. prototype . handleData = function ( data ) { for ( var i = 0 ; i < data. length ; i ++ ) { var char = data. charAt ( i ) ; this . buffer += char ; if ( char == " \n " ) { this . buffer = this . buffer . replace ( " \r \n " , "" ) ; this . buffer = this . buffer . replace ( " \n " , "" ) ; this . emit ( "line" , this . buffer ) ; this . buffer = "" ; } } } ;   // Start the server! server = new ChatServer ( ) ; \ No newline at end of file diff --git a/rosetta/file46.ocaml b/rosetta/file46.ocaml new file mode 100644 index 0000000..d14af7c --- /dev/null +++ b/rosetta/file46.ocaml @@ -0,0 +1 @@ +let addnums x y = x + y (* declare a curried function *)   let add1 = addnums 1 (* bind the first argument to get another function *) add1 42 (* apply to actually compute a result, 43 *) \ No newline at end of file diff --git a/rosetta/file46.perl b/rosetta/file46.perl new file mode 100644 index 0000000..bdd7641 --- /dev/null +++ b/rosetta/file46.perl @@ -0,0 +1 @@ +use LWP :: UserAgent qw ( ) ; my $ua = LWP :: UserAgent -> new ; my $netloc = 'http://www.buddhism-dict.net/cgi-bin/xpr-dealt.pl:80' ; $ua -> credentials ( $netloc , 'CJK-E and Buddhist Dictionaries' , # basic realm 'guest' , # user '' , # empty pw ) ; my $response = $ua -> get ( $netloc ) ;   use WWW :: Mechanize qw ( ) ; my $mech = WWW :: Mechanize -> new ; $mech -> get ( 'https://login.yahoo.com/' ) ; $mech -> submit_form ( with_fields => { login => 'XXXXXX' , passwd => 'YYYYYY' , '.persistent' => 'y' , # tick checkbox } ) ; \ No newline at end of file diff --git a/rosetta/file46.php b/rosetta/file46.php new file mode 100644 index 0000000..74c4687 --- /dev/null +++ b/rosetta/file46.php @@ -0,0 +1 @@ + "e38ca1d920c4b8b8d3946b2c72f01680" \ No newline at end of file diff --git a/rosetta/file46.scala b/rosetta/file46.scala new file mode 100644 index 0000000..b818f31 --- /dev/null +++ b/rosetta/file46.scala @@ -0,0 +1 @@ +object CsvToHTML extends App { val header = < head > < title > CsvToHTML < /title > < style type = "text/css" > td { { background-color :# ddddff ; } } thead td { { background-color :# ddffdd ; text-align : center ; } } < /style > < /head > val csv = "" "Character,Speech |The multitude,The messiah! Show us the messiah! |Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! |The multitude,Who are you? |Brians mother,I'm his mother; that's who! |The multitude,Behold his mother! Behold his mother!" "" . stripMargin   def csv2html ( csv : String, withHead : Boolean ) = {   def processRow ( text : String ) = < tr > { text. split ( ',' ) . map ( s => < td > { s } < /td > ) } < /tr >   val ( first :: rest ) = csv. lines . toList // Separate the header and the rest   def tableHead = if ( withHead ) < thead > { processRow ( first ) } < /thead > else processRow ( first )   < html > { header } < body > < table > { tableHead } { rest. map ( processRow ) } < /table > < /body > < /html > }   println ( csv2html ( csv, true ) ) } \ No newline at end of file diff --git a/rosetta/file46.ss b/rosetta/file46.ss new file mode 100644 index 0000000..1799ed5 --- /dev/null +++ b/rosetta/file46.ss @@ -0,0 +1 @@ +    ;generate a random non-repeating list of 4 digits, 1-9 inclusive ( define ( get - num ) ( define ( gen lst ) ( if ( = ( length lst ) 4 ) lst ( let ( ( digit ( + ( random 9 ) 1 ) ) ) ( if ( member digit lst ) ;make sure the new digit isn't in the ;list ( gen lst ) ( gen ( cons digit lst ) ) ) ) ) ) ( string -> list ( apply string-append ( map number -> string ( gen ' ( ) ) ) ) ) )   ;is g a valid guess (that is, non-repeating, four digits 1-9 ;inclusive?) ( define ( valid - guess? g ) ( let ( ( g - num ( string -> number ( apply string g ) ) ) ) ;does the same digit appear twice in lst? ( define ( repeats? lst ) ( cond ( ( null? lst ) #f ) ( ( member ( car lst ) ( cdr lst ) ) #t ) ( else ( repeats? ( cdr lst ) ) ) ) ) ( and g - num ( > g - num 1233 ) ( < g - num 9877 ) ( not ( repeats? g ) ) ) ) )   ;return '(cows bulls) for the given guess ( define ( score answer guess ) ;total cows + bulls ( define ( cows & bulls a g ) ( cond ( ( null? a ) 0 ) ( ( member ( car a ) g ) ( + 1 ( cows & bulls ( cdr a ) g ) ) ) ( else ( cows & bulls ( cdr a ) g ) ) ) ) ;bulls only ( define ( bulls a g ) ( cond ( ( null? a ) 0 ) ( ( equal? ( car a ) ( car g ) ) ( + 1 ( bulls ( cdr a ) ( cdr g ) ) ) ) ( else ( bulls ( cdr a ) ( cdr g ) ) ) ) ) ( list ( - ( cows & bulls answer guess ) ( bulls answer guess ) ) ( bulls answer guess ) ) )   ;play the game ( define ( bull - cow answer ) ;get the user's guess as a list ( define ( get - guess ) ( let ( ( e ( read ) ) ) ( if ( number? e ) ( string -> list ( number -> string e ) ) ( string -> list ( symbol -> string e ) ) ) ) ) ( display "Enter a guess: " ) ( let ( ( guess ( get - guess ) ) ) ( if ( valid - guess? guess ) ( let ( ( bulls ( cadr ( score answer guess ) ) ) ( cows ( car ( score answer guess ) ) ) ) ( if ( = bulls 4 ) ( display "You win! \n " ) ( begin ( display bulls ) ( display " bulls, " ) ( display cows ) ( display " cows. \n " ) ( bull - cow answer ) ) ) ) ( begin ( display "Invalid guess. \n " ) ( bull - cow answer ) ) ) ) )   ( bull - cow ( get - num ) )   \ No newline at end of file diff --git a/rosetta/file46.tcl b/rosetta/file46.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file46.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file47.clojure b/rosetta/file47.clojure new file mode 100644 index 0000000..9a2fb2f --- /dev/null +++ b/rosetta/file47.clojure @@ -0,0 +1 @@ +( defn encrypt - character [ offset c ] ( if ( Character / isLetter c ) ( let [ v ( int c ) base ( if ( >= v ( int \a ) ) ( int \a ) ( int \A ) ) offset ( mod offset 26 ) ] ;works with negative offsets too! ( char ( + ( mod ( + ( - v base ) offset ) 26 ) base ) ) ) c ) )   ( defn encrypt [ offset text ] ( apply str ( map # ( encrypt - character offset % ) text ) ) )   ( defn decrypt [ offset text ] ( encrypt ( - 26 offset ) text ) )     ( let [ text "The Quick Brown Fox Jumps Over The Lazy Dog." enc ( encrypt - 1 text ) ] ( print "Original text:" text " \n " ) ( print "Encryption:" enc " \n " ) ( print "Decryption:" ( decrypt - 1 enc ) " \n " ) ) \ No newline at end of file diff --git a/rosetta/file47.hs b/rosetta/file47.hs new file mode 100644 index 0000000..2fcc2a7 --- /dev/null +++ b/rosetta/file47.hs @@ -0,0 +1 @@ +multiply x y = x * y \ No newline at end of file diff --git a/rosetta/file47.java b/rosetta/file47.java new file mode 100644 index 0000000..fbc1b76 --- /dev/null +++ b/rosetta/file47.java @@ -0,0 +1 @@ +import java.util.stream.Stream ;   public class ReduceTask {   public static void main ( String [ ] args ) { System . out . println ( Stream. of ( 1 , 2 , 3 , 4 , 5 ) . mapToInt ( i -> i ) . sum ( ) ) ; System . out . println ( Stream. of ( 1 , 2 , 3 , 4 , 5 ) . reduce ( 1 , ( a, b ) -> a * b ) ) ; } } \ No newline at end of file diff --git a/rosetta/file47.js b/rosetta/file47.js new file mode 100644 index 0000000..ac5ab52 --- /dev/null +++ b/rosetta/file47.js @@ -0,0 +1 @@ +var fso = new ActiveXObject ( "Scripting.FileSystemObject" ) ;   fso. FileExists ( 'input.txt' ) ; fso. FileExists ( 'c:/input.txt' ) ; fso. FolderExists ( 'docs' ) ; fso. FolderExists ( 'c:/docs' ) ; \ No newline at end of file diff --git a/rosetta/file47.ocaml b/rosetta/file47.ocaml new file mode 100644 index 0000000..5e64ad3 --- /dev/null +++ b/rosetta/file47.ocaml @@ -0,0 +1 @@ +# # load "unix.cma" ;; # open Unix ;;   # let t = time ( ) ;; val t : float = 1219997516 .   # let gmt = gmtime t ;; val gmt : Unix . tm = { tm_sec = 56 ; tm_min = 11 ; tm_hour = 8 ; tm_mday = 29 ; tm_mon = 7 ; tm_year = 108 ; tm_wday = 5 ; tm_yday = 241 ; tm_isdst = false }   # Printf . sprintf "%d-%02d-%02d" ( 1900 + gmt . tm_year ) ( 1 + gmt . tm_mon ) gmt . tm_mday ;; - : string = "2008-08-29" \ No newline at end of file diff --git a/rosetta/file47.perl b/rosetta/file47.perl new file mode 100644 index 0000000..8a570d9 --- /dev/null +++ b/rosetta/file47.perl @@ -0,0 +1 @@ +sub identity_matrix { my $n = shift ; map { my $i = $_ ; [ map { ( $_ == $i ) - 0 } 1 .. $n ] } 1 .. $n ; }   @ ARGV = ( 4 , 5 , 6 ) unless @ ARGV ;   for ( @ ARGV ) { my @id = identity_matrix $_ ; print "$_: \n " ; for ( my $i = 0 ; $i < @id ; ++ $i ) { print join ' ' , @ { $id [ $i ] } , " \n " ; } print " \n " ; }   \ No newline at end of file diff --git a/rosetta/file47.php b/rosetta/file47.php new file mode 100644 index 0000000..74c4687 --- /dev/null +++ b/rosetta/file47.php @@ -0,0 +1 @@ +>> 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 >>> \ No newline at end of file diff --git a/rosetta/file47.rb b/rosetta/file47.rb new file mode 100644 index 0000000..08e953a --- /dev/null +++ b/rosetta/file47.rb @@ -0,0 +1 @@ +class IDVictim   # Create elements of this man, woman, or child's identification. attr_accessor :name , :birthday , :gender , :hometown   # Allows you to put in a space for anything which is not covered by the # preexisting elements. def self . new_element ( element ) attr_accessor element end   end \ No newline at end of file diff --git a/rosetta/file47.scala b/rosetta/file47.scala new file mode 100644 index 0000000..21bd646 --- /dev/null +++ b/rosetta/file47.scala @@ -0,0 +1 @@ +import java. util . { Calendar, GregorianCalendar } import Calendar. { DAY _ OF _ WEEK, DECEMBER, SUNDAY }   object DayOfTheWeek extends App { val years = 2008 to 2121   val yuletide = years. filter ( year => ( new GregorianCalendar ( year, DECEMBER, 25 ) ) . get ( DAY _ OF _ WEEK ) == SUNDAY )   // If you want a test: (optional) assert ( yuletide == Seq ( 2011 , 2016 , 2022 , 2033 , 2039 , 2044 , 2050 , 2061 , 2067 , 2072 , 2078 , 2089 , 2095 , 2101 , 2107 , 2112 , 2118 ) )   println ( yuletide. mkString ( s "${yuletide.length} Years between ${years.head} and ${years.last}" + " including where Christmas is observed on Sunday: \n " , ", " , "." ) ) } \ No newline at end of file diff --git a/rosetta/file47.ss b/rosetta/file47.ss new file mode 100644 index 0000000..260abfe --- /dev/null +++ b/rosetta/file47.ss @@ -0,0 +1 @@ +; ; Works with R7RS-compatible Schemes (e.g. Chibi). ; Also current versions of Chicken, Gauche and Kawa. ; ( cond - expand ( chicken ( use srfi - 13 ) ) ( gauche ( use srfi - 13 ) ) ( kawa ( import ( srfi : 13 ) ) ) ( else ( import ( scheme base ) ( scheme write ) ) ) ) ; R7RS     ( define msg "The quick brown fox jumps over the lazy dog." ) ( define key 13 )   ( define ( caesar char ) ( define A ( char -> integer #\A ) ) ( define Z ( char -> integer #\Z ) ) ( define a ( char -> integer #\a ) ) ( define z ( char -> integer #\z ) ) ( define c ( char -> integer char ) ) ( integer -> char ( cond ( ( <= A c Z ) ( + A ( modulo ( + key ( - c A ) ) 26 ) ) ) ( ( <= a c z ) ( + a ( modulo ( + key ( - c a ) ) 26 ) ) ) ( else c ) ) ) ) ; Return other characters verbatim.   ( display ( string - map caesar msg ) ) ( newline )   \ No newline at end of file diff --git a/rosetta/file47.tcl b/rosetta/file47.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file47.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file48.clojure b/rosetta/file48.clojure new file mode 100644 index 0000000..9a2fb2f --- /dev/null +++ b/rosetta/file48.clojure @@ -0,0 +1 @@ +( defn encrypt - character [ offset c ] ( if ( Character / isLetter c ) ( let [ v ( int c ) base ( if ( >= v ( int \a ) ) ( int \a ) ( int \A ) ) offset ( mod offset 26 ) ] ;works with negative offsets too! ( char ( + ( mod ( + ( - v base ) offset ) 26 ) base ) ) ) c ) )   ( defn encrypt [ offset text ] ( apply str ( map # ( encrypt - character offset % ) text ) ) )   ( defn decrypt [ offset text ] ( encrypt ( - 26 offset ) text ) )     ( let [ text "The Quick Brown Fox Jumps Over The Lazy Dog." enc ( encrypt - 1 text ) ] ( print "Original text:" text " \n " ) ( print "Encryption:" enc " \n " ) ( print "Decryption:" ( decrypt - 1 enc ) " \n " ) ) \ No newline at end of file diff --git a/rosetta/file48.hs b/rosetta/file48.hs new file mode 100644 index 0000000..2fcc2a7 --- /dev/null +++ b/rosetta/file48.hs @@ -0,0 +1 @@ +multiply x y = x * y \ No newline at end of file diff --git a/rosetta/file48.java b/rosetta/file48.java new file mode 100644 index 0000000..fb0c3eb --- /dev/null +++ b/rosetta/file48.java @@ -0,0 +1 @@ +import java.io.* ; import java.net.* ; import java.util.* ;   public class ChatServer implements Runnable { private int port = 0 ; private List < Client > clients = new ArrayList < Client > ( ) ;   public ChatServer ( int port ) { this . port = port ; }   public void run ( ) { try { ServerSocket ss = new ServerSocket ( port ) ; while ( true ) { Socket s = ss. accept ( ) ; new Thread ( new Client ( s ) ) . start ( ) ; } } catch ( Exception e ) { e. printStackTrace ( ) ; } }   private synchronized boolean registerClient ( Client client ) { for ( Client otherClient : clients ) if ( otherClient. clientName . equalsIgnoreCase ( client. clientName ) ) return false ; clients. add ( client ) ; return true ; }   private void deregisterClient ( Client client ) { boolean wasRegistered = false ; synchronized ( this ) { wasRegistered = clients. remove ( client ) ; } if ( wasRegistered ) broadcast ( client, "--- " + client. clientName + " left ---" ) ; }   private synchronized String getOnlineListCSV ( ) { StringBuilder sb = new StringBuilder ( ) ; sb. append ( clients. size ( ) ) . append ( " user(s) online: " ) ; for ( int i = 0 ; i < clients. size ( ) ; i ++ ) sb. append ( ( i > 0 ) ? ", " : "" ) . append ( clients. get ( i ) . clientName ) ; return sb. toString ( ) ; }   private void broadcast ( Client fromClient, String msg ) { // Copy client list (don't want to hold lock while doing IO) List < Client > clients = null ; synchronized ( this ) { clients = new ArrayList < Client > ( this . clients ) ; } for ( Client client : clients ) { if ( client. equals ( fromClient ) ) continue ; try { client. write ( msg + " \r \n " ) ; } catch ( Exception e ) { } } }   public class Client implements Runnable { private Socket socket = null ; private Writer output = null ; private String clientName = null ;   public Client ( Socket socket ) { this . socket = socket ; }   public void run ( ) { try { socket. setSendBufferSize ( 16384 ) ; socket. setTcpNoDelay ( true ) ; BufferedReader input = new BufferedReader ( new InputStreamReader ( socket. getInputStream ( ) ) ) ; output = new OutputStreamWriter ( socket. getOutputStream ( ) ) ; write ( "Please enter your name: " ) ; String line = null ; while ( ( line = input. readLine ( ) ) != null ) { if ( clientName == null ) { line = line. trim ( ) ; if ( line. isEmpty ( ) ) { write ( "A name is required. Please enter your name: " ) ; continue ; } clientName = line ; if ( ! registerClient ( this ) ) { clientName = null ; write ( "Name already registered. Please enter your name: " ) ; continue ; } write ( getOnlineListCSV ( ) + " \r \n " ) ; broadcast ( this , "+++ " + clientName + " arrived +++" ) ; continue ; } if ( line. equalsIgnoreCase ( "/quit" ) ) return ; broadcast ( this , clientName + "> " + line ) ; } } catch ( Exception e ) { } finally { deregisterClient ( this ) ; output = null ; try { socket. close ( ) ; } catch ( Exception e ) { } socket = null ; } }   public void write ( String msg ) throws IOException { output. write ( msg ) ; output. flush ( ) ; }   public boolean equals ( Client client ) { return ( client != null ) && ( client instanceof Client ) && ( clientName != null ) && ( client. clientName != null ) && clientName. equals ( client. clientName ) ; } }   public static void main ( String [ ] args ) { int port = 4004 ; if ( args. length > 0 ) port = Integer . parseInt ( args [ 0 ] ) ; new ChatServer ( port ) . run ( ) ; } }   \ No newline at end of file diff --git a/rosetta/file48.js b/rosetta/file48.js new file mode 100644 index 0000000..ac5ab52 --- /dev/null +++ b/rosetta/file48.js @@ -0,0 +1 @@ +var fso = new ActiveXObject ( "Scripting.FileSystemObject" ) ;   fso. FileExists ( 'input.txt' ) ; fso. FileExists ( 'c:/input.txt' ) ; fso. FolderExists ( 'docs' ) ; fso. FolderExists ( 'c:/docs' ) ; \ No newline at end of file diff --git a/rosetta/file48.ocaml b/rosetta/file48.ocaml new file mode 100644 index 0000000..9388c31 --- /dev/null +++ b/rosetta/file48.ocaml @@ -0,0 +1 @@ +let srnd x = (* since OCaml's built-in int type is at least 31 (note: not 32) bits wide, and this problem takes mod 2^31, it is just enough if we treat it as an unsigned integer, which means taking the logical right shift *) let seed = ref x in fun ( ) -> seed := ( ! seed * 214013 + 2531011 ) land 0x7fffffff ; ! seed lsr 16   let deal s = let rnd = srnd s in let t = Array . init 52 ( fun i -> i ) in let cards = Array . init 52 ( fun j -> let n = 52 - j in let i = rnd ( ) mod n in let this = t . ( i ) in t . ( i ) <- t . ( pred n ) ; this ) in ( cards )   let show cards = let suits = "CDHS" and nums = "A23456789TJQK" in Array . iteri ( fun i card -> Printf . printf "%c%c%c" nums . [ card / 4 ] suits . [ card mod 4 ] ( if ( i mod 8 ) = 7 then ' \n ' else ' ' ) ) cards ; print_newline ( )   let ( ) = let s = try int_of_string Sys . argv . ( 1 ) with _ -> 11982 in Printf . printf "Deal %d:\n" s ; let cards = deal s in show cards \ No newline at end of file diff --git a/rosetta/file48.perl b/rosetta/file48.perl new file mode 100644 index 0000000..8a570d9 --- /dev/null +++ b/rosetta/file48.perl @@ -0,0 +1 @@ +sub identity_matrix { my $n = shift ; map { my $i = $_ ; [ map { ( $_ == $i ) - 0 } 1 .. $n ] } 1 .. $n ; }   @ ARGV = ( 4 , 5 , 6 ) unless @ ARGV ;   for ( @ ARGV ) { my @id = identity_matrix $_ ; print "$_: \n " ; for ( my $i = 0 ; $i < @id ; ++ $i ) { print join ' ' , @ { $id [ $i ] } , " \n " ; } print " \n " ; }   \ No newline at end of file diff --git a/rosetta/file48.php b/rosetta/file48.php new file mode 100644 index 0000000..6520618 --- /dev/null +++ b/rosetta/file48.php @@ -0,0 +1 @@ +// Static method MyClass :: method ( $someParameter ) ; // In PHP 5.3+, static method can be called on a string of the class name $foo = 'MyClass' ; $foo :: method ( $someParameter ) ;     // Instance method $myInstance -> method ( $someParameter ) ; \ No newline at end of file diff --git a/rosetta/file48.py b/rosetta/file48.py new file mode 100644 index 0000000..4bff2c7 --- /dev/null +++ b/rosetta/file48.py @@ -0,0 +1 @@ +>>> from math import sqrt >>> # (Using the fact that round(X) is equivalent to floor(0.5+X) for our range of X) >>> def nonsqr ( n ) : return n + int ( round ( sqrt ( n ) ) )   >>> # first 22 values (as a list) has no squares: >>> [ nonsqr ( i ) for i in xrange ( 1 , 23 ) ] [ 2 , 3 , 5 , 6 , 7 , 8 , 10 , 11 , 12 , 13 , 14 , 15 , 17 , 18 , 19 , 20 , 21 , 22 , 23 , 24 , 26 , 27 ] >>> # The following check shows no squares up to one million: >>> for i in xrange ( 1 , 1000000 ) : j = sqrt ( nonsqr ( i ) ) assert j != int ( j ) , "Found a square in the sequence: %i"  % i     >>> \ No newline at end of file diff --git a/rosetta/file48.rb b/rosetta/file48.rb new file mode 100644 index 0000000..08e953a --- /dev/null +++ b/rosetta/file48.rb @@ -0,0 +1 @@ +class IDVictim   # Create elements of this man, woman, or child's identification. attr_accessor :name , :birthday , :gender , :hometown   # Allows you to put in a space for anything which is not covered by the # preexisting elements. def self . new_element ( element ) attr_accessor element end   end \ No newline at end of file diff --git a/rosetta/file48.scala b/rosetta/file48.scala new file mode 100644 index 0000000..21bd646 --- /dev/null +++ b/rosetta/file48.scala @@ -0,0 +1 @@ +import java. util . { Calendar, GregorianCalendar } import Calendar. { DAY _ OF _ WEEK, DECEMBER, SUNDAY }   object DayOfTheWeek extends App { val years = 2008 to 2121   val yuletide = years. filter ( year => ( new GregorianCalendar ( year, DECEMBER, 25 ) ) . get ( DAY _ OF _ WEEK ) == SUNDAY )   // If you want a test: (optional) assert ( yuletide == Seq ( 2011 , 2016 , 2022 , 2033 , 2039 , 2044 , 2050 , 2061 , 2067 , 2072 , 2078 , 2089 , 2095 , 2101 , 2107 , 2112 , 2118 ) )   println ( yuletide. mkString ( s "${yuletide.length} Years between ${years.head} and ${years.last}" + " including where Christmas is observed on Sunday: \n " , ", " , "." ) ) } \ No newline at end of file diff --git a/rosetta/file48.ss b/rosetta/file48.ss new file mode 100644 index 0000000..260abfe --- /dev/null +++ b/rosetta/file48.ss @@ -0,0 +1 @@ +; ; Works with R7RS-compatible Schemes (e.g. Chibi). ; Also current versions of Chicken, Gauche and Kawa. ; ( cond - expand ( chicken ( use srfi - 13 ) ) ( gauche ( use srfi - 13 ) ) ( kawa ( import ( srfi : 13 ) ) ) ( else ( import ( scheme base ) ( scheme write ) ) ) ) ; R7RS     ( define msg "The quick brown fox jumps over the lazy dog." ) ( define key 13 )   ( define ( caesar char ) ( define A ( char -> integer #\A ) ) ( define Z ( char -> integer #\Z ) ) ( define a ( char -> integer #\a ) ) ( define z ( char -> integer #\z ) ) ( define c ( char -> integer char ) ) ( integer -> char ( cond ( ( <= A c Z ) ( + A ( modulo ( + key ( - c A ) ) 26 ) ) ) ( ( <= a c z ) ( + a ( modulo ( + key ( - c a ) ) 26 ) ) ) ( else c ) ) ) ) ; Return other characters verbatim.   ( display ( string - map caesar msg ) ) ( newline )   \ No newline at end of file diff --git a/rosetta/file48.tcl b/rosetta/file48.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file48.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file49.clojure b/rosetta/file49.clojure new file mode 100644 index 0000000..9a2fb2f --- /dev/null +++ b/rosetta/file49.clojure @@ -0,0 +1 @@ +( defn encrypt - character [ offset c ] ( if ( Character / isLetter c ) ( let [ v ( int c ) base ( if ( >= v ( int \a ) ) ( int \a ) ( int \A ) ) offset ( mod offset 26 ) ] ;works with negative offsets too! ( char ( + ( mod ( + ( - v base ) offset ) 26 ) base ) ) ) c ) )   ( defn encrypt [ offset text ] ( apply str ( map # ( encrypt - character offset % ) text ) ) )   ( defn decrypt [ offset text ] ( encrypt ( - 26 offset ) text ) )     ( let [ text "The Quick Brown Fox Jumps Over The Lazy Dog." enc ( encrypt - 1 text ) ] ( print "Original text:" text " \n " ) ( print "Encryption:" enc " \n " ) ( print "Decryption:" ( decrypt - 1 enc ) " \n " ) ) \ No newline at end of file diff --git a/rosetta/file49.hs b/rosetta/file49.hs new file mode 100644 index 0000000..9412a55 --- /dev/null +++ b/rosetta/file49.hs @@ -0,0 +1 @@ +cof :: [ Double ] cof = [ 76.18009172947146 ,- 86.50532032941677 , 24.01409824083091 ,- 1.231739572450155 , 0.001208650973866179 ,- 0.000005395239384953 ]   ser :: Double ser = 1.000000000190015   gammaln :: Double -> Double gammaln xx = let tmp ' = (xx+5.5) - (xx+0.5)*log(xx+5.5) ser' = ser + sum ( zipWith ( / ) cof [ xx + 1 .. ] ) in - tmp ' + log(2.5066282746310005 * ser' / xx ) \ No newline at end of file diff --git a/rosetta/file49.java b/rosetta/file49.java new file mode 100644 index 0000000..34e947d --- /dev/null +++ b/rosetta/file49.java @@ -0,0 +1 @@ +import java.util.Scanner ; import java.util.Random ;   public class CheckpointSync { public static void main ( String [ ] args ) { System . out . print ( "Enter number of workers to use: " ) ; Scanner in = new Scanner ( System . in ) ; Worker. nWorkers = in. nextInt ( ) ; System . out . print ( "Enter number of tasks to complete:" ) ; runTasks ( in. nextInt ( ) ) ; }   /* * Informs that workers started working on the task and * starts running threads. Prior to proceeding with next * task syncs using static Worker.checkpoint() method. */ private static void runTasks ( int nTasks ) { for ( int i = 0 ; i < nTasks ; i ++ ) { System . out . println ( "Starting task number " + ( i + 1 ) + "." ) ; runThreads ( ) ; Worker. checkpoint ( ) ; } }   /* * Creates a thread for each worker and runs it. */ private static void runThreads ( ) { for ( int i = 0 ; i < Worker. nWorkers ; i ++ ) { new Thread ( new Worker ( i + 1 ) ) . start ( ) ; } }   /* * Worker inner static class. */ public static class Worker implements Runnable { public Worker ( int threadID ) { this . threadID = threadID ; } public void run ( ) { work ( ) ; }   /* * Notifies that thread started running for 100 to 1000 msec. * Once finished increments static counter 'nFinished' * that counts number of workers finished their work. */ private synchronized void work ( ) { try { int workTime = rgen. nextInt ( 900 ) + 100 ; System . out . println ( "Worker " + threadID + " will work for " + workTime + " msec." ) ; Thread . sleep ( workTime ) ; //work for 'workTime' nFinished ++; //increases work finished counter System . out . println ( "Worker " + threadID + " is ready" ) ; } catch ( InterruptedException e ) { System . err . println ( "Error: thread execution interrupted" ) ; e. printStackTrace ( ) ; } }   /* * Used to synchronize Worker threads using 'nFinished' static integer. * Waits (with step of 10 msec) until 'nFinished' equals to 'nWorkers'. * Once they are equal resets 'nFinished' counter. */ public static synchronized void checkpoint ( ) { while ( nFinished != nWorkers ) { try { Thread . sleep ( 10 ) ; } catch ( InterruptedException e ) { System . err . println ( "Error: thread execution interrupted" ) ; e. printStackTrace ( ) ; } } nFinished = 0 ; }   /* inner class instance variables */ private int threadID ;   /* static variables */ private static Random rgen = new Random ( ) ; private static int nFinished = 0 ; public static int nWorkers = 0 ; } } \ No newline at end of file diff --git a/rosetta/file49.js b/rosetta/file49.js new file mode 100644 index 0000000..ac5ab52 --- /dev/null +++ b/rosetta/file49.js @@ -0,0 +1 @@ +var fso = new ActiveXObject ( "Scripting.FileSystemObject" ) ;   fso. FileExists ( 'input.txt' ) ; fso. FileExists ( 'c:/input.txt' ) ; fso. FolderExists ( 'docs' ) ; fso. FolderExists ( 'c:/docs' ) ; \ No newline at end of file diff --git a/rosetta/file49.ocaml b/rosetta/file49.ocaml new file mode 100644 index 0000000..9388c31 --- /dev/null +++ b/rosetta/file49.ocaml @@ -0,0 +1 @@ +let srnd x = (* since OCaml's built-in int type is at least 31 (note: not 32) bits wide, and this problem takes mod 2^31, it is just enough if we treat it as an unsigned integer, which means taking the logical right shift *) let seed = ref x in fun ( ) -> seed := ( ! seed * 214013 + 2531011 ) land 0x7fffffff ; ! seed lsr 16   let deal s = let rnd = srnd s in let t = Array . init 52 ( fun i -> i ) in let cards = Array . init 52 ( fun j -> let n = 52 - j in let i = rnd ( ) mod n in let this = t . ( i ) in t . ( i ) <- t . ( pred n ) ; this ) in ( cards )   let show cards = let suits = "CDHS" and nums = "A23456789TJQK" in Array . iteri ( fun i card -> Printf . printf "%c%c%c" nums . [ card / 4 ] suits . [ card mod 4 ] ( if ( i mod 8 ) = 7 then ' \n ' else ' ' ) ) cards ; print_newline ( )   let ( ) = let s = try int_of_string Sys . argv . ( 1 ) with _ -> 11982 in Printf . printf "Deal %d:\n" s ; let cards = deal s in show cards \ No newline at end of file diff --git a/rosetta/file49.perl b/rosetta/file49.perl new file mode 100644 index 0000000..9f9ee18 --- /dev/null +++ b/rosetta/file49.perl @@ -0,0 +1 @@ +my @prisoner = 0 .. 40 ; my $k = 3 ; until ( @prisoner == 1 ) { push @prisoner , shift @prisoner for 1 .. $k - 1 ; shift @prisoner ; }   print "Prisoner @prisoner survived. \n " \ No newline at end of file diff --git a/rosetta/file49.php b/rosetta/file49.php new file mode 100644 index 0000000..6520618 --- /dev/null +++ b/rosetta/file49.php @@ -0,0 +1 @@ +// Static method MyClass :: method ( $someParameter ) ; // In PHP 5.3+, static method can be called on a string of the class name $foo = 'MyClass' ; $foo :: method ( $someParameter ) ;     // Instance method $myInstance -> method ( $someParameter ) ; \ No newline at end of file diff --git a/rosetta/file49.py b/rosetta/file49.py new file mode 100644 index 0000000..5bf91dd --- /dev/null +++ b/rosetta/file49.py @@ -0,0 +1 @@ +>>> import hashlib >>> hashlib. sha256 ( "Rosetta code" . encode ( ) ) . hexdigest ( ) '764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf' >>> \ No newline at end of file diff --git a/rosetta/file49.rb b/rosetta/file49.rb new file mode 100644 index 0000000..1d33c7b --- /dev/null +++ b/rosetta/file49.rb @@ -0,0 +1 @@ +def leftrect ( f, left, right ) f. call ( left ) end   def midrect ( f, left, right ) f. call ( ( left + right ) / 2.0 ) end   def rightrect ( f, left, right ) f. call ( right ) end   def trapezium ( f, left, right ) ( f. call ( left ) + f. call ( right ) ) / 2.0 end   def simpson ( f, left, right ) ( f. call ( left ) + 4 * f. call ( ( left + right ) / 2.0 ) + f. call ( right ) ) / 6.0 end   def integrate ( f, a, b, steps, method ) delta = 1.0 * ( b - a ) / steps total = 0.0 steps. times do | i | left = a + i * delta right = left + delta total + = delta * send ( method, f, left, right ) end total end   def square ( x ) x ** 2 end   def def_int ( f, a, b ) l = case f. to_s when / sin >/ lambda { | x | - Math . cos ( x ) } when / square >/ lambda { | x | ( x ** 3 ) / 3.0 } end l. call ( b ) - l. call ( a ) end   a = 0 b = Math ::PI steps = 10   for func in [ method ( :square ) , Math . method ( :sin ) ] puts "integral of #{func} from #{a} to #{b} in #{steps} steps" actual = def_int ( func, a, b ) for method in [ :leftrect , :midrect , :rightrect , :trapezium , :simpson ] int = integrate ( func, a, b, steps, method ) diff = ( int - actual ) * 100.0 / actual printf "  %-10s  %s \t (%.1f%%) \n " , method, int, diff end end \ No newline at end of file diff --git a/rosetta/file49.scala b/rosetta/file49.scala new file mode 100644 index 0000000..21bd646 --- /dev/null +++ b/rosetta/file49.scala @@ -0,0 +1 @@ +import java. util . { Calendar, GregorianCalendar } import Calendar. { DAY _ OF _ WEEK, DECEMBER, SUNDAY }   object DayOfTheWeek extends App { val years = 2008 to 2121   val yuletide = years. filter ( year => ( new GregorianCalendar ( year, DECEMBER, 25 ) ) . get ( DAY _ OF _ WEEK ) == SUNDAY )   // If you want a test: (optional) assert ( yuletide == Seq ( 2011 , 2016 , 2022 , 2033 , 2039 , 2044 , 2050 , 2061 , 2067 , 2072 , 2078 , 2089 , 2095 , 2101 , 2107 , 2112 , 2118 ) )   println ( yuletide. mkString ( s "${yuletide.length} Years between ${years.head} and ${years.last}" + " including where Christmas is observed on Sunday: \n " , ", " , "." ) ) } \ No newline at end of file diff --git a/rosetta/file49.ss b/rosetta/file49.ss new file mode 100644 index 0000000..260abfe --- /dev/null +++ b/rosetta/file49.ss @@ -0,0 +1 @@ +; ; Works with R7RS-compatible Schemes (e.g. Chibi). ; Also current versions of Chicken, Gauche and Kawa. ; ( cond - expand ( chicken ( use srfi - 13 ) ) ( gauche ( use srfi - 13 ) ) ( kawa ( import ( srfi : 13 ) ) ) ( else ( import ( scheme base ) ( scheme write ) ) ) ) ; R7RS     ( define msg "The quick brown fox jumps over the lazy dog." ) ( define key 13 )   ( define ( caesar char ) ( define A ( char -> integer #\A ) ) ( define Z ( char -> integer #\Z ) ) ( define a ( char -> integer #\a ) ) ( define z ( char -> integer #\z ) ) ( define c ( char -> integer char ) ) ( integer -> char ( cond ( ( <= A c Z ) ( + A ( modulo ( + key ( - c A ) ) 26 ) ) ) ( ( <= a c z ) ( + a ( modulo ( + key ( - c a ) ) 26 ) ) ) ( else c ) ) ) ) ; Return other characters verbatim.   ( display ( string - map caesar msg ) ) ( newline )   \ No newline at end of file diff --git a/rosetta/file49.tcl b/rosetta/file49.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file49.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file5.clojure b/rosetta/file5.clojure new file mode 100644 index 0000000..edf5a6b --- /dev/null +++ b/rosetta/file5.clojure @@ -0,0 +1 @@ +( defn ackermann [ m n ] ( cond ( zero? m ) ( inc n ) ( zero? n ) ( ackermann ( dec m ) 1 )  : else ( ackermann ( dec m ) ( ackermann m ( dec n ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file5.hs b/rosetta/file5.hs new file mode 100644 index 0000000..532b8cb --- /dev/null +++ b/rosetta/file5.hs @@ -0,0 +1 @@ +main = do let y = show ( 5 ^ 4 ^ 3 ^ 2 ) let l = length y putStrLn ( "5**4**3**2 = " ++ take 20 y ++ "..." ++ drop ( l - 20 ) y ++ " and has " ++ show l ++ " digits" ) \ No newline at end of file diff --git a/rosetta/file5.java b/rosetta/file5.java new file mode 100644 index 0000000..5b18f44 --- /dev/null +++ b/rosetta/file5.java @@ -0,0 +1 @@ +import java.io.IOException ; import java.util.Arrays ;   import org.apache.directory.ldap.client.api.LdapConnection ; import org.apache.directory.ldap.client.api.LdapNetworkConnection ; import org.apache.directory.shared.ldap.model.cursor.EntryCursor ; import org.apache.directory.shared.ldap.model.entry.Entry ; import org.apache.directory.shared.ldap.model.exception.LdapException ; import org.apache.directory.shared.ldap.model.message.SearchScope ; import org.slf4j.Logger ; import org.slf4j.LoggerFactory ;     public class RDirectorySearchLDAP {   protected static final Logger log_ ; private static LdapConnection connection ; private static final String ldapHostName ; private static final int ldapPort ; private static final String ldapDnStr ; private static final String ldapCreds ;   static {   log_ = LoggerFactory. getLogger ( RDirectorySearchLDAP. class ) ;   ldapHostName = "localhost" ; ldapPort = 11389 ; ldapDnStr = "uid=admin,ou=system" ; ldapCreds = "********" ; }   public static void main ( String [ ] args ) {   boolean connected = false ;   try { connected = setUp ( ) ; if ( connected ) { search ( "*mil*" ) ; } } finally { if ( connected ) { tearDown ( ) ; } }   return ; }   private static boolean search ( String uid ) {   boolean state ; EntryCursor cursor ; Entry ev ; String baseDn ; String filter ; SearchScope scope ; String attributes [ ] ; int ksearch = 0 ;   state = true ;   baseDn = "ou=users,o=mojo" ; filter = "(&(objectClass=person)(&(uid=" + uid + ")))" ; scope = SearchScope. SUBTREE ; attributes = new java. lang . String [ ] { "dn" , "cn" , "sn" , "uid" } ;   try { if ( log_. isTraceEnabled ( ) ) { log_. trace ( "LDAP search" ) ; } if ( log_. isInfoEnabled ( ) ) { log_. info ( "Begin search" ) ; log_. info ( " search base distinguished name: " + baseDn ) ; log_. info ( " search filter: " + filter ) ; log_. info ( " search attributes: " + ( Arrays . asList ( attributes ) . toString ( ) ) ) ; } cursor = connection. search ( baseDn, filter, scope, attributes ) ; while ( cursor. next ( ) ) { ksearch ++; ev = cursor. get ( ) ; if ( log_. isInfoEnabled ( ) ) { log_. info ( "Search cursor entry count: " + ksearch ) ; } if ( log_. isInfoEnabled ( ) ) { log_. info ( ev. toString ( ) ) ; } } } catch ( LdapException lex ) { state = false ; log_. error ( "LDAP Error in cursor loop: Iteration " + ksearch, lex ) ; } catch ( Exception ex ) { state = false ; log_. error ( "I/O Error in cursor loop: Iteration " + ksearch, ex ) ; }   return state ; }   private static boolean search ( ) {   return search ( "*" ) ; }   private static boolean setUp ( ) {   boolean state = false ;   try { if ( log_. isInfoEnabled ( ) ) { log_. info ( "LDAP Connection to " + ldapHostName + " on port " + ldapPort ) ; } connection = new LdapNetworkConnection ( ldapHostName, ldapPort ) ;   if ( log_. isTraceEnabled ( ) ) { log_. trace ( "LDAP bind" ) ; } connection. bind ( ldapDnStr, ldapCreds ) ;   state = true ; } catch ( LdapException lex ) { state = false ; log_. error ( "LDAP Error" , lex ) ; } catch ( IOException iox ) { state = false ; log_. error ( "I/O Error" , iox ) ; }   return state ; }   private static boolean tearDown ( ) {   boolean state = false ;   try { if ( log_. isTraceEnabled ( ) ) { log_. trace ( "LDAP unbind" ) ; } connection. unBind ( ) ; state = true ; } catch ( LdapException lex ) { state = false ; log_. error ( "LDAP Error" , lex ) ; } finally { try { connection. close ( ) ; } catch ( IOException iox ) { state = false ; log_. error ( "I/O Error on connection.close()" , iox ) ; } }   return state ; } } \ No newline at end of file diff --git a/rosetta/file5.js b/rosetta/file5.js new file mode 100644 index 0000000..7e11956 --- /dev/null +++ b/rosetta/file5.js @@ -0,0 +1 @@ +e = { } // generic object e. foo = 1 e [ "bar" ] = 2 // name specified at runtime \ No newline at end of file diff --git a/rosetta/file5.ocaml b/rosetta/file5.ocaml new file mode 100644 index 0000000..166b4cd --- /dev/null +++ b/rosetta/file5.ocaml @@ -0,0 +1 @@ +let address_of ( x :' a ) : nativeint = if Obj . is_block ( Obj . repr x ) then Nativeint . shift_left ( Nativeint . of_int ( Obj . magic x ) ) 1 (* magic *) else invalid_arg "Can only find address of boxed values." ;;   let ( ) = let a = 3.14 in Printf . printf "%nx\n" ( address_of a ) ;; let b = ref 42 in Printf . printf "%nx\n" ( address_of b ) ;; let c = 17 in Printf . printf "%nx\n" ( address_of c ) ;; (* error, because int is unboxed *) \ No newline at end of file diff --git a/rosetta/file5.perl b/rosetta/file5.perl new file mode 100644 index 0000000..5beb597 --- /dev/null +++ b/rosetta/file5.perl @@ -0,0 +1 @@ +sub binary_search { my ( $array_ref , $value , $left , $right ) = @_ ; while ( $left <= $right ) { my $middle = int ( ( $right + $left ) / 2 ) ; if ( $array_ref -> [ $middle ] == $value ) { return 1 ; } if ( $value < $array_ref -> [ $middle ] ) { $right = $middle - 1 ; } else { $left = $middle + 1 ; } } return 0 ; } \ No newline at end of file diff --git a/rosetta/file5.php b/rosetta/file5.php new file mode 100644 index 0000000..d3eb834 --- /dev/null +++ b/rosetta/file5.php @@ -0,0 +1 @@ +class E { } ;   $e = new E ( ) ;   $e -> foo = 1 ;   $e -> { "foo" } = 1 ; // using a runtime name $x = "foo" ; $e -> $x = 1 ; // using a runtime name in a variable \ No newline at end of file diff --git a/rosetta/file5.py b/rosetta/file5.py new file mode 100644 index 0000000..9c080ea --- /dev/null +++ b/rosetta/file5.py @@ -0,0 +1 @@ +def cubicbezier ( self , x0 , y0 , x1 , y1 , x2 , y2 , x3 , y3 , n = 20 ) : pts = [ ] for i in range ( n+ 1 ) : t = i / n a = ( 1 . - t ) ** 3 b = 3 . * t * ( 1 . - t ) ** 2 c = 3.0 * t** 2 * ( 1.0 - t ) d = t** 3   x = int ( a * x0 + b * x1 + c * x2 + d * x3 ) y = int ( a * y0 + b * y1 + c * y2 + d * y3 ) pts. append ( ( x , y ) ) for i in range ( n ) : self . line ( pts [ i ] [ 0 ] , pts [ i ] [ 1 ] , pts [ i+ 1 ] [ 0 ] , pts [ i+ 1 ] [ 1 ] ) Bitmap. cubicbezier = cubicbezier   bitmap = Bitmap ( 17 , 17 ) bitmap. cubicbezier ( 16 , 1 , 1 , 4 , 3 , 16 , 15 , 11 ) bitmap. chardisplay ( )     ''' The origin, 0,0; is the lower left, with x increasing to the right, and Y increasing upwards.   The chardisplay above produces the following output : +-----------------+ | | | | | | | | | @@@@ | | @@@ @@@ | | @ | | @ | | @ | | @ | | @ | | @ | | @ | | @ | | @@@@ | | @@@@| | | +-----------------+ ''' \ No newline at end of file diff --git a/rosetta/file5.rb b/rosetta/file5.rb new file mode 100644 index 0000000..ac35f08 --- /dev/null +++ b/rosetta/file5.rb @@ -0,0 +1 @@ +  require 'ffi'   module LibC extend FFI::Library ffi_lib FFI::Platform::LIBC   attach_function :strdup , [ : string ] , :pointer attach_function :free , [ :pointer ] , :void end   string = "Hello, World!" duplicate = LibC. strdup ( string ) puts duplicate. get_string ( 0 ) LibC. free ( duplicate )   \ No newline at end of file diff --git a/rosetta/file5.scala b/rosetta/file5.scala new file mode 100644 index 0000000..d65bb3b --- /dev/null +++ b/rosetta/file5.scala @@ -0,0 +1 @@ +scala > BigInt ( 5 ) modPow ( BigInt ( 4 ) pow ( BigInt ( 3 ) pow 2 ) . toInt , BigInt ( 10 ) pow 20 ) res21 : scala. math . BigInt = 92256259918212890625   scala > ( BigInt ( 5 ) pow ( BigInt ( 4 ) pow ( BigInt ( 3 ) pow 2 ) . toInt ) . toInt ) . toString res22 : String = 6206069878660874470748320557284679309194219265199117173177383244 78446890420544620839553285931321349485035253770303663683982841794590287939217907 89641300156281305613064874236198955114921296922487632406742326659692228562195387 46210423235340883954495598715281862895110697243759768434501295076608139350684049 01191160699929926568099301259938271975526587719565309995276438998093283175080241 55833224724855977970015112594128926594587205662421861723789001208275184293399910 13912158886504596553858675842231519094813553261073608575593794241686443569888058 92732524316323249492420512640962691673104618378381545202638771401061171968052873 21414945463925055899307933774904078819911387324217976311238875802878310483037255 33789567769926391314746986316354035923183981697660495275234703657750678459919 ... scala > res22 take 20 res23 : String = 62060698786608744707   scala > res22 length res24 : Int = 183231   scala > \ No newline at end of file diff --git a/rosetta/file5.ss b/rosetta/file5.ss new file mode 100644 index 0000000..c506a9b --- /dev/null +++ b/rosetta/file5.ss @@ -0,0 +1 @@ +( define ( A m n ) ( cond ( ( = m 0 ) ( + n 1 ) ) ( ( = n 0 ) ( A ( - m 1 ) 1 ) ) ( else ( A ( - m 1 ) ( A m ( - n 1 ) ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file5.tcl b/rosetta/file5.tcl new file mode 100644 index 0000000..1340d11 --- /dev/null +++ b/rosetta/file5.tcl @@ -0,0 +1 @@ +package require struct:: matrix package require math:: complexnumbers   proc complexMatrix.equal { m1 m2 { epsilon 1e-14 } } { if { [ $m1 rows ] ! = [ $m2 rows ] || [ $m1 columns ] ! = [ $m2 columns ] } { return 0 } # Compute the magnitude of the difference between two complex numbers set ceq [ list apply { { epsilon a b } { expr { [ mod [ - $a $b ] ] < $epsilon } }  :: math :: complexnumbers } $epsilon ] for { set i 0 } { $i < [ $m1 columns ] } { incr i } { for { set j 0 } { $j < [ $m1 rows ] } { incr j } { if { ! [ { * } $ceq [ $m1 get cell $i $j ] [ $m2 get cell $i $j ] ] } { return 0 } } } return 1 }   proc complexMatrix.multiply { a b } { if { [ $a columns ] ! = [ $b rows ] } { error "incompatible sizes" } # Simplest to use a lambda in the complex NS set cpm { { sum a b } { + $sum [ * $a $b ] }  :: math :: complexnumbers } set c0 [ math:: complexnumbers :: complex 0.0 0.0 ] ; # Complex zero set c [ struct:: matrix ] $c add columns [ $b columns ] $c add rows [ $a rows ] for { set i 0 } { $i < [ $a rows ] } { incr i } { for { set j 0 } { $j < [ $b columns ] } { incr j } { set sum $c0 foreach rv [ $a get row $i ] cv [ $b get column $j ] { set sum [ apply $cpm $sum $rv $cv ] } $c set cell $j $i $sum } } return $c }   proc complexMatrix.conjugateTranspose { matrix } { set mat [ struct:: matrix ] $mat = $matrix $mat transpose for { set c 0 } { $c < [ $mat columns ] } { incr c } { for { set r 0 } { $r < [ $mat rows ] } { incr r } { set val [ $mat get cell $c $r ] $mat set cell $c $r [ math:: complexnumbers :: conj $val ] } } return $mat } \ No newline at end of file diff --git a/rosetta/file50.clojure b/rosetta/file50.clojure new file mode 100644 index 0000000..9a2fb2f --- /dev/null +++ b/rosetta/file50.clojure @@ -0,0 +1 @@ +( defn encrypt - character [ offset c ] ( if ( Character / isLetter c ) ( let [ v ( int c ) base ( if ( >= v ( int \a ) ) ( int \a ) ( int \A ) ) offset ( mod offset 26 ) ] ;works with negative offsets too! ( char ( + ( mod ( + ( - v base ) offset ) 26 ) base ) ) ) c ) )   ( defn encrypt [ offset text ] ( apply str ( map # ( encrypt - character offset % ) text ) ) )   ( defn decrypt [ offset text ] ( encrypt ( - 26 offset ) text ) )     ( let [ text "The Quick Brown Fox Jumps Over The Lazy Dog." enc ( encrypt - 1 text ) ] ( print "Original text:" text " \n " ) ( print "Encryption:" enc " \n " ) ( print "Decryption:" ( decrypt - 1 enc ) " \n " ) ) \ No newline at end of file diff --git a/rosetta/file50.hs b/rosetta/file50.hs new file mode 100644 index 0000000..b12be0d --- /dev/null +++ b/rosetta/file50.hs @@ -0,0 +1 @@ +import Data . List ( tails , elemIndices , isPrefixOf )   replace :: String -> String -> String -> String replace [ ] _ xs = xs replace _ [ ] xs = xs replace _ _ [ ] = [ ] replace a b xs = replAll where -- make substrings, dropping one element each time xtails = tails xs -- what substrings begin with the string to replace? -- get their indices matches = elemIndices True $ map ( isPrefixOf a ) xtails -- replace one occurrence repl ys n = take n ys ++ b ++ drop ( n + length b ) ys -- replace all occurrences consecutively replAll = foldl repl xs matches   replaceInFiles a1 a2 files = do f <- mapM readFile files return $ map ( replace a1 a2 ) f   \ No newline at end of file diff --git a/rosetta/file50.java b/rosetta/file50.java new file mode 100644 index 0000000..34e947d --- /dev/null +++ b/rosetta/file50.java @@ -0,0 +1 @@ +import java.util.Scanner ; import java.util.Random ;   public class CheckpointSync { public static void main ( String [ ] args ) { System . out . print ( "Enter number of workers to use: " ) ; Scanner in = new Scanner ( System . in ) ; Worker. nWorkers = in. nextInt ( ) ; System . out . print ( "Enter number of tasks to complete:" ) ; runTasks ( in. nextInt ( ) ) ; }   /* * Informs that workers started working on the task and * starts running threads. Prior to proceeding with next * task syncs using static Worker.checkpoint() method. */ private static void runTasks ( int nTasks ) { for ( int i = 0 ; i < nTasks ; i ++ ) { System . out . println ( "Starting task number " + ( i + 1 ) + "." ) ; runThreads ( ) ; Worker. checkpoint ( ) ; } }   /* * Creates a thread for each worker and runs it. */ private static void runThreads ( ) { for ( int i = 0 ; i < Worker. nWorkers ; i ++ ) { new Thread ( new Worker ( i + 1 ) ) . start ( ) ; } }   /* * Worker inner static class. */ public static class Worker implements Runnable { public Worker ( int threadID ) { this . threadID = threadID ; } public void run ( ) { work ( ) ; }   /* * Notifies that thread started running for 100 to 1000 msec. * Once finished increments static counter 'nFinished' * that counts number of workers finished their work. */ private synchronized void work ( ) { try { int workTime = rgen. nextInt ( 900 ) + 100 ; System . out . println ( "Worker " + threadID + " will work for " + workTime + " msec." ) ; Thread . sleep ( workTime ) ; //work for 'workTime' nFinished ++; //increases work finished counter System . out . println ( "Worker " + threadID + " is ready" ) ; } catch ( InterruptedException e ) { System . err . println ( "Error: thread execution interrupted" ) ; e. printStackTrace ( ) ; } }   /* * Used to synchronize Worker threads using 'nFinished' static integer. * Waits (with step of 10 msec) until 'nFinished' equals to 'nWorkers'. * Once they are equal resets 'nFinished' counter. */ public static synchronized void checkpoint ( ) { while ( nFinished != nWorkers ) { try { Thread . sleep ( 10 ) ; } catch ( InterruptedException e ) { System . err . println ( "Error: thread execution interrupted" ) ; e. printStackTrace ( ) ; } } nFinished = 0 ; }   /* inner class instance variables */ private int threadID ;   /* static variables */ private static Random rgen = new Random ( ) ; private static int nFinished = 0 ; public static int nWorkers = 0 ; } } \ No newline at end of file diff --git a/rosetta/file50.js b/rosetta/file50.js new file mode 100644 index 0000000..ac5ab52 --- /dev/null +++ b/rosetta/file50.js @@ -0,0 +1 @@ +var fso = new ActiveXObject ( "Scripting.FileSystemObject" ) ;   fso. FileExists ( 'input.txt' ) ; fso. FileExists ( 'c:/input.txt' ) ; fso. FolderExists ( 'docs' ) ; fso. FolderExists ( 'c:/docs' ) ; \ No newline at end of file diff --git a/rosetta/file50.ocaml b/rosetta/file50.ocaml new file mode 100644 index 0000000..9388c31 --- /dev/null +++ b/rosetta/file50.ocaml @@ -0,0 +1 @@ +let srnd x = (* since OCaml's built-in int type is at least 31 (note: not 32) bits wide, and this problem takes mod 2^31, it is just enough if we treat it as an unsigned integer, which means taking the logical right shift *) let seed = ref x in fun ( ) -> seed := ( ! seed * 214013 + 2531011 ) land 0x7fffffff ; ! seed lsr 16   let deal s = let rnd = srnd s in let t = Array . init 52 ( fun i -> i ) in let cards = Array . init 52 ( fun j -> let n = 52 - j in let i = rnd ( ) mod n in let this = t . ( i ) in t . ( i ) <- t . ( pred n ) ; this ) in ( cards )   let show cards = let suits = "CDHS" and nums = "A23456789TJQK" in Array . iteri ( fun i card -> Printf . printf "%c%c%c" nums . [ card / 4 ] suits . [ card mod 4 ] ( if ( i mod 8 ) = 7 then ' \n ' else ' ' ) ) cards ; print_newline ( )   let ( ) = let s = try int_of_string Sys . argv . ( 1 ) with _ -> 11982 in Printf . printf "Deal %d:\n" s ; let cards = deal s in show cards \ No newline at end of file diff --git a/rosetta/file50.perl b/rosetta/file50.perl new file mode 100644 index 0000000..0851011 --- /dev/null +++ b/rosetta/file50.perl @@ -0,0 +1 @@ +sub outer { print "In outer, calling inner: \n " ; inner ( ) ; OUTER : print "at label OUTER \n " ; }   sub inner { print "In inner \n " ;   goto SKIP ; # goto same block level print "This should be skipped \n " ; SKIP : print "at label SKIP \n " ;   goto OUTER ; # goto whatever OUTER label there is on frame stack. # if there isn't any, exception will be raised print "Inner should never reach here \n " ; }   sub disguise { goto &outer ; # a different type of goto, it replaces the stack frame # with the outer() function's and pretend we called # that function to begin with print "Can't reach this statement \n " ; }   print "Calling outer: \n " ; outer ( ) ;   print " \n Calling disguise: \n " ; disguise ( ) ;   print " \n Calling inner: \n " ; inner ( ) ; # will die \ No newline at end of file diff --git a/rosetta/file50.php b/rosetta/file50.php new file mode 100644 index 0000000..6520618 --- /dev/null +++ b/rosetta/file50.php @@ -0,0 +1 @@ +// Static method MyClass :: method ( $someParameter ) ; // In PHP 5.3+, static method can be called on a string of the class name $foo = 'MyClass' ; $foo :: method ( $someParameter ) ;     // Instance method $myInstance -> method ( $someParameter ) ; \ No newline at end of file diff --git a/rosetta/file50.py b/rosetta/file50.py new file mode 100644 index 0000000..487a82e --- /dev/null +++ b/rosetta/file50.py @@ -0,0 +1 @@ +board = [ ] given = [ ] start = None   def setup ( s ) : global board , given , start lines = s. splitlines ( ) ncols = len ( lines [ 0 ] . split ( ) ) nrows = len ( lines ) board = [ [ - 1 ] * ( ncols + 2 ) for _ in xrange ( nrows + 2 ) ]   for r , row in enumerate ( lines ) : for c , cell in enumerate ( row. split ( ) ) : if cell == "__"  : board [ r + 1 ] [ c + 1 ] = 0 continue elif cell == "." : continue # -1 else : val = int ( cell ) board [ r + 1 ] [ c + 1 ] = val given. append ( val ) if val == 1 : start = ( r + 1 , c + 1 ) given. sort ( )   def solve ( r , c , n , next = 0 ) : if n > given [ - 1 ] : return True if board [ r ] [ c ] and board [ r ] [ c ] != n: return False if board [ r ] [ c ] == 0 and given [ next ] == n: return False   back = 0 if board [ r ] [ c ] == n: next + = 1 back = n   board [ r ] [ c ] = n for i in xrange ( - 1 , 2 ) : for j in xrange ( - 1 , 2 ) : if solve ( r + i , c + j , n + 1 , next ) : return True board [ r ] [ c ] = back return False   def print_board ( ) : d = { - 1 : " " , 0 : "__" } bmax = max ( max ( r ) for r in board ) form = "%" + str ( len ( str ( bmax ) ) + 1 ) + "s" for r in board [ 1 :- 1 ] : print "" . join ( form % d. get ( c , str ( c ) ) for c in r [ 1 :- 1 ] )   hi = """ \ __ 33 35 __ __ . . . __ __ 24 22 __ . . . __ __ __ 21 __ __ . . __ 26 __ 13 40 11 . . 27 __ __ __ 9 __ 1 . . . __ __ 18 __ __ . . . . . __ 7 __ __ . . . . . . 5 __"""   setup ( hi ) print_board ( ) solve ( start [ 0 ] , start [ 1 ] , 1 ) print print_board ( ) \ No newline at end of file diff --git a/rosetta/file50.rb b/rosetta/file50.rb new file mode 100644 index 0000000..9224a09 --- /dev/null +++ b/rosetta/file50.rb @@ -0,0 +1 @@ +descriptions = { :fly => "I don't know why S" , :spider => "That wriggled and jiggled and tickled inside her." , :bird => "Quite absurd T" , :cat => "Fancy that, S" , :dog => "What a hog, S" , :goat => "She opened her throat T" , :cow => "I don't know how S" , :horse => "She's dead, of course." , } animals = descriptions. keys   animals. each_with_index do | animal, idx | puts "There was an old lady who swallowed a #{animal}."   d = descriptions [ animal ] case d [ - 1 ] when "S" then d [ - 1 ] = "she swallowed a #{animal}." when "T" then d [ - 1 ] = "to swallow a #{animal}." end puts d break if animal == :horse   idx. downto ( 1 ) do | i | puts "She swallowed the #{animals[i]} to catch the #{animals[i-1]}." case animals [ i - 1 ] when :spider , :fly then puts descriptions [ animals [ i - 1 ] ] end end   print "Perhaps she'll die. \n \n " end \ No newline at end of file diff --git a/rosetta/file50.scala b/rosetta/file50.scala new file mode 100644 index 0000000..21bd646 --- /dev/null +++ b/rosetta/file50.scala @@ -0,0 +1 @@ +import java. util . { Calendar, GregorianCalendar } import Calendar. { DAY _ OF _ WEEK, DECEMBER, SUNDAY }   object DayOfTheWeek extends App { val years = 2008 to 2121   val yuletide = years. filter ( year => ( new GregorianCalendar ( year, DECEMBER, 25 ) ) . get ( DAY _ OF _ WEEK ) == SUNDAY )   // If you want a test: (optional) assert ( yuletide == Seq ( 2011 , 2016 , 2022 , 2033 , 2039 , 2044 , 2050 , 2061 , 2067 , 2072 , 2078 , 2089 , 2095 , 2101 , 2107 , 2112 , 2118 ) )   println ( yuletide. mkString ( s "${yuletide.length} Years between ${years.head} and ${years.last}" + " including where Christmas is observed on Sunday: \n " , ", " , "." ) ) } \ No newline at end of file diff --git a/rosetta/file50.ss b/rosetta/file50.ss new file mode 100644 index 0000000..260abfe --- /dev/null +++ b/rosetta/file50.ss @@ -0,0 +1 @@ +; ; Works with R7RS-compatible Schemes (e.g. Chibi). ; Also current versions of Chicken, Gauche and Kawa. ; ( cond - expand ( chicken ( use srfi - 13 ) ) ( gauche ( use srfi - 13 ) ) ( kawa ( import ( srfi : 13 ) ) ) ( else ( import ( scheme base ) ( scheme write ) ) ) ) ; R7RS     ( define msg "The quick brown fox jumps over the lazy dog." ) ( define key 13 )   ( define ( caesar char ) ( define A ( char -> integer #\A ) ) ( define Z ( char -> integer #\Z ) ) ( define a ( char -> integer #\a ) ) ( define z ( char -> integer #\z ) ) ( define c ( char -> integer char ) ) ( integer -> char ( cond ( ( <= A c Z ) ( + A ( modulo ( + key ( - c A ) ) 26 ) ) ) ( ( <= a c z ) ( + a ( modulo ( + key ( - c a ) ) 26 ) ) ) ( else c ) ) ) ) ; Return other characters verbatim.   ( display ( string - map caesar msg ) ) ( newline )   \ No newline at end of file diff --git a/rosetta/file50.tcl b/rosetta/file50.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file50.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file51.clojure b/rosetta/file51.clojure new file mode 100644 index 0000000..3dbdeeb --- /dev/null +++ b/rosetta/file51.clojure @@ -0,0 +1 @@ +( Long / toHexString 15 ) ; use forward slash for static methods ( System / currentTimeMillis )   ( . equals 1 2 ) ; use dot operator to call instance methods ( . 1 ( equals 2 ) ) ; alternative style \ No newline at end of file diff --git a/rosetta/file51.hs b/rosetta/file51.hs new file mode 100644 index 0000000..720837b --- /dev/null +++ b/rosetta/file51.hs @@ -0,0 +1 @@ +  import Control . Monad import System . Random   -- Repeat the action until the predicate is true. until _ act pred = act >>= pred >>= flip unless ( until _ act pred )   answerIs ans guess = case compare ans guess of LT -> putStrLn "Too high. Guess again." >> return False EQ -> putStrLn "You got it!" >> return True GT -> putStrLn "Too low. Guess again." >> return False   -- Repeatedly read until the input *starts* with a number. (Since -- we use "reads" we allow garbage to follow it, though.) ask = do line <- getLine case reads line of ( ( num ,_ ) : _ ) -> return num otherwise -> putStrLn "Please enter a number." >> ask   main = do ans <- randomRIO ( 1 , 100 ) :: IO Int putStrLn "Try to guess my secret number between 1 and 100." ask `until _ ` answerIs ans   \ No newline at end of file diff --git a/rosetta/file51.java b/rosetta/file51.java new file mode 100644 index 0000000..34e947d --- /dev/null +++ b/rosetta/file51.java @@ -0,0 +1 @@ +import java.util.Scanner ; import java.util.Random ;   public class CheckpointSync { public static void main ( String [ ] args ) { System . out . print ( "Enter number of workers to use: " ) ; Scanner in = new Scanner ( System . in ) ; Worker. nWorkers = in. nextInt ( ) ; System . out . print ( "Enter number of tasks to complete:" ) ; runTasks ( in. nextInt ( ) ) ; }   /* * Informs that workers started working on the task and * starts running threads. Prior to proceeding with next * task syncs using static Worker.checkpoint() method. */ private static void runTasks ( int nTasks ) { for ( int i = 0 ; i < nTasks ; i ++ ) { System . out . println ( "Starting task number " + ( i + 1 ) + "." ) ; runThreads ( ) ; Worker. checkpoint ( ) ; } }   /* * Creates a thread for each worker and runs it. */ private static void runThreads ( ) { for ( int i = 0 ; i < Worker. nWorkers ; i ++ ) { new Thread ( new Worker ( i + 1 ) ) . start ( ) ; } }   /* * Worker inner static class. */ public static class Worker implements Runnable { public Worker ( int threadID ) { this . threadID = threadID ; } public void run ( ) { work ( ) ; }   /* * Notifies that thread started running for 100 to 1000 msec. * Once finished increments static counter 'nFinished' * that counts number of workers finished their work. */ private synchronized void work ( ) { try { int workTime = rgen. nextInt ( 900 ) + 100 ; System . out . println ( "Worker " + threadID + " will work for " + workTime + " msec." ) ; Thread . sleep ( workTime ) ; //work for 'workTime' nFinished ++; //increases work finished counter System . out . println ( "Worker " + threadID + " is ready" ) ; } catch ( InterruptedException e ) { System . err . println ( "Error: thread execution interrupted" ) ; e. printStackTrace ( ) ; } }   /* * Used to synchronize Worker threads using 'nFinished' static integer. * Waits (with step of 10 msec) until 'nFinished' equals to 'nWorkers'. * Once they are equal resets 'nFinished' counter. */ public static synchronized void checkpoint ( ) { while ( nFinished != nWorkers ) { try { Thread . sleep ( 10 ) ; } catch ( InterruptedException e ) { System . err . println ( "Error: thread execution interrupted" ) ; e. printStackTrace ( ) ; } } nFinished = 0 ; }   /* inner class instance variables */ private int threadID ;   /* static variables */ private static Random rgen = new Random ( ) ; private static int nFinished = 0 ; public static int nWorkers = 0 ; } } \ No newline at end of file diff --git a/rosetta/file51.js b/rosetta/file51.js new file mode 100644 index 0000000..550be7d --- /dev/null +++ b/rosetta/file51.js @@ -0,0 +1 @@ +var array = [ ] ; array. push ( 'abc' ) ; array. push ( 123 ) ; array. push ( new MyClass ) ; alert ( array [ 2 ] ) ; \ No newline at end of file diff --git a/rosetta/file51.ocaml b/rosetta/file51.ocaml new file mode 100644 index 0000000..5ea9a6b --- /dev/null +++ b/rosetta/file51.ocaml @@ -0,0 +1 @@ +exception Out_of_bounds   type ' a bounds = { min : ' a ; max : ' a }   type ' a bounded = { value : ' a ; bounds : ' a bounds }   let mk_bounds ~ min ~ max = { min = min ; max = max } ;; (** val mk_bounds : min:'a -> max:'a -> 'a bounds *)   let check_bounds ~value ~bounds = if value < bounds . min || value > bounds . max then raise Out_of_bounds ;; (** val check_bounds : value:'a -> bounds:'a bounds -> unit *)   let mk_bounded ~value ~bounds = check_bounds ~value ~bounds ; { value = value ; bounds = bounds } ;; (** val mk_bounded : value:'a -> bounds:'a bounds -> 'a bounded *)   let op f a b = let res = f a . value b . value in if a . bounds <> b . bounds then invalid_arg "different bounds" ; check_bounds res a . bounds ; ( mk_bounded res a . bounds ) ;; (** val op : ('a -> 'a -> 'a) -> 'a bounded -> 'a bounded -> 'a bounded *) \ No newline at end of file diff --git a/rosetta/file51.perl b/rosetta/file51.perl new file mode 100644 index 0000000..0851011 --- /dev/null +++ b/rosetta/file51.perl @@ -0,0 +1 @@ +sub outer { print "In outer, calling inner: \n " ; inner ( ) ; OUTER : print "at label OUTER \n " ; }   sub inner { print "In inner \n " ;   goto SKIP ; # goto same block level print "This should be skipped \n " ; SKIP : print "at label SKIP \n " ;   goto OUTER ; # goto whatever OUTER label there is on frame stack. # if there isn't any, exception will be raised print "Inner should never reach here \n " ; }   sub disguise { goto &outer ; # a different type of goto, it replaces the stack frame # with the outer() function's and pretend we called # that function to begin with print "Can't reach this statement \n " ; }   print "Calling outer: \n " ; outer ( ) ;   print " \n Calling disguise: \n " ; disguise ( ) ;   print " \n Calling inner: \n " ; inner ( ) ; # will die \ No newline at end of file diff --git a/rosetta/file51.php b/rosetta/file51.php new file mode 100644 index 0000000..6520618 --- /dev/null +++ b/rosetta/file51.php @@ -0,0 +1 @@ +// Static method MyClass :: method ( $someParameter ) ; // In PHP 5.3+, static method can be called on a string of the class name $foo = 'MyClass' ; $foo :: method ( $someParameter ) ;     // Instance method $myInstance -> method ( $someParameter ) ; \ No newline at end of file diff --git a/rosetta/file51.py b/rosetta/file51.py new file mode 100644 index 0000000..487a82e --- /dev/null +++ b/rosetta/file51.py @@ -0,0 +1 @@ +board = [ ] given = [ ] start = None   def setup ( s ) : global board , given , start lines = s. splitlines ( ) ncols = len ( lines [ 0 ] . split ( ) ) nrows = len ( lines ) board = [ [ - 1 ] * ( ncols + 2 ) for _ in xrange ( nrows + 2 ) ]   for r , row in enumerate ( lines ) : for c , cell in enumerate ( row. split ( ) ) : if cell == "__"  : board [ r + 1 ] [ c + 1 ] = 0 continue elif cell == "." : continue # -1 else : val = int ( cell ) board [ r + 1 ] [ c + 1 ] = val given. append ( val ) if val == 1 : start = ( r + 1 , c + 1 ) given. sort ( )   def solve ( r , c , n , next = 0 ) : if n > given [ - 1 ] : return True if board [ r ] [ c ] and board [ r ] [ c ] != n: return False if board [ r ] [ c ] == 0 and given [ next ] == n: return False   back = 0 if board [ r ] [ c ] == n: next + = 1 back = n   board [ r ] [ c ] = n for i in xrange ( - 1 , 2 ) : for j in xrange ( - 1 , 2 ) : if solve ( r + i , c + j , n + 1 , next ) : return True board [ r ] [ c ] = back return False   def print_board ( ) : d = { - 1 : " " , 0 : "__" } bmax = max ( max ( r ) for r in board ) form = "%" + str ( len ( str ( bmax ) ) + 1 ) + "s" for r in board [ 1 :- 1 ] : print "" . join ( form % d. get ( c , str ( c ) ) for c in r [ 1 :- 1 ] )   hi = """ \ __ 33 35 __ __ . . . __ __ 24 22 __ . . . __ __ __ 21 __ __ . . __ 26 __ 13 40 11 . . 27 __ __ __ 9 __ 1 . . . __ __ 18 __ __ . . . . . __ 7 __ __ . . . . . . 5 __"""   setup ( hi ) print_board ( ) solve ( start [ 0 ] , start [ 1 ] , 1 ) print print_board ( ) \ No newline at end of file diff --git a/rosetta/file51.rb b/rosetta/file51.rb new file mode 100644 index 0000000..022e611 --- /dev/null +++ b/rosetta/file51.rb @@ -0,0 +1 @@ +require 'rubygems' require 'gl' require 'glut'   include Gl include Glut   paint = lambda do glClearColor ( 0.3 , 0.3 , 0.3 , 0.0 ) glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT )   glShadeModel ( GL_SMOOTH )   glLoadIdentity glTranslatef ( - 15.0 , - 15.0 , 0.0 )   glBegin ( GL_TRIANGLES ) glColor3f ( 1.0 , 0.0 , 0.0 ) glVertex2f ( 0.0 , 0.0 ) glColor3f ( 0.0 , 1.0 , 0.0 ) glVertex2f ( 30.0 , 0.0 ) glColor3f ( 0.0 , 0.0 , 1.0 ) glVertex2f ( 0.0 , 30.0 ) glEnd   glFlush end   reshape = lambda do | width, height | glViewport ( 0 , 0 , width, height ) glMatrixMode ( GL_PROJECTION ) glLoadIdentity glOrtho ( - 30.0 , 30.0 , - 30.0 , 30.0 , - 30.0 , 30.0 ) glMatrixMode ( GL_MODELVIEW ) end   glutInit glutInitWindowSize ( 640 , 480 ) glutCreateWindow ( "Triangle" )   glutDisplayFunc ( paint ) glutReshapeFunc ( reshape )   glutMainLoop \ No newline at end of file diff --git a/rosetta/file51.scala b/rosetta/file51.scala new file mode 100644 index 0000000..21bd646 --- /dev/null +++ b/rosetta/file51.scala @@ -0,0 +1 @@ +import java. util . { Calendar, GregorianCalendar } import Calendar. { DAY _ OF _ WEEK, DECEMBER, SUNDAY }   object DayOfTheWeek extends App { val years = 2008 to 2121   val yuletide = years. filter ( year => ( new GregorianCalendar ( year, DECEMBER, 25 ) ) . get ( DAY _ OF _ WEEK ) == SUNDAY )   // If you want a test: (optional) assert ( yuletide == Seq ( 2011 , 2016 , 2022 , 2033 , 2039 , 2044 , 2050 , 2061 , 2067 , 2072 , 2078 , 2089 , 2095 , 2101 , 2107 , 2112 , 2118 ) )   println ( yuletide. mkString ( s "${yuletide.length} Years between ${years.head} and ${years.last}" + " including where Christmas is observed on Sunday: \n " , ", " , "." ) ) } \ No newline at end of file diff --git a/rosetta/file51.ss b/rosetta/file51.ss new file mode 100644 index 0000000..260abfe --- /dev/null +++ b/rosetta/file51.ss @@ -0,0 +1 @@ +; ; Works with R7RS-compatible Schemes (e.g. Chibi). ; Also current versions of Chicken, Gauche and Kawa. ; ( cond - expand ( chicken ( use srfi - 13 ) ) ( gauche ( use srfi - 13 ) ) ( kawa ( import ( srfi : 13 ) ) ) ( else ( import ( scheme base ) ( scheme write ) ) ) ) ; R7RS     ( define msg "The quick brown fox jumps over the lazy dog." ) ( define key 13 )   ( define ( caesar char ) ( define A ( char -> integer #\A ) ) ( define Z ( char -> integer #\Z ) ) ( define a ( char -> integer #\a ) ) ( define z ( char -> integer #\z ) ) ( define c ( char -> integer char ) ) ( integer -> char ( cond ( ( <= A c Z ) ( + A ( modulo ( + key ( - c A ) ) 26 ) ) ) ( ( <= a c z ) ( + a ( modulo ( + key ( - c a ) ) 26 ) ) ) ( else c ) ) ) ) ; Return other characters verbatim.   ( display ( string - map caesar msg ) ) ( newline )   \ No newline at end of file diff --git a/rosetta/file51.tcl b/rosetta/file51.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file51.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file52.clojure b/rosetta/file52.clojure new file mode 100644 index 0000000..3dbdeeb --- /dev/null +++ b/rosetta/file52.clojure @@ -0,0 +1 @@ +( Long / toHexString 15 ) ; use forward slash for static methods ( System / currentTimeMillis )   ( . equals 1 2 ) ; use dot operator to call instance methods ( . 1 ( equals 2 ) ) ; alternative style \ No newline at end of file diff --git a/rosetta/file52.hs b/rosetta/file52.hs new file mode 100644 index 0000000..5038f0c --- /dev/null +++ b/rosetta/file52.hs @@ -0,0 +1 @@ +import Graphics . UI . WX import System . Random   main :: IO ( ) main = start $ do frm <- frame [ text : = "Interact" ] fld <- textEntry frm [ text : = "0" , on keyboard : = checkKeys ] inc <- button frm [ text : = "increment" , on command : = increment fld ] ran <- button frm [ text : = "random" , on command : = ( randReplace fld frm ) ] set frm [ layout : = margin 5 $ floatCentre $ column 2 [ centre $ widget fld , row 2 [ widget inc , widget ran ] ] ]   increment :: Textual w => w -> IO ( ) increment field = do val <- get field text when ( ( not . null ) val ) $ set field [ text : = show $ 1 + read val ]   checkKeys :: EventKey -> IO ( ) checkKeys ( EventKey key _ _ ) = when ( elem ( show key ) $ "Backspace"  : map show [ 0 .. 9 ] ) propagateEvent   randReplace :: Textual w => w -> Window a -> IO ( ) randReplace field frame = do answer <- confirmDialog frame "Random" "Generate a random number?" True when answer $ getStdRandom ( randomR ( 1 , 100 ) ) >>= \num -> set field [ text : = show ( num :: Int ) ] \ No newline at end of file diff --git a/rosetta/file52.java b/rosetta/file52.java new file mode 100644 index 0000000..39bef8b --- /dev/null +++ b/rosetta/file52.java @@ -0,0 +1 @@ +import java.util.function.Supplier ; import java.util.ArrayList ;   public class ValueCapture { public static void main ( String [ ] args ) { ArrayList < Supplier < Integer >> funcs = new ArrayList <> ( ) ; for ( int i = 0 ; i < 10 ; i ++ ) { int j = i ; funcs. add ( ( ) -> j * j ) ; }   Supplier < Integer > foo = funcs. get ( 3 ) ; System . out . println ( foo. get ( ) ) ; // prints "9" } } \ No newline at end of file diff --git a/rosetta/file52.js b/rosetta/file52.js new file mode 100644 index 0000000..550be7d --- /dev/null +++ b/rosetta/file52.js @@ -0,0 +1 @@ +var array = [ ] ; array. push ( 'abc' ) ; array. push ( 123 ) ; array. push ( new MyClass ) ; alert ( array [ 2 ] ) ; \ No newline at end of file diff --git a/rosetta/file52.ocaml b/rosetta/file52.ocaml new file mode 100644 index 0000000..e3d058a --- /dev/null +++ b/rosetta/file52.ocaml @@ -0,0 +1 @@ +open Sem   let ( ) = let oflags = [ Unix . O_CREAT ; Unix . O_EXCL ] in let sem = sem_open "MyUniqueName" ~oflags ( ) in (* here the real code of the app *) Unix . sleep 20 ; (* end of the app *) sem_unlink "MyUniqueName" ; sem_close sem \ No newline at end of file diff --git a/rosetta/file52.perl b/rosetta/file52.perl new file mode 100644 index 0000000..5197458 --- /dev/null +++ b/rosetta/file52.perl @@ -0,0 +1 @@ +use Term :: ReadKey ; ReadMode 'restore' ; # Flush the keyboard and returns input stream to initial state # ReadMode 0; # Numerical equivalent of keyboard restore (move comment marker to use instead)   # A more complete example for use in keyboard handler programming. # We should also check we are being used in an interactive context (not done here).   use Term :: ReadKey ; ReadMode 'cbreak' ;   # Flush the keyboard in terminal character break mode while ( defined ReadKey - 1 ) { # Do nothing }   # Don't forget to restore the readmode, when we are finished using the keyboard ReadMode 'restore' ; \ No newline at end of file diff --git a/rosetta/file52.php b/rosetta/file52.php new file mode 100644 index 0000000..c3a105d --- /dev/null +++ b/rosetta/file52.php @@ -0,0 +1 @@ + 1 ) ;   private function fill_cache ( $i ) { $accum = 0 ; $n = $i - 1 ; for ( $k = 0 ; $k <= $n ; $k ++ ) { $accum += $this -> item ( $k ) * $this -> item ( $n - $k ) ; } self :: $cache [ $i ] = $accum ; } function item ( $i ) { if ( ! isset ( self :: $cache [ $i ] ) ) { $this -> fill_cache ( $i ) ; } return self :: $cache [ $i ] ; } }   $cn = new CatalanNumbersSerie ( ) ; for ( $i = 0 ; $i <= 15 ; $i ++ ) { $r = $cn -> item ( $i ) ; echo " $i = $r \r \n " ; } ?> \ No newline at end of file diff --git a/rosetta/file52.py b/rosetta/file52.py new file mode 100644 index 0000000..487a82e --- /dev/null +++ b/rosetta/file52.py @@ -0,0 +1 @@ +board = [ ] given = [ ] start = None   def setup ( s ) : global board , given , start lines = s. splitlines ( ) ncols = len ( lines [ 0 ] . split ( ) ) nrows = len ( lines ) board = [ [ - 1 ] * ( ncols + 2 ) for _ in xrange ( nrows + 2 ) ]   for r , row in enumerate ( lines ) : for c , cell in enumerate ( row. split ( ) ) : if cell == "__"  : board [ r + 1 ] [ c + 1 ] = 0 continue elif cell == "." : continue # -1 else : val = int ( cell ) board [ r + 1 ] [ c + 1 ] = val given. append ( val ) if val == 1 : start = ( r + 1 , c + 1 ) given. sort ( )   def solve ( r , c , n , next = 0 ) : if n > given [ - 1 ] : return True if board [ r ] [ c ] and board [ r ] [ c ] != n: return False if board [ r ] [ c ] == 0 and given [ next ] == n: return False   back = 0 if board [ r ] [ c ] == n: next + = 1 back = n   board [ r ] [ c ] = n for i in xrange ( - 1 , 2 ) : for j in xrange ( - 1 , 2 ) : if solve ( r + i , c + j , n + 1 , next ) : return True board [ r ] [ c ] = back return False   def print_board ( ) : d = { - 1 : " " , 0 : "__" } bmax = max ( max ( r ) for r in board ) form = "%" + str ( len ( str ( bmax ) ) + 1 ) + "s" for r in board [ 1 :- 1 ] : print "" . join ( form % d. get ( c , str ( c ) ) for c in r [ 1 :- 1 ] )   hi = """ \ __ 33 35 __ __ . . . __ __ 24 22 __ . . . __ __ __ 21 __ __ . . __ 26 __ 13 40 11 . . 27 __ __ __ 9 __ 1 . . . __ __ 18 __ __ . . . . . __ 7 __ __ . . . . . . 5 __"""   setup ( hi ) print_board ( ) solve ( start [ 0 ] , start [ 1 ] , 1 ) print print_board ( ) \ No newline at end of file diff --git a/rosetta/file52.rb b/rosetta/file52.rb new file mode 100644 index 0000000..a20de8e --- /dev/null +++ b/rosetta/file52.rb @@ -0,0 +1 @@ +MAX_N = 500 BRANCH = 4   def tree ( br, n, l=n, sum= 1 , cnt= 1 ) for b in br + 1 .. BRANCH sum + = n return if sum > = MAX_N # prevent unneeded long math return if l * 2 > = sum and b > = BRANCH if b == br + 1 c = $ra [ n ] * cnt else c = c * ( $ra [ n ] + ( b - br - 1 ) ) / ( b - br ) end $unrooted [ sum ] + = c if l * 2 < sum next if b > = BRANCH $ra [ sum ] + = c ( 1 ... n ) . each { | m | tree ( b, m, l, sum, c ) } end end   def bicenter ( s ) return if s. odd ? aux = $ra [ s / 2 ] $unrooted [ s ] + = aux * ( aux + 1 ) / 2 end   $ra = [ 0 ] * MAX_N $unrooted = [ 0 ] * MAX_N   $ra [ 0 ] = $ra [ 1 ] = $unrooted [ 0 ] = $unrooted [ 1 ] = 1 for n in 1 ... MAX_N tree ( 0 , n ) bicenter ( n ) puts "%d: %d" % [ n, $unrooted [ n ] ] end \ No newline at end of file diff --git a/rosetta/file52.scala b/rosetta/file52.scala new file mode 100644 index 0000000..2b5b859 --- /dev/null +++ b/rosetta/file52.scala @@ -0,0 +1 @@ + class TinyInt ( val int : Byte ) { import TinyInt. _ require ( int >= lower && int <= upper, "TinyInt out of bounds." )   override def toString = int . toString }   object TinyInt { val ( lower, upper ) = ( 1 , 10 )   def apply ( i : Byte ) = new TinyInt ( i ) }   val test = ( TinyInt. lower to TinyInt. upper ) . map ( n => TinyInt ( n. toByte ) ) \ No newline at end of file diff --git a/rosetta/file52.ss b/rosetta/file52.ss new file mode 100644 index 0000000..260abfe --- /dev/null +++ b/rosetta/file52.ss @@ -0,0 +1 @@ +; ; Works with R7RS-compatible Schemes (e.g. Chibi). ; Also current versions of Chicken, Gauche and Kawa. ; ( cond - expand ( chicken ( use srfi - 13 ) ) ( gauche ( use srfi - 13 ) ) ( kawa ( import ( srfi : 13 ) ) ) ( else ( import ( scheme base ) ( scheme write ) ) ) ) ; R7RS     ( define msg "The quick brown fox jumps over the lazy dog." ) ( define key 13 )   ( define ( caesar char ) ( define A ( char -> integer #\A ) ) ( define Z ( char -> integer #\Z ) ) ( define a ( char -> integer #\a ) ) ( define z ( char -> integer #\z ) ) ( define c ( char -> integer char ) ) ( integer -> char ( cond ( ( <= A c Z ) ( + A ( modulo ( + key ( - c A ) ) 26 ) ) ) ( ( <= a c z ) ( + a ( modulo ( + key ( - c a ) ) 26 ) ) ) ( else c ) ) ) ) ; Return other characters verbatim.   ( display ( string - map caesar msg ) ) ( newline )   \ No newline at end of file diff --git a/rosetta/file52.tcl b/rosetta/file52.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file52.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file53.clojure b/rosetta/file53.clojure new file mode 100644 index 0000000..3dbdeeb --- /dev/null +++ b/rosetta/file53.clojure @@ -0,0 +1 @@ +( Long / toHexString 15 ) ; use forward slash for static methods ( System / currentTimeMillis )   ( . equals 1 2 ) ; use dot operator to call instance methods ( . 1 ( equals 2 ) ) ; alternative style \ No newline at end of file diff --git a/rosetta/file53.hs b/rosetta/file53.hs new file mode 100644 index 0000000..01adb7f --- /dev/null +++ b/rosetta/file53.hs @@ -0,0 +1 @@ +  import System . Cmd   cmd = "echo \" Hello World! \" | lpr"   main = system cmd   \ No newline at end of file diff --git a/rosetta/file53.java b/rosetta/file53.java new file mode 100644 index 0000000..1d5f95a --- /dev/null +++ b/rosetta/file53.java @@ -0,0 +1 @@ +public static Color getColorAt ( int x, int y ) { return new Robot ( ) . getPixelColor ( x, y ) ; } \ No newline at end of file diff --git a/rosetta/file53.js b/rosetta/file53.js new file mode 100644 index 0000000..550be7d --- /dev/null +++ b/rosetta/file53.js @@ -0,0 +1 @@ +var array = [ ] ; array. push ( 'abc' ) ; array. push ( 123 ) ; array. push ( new MyClass ) ; alert ( array [ 2 ] ) ; \ No newline at end of file diff --git a/rosetta/file53.ocaml b/rosetta/file53.ocaml new file mode 100644 index 0000000..e3d058a --- /dev/null +++ b/rosetta/file53.ocaml @@ -0,0 +1 @@ +open Sem   let ( ) = let oflags = [ Unix . O_CREAT ; Unix . O_EXCL ] in let sem = sem_open "MyUniqueName" ~oflags ( ) in (* here the real code of the app *) Unix . sleep 20 ; (* end of the app *) sem_unlink "MyUniqueName" ; sem_close sem \ No newline at end of file diff --git a/rosetta/file53.perl b/rosetta/file53.perl new file mode 100644 index 0000000..b3fba0f --- /dev/null +++ b/rosetta/file53.perl @@ -0,0 +1 @@ +use Term :: ReadKey ;   ReadMode 4 ; # change to raw input mode   my $key = '' ;   while ( $key !~ /(Y|N)/i ) { 1 while defined ReadKey - 1 ; # discard any previous input print "Type Y/N: " ; $key = ReadKey 0 ; # read a single character print "$key \n " ; }   ReadMode 0 ; # reset the terminal to normal mode   print " \n You typed: $key \n " ;   \ No newline at end of file diff --git a/rosetta/file53.php b/rosetta/file53.php new file mode 100644 index 0000000..c3a105d --- /dev/null +++ b/rosetta/file53.php @@ -0,0 +1 @@ + 1 ) ;   private function fill_cache ( $i ) { $accum = 0 ; $n = $i - 1 ; for ( $k = 0 ; $k <= $n ; $k ++ ) { $accum += $this -> item ( $k ) * $this -> item ( $n - $k ) ; } self :: $cache [ $i ] = $accum ; } function item ( $i ) { if ( ! isset ( self :: $cache [ $i ] ) ) { $this -> fill_cache ( $i ) ; } return self :: $cache [ $i ] ; } }   $cn = new CatalanNumbersSerie ( ) ; for ( $i = 0 ; $i <= 15 ; $i ++ ) { $r = $cn -> item ( $i ) ; echo " $i = $r \r \n " ; } ?> \ No newline at end of file diff --git a/rosetta/file53.py b/rosetta/file53.py new file mode 100644 index 0000000..ac55782 --- /dev/null +++ b/rosetta/file53.py @@ -0,0 +1 @@ +>>> def sort_disjoint_sublist ( data , indices ) : indices = sorted ( indices ) values = sorted ( data [ i ] for i in indices ) for index , value in zip ( indices , values ) : data [ index ] = value     >>> d = [ 7 , 6 , 5 , 4 , 3 , 2 , 1 , 0 ] >>> i = set ( [ 6 , 1 , 7 ] ) >>> sort_disjoint_sublist ( d , i ) >>> d [ 7 , 0 , 5 , 4 , 3 , 2 , 1 , 6 ] >>> # Which could be more cryptically written as: >>> def sort_disjoint_sublist ( data , indices ) : for index , value in zip ( sorted ( indices ) , sorted ( data [ i ] for i in indices ) ) : data [ index ] = value     >>> \ No newline at end of file diff --git a/rosetta/file53.rb b/rosetta/file53.rb new file mode 100644 index 0000000..a20de8e --- /dev/null +++ b/rosetta/file53.rb @@ -0,0 +1 @@ +MAX_N = 500 BRANCH = 4   def tree ( br, n, l=n, sum= 1 , cnt= 1 ) for b in br + 1 .. BRANCH sum + = n return if sum > = MAX_N # prevent unneeded long math return if l * 2 > = sum and b > = BRANCH if b == br + 1 c = $ra [ n ] * cnt else c = c * ( $ra [ n ] + ( b - br - 1 ) ) / ( b - br ) end $unrooted [ sum ] + = c if l * 2 < sum next if b > = BRANCH $ra [ sum ] + = c ( 1 ... n ) . each { | m | tree ( b, m, l, sum, c ) } end end   def bicenter ( s ) return if s. odd ? aux = $ra [ s / 2 ] $unrooted [ s ] + = aux * ( aux + 1 ) / 2 end   $ra = [ 0 ] * MAX_N $unrooted = [ 0 ] * MAX_N   $ra [ 0 ] = $ra [ 1 ] = $unrooted [ 0 ] = $unrooted [ 1 ] = 1 for n in 1 ... MAX_N tree ( 0 , n ) bicenter ( n ) puts "%d: %d" % [ n, $unrooted [ n ] ] end \ No newline at end of file diff --git a/rosetta/file53.scala b/rosetta/file53.scala new file mode 100644 index 0000000..f387560 --- /dev/null +++ b/rosetta/file53.scala @@ -0,0 +1 @@ +  def isNumeric ( input : String ) : Boolean = input. forall ( _ . isDigit )   \ No newline at end of file diff --git a/rosetta/file53.ss b/rosetta/file53.ss new file mode 100644 index 0000000..260abfe --- /dev/null +++ b/rosetta/file53.ss @@ -0,0 +1 @@ +; ; Works with R7RS-compatible Schemes (e.g. Chibi). ; Also current versions of Chicken, Gauche and Kawa. ; ( cond - expand ( chicken ( use srfi - 13 ) ) ( gauche ( use srfi - 13 ) ) ( kawa ( import ( srfi : 13 ) ) ) ( else ( import ( scheme base ) ( scheme write ) ) ) ) ; R7RS     ( define msg "The quick brown fox jumps over the lazy dog." ) ( define key 13 )   ( define ( caesar char ) ( define A ( char -> integer #\A ) ) ( define Z ( char -> integer #\Z ) ) ( define a ( char -> integer #\a ) ) ( define z ( char -> integer #\z ) ) ( define c ( char -> integer char ) ) ( integer -> char ( cond ( ( <= A c Z ) ( + A ( modulo ( + key ( - c A ) ) 26 ) ) ) ( ( <= a c z ) ( + a ( modulo ( + key ( - c a ) ) 26 ) ) ) ( else c ) ) ) ) ; Return other characters verbatim.   ( display ( string - map caesar msg ) ) ( newline )   \ No newline at end of file diff --git a/rosetta/file53.tcl b/rosetta/file53.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file53.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file54.clojure b/rosetta/file54.clojure new file mode 100644 index 0000000..3dbdeeb --- /dev/null +++ b/rosetta/file54.clojure @@ -0,0 +1 @@ +( Long / toHexString 15 ) ; use forward slash for static methods ( System / currentTimeMillis )   ( . equals 1 2 ) ; use dot operator to call instance methods ( . 1 ( equals 2 ) ) ; alternative style \ No newline at end of file diff --git a/rosetta/file54.hs b/rosetta/file54.hs new file mode 100644 index 0000000..be89005 --- /dev/null +++ b/rosetta/file54.hs @@ -0,0 +1 @@ +{-# LANGUAGE OverloadedStrings #-}   import Data . ByteString . Char8 ( ) import Data . Conduit ( ( $$ ) , yield ) import Data . Conduit . Network ( ServerSettings ( .. ) , runTCPServer )   main :: IO ( ) main = runTCPServer ( ServerSettings 8080 "127.0.0.1" ) $ const ( yield response $$ ) where response = "HTTP/1.0 200 OK \n Content-Length: 16 \n \n Goodbye, World! \n " \ No newline at end of file diff --git a/rosetta/file54.java b/rosetta/file54.java new file mode 100644 index 0000000..b3edb60 --- /dev/null +++ b/rosetta/file54.java @@ -0,0 +1 @@ +import java.awt.* ; import static java. awt . Color . *; import javax.swing.* ;   public class ColourPinstripeDisplay extends JPanel { final static Color [ ] palette = { black, red, green, blue, magenta,cyan, yellow, white } ;   final int bands = 4 ;   public ColourPinstripeDisplay ( ) { setPreferredSize ( new Dimension ( 900 , 600 ) ) ; }   @Override public void paintComponent ( Graphics g ) { super . paintComponent ( g ) ; int h = getHeight ( ) ; for ( int b = 1 ; b <= bands ; b ++ ) { for ( int x = 0 , colIndex = 0 ; x < getWidth ( ) ; x += b, colIndex ++ ) { g. setColor ( palette [ colIndex % palette. length ] ) ; g. fillRect ( x, ( b - 1 ) * ( h / bands ) , x + b, b * ( h / bands ) ) ; } } }   public static void main ( String [ ] args ) { SwingUtilities . invokeLater ( ( ) -> { JFrame f = new JFrame ( ) ; f. setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE ) ; f. setTitle ( "ColourPinstripeDisplay" ) ; f. add ( new ColourPinstripeDisplay ( ) , BorderLayout . CENTER ) ; f. pack ( ) ; f. setLocationRelativeTo ( null ) ; f. setVisible ( true ) ; } ) ; } } \ No newline at end of file diff --git a/rosetta/file54.js b/rosetta/file54.js new file mode 100644 index 0000000..550be7d --- /dev/null +++ b/rosetta/file54.js @@ -0,0 +1 @@ +var array = [ ] ; array. push ( 'abc' ) ; array. push ( 123 ) ; array. push ( new MyClass ) ; alert ( array [ 2 ] ) ; \ No newline at end of file diff --git a/rosetta/file54.ocaml b/rosetta/file54.ocaml new file mode 100644 index 0000000..e3d058a --- /dev/null +++ b/rosetta/file54.ocaml @@ -0,0 +1 @@ +open Sem   let ( ) = let oflags = [ Unix . O_CREAT ; Unix . O_EXCL ] in let sem = sem_open "MyUniqueName" ~oflags ( ) in (* here the real code of the app *) Unix . sleep 20 ; (* end of the app *) sem_unlink "MyUniqueName" ; sem_close sem \ No newline at end of file diff --git a/rosetta/file54.perl b/rosetta/file54.perl new file mode 100644 index 0000000..6342862 --- /dev/null +++ b/rosetta/file54.perl @@ -0,0 +1 @@ +my $n = 1024 ; while ( $n ) { print "$n \n " ; $n = int $n / 2 ; } \ No newline at end of file diff --git a/rosetta/file54.php b/rosetta/file54.php new file mode 100644 index 0000000..c3a105d --- /dev/null +++ b/rosetta/file54.php @@ -0,0 +1 @@ + 1 ) ;   private function fill_cache ( $i ) { $accum = 0 ; $n = $i - 1 ; for ( $k = 0 ; $k <= $n ; $k ++ ) { $accum += $this -> item ( $k ) * $this -> item ( $n - $k ) ; } self :: $cache [ $i ] = $accum ; } function item ( $i ) { if ( ! isset ( self :: $cache [ $i ] ) ) { $this -> fill_cache ( $i ) ; } return self :: $cache [ $i ] ; } }   $cn = new CatalanNumbersSerie ( ) ; for ( $i = 0 ; $i <= 15 ; $i ++ ) { $r = $cn -> item ( $i ) ; echo " $i = $r \r \n " ; } ?> \ No newline at end of file diff --git a/rosetta/file54.py b/rosetta/file54.py new file mode 100644 index 0000000..f846ab8 --- /dev/null +++ b/rosetta/file54.py @@ -0,0 +1 @@ +import re try : raw_input except : raw_input = input   # Unicode: 9601, 9602, 9603, 9604, 9605, 9606, 9607, 9608 try : bar = u '▁▂▃▄▅▆▇█' except : bar = '▁▂▃▄▅▆▇█' barcount = len ( bar ) - 1 while True : line = raw_input ( 'Numbers please separated by space/commas: ' ) numbers = [ float ( n ) for n in re . split ( r '[ \s ,]+' , line. strip ( ) ) ] mn , mx = min ( numbers ) , max ( numbers ) extent = mx - mn sparkline = '' . join ( bar [ int ( ( n - mn ) / extent * barcount ) ] for n in numbers ) print ( 'min: %5f; max: %5f'  % ( mn , mx ) ) print ( sparkline ) \ No newline at end of file diff --git a/rosetta/file54.rb b/rosetta/file54.rb new file mode 100644 index 0000000..154bf92 --- /dev/null +++ b/rosetta/file54.rb @@ -0,0 +1 @@ +require 'rref'   pyramid = [ [ 151 ] , [ nil , nil ] , [ 40 , nil , nil ] , [ nil , nil , nil , nil ] , [ "x" , 11 , "y" , 4 , "z" ] ] pyramid. each { | row | p row }   equations = [ [ 1 , - 1 , 1 , 0 ] ] # y = x + z   def parse_equation ( str ) eqn = [ 0 ] * 4 lhs, rhs = str. split ( "=" ) eqn [ 3 ] = rhs. to_i for term in lhs. split ( "+" ) case term when "x" then eqn [ 0 ] + = 1 when "y" then eqn [ 1 ] + = 1 when "z" then eqn [ 2 ] + = 1 else eqn [ 3 ] - = term. to_i end end eqn end   - 2 . downto ( - 5 ) do | row | pyramid [ row ] . each_index do | col | val = pyramid [ row ] [ col ] sum = "%s+%s" % [ pyramid [ row + 1 ] [ col ] , pyramid [ row + 1 ] [ col + 1 ] ] if val. nil ? pyramid [ row ] [ col ] = sum else equations << parse_equation ( sum + "=#{val}" ) end end end   reduced = convert_to ( reduced_row_echelon_form ( equations ) , :to_i )   for eqn in reduced if eqn [ 0 ] + eqn [ 1 ] + eqn [ 2 ]  != 1 fail "no unique solution! #{equations.inspect} ==> #{reduced.inspect}" elsif eqn [ 0 ] == 1 then x = eqn [ 3 ] elsif eqn [ 1 ] == 1 then y = eqn [ 3 ] elsif eqn [ 2 ] == 1 then z = eqn [ 3 ] end end   puts puts "x == #{x}" puts "y == #{y}" puts "z == #{z}"   answer = [ ] for row in pyramid answer << row. collect { | cell | eval cell. to_s } end puts answer. each { | row | p row } \ No newline at end of file diff --git a/rosetta/file54.scala b/rosetta/file54.scala new file mode 100644 index 0000000..aacecf0 --- /dev/null +++ b/rosetta/file54.scala @@ -0,0 +1 @@ +import scala. math . abs   object Dinesman3 extends App { val tenants = List ( "Baker" , "Cooper2" , "Fletcher4" , "Miller" , "Smith" ) val ( groundFloor, topFloor ) = ( 1 , tenants. size )   /** Rules with related tenants and restrictions*/ val exclusions = List ( ( suggestedFloor0 : Map [ String, Int ] ) => suggestedFloor0 ( "Baker" ) != topFloor, ( suggestedFloor1 : Map [ String, Int ] ) => suggestedFloor1 ( "Cooper2" ) != groundFloor, ( suggestedFloor2 : Map [ String, Int ] ) => ! List ( groundFloor, topFloor ) . contains ( suggestedFloor2 ( "Fletcher4" ) ) , ( suggestedFloor3 : Map [ String, Int ] ) => suggestedFloor3 ( "Miller" ) > suggestedFloor3 ( "Cooper2" ) , ( suggestedFloor4 : Map [ String, Int ] ) => abs ( suggestedFloor4 ( "Smith" ) - suggestedFloor4 ( "Fletcher4" ) ) != 1 , ( suggestedFloor5 : Map [ String, Int ] ) => abs ( suggestedFloor5 ( "Fletcher4" ) - suggestedFloor5 ( "Cooper2" ) ) != 1 )   tenants. permutations . map ( _ zip ( groundFloor to topFloor ) ) . filter ( p => exclusions. forall ( _ ( p. toMap ) ) ) . toList match { case Nil => println ( "No solution" ) case xss => { println ( s "Solutions: ${xss.size}" ) xss. foreach { l => println ( "possible solution:" ) l. foreach ( p => println ( f "${p._1}%11s lives on floor number ${p._2}" ) ) } } } } \ No newline at end of file diff --git a/rosetta/file54.ss b/rosetta/file54.ss new file mode 100644 index 0000000..260abfe --- /dev/null +++ b/rosetta/file54.ss @@ -0,0 +1 @@ +; ; Works with R7RS-compatible Schemes (e.g. Chibi). ; Also current versions of Chicken, Gauche and Kawa. ; ( cond - expand ( chicken ( use srfi - 13 ) ) ( gauche ( use srfi - 13 ) ) ( kawa ( import ( srfi : 13 ) ) ) ( else ( import ( scheme base ) ( scheme write ) ) ) ) ; R7RS     ( define msg "The quick brown fox jumps over the lazy dog." ) ( define key 13 )   ( define ( caesar char ) ( define A ( char -> integer #\A ) ) ( define Z ( char -> integer #\Z ) ) ( define a ( char -> integer #\a ) ) ( define z ( char -> integer #\z ) ) ( define c ( char -> integer char ) ) ( integer -> char ( cond ( ( <= A c Z ) ( + A ( modulo ( + key ( - c A ) ) 26 ) ) ) ( ( <= a c z ) ( + a ( modulo ( + key ( - c a ) ) 26 ) ) ) ( else c ) ) ) ) ; Return other characters verbatim.   ( display ( string - map caesar msg ) ) ( newline )   \ No newline at end of file diff --git a/rosetta/file54.tcl b/rosetta/file54.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file54.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file55.clojure b/rosetta/file55.clojure new file mode 100644 index 0000000..ea70b6f --- /dev/null +++ b/rosetta/file55.clojure @@ -0,0 +1 @@ +( def ! ( memoize # ( apply * ( range 1 ( inc % ) ) ) ) )   ( defn catalan - numbers - direct [ ] ( map # ( / ( ! ( * 2 % ) ) ( * ( ! ( inc % ) ) ( ! % ) ) ) ( range ) ) )   ( def catalan - numbers - recursive # ( ->> [ 1 1 ] ; [c0 n1] ( iterate ( fn [ [ c n ] ] [ ( * 2 ( dec ( * 2 n ) ) ( / ( inc n ) ) c ) ( inc n ) ] ) , ) ( map first , ) ) )   user > ( take 15 ( catalan - numbers - direct ) ) ( 1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 )   user > ( take 15 ( catalan - numbers - recursive ) ) ( 1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 ) \ No newline at end of file diff --git a/rosetta/file55.hs b/rosetta/file55.hs new file mode 100644 index 0000000..d187bec --- /dev/null +++ b/rosetta/file55.hs @@ -0,0 +1 @@ +import qualified Data . List as L import Data . Maybe import Data . Ord import Text . Printf   -- Determine if a number n is a perfect square and return its square root if so. -- This is used instead of sqrt to avoid fixed sized floating point numbers. perfectSqrt :: Integral a => a -> Maybe a perfectSqrt n | n == 1 = Just 1 | n < 4 = Nothing | otherwise = let search low high = let guess = ( low + high ) ` div ` 2 square = guess ^ 2 next | square == n = Just guess | low == guess = Nothing | square < n = search guess high | otherwise = search low guess in next in search 0 n   -- Determine the area of a Heronian triangle if it is one. heronTri :: Integral a => a -> a -> a -> Maybe a heronTri a b c = let -- Rewrite Heron's formula to factor out the term 16 under the root. areaSq16 = ( a + b + c ) * ( b + c - a ) * ( a + c - b ) * ( a + b - c ) ( areaSq , r ) = areaSq16 ` divMod ` 16 in if r == 0 then perfectSqrt areaSq else Nothing   isPrimitive :: Integral a => a -> a -> a -> a isPrimitive a b c = gcd a ( gcd b c )   third ( _, _, x , _, _ ) = x fourth ( _, _, _, x , _ ) = x fifth ( _, _, _, _, x ) = x   orders :: Ord b => [ ( a -> b ) ] -> a -> a -> Ordering orders [ f ] a b = comparing f a b orders ( f:fx ) a b = case comparing f a b of EQ -> orders fx a b n -> n   main :: IO ( ) main = do let range = [ 1 .. 200 ] tris :: [ ( Integer , Integer , Integer , Integer , Integer ) ] tris = L . sortBy ( orders [ fifth , fourth , third ] ) $ map ( \ ( a , b , c , d , e ) -> ( a , b , c , d , fromJust e ) ) $ filter ( isJust . fifth ) [ ( a , b , c , a + b + c , heronTri a b c ) | a <- range , b <- range , c <- range , a <= b , b <= c , isPrimitive a b c == 1 ] printTri ( a , b , c , d , e ) = printf "%3d %3d %3d %9d %4d \n " a b c d e printf "Heronian triangles found: %d \n \n " $ length tris putStrLn " Sides Perimeter Area" mapM_ printTri $ take 10 tris putStrLn "" mapM_ printTri $ filter ( ( == 210 ) . fifth ) tris \ No newline at end of file diff --git a/rosetta/file55.java b/rosetta/file55.java new file mode 100644 index 0000000..b3edb60 --- /dev/null +++ b/rosetta/file55.java @@ -0,0 +1 @@ +import java.awt.* ; import static java. awt . Color . *; import javax.swing.* ;   public class ColourPinstripeDisplay extends JPanel { final static Color [ ] palette = { black, red, green, blue, magenta,cyan, yellow, white } ;   final int bands = 4 ;   public ColourPinstripeDisplay ( ) { setPreferredSize ( new Dimension ( 900 , 600 ) ) ; }   @Override public void paintComponent ( Graphics g ) { super . paintComponent ( g ) ; int h = getHeight ( ) ; for ( int b = 1 ; b <= bands ; b ++ ) { for ( int x = 0 , colIndex = 0 ; x < getWidth ( ) ; x += b, colIndex ++ ) { g. setColor ( palette [ colIndex % palette. length ] ) ; g. fillRect ( x, ( b - 1 ) * ( h / bands ) , x + b, b * ( h / bands ) ) ; } } }   public static void main ( String [ ] args ) { SwingUtilities . invokeLater ( ( ) -> { JFrame f = new JFrame ( ) ; f. setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE ) ; f. setTitle ( "ColourPinstripeDisplay" ) ; f. add ( new ColourPinstripeDisplay ( ) , BorderLayout . CENTER ) ; f. pack ( ) ; f. setLocationRelativeTo ( null ) ; f. setVisible ( true ) ; } ) ; } } \ No newline at end of file diff --git a/rosetta/file55.js b/rosetta/file55.js new file mode 100644 index 0000000..550be7d --- /dev/null +++ b/rosetta/file55.js @@ -0,0 +1 @@ +var array = [ ] ; array. push ( 'abc' ) ; array. push ( 123 ) ; array. push ( new MyClass ) ; alert ( array [ 2 ] ) ; \ No newline at end of file diff --git a/rosetta/file55.ocaml b/rosetta/file55.ocaml new file mode 100644 index 0000000..e3d058a --- /dev/null +++ b/rosetta/file55.ocaml @@ -0,0 +1 @@ +open Sem   let ( ) = let oflags = [ Unix . O_CREAT ; Unix . O_EXCL ] in let sem = sem_open "MyUniqueName" ~oflags ( ) in (* here the real code of the app *) Unix . sleep 20 ; (* end of the app *) sem_unlink "MyUniqueName" ; sem_close sem \ No newline at end of file diff --git a/rosetta/file55.perl b/rosetta/file55.perl new file mode 100644 index 0000000..864f1e3 --- /dev/null +++ b/rosetta/file55.perl @@ -0,0 +1 @@ +# Compress a string to a list of output symbols. sub compress { my $uncompressed = shift ;   # Build the dictionary. my $dict_size = 256 ; my %dictionary = map { chr $_ => chr $_ } 0 .. $dict_size - 1 ;   my $w = "" ; my @result ; foreach my $c ( split '' , $uncompressed ) { my $wc = $w . $c ; if ( exists $dictionary { $wc } ) { $w = $wc ; } else { push @result , $dictionary { $w } ; # Add wc to the dictionary. $dictionary { $wc } = $dict_size ; $dict_size ++; $w = $c ; } }   # Output the code for w. if ( $w ) { push @result , $dictionary { $w } ; } return @result ; }   # Decompress a list of output ks to a string. sub decompress { my @compressed = @_ ;   # Build the dictionary. my $dict_size = 256 ; my %dictionary = map { chr $_ => chr $_ } 0 .. $dict_size - 1 ;   my $w = shift @compressed ; my $result = $w ; foreach my $k ( @compressed ) { my $entry ; if ( exists $dictionary { $k } ) { $entry = $dictionary { $k } ; } elsif ( $k == $dict_size ) { $entry = $w . substr ( $w , 0 , 1 ) ; } else { die "Bad compressed k: $k" ; } $result .= $entry ;   # Add w+entry[0] to the dictionary. $dictionary { $dict_size } = $w . substr ( $entry , 0 , 1 ) ; $dict_size ++;   $w = $entry ; } return $result ; }   # How to use: my @compressed = compress ( 'TOBEORNOTTOBEORTOBEORNOT' ) ; print "@compressed \n " ; my $decompressed = decompress ( @compressed ) ; print "$decompressed \n " ; \ No newline at end of file diff --git a/rosetta/file55.php b/rosetta/file55.php new file mode 100644 index 0000000..03f3335 --- /dev/null +++ b/rosetta/file55.php @@ -0,0 +1 @@ +echo ord ( 'a' ) , " \n " ; // prints "97" echo chr ( 97 ) , " \n " ; // prints "a" \ No newline at end of file diff --git a/rosetta/file55.py b/rosetta/file55.py new file mode 100644 index 0000000..2d14a03 --- /dev/null +++ b/rosetta/file55.py @@ -0,0 +1 @@ +names = sorted ( ( set ( globals ( ) . keys ( ) ) | set ( __builtins__. __dict__ . keys ( ) ) ) - set ( '_ names i' . split ( ) ) ) print ( ' \n ' . join ( ' ' . join ( names [ i:i+ 8 ] ) for i in range ( 0 , len ( names ) , 8 ) ) ) \ No newline at end of file diff --git a/rosetta/file55.rb b/rosetta/file55.rb new file mode 100644 index 0000000..2488391 --- /dev/null +++ b/rosetta/file55.rb @@ -0,0 +1 @@ +require 'raster_graphics'   class RGBColour # the difference between two colours def - ( a_colour ) ( @red - a_colour. red ) . abs + ( @green - a_colour. green ) . abs + ( @blue - a_colour. blue ) . abs end end   class Pixmap # the difference between two images def - ( a_pixmap ) if @width  != a_pixmap. width or @height  != a_pixmap. height raise ArgumentError , "can't compare images with different sizes" end sum = 0 each_pixel { | x,y | sum + = self [ x,y ] - a_pixmap [ x,y ] } Float ( sum ) / ( @width * @height * 255 * 3 ) end end   lenna50 = Pixmap. open_from_jpeg ( 'Lenna50.jpg' ) lenna100 = Pixmap. open_from_jpeg ( 'Lenna100.jpg' )   puts "difference: %.5f%%" % ( 100.0 * ( lenna50 - lenna100 ) ) \ No newline at end of file diff --git a/rosetta/file55.scala b/rosetta/file55.scala new file mode 100644 index 0000000..c5253ac --- /dev/null +++ b/rosetta/file55.scala @@ -0,0 +1 @@ + val DISCORDIAN _ SEASONS = Array ( "Chaos" , "Discord" , "Confusion" , "Bureaucracy" , "The Aftermath" ) // month from 1-12; day from 1-31 def ddate ( year : Int, month : Int, day : Int ) : String = { val date = new GregorianCalendar ( year, month - 1 , day ) val dyear = year + 1166   val isLeapYear = date. isLeapYear ( year ) if ( isLeapYear && month == 2 && day == 29 ) // 2 means February "St. Tib's Day " + dyear + " YOLD" else { var dayOfYear = date. get ( Calendar. DAY_OF_YEAR ) if ( isLeapYear && dayOfYear >= 60 ) dayOfYear - = 1 // compensate for St. Tib's Day   val dday = dayOfYear % 73 val season = dayOfYear / 73 "%s %d, %d YOLD" . format ( DISCORDIAN _ SEASONS ( season ) , dday, dyear ) } } \ No newline at end of file diff --git a/rosetta/file55.ss b/rosetta/file55.ss new file mode 100644 index 0000000..f66f2e2 --- /dev/null +++ b/rosetta/file55.ss @@ -0,0 +1 @@ +( define dog "Benjamin" ) ( define Dog "Samba" ) ( define DOG "Bernie" )   ( if ( eq? dog DOG ) ( begin ( display "There is one dog named " ) ( display DOG ) ( display "." ) ( newline ) ) ( begin ( display "The three dogs are named " ) ( display dog ) ( display ", " ) ( display Dog ) ( display " and " ) ( display DOG ) ( display "." ) ( newline ) ) ) \ No newline at end of file diff --git a/rosetta/file55.tcl b/rosetta/file55.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file55.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file56.clojure b/rosetta/file56.clojure new file mode 100644 index 0000000..dbb94ac --- /dev/null +++ b/rosetta/file56.clojure @@ -0,0 +1 @@ +; Basic usage > ( reduce * ' ( 1 2 3 4 5 ) ) 120 ; Using an initial value > ( reduce + 100 ' ( 1 2 3 4 5 ) ) 115   \ No newline at end of file diff --git a/rosetta/file56.hs b/rosetta/file56.hs new file mode 100644 index 0000000..f6f4f44 --- /dev/null +++ b/rosetta/file56.hs @@ -0,0 +1 @@ +import Data . List import Data . Ord import Data . Array import Text . Printf   hc :: Int -> Array Int Int hc n = arr where arr = listArray ( 1 , n ) $ 1  : 1  : map ( f ( arr ! ) ) [ 3 .. n ] f a i = a ( a $ i - 1 ) + a ( i - a ( i - 1 ) )   printMaxima :: ( Int , ( Int , Double ) ) -> IO ( ) printMaxima ( n , ( pos , m ) ) = printf "Max between 2^%-2d and 2^%-2d is %1.5f at n = %6d \n " n ( n + 1 ) m pos   main = do mapM_ printMaxima maxima printf "Mallows's number is %d \n " mallows where hca = hc $ 2 ^ 20 hc ' n = fromIntegral (hca!n) / fromIntegral n maxima = zip [0..] $ map max powers max seq = maximumBy (comparing snd) $ zip seq (map hc' seq ) powers = map ( \n -> [ 2 ^ n .. 2 ^ ( n + 1 ) - 1 ] ) [ 0 .. 19 ] mallows = last . takeWhile ( ( < 0.55 ) . hc ') $ [2^20, 2^20 - 1 .. 1] \ No newline at end of file diff --git a/rosetta/file56.java b/rosetta/file56.java new file mode 100644 index 0000000..b3edb60 --- /dev/null +++ b/rosetta/file56.java @@ -0,0 +1 @@ +import java.awt.* ; import static java. awt . Color . *; import javax.swing.* ;   public class ColourPinstripeDisplay extends JPanel { final static Color [ ] palette = { black, red, green, blue, magenta,cyan, yellow, white } ;   final int bands = 4 ;   public ColourPinstripeDisplay ( ) { setPreferredSize ( new Dimension ( 900 , 600 ) ) ; }   @Override public void paintComponent ( Graphics g ) { super . paintComponent ( g ) ; int h = getHeight ( ) ; for ( int b = 1 ; b <= bands ; b ++ ) { for ( int x = 0 , colIndex = 0 ; x < getWidth ( ) ; x += b, colIndex ++ ) { g. setColor ( palette [ colIndex % palette. length ] ) ; g. fillRect ( x, ( b - 1 ) * ( h / bands ) , x + b, b * ( h / bands ) ) ; } } }   public static void main ( String [ ] args ) { SwingUtilities . invokeLater ( ( ) -> { JFrame f = new JFrame ( ) ; f. setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE ) ; f. setTitle ( "ColourPinstripeDisplay" ) ; f. add ( new ColourPinstripeDisplay ( ) , BorderLayout . CENTER ) ; f. pack ( ) ; f. setLocationRelativeTo ( null ) ; f. setVisible ( true ) ; } ) ; } } \ No newline at end of file diff --git a/rosetta/file56.js b/rosetta/file56.js new file mode 100644 index 0000000..3bfcfdb --- /dev/null +++ b/rosetta/file56.js @@ -0,0 +1 @@ +function bitprint ( u ) { var s = "" ; for ( var n = 0 ; u ; ++ n , u >>= 1 ) if ( u & 1 ) s += n + " " ; return s ; } function bitcount ( u ) { for ( var n = 0 ; u ; ++ n , u = u & ( u - 1 ) ) ; return n ; } function comb ( c , n ) { var s = [ ] ; for ( var u = 0 ; u < 1 << n ; u ++ ) if ( bitcount ( u ) == c ) s. push ( bitprint ( u ) ) return s. sort ( ) ; } comb ( 3 , 5 ) \ No newline at end of file diff --git a/rosetta/file56.ocaml b/rosetta/file56.ocaml new file mode 100644 index 0000000..e3d058a --- /dev/null +++ b/rosetta/file56.ocaml @@ -0,0 +1 @@ +open Sem   let ( ) = let oflags = [ Unix . O_CREAT ; Unix . O_EXCL ] in let sem = sem_open "MyUniqueName" ~oflags ( ) in (* here the real code of the app *) Unix . sleep 20 ; (* end of the app *) sem_unlink "MyUniqueName" ; sem_close sem \ No newline at end of file diff --git a/rosetta/file56.perl b/rosetta/file56.perl new file mode 100644 index 0000000..8164da1 --- /dev/null +++ b/rosetta/file56.perl @@ -0,0 +1 @@ +#!/usr/bin/perl use warnings ; use strict ;   my $template = shift ; open my $IN , '<' , $template or die $! ; my $story = do { local $/ ; < $IN > } ;   my %blanks ; undef $blanks { $_ } for $story =~ m/<(.*?)>/g ;   for my $blank ( sort keys %blanks ) { print "$blank: " ; chomp ( my $replacement = <> ) ; $blanks { $blank } = $replacement ; }   $story =~ s/<(.*?)>/$blanks{$1}/g ; print $story ; \ No newline at end of file diff --git a/rosetta/file56.php b/rosetta/file56.php new file mode 100644 index 0000000..03f3335 --- /dev/null +++ b/rosetta/file56.php @@ -0,0 +1 @@ +echo ord ( 'a' ) , " \n " ; // prints "97" echo chr ( 97 ) , " \n " ; // prints "a" \ No newline at end of file diff --git a/rosetta/file56.py b/rosetta/file56.py new file mode 100644 index 0000000..dd4d7d3 --- /dev/null +++ b/rosetta/file56.py @@ -0,0 +1 @@ +>>> from math import sqrt >>> def sd ( x ) : sd. sum + = x sd. sum2 + = x*x sd. n + = 1.0 sum , sum2 , n = sd. sum , sd. sum2 , sd. n return sqrt ( sum2/n - sum * sum /n/n )   >>> sd. sum = sd. sum2 = sd. n = 0 >>> for value in ( 2 , 4 , 4 , 4 , 5 , 5 , 7 , 9 ) : print ( value , sd ( value ) )     ( 2 , 0.0 ) ( 4 , 1.0 ) ( 4 , 0.94280904158206258 ) ( 4 , 0.8660254037844386 ) ( 5 , 0.97979589711327075 ) ( 5 , 1.0 ) ( 7 , 1.3997084244475311 ) ( 9 , 2.0 ) >>> \ No newline at end of file diff --git a/rosetta/file56.rb b/rosetta/file56.rb new file mode 100644 index 0000000..2488391 --- /dev/null +++ b/rosetta/file56.rb @@ -0,0 +1 @@ +require 'raster_graphics'   class RGBColour # the difference between two colours def - ( a_colour ) ( @red - a_colour. red ) . abs + ( @green - a_colour. green ) . abs + ( @blue - a_colour. blue ) . abs end end   class Pixmap # the difference between two images def - ( a_pixmap ) if @width  != a_pixmap. width or @height  != a_pixmap. height raise ArgumentError , "can't compare images with different sizes" end sum = 0 each_pixel { | x,y | sum + = self [ x,y ] - a_pixmap [ x,y ] } Float ( sum ) / ( @width * @height * 255 * 3 ) end end   lenna50 = Pixmap. open_from_jpeg ( 'Lenna50.jpg' ) lenna100 = Pixmap. open_from_jpeg ( 'Lenna100.jpg' )   puts "difference: %.5f%%" % ( 100.0 * ( lenna50 - lenna100 ) ) \ No newline at end of file diff --git a/rosetta/file56.scala b/rosetta/file56.scala new file mode 100644 index 0000000..dd6ea35 --- /dev/null +++ b/rosetta/file56.scala @@ -0,0 +1 @@ +import java. net . { InetAddress,Inet4Address,Inet6Address }   object DnsQuery extends App { val ipAddresses = InetAddress. getAllByName ( "www.kame.net" ) ; ipAddresses. foreach { ipAddr => if ( ipAddr. isInstanceOf [ Inet4Address ] ) println ( "IPv4 : " + ipAddr. getHostAddress ( ) ) else if ( ipAddr. isInstanceOf [ Inet6Address ] ) println ( "IPv6 : " + ipAddr. getHostAddress ( ) ) } } \ No newline at end of file diff --git a/rosetta/file56.ss b/rosetta/file56.ss new file mode 100644 index 0000000..f947d41 --- /dev/null +++ b/rosetta/file56.ss @@ -0,0 +1 @@ +( define ( catalan m ) ( let loop ( ( c 1 ) ( n 0 ) ) ( if ( not ( eqv? n m ) ) ( begin ( display n ) ( display ": " ) ( display c ) ( newline ) ( loop ( * ( / ( * 2 ( - ( * 2 ( + n 1 ) ) 1 ) ) ( + ( + n 1 ) 1 ) ) c ) ( + n 1 ) ) ) ) ) )   ( catalan 15 ) \ No newline at end of file diff --git a/rosetta/file56.tcl b/rosetta/file56.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file56.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file57.clojure b/rosetta/file57.clojure new file mode 100644 index 0000000..dc66962 --- /dev/null +++ b/rosetta/file57.clojure @@ -0,0 +1 @@ +( print ( int \a ) ) ; prints "97" ( print ( char 97 ) ) ; prints \a   ; Unicode is also available, as Clojure uses the underlying java Strings & chars ( print ( int \π ) ) ; prints 960 ( print ( char 960 ) ) ; prints \π   ; use String because char in Java can't represent characters outside Basic Multilingual Plane ( print ( . codePointAt "𝅘𝅥𝅮" 0 ) ) ; prints 119136 ( print ( String . ( int - array 1 119136 ) 0 1 ) ) ; prints 𝅘𝅥𝅮 \ No newline at end of file diff --git a/rosetta/file57.hs b/rosetta/file57.hs new file mode 100644 index 0000000..49e5a53 --- /dev/null +++ b/rosetta/file57.hs @@ -0,0 +1 @@ +# !/ usr / bin / runhaskell   import Network . HTTP . Conduit import qualified Data . ByteString . Lazy as L import Network ( withSocketsDo )   main = withSocketsDo $ simpleHttp "https://sourceforge.net/" >>= L . putStr \ No newline at end of file diff --git a/rosetta/file57.java b/rosetta/file57.java new file mode 100644 index 0000000..9bd88b0 --- /dev/null +++ b/rosetta/file57.java @@ -0,0 +1 @@ +/* This is a comment */ \ No newline at end of file diff --git a/rosetta/file57.js b/rosetta/file57.js new file mode 100644 index 0000000..871ee28 --- /dev/null +++ b/rosetta/file57.js @@ -0,0 +1 @@ +var objArgs = WScript. Arguments ; for ( var i = 0 ; i < objArgs. length ; i ++ ) WScript. Echo ( objArgs. Item ( i ) ) ; \ No newline at end of file diff --git a/rosetta/file57.ocaml b/rosetta/file57.ocaml new file mode 100644 index 0000000..1b3aeb0 --- /dev/null +++ b/rosetta/file57.ocaml @@ -0,0 +1 @@ +let dns_query ~host ~ai_family = let opts = [ Unix . AI_FAMILY ai_family ; Unix . AI_SOCKTYPE Unix . SOCK_DGRAM ; ] in let addr_infos = Unix . getaddrinfo host "" opts in match addr_infos with | [ ] -> failwith "dns_query" | ai :: _ -> match ai . Unix . ai_addr with | Unix . ADDR_INET ( addr, _ ) -> ( Unix . string_of_inet_addr addr ) | Unix . ADDR_UNIX addr -> failwith "addr_unix"   let ( ) = let host = "www.kame.net" in Printf . printf "primary addresses of %s are:\n" host ;   Printf . printf " IPv4 address: %s\n" ( dns_query host Unix . PF_INET ) ; Printf . printf " IPv6 address: %s\n" ( dns_query host Unix . PF_INET6 ) ; ;; \ No newline at end of file diff --git a/rosetta/file57.perl b/rosetta/file57.perl new file mode 100644 index 0000000..8164da1 --- /dev/null +++ b/rosetta/file57.perl @@ -0,0 +1 @@ +#!/usr/bin/perl use warnings ; use strict ;   my $template = shift ; open my $IN , '<' , $template or die $! ; my $story = do { local $/ ; < $IN > } ;   my %blanks ; undef $blanks { $_ } for $story =~ m/<(.*?)>/g ;   for my $blank ( sort keys %blanks ) { print "$blank: " ; chomp ( my $replacement = <> ) ; $blanks { $blank } = $replacement ; }   $story =~ s/<(.*?)>/$blanks{$1}/g ; print $story ; \ No newline at end of file diff --git a/rosetta/file57.php b/rosetta/file57.php new file mode 100644 index 0000000..89ae1e1 --- /dev/null +++ b/rosetta/file57.php @@ -0,0 +1 @@ +if ( file_exists ( 'input.txt' ) ) echo 'input.txt is here right by my side' ; if ( file_exists ( 'docs' ) ) echo 'docs is here with me' ; if ( file_exists ( '/input.txt' ) ) echo 'input.txt is over there in the root dir' ; if ( file_exists ( '/docs' ) ) echo 'docs is over there in the root dir' ; \ No newline at end of file diff --git a/rosetta/file57.py b/rosetta/file57.py new file mode 100644 index 0000000..cc13efd --- /dev/null +++ b/rosetta/file57.py @@ -0,0 +1 @@ +print u ' \u 00a3' \ No newline at end of file diff --git a/rosetta/file57.rb b/rosetta/file57.rb new file mode 100644 index 0000000..2488391 --- /dev/null +++ b/rosetta/file57.rb @@ -0,0 +1 @@ +require 'raster_graphics'   class RGBColour # the difference between two colours def - ( a_colour ) ( @red - a_colour. red ) . abs + ( @green - a_colour. green ) . abs + ( @blue - a_colour. blue ) . abs end end   class Pixmap # the difference between two images def - ( a_pixmap ) if @width  != a_pixmap. width or @height  != a_pixmap. height raise ArgumentError , "can't compare images with different sizes" end sum = 0 each_pixel { | x,y | sum + = self [ x,y ] - a_pixmap [ x,y ] } Float ( sum ) / ( @width * @height * 255 * 3 ) end end   lenna50 = Pixmap. open_from_jpeg ( 'Lenna50.jpg' ) lenna100 = Pixmap. open_from_jpeg ( 'Lenna100.jpg' )   puts "difference: %.5f%%" % ( 100.0 * ( lenna50 - lenna100 ) ) \ No newline at end of file diff --git a/rosetta/file57.scala b/rosetta/file57.scala new file mode 100644 index 0000000..59219eb --- /dev/null +++ b/rosetta/file57.scala @@ -0,0 +1 @@ +class Dot [ T ] ( v1 : Seq [ T ] ) ( implicit n : Numeric [ T ] ) { import n. _ // import * operator def dot ( v2 : Seq [ T ] ) = { require ( v1. size == v2. size ) ( v1 zip v2 ) . map { Function. tupled ( _ * _ ) } . sum } }   object Main extends App { implicit def toDot [ T : Numeric ] ( v1 : Seq [ T ] ) = new Dot ( v1 )   val v1 = List ( 1 , 3 , - 5 ) val v2 = List ( 4 , - 2 , - 1 ) println ( v1 dot v2 ) } \ No newline at end of file diff --git a/rosetta/file57.ss b/rosetta/file57.ss new file mode 100644 index 0000000..f947d41 --- /dev/null +++ b/rosetta/file57.ss @@ -0,0 +1 @@ +( define ( catalan m ) ( let loop ( ( c 1 ) ( n 0 ) ) ( if ( not ( eqv? n m ) ) ( begin ( display n ) ( display ": " ) ( display c ) ( newline ) ( loop ( * ( / ( * 2 ( - ( * 2 ( + n 1 ) ) 1 ) ) ( + ( + n 1 ) 1 ) ) c ) ( + n 1 ) ) ) ) ) )   ( catalan 15 ) \ No newline at end of file diff --git a/rosetta/file57.tcl b/rosetta/file57.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file57.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file58.clojure b/rosetta/file58.clojure new file mode 100644 index 0000000..dc66962 --- /dev/null +++ b/rosetta/file58.clojure @@ -0,0 +1 @@ +( print ( int \a ) ) ; prints "97" ( print ( char 97 ) ) ; prints \a   ; Unicode is also available, as Clojure uses the underlying java Strings & chars ( print ( int \π ) ) ; prints 960 ( print ( char 960 ) ) ; prints \π   ; use String because char in Java can't represent characters outside Basic Multilingual Plane ( print ( . codePointAt "𝅘𝅥𝅮" 0 ) ) ; prints 119136 ( print ( String . ( int - array 1 119136 ) 0 1 ) ) ; prints 𝅘𝅥𝅮 \ No newline at end of file diff --git a/rosetta/file58.hs b/rosetta/file58.hs new file mode 100644 index 0000000..49e5a53 --- /dev/null +++ b/rosetta/file58.hs @@ -0,0 +1 @@ +# !/ usr / bin / runhaskell   import Network . HTTP . Conduit import qualified Data . ByteString . Lazy as L import Network ( withSocketsDo )   main = withSocketsDo $ simpleHttp "https://sourceforge.net/" >>= L . putStr \ No newline at end of file diff --git a/rosetta/file58.java b/rosetta/file58.java new file mode 100644 index 0000000..9bd88b0 --- /dev/null +++ b/rosetta/file58.java @@ -0,0 +1 @@ +/* This is a comment */ \ No newline at end of file diff --git a/rosetta/file58.js b/rosetta/file58.js new file mode 100644 index 0000000..871ee28 --- /dev/null +++ b/rosetta/file58.js @@ -0,0 +1 @@ +var objArgs = WScript. Arguments ; for ( var i = 0 ; i < objArgs. length ; i ++ ) WScript. Echo ( objArgs. Item ( i ) ) ; \ No newline at end of file diff --git a/rosetta/file58.ocaml b/rosetta/file58.ocaml new file mode 100644 index 0000000..cac9fd8 --- /dev/null +++ b/rosetta/file58.ocaml @@ -0,0 +1 @@ +let dot = List . fold_left2 ( fun z x y -> z +. x *. y ) 0 .   (* # dot [1.0; 3.0; -5.0] [4.0; -2.0; -1.0];; - : float = 3. *) \ No newline at end of file diff --git a/rosetta/file58.perl b/rosetta/file58.perl new file mode 100644 index 0000000..8164da1 --- /dev/null +++ b/rosetta/file58.perl @@ -0,0 +1 @@ +#!/usr/bin/perl use warnings ; use strict ;   my $template = shift ; open my $IN , '<' , $template or die $! ; my $story = do { local $/ ; < $IN > } ;   my %blanks ; undef $blanks { $_ } for $story =~ m/<(.*?)>/g ;   for my $blank ( sort keys %blanks ) { print "$blank: " ; chomp ( my $replacement = <> ) ; $blanks { $blank } = $replacement ; }   $story =~ s/<(.*?)>/$blanks{$1}/g ; print $story ; \ No newline at end of file diff --git a/rosetta/file58.php b/rosetta/file58.php new file mode 100644 index 0000000..89ae1e1 --- /dev/null +++ b/rosetta/file58.php @@ -0,0 +1 @@ +if ( file_exists ( 'input.txt' ) ) echo 'input.txt is here right by my side' ; if ( file_exists ( 'docs' ) ) echo 'docs is here with me' ; if ( file_exists ( '/input.txt' ) ) echo 'input.txt is over there in the root dir' ; if ( file_exists ( '/docs' ) ) echo 'docs is over there in the root dir' ; \ No newline at end of file diff --git a/rosetta/file58.py b/rosetta/file58.py new file mode 100644 index 0000000..d0672d8 --- /dev/null +++ b/rosetta/file58.py @@ -0,0 +1 @@ +#!/usr/bin/env python   print " \0 33[7mReversed \0 33[m Normal" \ No newline at end of file diff --git a/rosetta/file58.rb b/rosetta/file58.rb new file mode 100644 index 0000000..2488391 --- /dev/null +++ b/rosetta/file58.rb @@ -0,0 +1 @@ +require 'raster_graphics'   class RGBColour # the difference between two colours def - ( a_colour ) ( @red - a_colour. red ) . abs + ( @green - a_colour. green ) . abs + ( @blue - a_colour. blue ) . abs end end   class Pixmap # the difference between two images def - ( a_pixmap ) if @width  != a_pixmap. width or @height  != a_pixmap. height raise ArgumentError , "can't compare images with different sizes" end sum = 0 each_pixel { | x,y | sum + = self [ x,y ] - a_pixmap [ x,y ] } Float ( sum ) / ( @width * @height * 255 * 3 ) end end   lenna50 = Pixmap. open_from_jpeg ( 'Lenna50.jpg' ) lenna100 = Pixmap. open_from_jpeg ( 'Lenna100.jpg' )   puts "difference: %.5f%%" % ( 100.0 * ( lenna50 - lenna100 ) ) \ No newline at end of file diff --git a/rosetta/file58.scala b/rosetta/file58.scala new file mode 100644 index 0000000..59219eb --- /dev/null +++ b/rosetta/file58.scala @@ -0,0 +1 @@ +class Dot [ T ] ( v1 : Seq [ T ] ) ( implicit n : Numeric [ T ] ) { import n. _ // import * operator def dot ( v2 : Seq [ T ] ) = { require ( v1. size == v2. size ) ( v1 zip v2 ) . map { Function. tupled ( _ * _ ) } . sum } }   object Main extends App { implicit def toDot [ T : Numeric ] ( v1 : Seq [ T ] ) = new Dot ( v1 )   val v1 = List ( 1 , 3 , - 5 ) val v2 = List ( 4 , - 2 , - 1 ) println ( v1 dot v2 ) } \ No newline at end of file diff --git a/rosetta/file58.ss b/rosetta/file58.ss new file mode 100644 index 0000000..f947d41 --- /dev/null +++ b/rosetta/file58.ss @@ -0,0 +1 @@ +( define ( catalan m ) ( let loop ( ( c 1 ) ( n 0 ) ) ( if ( not ( eqv? n m ) ) ( begin ( display n ) ( display ": " ) ( display c ) ( newline ) ( loop ( * ( / ( * 2 ( - ( * 2 ( + n 1 ) ) 1 ) ) ( + ( + n 1 ) 1 ) ) c ) ( + n 1 ) ) ) ) ) )   ( catalan 15 ) \ No newline at end of file diff --git a/rosetta/file58.tcl b/rosetta/file58.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file58.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file59.clojure b/rosetta/file59.clojure new file mode 100644 index 0000000..4718932 --- /dev/null +++ b/rosetta/file59.clojure @@ -0,0 +1 @@ +( ns checkpoint . core ( : gen-class ) ( : require [ clojure . core . async : as async : refer [ go ! !! alts ! close ! ] ] [ clojure . string : as string ] ) )   ( defn coordinate [ ctl - ch resp - ch combine ] ( go ( ! outch % ) ) ) received ( if ( and ( pos? rcvd - count ) ( = rcvd - count ( count members ) ) ) ( do ( -> received vals combine release ) { } ) received ) [ v ch ] ( alts ! ( cons ctl - ch ( keys members ) ) ) ] ;receive a message on ctrl-ch or any member input channel ( if ( = ch ctl - ch ) ( let [ [ op inch outch ] v ] ;only a Checkpoint (see below) sends on ctl-ch ( condp = op  : join ( do ( >! resp - ch : ok ) ( recur ( assoc members inch outch ) received ) )  : part ( do ( >! resp - ch : ok ) ( close ! inch ) ( close ! outch ) ( recur ( dissoc members inch ) ( dissoc received inch ) ) )  : exit  : exit ) ) ( if ( nil? v ) ;is the channel closed? ( do ( close ! ( get members ch ) ) ( recur ( dissoc members ch ) ( dissoc received ch ) ) ) ( recur members ( assoc received ch v ) ) ) ) ) ) ) )   ( defprotocol ICheckpoint ( join [ this ] ) ( part [ this inch outch ] ) )   ( deftype Checkpoint [ ctl - ch resp - ch sync ] ICheckpoint ( join [ this ] ( let [ inch ( async / chan ) , outch ( async / chan 1 ) ] ( go ( >! ctl - ch [ : join inch outch ] ) ( ! ctl - ch [ : part inch outch ] ) ) ) )   ( defn checkpoint [ combine ] ( let [ ctl - ch ( async / chan ) , resp - ch ( async / chan 1 ) ] ( -> Checkpoint ctl - ch resp - ch ( coordinate ctl - ch resp - ch combine ) ) ) )   ( defn worker ( [ ckpt repeats ] ( worker ckpt repeats ( fn [ & args ] nil ) ) ) ( [ ckpt repeats mon ] ( go ( let [ [ send recv ] ( ! send n ) ( mon "sent" n ) ( 'a dlink -> unit *) let _insert anchor newlink = newlink . next <- anchor . next ; newlink . prev <- Some anchor ; begin match newlink . next with | None -> ( ) | Some next -> next . prev <- Some newlink ; end ; anchor . next <- Some newlink ;;   (* val insert : 'a dlink option -> 'a -> unit *) let insert dl v = match dl with | ( Some anchor ) -> _insert anchor { data = v ; prev = None ; next = None } | None -> invalid_arg "dlink empty" ;; \ No newline at end of file diff --git a/rosetta/file59.perl b/rosetta/file59.perl new file mode 100644 index 0000000..3e17eb2 --- /dev/null +++ b/rosetta/file59.perl @@ -0,0 +1 @@ +#!/usr/bin/perl -w use strict ;   sub mapValue { my ( $range1 , $range2 , $number ) = @_ ; return ( $range2 -> [ 0 ] + ( ( $number - $range1 -> [ 0 ] ) * ( $range2 -> [ 1 ] - $range2 -> [ 0 ] ) ) / ( $range1 -> [ - 1 ] - $range1 -> [ 0 ] ) ) ; } my @numbers = 0 .. 10 ; my @interval = ( - 1 , 0 ) ; print "The mapped value for $_ is " . mapValue ( \@numbers , \@interval , $_ ) . " ! \n " foreach @numbers ;   \ No newline at end of file diff --git a/rosetta/file59.php b/rosetta/file59.php new file mode 100644 index 0000000..89ae1e1 --- /dev/null +++ b/rosetta/file59.php @@ -0,0 +1 @@ +if ( file_exists ( 'input.txt' ) ) echo 'input.txt is here right by my side' ; if ( file_exists ( 'docs' ) ) echo 'docs is here with me' ; if ( file_exists ( '/input.txt' ) ) echo 'input.txt is over there in the root dir' ; if ( file_exists ( '/docs' ) ) echo 'docs is over there in the root dir' ; \ No newline at end of file diff --git a/rosetta/file59.py b/rosetta/file59.py new file mode 100644 index 0000000..b252a83 --- /dev/null +++ b/rosetta/file59.py @@ -0,0 +1 @@ +print " \a " \ No newline at end of file diff --git a/rosetta/file59.rb b/rosetta/file59.rb new file mode 100644 index 0000000..64c4832 --- /dev/null +++ b/rosetta/file59.rb @@ -0,0 +1 @@ +class PigGame Player = Struct . new ( :name , :safescore , :score ) do def bust! ( ) self . score = safescore end def stay! ( ) self . safescore = score end def to_s ( ) "#{name} (#{safescore}, #{score})" end end   def initialize ( names, maxscore= 100 , die_sides= 6 ) rotation = names. map { | name | Player. new ( name, 0 , 0 ) }   rotation. cycle do | player | loop do if wants_to_roll? ( player ) puts "Rolled: #{roll=roll_dice(die_sides)}" if bust? ( roll ) puts "Busted!" , '' player. bust ! break else player. score + = roll if player. score > = maxscore puts player. name + " wins!" return end end else player. stay ! puts "Staying with #{player.safescore}!" , '' break end end end end   def roll_dice ( die_sides ) rand ( 1 .. die_sides ) end def bust? ( roll ) roll== 1 end def wants_to_roll? ( player ) print "#{player}: Roll? (Y) " [ 'Y' , 'y' , '' ] . include ? ( gets . chomp ) end end   PigGame. new ( % w | Samuel Elizabeth | ) \ No newline at end of file diff --git a/rosetta/file59.scala b/rosetta/file59.scala new file mode 100644 index 0000000..59219eb --- /dev/null +++ b/rosetta/file59.scala @@ -0,0 +1 @@ +class Dot [ T ] ( v1 : Seq [ T ] ) ( implicit n : Numeric [ T ] ) { import n. _ // import * operator def dot ( v2 : Seq [ T ] ) = { require ( v1. size == v2. size ) ( v1 zip v2 ) . map { Function. tupled ( _ * _ ) } . sum } }   object Main extends App { implicit def toDot [ T : Numeric ] ( v1 : Seq [ T ] ) = new Dot ( v1 )   val v1 = List ( 1 , 3 , - 5 ) val v2 = List ( 4 , - 2 , - 1 ) println ( v1 dot v2 ) } \ No newline at end of file diff --git a/rosetta/file59.ss b/rosetta/file59.ss new file mode 100644 index 0000000..8892ec0 --- /dev/null +++ b/rosetta/file59.ss @@ -0,0 +1 @@ +( display ( char -> integer #\a ) ) ( newline ) ; prints "97" ( display ( integer -> char 97 ) ) ( newline ) ; prints "a" \ No newline at end of file diff --git a/rosetta/file59.tcl b/rosetta/file59.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file59.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file6.clojure b/rosetta/file6.clojure new file mode 100644 index 0000000..d4a2a2c --- /dev/null +++ b/rosetta/file6.clojure @@ -0,0 +1 @@ +( ns active - object ( : import ( java . util Timer TimerTask ) ) )   ( defn input [ integrator k ] ( send integrator assoc  : k k ) )   ( defn output [ integrator ] ( : s @integrator ) )   ( defn tick [ integrator t1 ] ( send integrator ( fn [ { : keys [ k s t0 ]  : as m } ] ( assoc m : s ( + s ( / ( * ( + ( k t1 ) ( k t0 ) ) ( - t1 t0 ) ) 2.0 ) )  : t0 t1 ) ) ) )   ( defn start - timer [ integrator interval ] ( let [ timer ( Timer . true ) start ( System / currentTimeMillis ) ] ( . scheduleAtFixedRate timer ( proxy [ TimerTask ] [ ] ( run [ ] ( tick integrator ( double ( / ( - ( System / currentTimeMillis ) start ) 1000 ) ) ) ) ) ( long 0 ) ( long interval ) ) # ( . cancel timer ) ) )   ( defn test - integrator [ ] ( let [ integrator ( agent { : k ( constantly 0.0 )  : s 0.0  : t0 0.0 } ) stop - timer ( start - timer integrator 10 ) ] ( input integrator # ( Math / sin ( * 2.0 Math / PI 0.5 % ) ) ) ( Thread / sleep 2000 ) ( input integrator ( constantly 0.0 ) ) ( Thread / sleep 500 ) ( println ( output integrator ) ) ( stop - timer ) ) )   user > ( test - integrator ) 1 . 414065859052494E - 5   \ No newline at end of file diff --git a/rosetta/file6.hs b/rosetta/file6.hs new file mode 100644 index 0000000..793ea32 --- /dev/null +++ b/rosetta/file6.hs @@ -0,0 +1 @@ +import Data . Complex ( cis , phase )   meanAngle = ( / pi ) . ( * 180 ) . phase . sum . map ( cis . ( / 180 ) . ( * pi ) )   main = mapM_ ( \angles -> putStrLn $ "The mean angle of " ++ show angles ++ " is: " ++ show ( meanAngle angles ) ++ " degrees" ) [ [ 350 , 10 ] , [ 90 , 180 , 270 , 360 ] , [ 10 , 20 , 30 ] ]   \ No newline at end of file diff --git a/rosetta/file6.java b/rosetta/file6.java new file mode 100644 index 0000000..5b18f44 --- /dev/null +++ b/rosetta/file6.java @@ -0,0 +1 @@ +import java.io.IOException ; import java.util.Arrays ;   import org.apache.directory.ldap.client.api.LdapConnection ; import org.apache.directory.ldap.client.api.LdapNetworkConnection ; import org.apache.directory.shared.ldap.model.cursor.EntryCursor ; import org.apache.directory.shared.ldap.model.entry.Entry ; import org.apache.directory.shared.ldap.model.exception.LdapException ; import org.apache.directory.shared.ldap.model.message.SearchScope ; import org.slf4j.Logger ; import org.slf4j.LoggerFactory ;     public class RDirectorySearchLDAP {   protected static final Logger log_ ; private static LdapConnection connection ; private static final String ldapHostName ; private static final int ldapPort ; private static final String ldapDnStr ; private static final String ldapCreds ;   static {   log_ = LoggerFactory. getLogger ( RDirectorySearchLDAP. class ) ;   ldapHostName = "localhost" ; ldapPort = 11389 ; ldapDnStr = "uid=admin,ou=system" ; ldapCreds = "********" ; }   public static void main ( String [ ] args ) {   boolean connected = false ;   try { connected = setUp ( ) ; if ( connected ) { search ( "*mil*" ) ; } } finally { if ( connected ) { tearDown ( ) ; } }   return ; }   private static boolean search ( String uid ) {   boolean state ; EntryCursor cursor ; Entry ev ; String baseDn ; String filter ; SearchScope scope ; String attributes [ ] ; int ksearch = 0 ;   state = true ;   baseDn = "ou=users,o=mojo" ; filter = "(&(objectClass=person)(&(uid=" + uid + ")))" ; scope = SearchScope. SUBTREE ; attributes = new java. lang . String [ ] { "dn" , "cn" , "sn" , "uid" } ;   try { if ( log_. isTraceEnabled ( ) ) { log_. trace ( "LDAP search" ) ; } if ( log_. isInfoEnabled ( ) ) { log_. info ( "Begin search" ) ; log_. info ( " search base distinguished name: " + baseDn ) ; log_. info ( " search filter: " + filter ) ; log_. info ( " search attributes: " + ( Arrays . asList ( attributes ) . toString ( ) ) ) ; } cursor = connection. search ( baseDn, filter, scope, attributes ) ; while ( cursor. next ( ) ) { ksearch ++; ev = cursor. get ( ) ; if ( log_. isInfoEnabled ( ) ) { log_. info ( "Search cursor entry count: " + ksearch ) ; } if ( log_. isInfoEnabled ( ) ) { log_. info ( ev. toString ( ) ) ; } } } catch ( LdapException lex ) { state = false ; log_. error ( "LDAP Error in cursor loop: Iteration " + ksearch, lex ) ; } catch ( Exception ex ) { state = false ; log_. error ( "I/O Error in cursor loop: Iteration " + ksearch, ex ) ; }   return state ; }   private static boolean search ( ) {   return search ( "*" ) ; }   private static boolean setUp ( ) {   boolean state = false ;   try { if ( log_. isInfoEnabled ( ) ) { log_. info ( "LDAP Connection to " + ldapHostName + " on port " + ldapPort ) ; } connection = new LdapNetworkConnection ( ldapHostName, ldapPort ) ;   if ( log_. isTraceEnabled ( ) ) { log_. trace ( "LDAP bind" ) ; } connection. bind ( ldapDnStr, ldapCreds ) ;   state = true ; } catch ( LdapException lex ) { state = false ; log_. error ( "LDAP Error" , lex ) ; } catch ( IOException iox ) { state = false ; log_. error ( "I/O Error" , iox ) ; }   return state ; }   private static boolean tearDown ( ) {   boolean state = false ;   try { if ( log_. isTraceEnabled ( ) ) { log_. trace ( "LDAP unbind" ) ; } connection. unBind ( ) ; state = true ; } catch ( LdapException lex ) { state = false ; log_. error ( "LDAP Error" , lex ) ; } finally { try { connection. close ( ) ; } catch ( IOException iox ) { state = false ; log_. error ( "I/O Error on connection.close()" , iox ) ; } }   return state ; } } \ No newline at end of file diff --git a/rosetta/file6.js b/rosetta/file6.js new file mode 100644 index 0000000..d05ebec --- /dev/null +++ b/rosetta/file6.js @@ -0,0 +1 @@ +  var justification = "center" , 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." ] , x , y , cols , max , cols = 0 , diff , left , right   String . prototype . repeat = function ( n ) { return new Array ( 1 + parseInt ( n ) ) . join ( this ) ; }   for ( x = 0 ; x < input. length ; x ++ ) { input [ x ] = input [ x ] . split ( "$" ) ; if ( input [ x ] . length > cols ) cols = input [ x ] . length ; } for ( x = 0 ; x < cols ; x ++ ) { max = 0 ; for ( y = 0 ; y < input. length ; y ++ ) if ( input [ y ] [ x ] && max < input [ y ] [ x ] . length ) max = input [ y ] [ x ] . length ; for ( y = 0 ; y < input. length ; y ++ ) if ( input [ y ] [ x ] ) { diff = ( max - input [ y ] [ x ] . length ) / 2 ; left = " " . repeat ( Math . floor ( diff ) ) ; right = " " . repeat ( Math . ceil ( diff ) ) ; if ( justification == "left" ) { right += left ; left = "" } if ( justification == "right" ) { left += right ; right = "" } input [ y ] [ x ] = left + input [ y ] [ x ] + right ; } } for ( x = 0 ; x < input. length ; x ++ ) input [ x ] = input [ x ] . join ( " " ) ; input = input. join ( " \n " ) ; document. write ( input ) ; \ No newline at end of file diff --git a/rosetta/file6.ocaml b/rosetta/file6.ocaml new file mode 100644 index 0000000..59e3a93 --- /dev/null +++ b/rosetta/file6.ocaml @@ -0,0 +1 @@ +# load "str.cma" open Str   let 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."   let ( ) = let lines = split ( regexp_string "\n" ) input in let fields_l = List . map ( split ( regexp_string "$" ) ) lines in let fields_l = List . map Array . of_list fields_l in let n = (* number of columns *) List . fold_left ( fun n fields -> max n ( Array . length fields ) ) 0 fields_l in let pads = Array . make n 0 in List . iter ( (* calculate the max padding for each column *) Array . iteri ( fun i word -> pads . ( i ) <- max pads . ( i ) ( String . length word ) ) ) fields_l ;   let print f = List . iter ( fun fields -> Array . iteri ( fun i word -> f word ( pads . ( i ) - ( String . length word ) ) ) fields ; print_newline ( ) ) fields_l ; in   (* left column-aligned output *) print ( fun word pad -> let spaces = String . make pad ' ' in Printf . printf "%s%s " word spaces ) ;   (* right column-aligned output *) print ( fun word pad -> let spaces = String . make pad ' ' in Printf . printf "%s%s " spaces word ) ;   (* center column-aligned output *) print ( fun word pad -> let pad1 = pad / 2 in let pad2 = pad - pad1 in let sp1 = String . make pad1 ' ' in let sp2 = String . make pad2 ' ' in Printf . printf "%s%s%s " sp1 word sp2 ) ; ;; \ No newline at end of file diff --git a/rosetta/file6.perl b/rosetta/file6.perl new file mode 100644 index 0000000..1424b40 --- /dev/null +++ b/rosetta/file6.perl @@ -0,0 +1 @@ +#! /usr/bin/perl use strict ; use Image :: Imlib2 ;   sub my_draw_line { my ( $img , $x0 , $y0 , $x1 , $y1 ) = @_ ;   my $steep = ( abs ( $y1 - $y0 ) > abs ( $x1 - $x0 ) ) ; if ( $steep ) { ( $y0 , $x0 ) = ( $x0 , $y0 ) ; ( $y1 , $x1 ) = ( $x1 , $y1 ) ; } if ( $x0 > $x1 ) { ( $x1 , $x0 ) = ( $x0 , $x1 ) ; ( $y1 , $y0 ) = ( $y0 , $y1 ) ; } my $deltax = $x1 - $x0 ; my $deltay = abs ( $y1 - $y0 ) ; my $error = $deltax / 2 ; my $ystep ; my $y = $y0 ; my $x ; $ystep = ( $y0 < $y1 ) ? 1 : - 1 ; for ( $x = $x0 ; $x <= $x1 ; $x += 1 ) { if ( $steep ) { $img -> draw_point ( $y , $x ) ; } else { $img -> draw_point ( $x , $y ) ; } $error -= $deltay ; if ( $error < 0 ) { $y += $ystep ; $error += $deltax ; } } }   # test my $img = Image :: Imlib2 -> new ( 160 , 160 ) ; $img -> set_color ( 255 , 255 , 255 , 255 ) ; # white $img -> fill_rectangle ( 0 , 0 , 160 , 160 ) ;   $img -> set_color ( 0 , 0 , 0 , 255 ) ; # black my_draw_line ( $img , 10 , 80 , 80 , 160 ) ; my_draw_line ( $img , 80 , 160 , 160 , 80 ) ; my_draw_line ( $img , 160 , 80 , 80 , 10 ) ; my_draw_line ( $img , 80 , 10 , 10 , 80 ) ;   $img -> save ( "test0.png" ) ;   # let's try the same using its internal algo $img -> set_color ( 255 , 255 , 255 , 255 ) ; # white $img -> fill_rectangle ( 0 , 0 , 160 , 160 ) ; $img -> set_color ( 0 , 0 , 0 , 255 ) ; # black $img -> draw_line ( 10 , 80 , 80 , 160 ) ; $img -> draw_line ( 80 , 160 , 160 , 80 ) ; $img -> draw_line ( 160 , 80 , 80 , 10 ) ; $img -> draw_line ( 80 , 10 , 10 , 80 ) ;   $img -> save ( "test1.png" ) ;   exit 0 ; \ No newline at end of file diff --git a/rosetta/file6.php b/rosetta/file6.php new file mode 100644 index 0000000..d3eb834 --- /dev/null +++ b/rosetta/file6.php @@ -0,0 +1 @@ +class E { } ;   $e = new E ( ) ;   $e -> foo = 1 ;   $e -> { "foo" } = 1 ; // using a runtime name $x = "foo" ; $e -> $x = 1 ; // using a runtime name in a variable \ No newline at end of file diff --git a/rosetta/file6.py b/rosetta/file6.py new file mode 100644 index 0000000..03d1e31 --- /dev/null +++ b/rosetta/file6.py @@ -0,0 +1 @@ +  import Image def FloodFill ( fileName , initNode , targetColor , replaceColor ) : img = Image. open ( fileName ) pix = img. load ( ) xsize , ysize = img. size Q = [ ] if pix [ initNode [ 0 ] , initNode [ 1 ] ] != targetColor: return img Q. append ( initNode ) while Q != [ ] : node = Q. pop ( 0 ) if pix [ node [ 0 ] , node [ 1 ] ] == targetColor: W = list ( node ) if node [ 0 ] + 1 < xsize: E = list ( [ node [ 0 ] + 1 , node [ 1 ] ] ) else : E = list ( node ) # Move west until color of node does not match targetColor while pix [ W [ 0 ] , W [ 1 ] ] == targetColor: pix [ W [ 0 ] , W [ 1 ] ] = replaceColor if W [ 1 ] + 1 < ysize: if pix [ W [ 0 ] , W [ 1 ] + 1 ] == targetColor: Q. append ( [ W [ 0 ] , W [ 1 ] + 1 ] ) if W [ 1 ] - 1 >= 0 : if pix [ W [ 0 ] , W [ 1 ] - 1 ] == targetColor: Q. append ( [ W [ 0 ] , W [ 1 ] - 1 ] ) if W [ 0 ] - 1 >= 0 : W [ 0 ] = W [ 0 ] - 1 else : break # Move east until color of node does not match targetColor while pix [ E [ 0 ] , E [ 1 ] ] == targetColor: pix [ E [ 0 ] , E [ 1 ] ] = replaceColor if E [ 1 ] + 1 < ysize: if pix [ E [ 0 ] , E [ 1 ] + 1 ] == targetColor: Q. append ( [ E [ 0 ] , E [ 1 ] + 1 ] ) if E [ 1 ] - 1 >= 0 : if pix [ E [ 0 ] , E [ 1 ] - 1 ] == targetColor: Q. append ( [ E [ 0 ] , E [ 1 ] - 1 ] ) if E [ 0 ] + 1 < xsize: E [ 0 ] = E [ 0 ] + 1 else : break return img   \ No newline at end of file diff --git a/rosetta/file6.rb b/rosetta/file6.rb new file mode 100644 index 0000000..14ab962 --- /dev/null +++ b/rosetta/file6.rb @@ -0,0 +1 @@ +# Class method MyClass. some_method ( some_parameter )   # Class may be computed at runtime foo = MyClass foo. some_method ( some_parameter )     # Instance method my_instance. method ( some_parameter )   # The parentheses are optional my_instance. method some_parameter   # Calling a method with no parameters my_instance. another_method \ No newline at end of file diff --git a/rosetta/file6.scala b/rosetta/file6.scala new file mode 100644 index 0000000..e5ace5e --- /dev/null +++ b/rosetta/file6.scala @@ -0,0 +1 @@ +  def agm ( a : Double, g : Double, eps : Double ) : Double = { if ( math. abs ( a - g ) < eps ) ( a + g ) / 2 else agm ( ( a + g ) / 2 , math. sqrt ( a * g ) , eps ) }   agm ( 1 , math. sqrt ( 2 ) / 2 , 1e-15 )   \ No newline at end of file diff --git a/rosetta/file6.ss b/rosetta/file6.ss new file mode 100644 index 0000000..c506a9b --- /dev/null +++ b/rosetta/file6.ss @@ -0,0 +1 @@ +( define ( A m n ) ( cond ( ( = m 0 ) ( + n 1 ) ) ( ( = n 0 ) ( A ( - m 1 ) 1 ) ) ( else ( A ( - m 1 ) ( A m ( - n 1 ) ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file6.tcl b/rosetta/file6.tcl new file mode 100644 index 0000000..b65e906 --- /dev/null +++ b/rosetta/file6.tcl @@ -0,0 +1 @@ +puts [ exec ls ] \ No newline at end of file diff --git a/rosetta/file60.clojure b/rosetta/file60.clojure new file mode 100644 index 0000000..4718932 --- /dev/null +++ b/rosetta/file60.clojure @@ -0,0 +1 @@ +( ns checkpoint . core ( : gen-class ) ( : require [ clojure . core . async : as async : refer [ go ! !! alts ! close ! ] ] [ clojure . string : as string ] ) )   ( defn coordinate [ ctl - ch resp - ch combine ] ( go ( ! outch % ) ) ) received ( if ( and ( pos? rcvd - count ) ( = rcvd - count ( count members ) ) ) ( do ( -> received vals combine release ) { } ) received ) [ v ch ] ( alts ! ( cons ctl - ch ( keys members ) ) ) ] ;receive a message on ctrl-ch or any member input channel ( if ( = ch ctl - ch ) ( let [ [ op inch outch ] v ] ;only a Checkpoint (see below) sends on ctl-ch ( condp = op  : join ( do ( >! resp - ch : ok ) ( recur ( assoc members inch outch ) received ) )  : part ( do ( >! resp - ch : ok ) ( close ! inch ) ( close ! outch ) ( recur ( dissoc members inch ) ( dissoc received inch ) ) )  : exit  : exit ) ) ( if ( nil? v ) ;is the channel closed? ( do ( close ! ( get members ch ) ) ( recur ( dissoc members ch ) ( dissoc received ch ) ) ) ( recur members ( assoc received ch v ) ) ) ) ) ) ) )   ( defprotocol ICheckpoint ( join [ this ] ) ( part [ this inch outch ] ) )   ( deftype Checkpoint [ ctl - ch resp - ch sync ] ICheckpoint ( join [ this ] ( let [ inch ( async / chan ) , outch ( async / chan 1 ) ] ( go ( >! ctl - ch [ : join inch outch ] ) ( ! ctl - ch [ : part inch outch ] ) ) ) )   ( defn checkpoint [ combine ] ( let [ ctl - ch ( async / chan ) , resp - ch ( async / chan 1 ) ] ( -> Checkpoint ctl - ch resp - ch ( coordinate ctl - ch resp - ch combine ) ) ) )   ( defn worker ( [ ckpt repeats ] ( worker ckpt repeats ( fn [ & args ] nil ) ) ) ( [ ckpt repeats mon ] ( go ( let [ [ send recv ] ( ! send n ) ( mon "sent" n ) ( [ Int ] prisoners n = [ 0 .. n - 1 ]   counter :: Int -> [ Int ] counter k = cycle [ k , k - 1 .. 1 ]   killList :: [ Int ] -> [ Int ] -> ( [ Int ] , [ Int ] , [ Int ] ) killList xs cs = ( killed , survivors , newCs ) where ( killed , newCs ) = kill xs cs [ ] survivors = xs \\ killed kill [ ] cs rs = ( rs , cs ) kill ( x:xs ) ( c:cs ) rs | c == 1 = let ts = rs ++ [ x ] in kill xs cs ts | otherwise = kill xs cs rs   killRecursive :: [ Int ] -> [ Int ] -> Int -> ( [ Int ] , [ Int ] ) killRecursive xs cs m = killR ( [ ] , xs , cs ) where killR ( killed , remaining , counter ) | length remaining <= m = ( killed , remaining ) | otherwise = let ( newKilled , newRemaining , newCounter ) = killList remaining counter allKilled = killed ++ newKilled in killR ( allKilled , newRemaining , newCounter )   main :: IO ( ) main = do args <- getArgs case args of [ n , k , m ] -> print $ snd $ killRecursive ( prisoners ( read n ) ) ( counter ( read k ) ) ( read m ) _ -> print $ snd $ killRecursive ( prisoners 41 ) ( counter 3 ) 1   \ No newline at end of file diff --git a/rosetta/file60.java b/rosetta/file60.java new file mode 100644 index 0000000..114959a --- /dev/null +++ b/rosetta/file60.java @@ -0,0 +1 @@ +a = 3 if ( a == 1 ) { io. writeln ( 'a == 1' ) } else if ( a == 3 ) { io. writeln ( 'a == 3' ) } else { io. writeln ( 'a is neither 1 nor 3' ) } \ No newline at end of file diff --git a/rosetta/file60.js b/rosetta/file60.js new file mode 100644 index 0000000..3fdb65b --- /dev/null +++ b/rosetta/file60.js @@ -0,0 +1 @@ +if ( s == "Hello World" ) { foo ( ) ; } else if ( s == "Bye World" ) { bar ( ) ; } else { deusEx ( ) ; } \ No newline at end of file diff --git a/rosetta/file60.ocaml b/rosetta/file60.ocaml new file mode 100644 index 0000000..5ce1a97 --- /dev/null +++ b/rosetta/file60.ocaml @@ -0,0 +1 @@ +#!/ usr / bin / env ocaml # load "unix.cma" # load "graphics.cma" open Graphics   let pi = 4.0 *. atan 1.0 let angle v max = float v /. max *. 2.0 *. pi   let ( ) = open_graph "" ; set_window_title "OCaml Clock" ; resize_window 256 256 ; auto_synchronize false ; let w = size_x ( ) and h = size_y ( ) in let rec loop ( ) = clear_graph ( ) ;   let point radius r a = let x = int_of_float ( radius *. sin a ) and y = int_of_float ( radius *. cos a ) in fill_circle ( w / 2 + x ) ( h / 2 + y ) r ; in set_color ( rgb 192 192 192 ) ; point 84.0 8 0.0 ; point 84.0 8 ( angle 90 360.0 ) ; point 84.0 8 ( angle 180 360.0 ) ; point 84.0 8 ( angle 270 360.0 ) ; set_color ( rgb 224 224 224 ) ; point 84.0 6 ( angle 30 360.0 ) ; point 84.0 6 ( angle 60 360.0 ) ; point 84.0 6 ( angle 120 360.0 ) ; point 84.0 6 ( angle 150 360.0 ) ; point 84.0 6 ( angle 210 360.0 ) ; point 84.0 6 ( angle 240 360.0 ) ; point 84.0 6 ( angle 300 360.0 ) ; point 84.0 6 ( angle 330 360.0 ) ;   set_line_width 9 ; set_color ( rgb 192 192 192 ) ; draw_circle ( w / 2 ) ( h / 2 ) 100 ;   let tm = Unix . localtime ( Unix . gettimeofday ( ) ) in let sec = angle tm . Unix . tm_sec 60.0 in let min = angle tm . Unix . tm_min 60.0 in let hour = angle ( tm . Unix . tm_hour * 60 + tm . Unix . tm_min ) ( 24.0 *. 60.0 ) in let hour = hour *. 2.0 in   let hand t radius width color = let x = int_of_float ( radius *. sin t ) and y = int_of_float ( radius *. cos t ) in set_line_width width ; set_color color ; moveto ( w / 2 ) ( h / 2 ) ; rlineto x y ; in hand sec 90.0 2 ( rgb 0 128 255 ) ; hand min 82.0 4 ( rgb 0 0 128 ) ; hand hour 72.0 6 ( rgb 255 0 128 ) ;   synchronize ( ) ; Unix . sleep 1 ; loop ( ) in try loop ( ) with _ -> close_graph ( ) \ No newline at end of file diff --git a/rosetta/file60.perl b/rosetta/file60.perl new file mode 100644 index 0000000..baabe6a --- /dev/null +++ b/rosetta/file60.perl @@ -0,0 +1 @@ +use Digest :: MD5 qw ( md5_hex ) ;   print md5_hex ( "The quick brown fox jumped over the lazy dog's back" ) , " \n " ; \ No newline at end of file diff --git a/rosetta/file60.php b/rosetta/file60.php new file mode 100644 index 0000000..89ae1e1 --- /dev/null +++ b/rosetta/file60.php @@ -0,0 +1 @@ +if ( file_exists ( 'input.txt' ) ) echo 'input.txt is here right by my side' ; if ( file_exists ( 'docs' ) ) echo 'docs is here with me' ; if ( file_exists ( '/input.txt' ) ) echo 'input.txt is over there in the root dir' ; if ( file_exists ( '/docs' ) ) echo 'docs is over there in the root dir' ; \ No newline at end of file diff --git a/rosetta/file60.py b/rosetta/file60.py new file mode 100644 index 0000000..4923854 --- /dev/null +++ b/rosetta/file60.py @@ -0,0 +1 @@ +gifts = ''' \ A partridge in a pear tree. Two turtle doves Three french hens Four calling birds Five golden rings Six geese a-laying Seven swans a-swimming Eight maids a-milking Nine ladies dancing Ten lords a-leaping Eleven pipers piping Twelve drummers drumming''' . split ( ' \n ' )   days = '''first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth''' . split ( )   for n , day in enumerate ( days , 1 ) : g = gifts [ :n ] [ ::- 1 ] print ( ( ' \n On the %s day of Christmas \n My true love gave to me: \n '  % day ) + ' \n ' . join ( g [ :- 1 ] ) + ( ' and \n ' + g [ - 1 ] if n > 1 else g [ - 1 ] . capitalize ( ) ) ) \ No newline at end of file diff --git a/rosetta/file60.rb b/rosetta/file60.rb new file mode 100644 index 0000000..64c4832 --- /dev/null +++ b/rosetta/file60.rb @@ -0,0 +1 @@ +class PigGame Player = Struct . new ( :name , :safescore , :score ) do def bust! ( ) self . score = safescore end def stay! ( ) self . safescore = score end def to_s ( ) "#{name} (#{safescore}, #{score})" end end   def initialize ( names, maxscore= 100 , die_sides= 6 ) rotation = names. map { | name | Player. new ( name, 0 , 0 ) }   rotation. cycle do | player | loop do if wants_to_roll? ( player ) puts "Rolled: #{roll=roll_dice(die_sides)}" if bust? ( roll ) puts "Busted!" , '' player. bust ! break else player. score + = roll if player. score > = maxscore puts player. name + " wins!" return end end else player. stay ! puts "Staying with #{player.safescore}!" , '' break end end end end   def roll_dice ( die_sides ) rand ( 1 .. die_sides ) end def bust? ( roll ) roll== 1 end def wants_to_roll? ( player ) print "#{player}: Roll? (Y) " [ 'Y' , 'y' , '' ] . include ? ( gets . chomp ) end end   PigGame. new ( % w | Samuel Elizabeth | ) \ No newline at end of file diff --git a/rosetta/file60.scala b/rosetta/file60.scala new file mode 100644 index 0000000..59219eb --- /dev/null +++ b/rosetta/file60.scala @@ -0,0 +1 @@ +class Dot [ T ] ( v1 : Seq [ T ] ) ( implicit n : Numeric [ T ] ) { import n. _ // import * operator def dot ( v2 : Seq [ T ] ) = { require ( v1. size == v2. size ) ( v1 zip v2 ) . map { Function. tupled ( _ * _ ) } . sum } }   object Main extends App { implicit def toDot [ T : Numeric ] ( v1 : Seq [ T ] ) = new Dot ( v1 )   val v1 = List ( 1 , 3 , - 5 ) val v2 = List ( 4 , - 2 , - 1 ) println ( v1 dot v2 ) } \ No newline at end of file diff --git a/rosetta/file60.ss b/rosetta/file60.ss new file mode 100644 index 0000000..8892ec0 --- /dev/null +++ b/rosetta/file60.ss @@ -0,0 +1 @@ +( display ( char -> integer #\a ) ) ( newline ) ; prints "97" ( display ( integer -> char 97 ) ) ( newline ) ; prints "a" \ No newline at end of file diff --git a/rosetta/file60.tcl b/rosetta/file60.tcl new file mode 100644 index 0000000..918e0e7 --- /dev/null +++ b/rosetta/file60.tcl @@ -0,0 +1 @@ +proc zigzag { size } { set m [ lrepeat $size [ lrepeat $size . ] ] set x 0 ; set dx - 1 set y 0 ; set dy 1   for { set i 0 } { $i < $size ** 2 } { incr i } { if { $x > = $size } { incr x - 1 incr y 2 negate dx dy } elseif { $y > = $size } { incr x 2 incr y - 1 negate dx dy } elseif { $x < 0 && $y > = 0 } { incr x negate dx dy } elseif { $x > = 0 && $y < 0 } { incr y negate dx dy } lset m $x $y $i incr x $dx incr y $dy } return $m }   proc negate { args } { foreach varname $args { upvar 1 $varname var set var [ expr { - 1 * $var } ] } }   print_matrix [ zigzag 5 ] \ No newline at end of file diff --git a/rosetta/file7.clojure b/rosetta/file7.clojure new file mode 100644 index 0000000..d4a2a2c --- /dev/null +++ b/rosetta/file7.clojure @@ -0,0 +1 @@ +( ns active - object ( : import ( java . util Timer TimerTask ) ) )   ( defn input [ integrator k ] ( send integrator assoc  : k k ) )   ( defn output [ integrator ] ( : s @integrator ) )   ( defn tick [ integrator t1 ] ( send integrator ( fn [ { : keys [ k s t0 ]  : as m } ] ( assoc m : s ( + s ( / ( * ( + ( k t1 ) ( k t0 ) ) ( - t1 t0 ) ) 2.0 ) )  : t0 t1 ) ) ) )   ( defn start - timer [ integrator interval ] ( let [ timer ( Timer . true ) start ( System / currentTimeMillis ) ] ( . scheduleAtFixedRate timer ( proxy [ TimerTask ] [ ] ( run [ ] ( tick integrator ( double ( / ( - ( System / currentTimeMillis ) start ) 1000 ) ) ) ) ) ( long 0 ) ( long interval ) ) # ( . cancel timer ) ) )   ( defn test - integrator [ ] ( let [ integrator ( agent { : k ( constantly 0.0 )  : s 0.0  : t0 0.0 } ) stop - timer ( start - timer integrator 10 ) ] ( input integrator # ( Math / sin ( * 2.0 Math / PI 0.5 % ) ) ) ( Thread / sleep 2000 ) ( input integrator ( constantly 0.0 ) ) ( Thread / sleep 500 ) ( println ( output integrator ) ) ( stop - timer ) ) )   user > ( test - integrator ) 1 . 414065859052494E - 5   \ No newline at end of file diff --git a/rosetta/file7.hs b/rosetta/file7.hs new file mode 100644 index 0000000..393b272 --- /dev/null +++ b/rosetta/file7.hs @@ -0,0 +1 @@ +import Text . Regex {- The above import is needed only for the last function. It is used there purely for readability and conciseness -}   {- Assigning a string to a 'variable'. We're being explicit about it just for show. Haskell would be able to figure out the type of "world" -} string = "world" :: String \ No newline at end of file diff --git a/rosetta/file7.java b/rosetta/file7.java new file mode 100644 index 0000000..5b18f44 --- /dev/null +++ b/rosetta/file7.java @@ -0,0 +1 @@ +import java.io.IOException ; import java.util.Arrays ;   import org.apache.directory.ldap.client.api.LdapConnection ; import org.apache.directory.ldap.client.api.LdapNetworkConnection ; import org.apache.directory.shared.ldap.model.cursor.EntryCursor ; import org.apache.directory.shared.ldap.model.entry.Entry ; import org.apache.directory.shared.ldap.model.exception.LdapException ; import org.apache.directory.shared.ldap.model.message.SearchScope ; import org.slf4j.Logger ; import org.slf4j.LoggerFactory ;     public class RDirectorySearchLDAP {   protected static final Logger log_ ; private static LdapConnection connection ; private static final String ldapHostName ; private static final int ldapPort ; private static final String ldapDnStr ; private static final String ldapCreds ;   static {   log_ = LoggerFactory. getLogger ( RDirectorySearchLDAP. class ) ;   ldapHostName = "localhost" ; ldapPort = 11389 ; ldapDnStr = "uid=admin,ou=system" ; ldapCreds = "********" ; }   public static void main ( String [ ] args ) {   boolean connected = false ;   try { connected = setUp ( ) ; if ( connected ) { search ( "*mil*" ) ; } } finally { if ( connected ) { tearDown ( ) ; } }   return ; }   private static boolean search ( String uid ) {   boolean state ; EntryCursor cursor ; Entry ev ; String baseDn ; String filter ; SearchScope scope ; String attributes [ ] ; int ksearch = 0 ;   state = true ;   baseDn = "ou=users,o=mojo" ; filter = "(&(objectClass=person)(&(uid=" + uid + ")))" ; scope = SearchScope. SUBTREE ; attributes = new java. lang . String [ ] { "dn" , "cn" , "sn" , "uid" } ;   try { if ( log_. isTraceEnabled ( ) ) { log_. trace ( "LDAP search" ) ; } if ( log_. isInfoEnabled ( ) ) { log_. info ( "Begin search" ) ; log_. info ( " search base distinguished name: " + baseDn ) ; log_. info ( " search filter: " + filter ) ; log_. info ( " search attributes: " + ( Arrays . asList ( attributes ) . toString ( ) ) ) ; } cursor = connection. search ( baseDn, filter, scope, attributes ) ; while ( cursor. next ( ) ) { ksearch ++; ev = cursor. get ( ) ; if ( log_. isInfoEnabled ( ) ) { log_. info ( "Search cursor entry count: " + ksearch ) ; } if ( log_. isInfoEnabled ( ) ) { log_. info ( ev. toString ( ) ) ; } } } catch ( LdapException lex ) { state = false ; log_. error ( "LDAP Error in cursor loop: Iteration " + ksearch, lex ) ; } catch ( Exception ex ) { state = false ; log_. error ( "I/O Error in cursor loop: Iteration " + ksearch, ex ) ; }   return state ; }   private static boolean search ( ) {   return search ( "*" ) ; }   private static boolean setUp ( ) {   boolean state = false ;   try { if ( log_. isInfoEnabled ( ) ) { log_. info ( "LDAP Connection to " + ldapHostName + " on port " + ldapPort ) ; } connection = new LdapNetworkConnection ( ldapHostName, ldapPort ) ;   if ( log_. isTraceEnabled ( ) ) { log_. trace ( "LDAP bind" ) ; } connection. bind ( ldapDnStr, ldapCreds ) ;   state = true ; } catch ( LdapException lex ) { state = false ; log_. error ( "LDAP Error" , lex ) ; } catch ( IOException iox ) { state = false ; log_. error ( "I/O Error" , iox ) ; }   return state ; }   private static boolean tearDown ( ) {   boolean state = false ;   try { if ( log_. isTraceEnabled ( ) ) { log_. trace ( "LDAP unbind" ) ; } connection. unBind ( ) ; state = true ; } catch ( LdapException lex ) { state = false ; log_. error ( "LDAP Error" , lex ) ; } finally { try { connection. close ( ) ; } catch ( IOException iox ) { state = false ; log_. error ( "I/O Error on connection.close()" , iox ) ; } }   return state ; } } \ No newline at end of file diff --git a/rosetta/file7.js b/rosetta/file7.js new file mode 100644 index 0000000..d05ebec --- /dev/null +++ b/rosetta/file7.js @@ -0,0 +1 @@ +  var justification = "center" , 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." ] , x , y , cols , max , cols = 0 , diff , left , right   String . prototype . repeat = function ( n ) { return new Array ( 1 + parseInt ( n ) ) . join ( this ) ; }   for ( x = 0 ; x < input. length ; x ++ ) { input [ x ] = input [ x ] . split ( "$" ) ; if ( input [ x ] . length > cols ) cols = input [ x ] . length ; } for ( x = 0 ; x < cols ; x ++ ) { max = 0 ; for ( y = 0 ; y < input. length ; y ++ ) if ( input [ y ] [ x ] && max < input [ y ] [ x ] . length ) max = input [ y ] [ x ] . length ; for ( y = 0 ; y < input. length ; y ++ ) if ( input [ y ] [ x ] ) { diff = ( max - input [ y ] [ x ] . length ) / 2 ; left = " " . repeat ( Math . floor ( diff ) ) ; right = " " . repeat ( Math . ceil ( diff ) ) ; if ( justification == "left" ) { right += left ; left = "" } if ( justification == "right" ) { left += right ; right = "" } input [ y ] [ x ] = left + input [ y ] [ x ] + right ; } } for ( x = 0 ; x < input. length ; x ++ ) input [ x ] = input [ x ] . join ( " " ) ; input = input. join ( " \n " ) ; document. write ( input ) ; \ No newline at end of file diff --git a/rosetta/file7.ocaml b/rosetta/file7.ocaml new file mode 100644 index 0000000..59e3a93 --- /dev/null +++ b/rosetta/file7.ocaml @@ -0,0 +1 @@ +# load "str.cma" open Str   let 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."   let ( ) = let lines = split ( regexp_string "\n" ) input in let fields_l = List . map ( split ( regexp_string "$" ) ) lines in let fields_l = List . map Array . of_list fields_l in let n = (* number of columns *) List . fold_left ( fun n fields -> max n ( Array . length fields ) ) 0 fields_l in let pads = Array . make n 0 in List . iter ( (* calculate the max padding for each column *) Array . iteri ( fun i word -> pads . ( i ) <- max pads . ( i ) ( String . length word ) ) ) fields_l ;   let print f = List . iter ( fun fields -> Array . iteri ( fun i word -> f word ( pads . ( i ) - ( String . length word ) ) ) fields ; print_newline ( ) ) fields_l ; in   (* left column-aligned output *) print ( fun word pad -> let spaces = String . make pad ' ' in Printf . printf "%s%s " word spaces ) ;   (* right column-aligned output *) print ( fun word pad -> let spaces = String . make pad ' ' in Printf . printf "%s%s " spaces word ) ;   (* center column-aligned output *) print ( fun word pad -> let pad1 = pad / 2 in let pad2 = pad - pad1 in let sp1 = String . make pad1 ' ' in let sp2 = String . make pad2 ' ' in Printf . printf "%s%s%s " sp1 word sp2 ) ; ;; \ No newline at end of file diff --git a/rosetta/file7.perl b/rosetta/file7.perl new file mode 100644 index 0000000..1424b40 --- /dev/null +++ b/rosetta/file7.perl @@ -0,0 +1 @@ +#! /usr/bin/perl use strict ; use Image :: Imlib2 ;   sub my_draw_line { my ( $img , $x0 , $y0 , $x1 , $y1 ) = @_ ;   my $steep = ( abs ( $y1 - $y0 ) > abs ( $x1 - $x0 ) ) ; if ( $steep ) { ( $y0 , $x0 ) = ( $x0 , $y0 ) ; ( $y1 , $x1 ) = ( $x1 , $y1 ) ; } if ( $x0 > $x1 ) { ( $x1 , $x0 ) = ( $x0 , $x1 ) ; ( $y1 , $y0 ) = ( $y0 , $y1 ) ; } my $deltax = $x1 - $x0 ; my $deltay = abs ( $y1 - $y0 ) ; my $error = $deltax / 2 ; my $ystep ; my $y = $y0 ; my $x ; $ystep = ( $y0 < $y1 ) ? 1 : - 1 ; for ( $x = $x0 ; $x <= $x1 ; $x += 1 ) { if ( $steep ) { $img -> draw_point ( $y , $x ) ; } else { $img -> draw_point ( $x , $y ) ; } $error -= $deltay ; if ( $error < 0 ) { $y += $ystep ; $error += $deltax ; } } }   # test my $img = Image :: Imlib2 -> new ( 160 , 160 ) ; $img -> set_color ( 255 , 255 , 255 , 255 ) ; # white $img -> fill_rectangle ( 0 , 0 , 160 , 160 ) ;   $img -> set_color ( 0 , 0 , 0 , 255 ) ; # black my_draw_line ( $img , 10 , 80 , 80 , 160 ) ; my_draw_line ( $img , 80 , 160 , 160 , 80 ) ; my_draw_line ( $img , 160 , 80 , 80 , 10 ) ; my_draw_line ( $img , 80 , 10 , 10 , 80 ) ;   $img -> save ( "test0.png" ) ;   # let's try the same using its internal algo $img -> set_color ( 255 , 255 , 255 , 255 ) ; # white $img -> fill_rectangle ( 0 , 0 , 160 , 160 ) ; $img -> set_color ( 0 , 0 , 0 , 255 ) ; # black $img -> draw_line ( 10 , 80 , 80 , 160 ) ; $img -> draw_line ( 80 , 160 , 160 , 80 ) ; $img -> draw_line ( 160 , 80 , 80 , 10 ) ; $img -> draw_line ( 80 , 10 , 10 , 80 ) ;   $img -> save ( "test1.png" ) ;   exit 0 ; \ No newline at end of file diff --git a/rosetta/file7.php b/rosetta/file7.php new file mode 100644 index 0000000..729cd3e --- /dev/null +++ b/rosetta/file7.php @@ -0,0 +1 @@ + STR_PAD_RIGHT , 'R' => STR_PAD_LEFT , 'C' => STR_PAD_BOTH ) ;   /** Justify columns of textual tabular input where the record separator is the newline and the field separator is a 'dollar' character. justification can be L, R, or C; (Left, Right, or Centered).   Return the justified output as a string */ function aligner ( $str , $justification = 'L' ) { global $j2justtype ; assert ( array_key_exists ( $justification , $j2justtype ) ) ; $justtype = $j2justtype [ $justification ] ;   $fieldsbyrow = array ( ) ; foreach ( explode ( " \n " , $str ) as $line ) $fieldsbyrow [ ] = explode ( '$' , $line ) ; $maxfields = max ( array_map ( 'count' , $fieldsbyrow ) ) ;   foreach ( range ( 0 , $maxfields - 1 ) as $col ) { $maxwidth = 0 ; foreach ( $fieldsbyrow as $fields ) $maxwidth = max ( $maxwidth , strlen ( $fields [ $col ] ) ) ; foreach ( $fieldsbyrow as & $fields ) $fields [ $col ] = str_pad ( $fields [ $col ] , $maxwidth , ' ' , $justtype ) ; unset ( $fields ) ; // see http://bugs.php.net/29992 } $result = '' ; foreach ( $fieldsbyrow as $fields ) $result .= implode ( ' ' , $fields ) . " \n " ; return $result ; }   $textinfile = '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 ( array ( 'L' , 'R' , 'C' ) as $j ) echo aligner ( $textinfile , $j ) ;   ?> \ No newline at end of file diff --git a/rosetta/file7.py b/rosetta/file7.py new file mode 100644 index 0000000..57252a9 --- /dev/null +++ b/rosetta/file7.py @@ -0,0 +1 @@ +def circle ( self , x0 , y0 , radius , colour = black ) : f = 1 - radius ddf_x = 1 ddf_y = - 2 * radius x = 0 y = radius self . set ( x0 , y0 + radius , colour ) self . set ( x0 , y0 - radius , colour ) self . set ( x0 + radius , y0 , colour ) self . set ( x0 - radius , y0 , colour )   while x < y: if f >= 0 : y - = 1 ddf_y + = 2 f + = ddf_y x + = 1 ddf_x + = 2 f + = ddf_x self . set ( x0 + x , y0 + y , colour ) self . set ( x0 - x , y0 + y , colour ) self . set ( x0 + x , y0 - y , colour ) self . set ( x0 - x , y0 - y , colour ) self . set ( x0 + y , y0 + x , colour ) self . set ( x0 - y , y0 + x , colour ) self . set ( x0 + y , y0 - x , colour ) self . set ( x0 - y , y0 - x , colour ) Bitmap. circle = circle   bitmap = Bitmap ( 25 , 25 ) bitmap. circle ( x0 = 12 , y0 = 12 , radius = 12 ) bitmap. chardisplay ( )   ''' The origin, 0,0; is the lower left, with x increasing to the right, and Y increasing upwards.   The program above produces the following display :   +-------------------------+ | @@@@@@@ | | @@ @@ | | @@ @@ | | @ @ | | @ @ | | @ @ | | @ @ | | @ @ | | @ @ | |@ @| |@ @| |@ @| |@ @| |@ @| |@ @| |@ @| | @ @ | | @ @ | | @ @ | | @ @ | | @ @ | | @ @ | | @@ @@ | | @@ @@ | | @@@@@@@ | +-------------------------+ '''   \ No newline at end of file diff --git a/rosetta/file7.rb b/rosetta/file7.rb new file mode 100644 index 0000000..54d666f --- /dev/null +++ b/rosetta/file7.rb @@ -0,0 +1 @@ +module FiveDogs dog = "Benjamin" dOg = "Dogley" doG = "Fido" Dog = "Samba" # this constant is FiveDogs::Dog DOG = "Bernie" # this constant is FiveDogs::DOG   names = [ dog, dOg, doG, Dog, DOG ] names. uniq ! puts "There are %d dogs named %s." % [ names. length , names. join ( ", " ) ] puts puts "The local variables are %s." % local_variables . join ( ", " ) puts "The constants are %s." % constants. join ( ", " ) end \ No newline at end of file diff --git a/rosetta/file7.scala b/rosetta/file7.scala new file mode 100644 index 0000000..ed36f77 --- /dev/null +++ b/rosetta/file7.scala @@ -0,0 +1 @@ +  object AtomicUpdates {   class Buckets ( ns : Int * ) {   import scala. actors . Actor . _   val buckets = ns. toArray   case class Get ( index : Int ) case class Transfer ( fromIndex : Int, toIndex : Int, amount : Int ) case object GetAll   val handler = actor { loop { react { case Get ( index ) => reply ( buckets ( index ) ) case Transfer ( fromIndex, toIndex, amount ) => assert ( amount >= 0 ) val actualAmount = Math. min ( amount, buckets ( fromIndex ) ) buckets ( fromIndex ) - = actualAmount buckets ( toIndex ) + = actualAmount case GetAll => reply ( buckets. toList ) } } }   def get ( index : Int ) : Int = ( handler !? Get ( index ) ) . asInstanceOf [ Int ] def transfer ( fromIndex : Int, toIndex : Int, amount : Int ) = handler ! Transfer ( fromIndex, toIndex, amount ) def getAll : List [ Int ] = ( handler !? GetAll ) . asInstanceOf [ List [ Int ] ] }   def randomPair ( n : Int ) : ( Int, Int ) = { import scala. util . Random . _ val pair = ( nextInt ( n ) , nextInt ( n ) ) if ( pair. _ 1 == pair. _ 2 ) randomPair ( n ) else pair }   def main ( args : Array [ String ] ) { import scala. actors . Scheduler . _ val buckets = new Buckets ( List. range ( 1 , 11 ) : _* ) val stop = new java. util . concurrent . atomic . AtomicBoolean ( false ) val latch = new java. util . concurrent . CountDownLatch ( 3 ) execute { while ( ! stop. get ) { val ( i1, i2 ) = randomPair ( 10 ) val ( n1, n2 ) = ( buckets. get ( i1 ) , buckets. get ( i2 ) ) val m = ( n1 + n2 ) / 2 if ( n1 < n2 ) buckets. transfer ( i2, i1, n2 - m ) else buckets. transfer ( i1, i2, n1 - m ) } latch. countDown } execute { while ( ! stop. get ) { val ( i1, i2 ) = randomPair ( 10 ) val n = buckets. get ( i1 ) buckets. transfer ( i1, i2, if ( n == 0 ) 0 else scala. util . Random . nextInt ( n ) ) } latch. countDown } execute { for ( i < - 1 to 20 ) { val all = buckets. getAll println ( all. sum + ":" + all ) Thread. sleep ( 500 ) } stop. set ( true ) latch. countDown } latch. await shutdown } }   \ No newline at end of file diff --git a/rosetta/file7.ss b/rosetta/file7.ss new file mode 100644 index 0000000..c506a9b --- /dev/null +++ b/rosetta/file7.ss @@ -0,0 +1 @@ +( define ( A m n ) ( cond ( ( = m 0 ) ( + n 1 ) ) ( ( = n 0 ) ( A ( - m 1 ) 1 ) ) ( else ( A ( - m 1 ) ( A m ( - n 1 ) ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file7.tcl b/rosetta/file7.tcl new file mode 100644 index 0000000..b65e906 --- /dev/null +++ b/rosetta/file7.tcl @@ -0,0 +1 @@ +puts [ exec ls ] \ No newline at end of file diff --git a/rosetta/file8.clojure b/rosetta/file8.clojure new file mode 100644 index 0000000..b044799 --- /dev/null +++ b/rosetta/file8.clojure @@ -0,0 +1 @@ +  ( ns rosettacode . align - columns ( : require [ clojure . contrib . string : as str ] ) )   ( def data "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." )   ( def table ( map # ( str / split # " \$ " % ) ( str / split - lines data ) ) )   ( defn col - width [ n table ] ( reduce max ( map # ( try ( count ( nth % n ) ) ( catch Exception _ 0 ) ) table ) ) ) ( defn spaces [ n ] ( str / repeat n " " ) ) ( defn add - padding "if the string is too big turncate it, else return a string with padding" [ string width justification ] ( if ( >= ( count string ) width ) ( str / take width string ) ( let [ pad - len ( int ( - width ( count string ) ) ) ;we don't want rationals half - pad - len ( int ( / pad - len 2 ) ) ] ( case justification  : right ( str ( spaces pad - len ) string )  : left ( str string ( spaces pad - len ) )  : center ( str ( spaces half - pad - len ) string ( spaces ( - pad - len half - pad - len ) ) ) ) ) ) )   ( defn aligned - table "get the width of each column, then generate a new table with propper padding for eath item" ( [ table justification ] ( let [ col - widths ( map # ( + 2 ( col - width % table ) ) ( range ( count ( first table ) ) ) ) ] ( map ( fn [ row ] ( map # ( add - padding % 1 % 2 justification ) row col - widths ) ) table ) ) ) )   ( defn print - table [ table ] ( do ( println ) ( print ( str / join "" ( flatten ( interleave table ( repeat " \n " ) ) ) ) ) ) )   ( print - table ( aligned - table table : center ) )   \ No newline at end of file diff --git a/rosetta/file8.hs b/rosetta/file8.hs new file mode 100644 index 0000000..393b272 --- /dev/null +++ b/rosetta/file8.hs @@ -0,0 +1 @@ +import Text . Regex {- The above import is needed only for the last function. It is used there purely for readability and conciseness -}   {- Assigning a string to a 'variable'. We're being explicit about it just for show. Haskell would be able to figure out the type of "world" -} string = "world" :: String \ No newline at end of file diff --git a/rosetta/file8.java b/rosetta/file8.java new file mode 100644 index 0000000..6a792be --- /dev/null +++ b/rosetta/file8.java @@ -0,0 +1 @@ +import java.io.IOException ; import java.nio.charset.StandardCharsets ; import java.nio.file.Files ; import java.nio.file.Paths ; import java.util.ArrayList ; import java.util.List ;   import org.apache.commons.lang3.StringUtils ;   /** * Aligns fields into columns, separated by "|" */ public class ColumnAligner { private List < String [ ] > words = new ArrayList <> ( ) ; private int columns = 0 ; private List < Integer > columnWidths = new ArrayList <> ( ) ;   /** * Initialize columns aligner from lines in a single string * * @param s * lines in a single string. Empty string does form a column. */ public ColumnAligner ( String s ) { String [ ] lines = s. split ( " \\ n" ) ; for ( String line : lines ) { processInputLine ( line ) ; } }   /** * Initialize columns aligner from lines in a list of strings * * @param lines * lines in a single string. Empty string does form a column. */ public ColumnAligner ( List < String > lines ) { for ( String line : lines ) { processInputLine ( line ) ; } }   private void processInputLine ( String line ) { String [ ] lineWords = line. split ( " \\ $" ) ; words. add ( lineWords ) ; columns = Math . max ( columns, lineWords. length ) ; for ( int i = 0 ; i < lineWords. length ; i ++ ) { String word = lineWords [ i ] ; if ( i >= columnWidths. size ( ) ) { columnWidths. add ( word. length ( ) ) ; } else { columnWidths. set ( i, Math . max ( columnWidths. get ( i ) , word. length ( ) ) ) ; } } }   interface AlignFunction { String align ( String s, int length ) ; }   /** * Left-align all columns * * @return Lines, terminated by "\n" of columns, separated by "|" */ public String alignLeft ( ) { return align ( new AlignFunction ( ) { @Override public String align ( String s, int length ) { return StringUtils. rightPad ( s, length ) ; } } ) ; }   /** * Right-align all columns * * @return Lines, terminated by "\n" of columns, separated by "|" */ public String alignRight ( ) { return align ( new AlignFunction ( ) { @Override public String align ( String s, int length ) { return StringUtils. leftPad ( s, length ) ; } } ) ; }   /** * Center-align all columns * * @return Lines, terminated by "\n" of columns, separated by "|" */ public String alignCenter ( ) { return align ( new AlignFunction ( ) { @Override public String align ( String s, int length ) { return StringUtils. center ( s, length ) ; } } ) ; }   private String align ( AlignFunction a ) { StringBuilder result = new StringBuilder ( ) ; for ( String [ ] lineWords : words ) { for ( int i = 0 ; i < lineWords. length ; i ++ ) { String word = lineWords [ i ] ; if ( i == 0 ) { result. append ( "|" ) ; } result. append ( a. align ( word, columnWidths. get ( i ) ) + "|" ) ; } result. append ( " \n " ) ; } return result. toString ( ) ; }   public static void main ( String args [ ] ) throws IOException { if ( args. length < 1 ) { System . out . println ( "Usage: ColumnAligner file [left|right|center]" ) ; return ; } String filePath = args [ 0 ] ; String alignment = "left" ; if ( args. length >= 2 ) { alignment = args [ 1 ] ; } ColumnAligner ca = new ColumnAligner ( Files. readAllLines ( Paths. get ( filePath ) , StandardCharsets. UTF_8 ) ) ; switch ( alignment ) { case "left" : System . out . print ( ca. alignLeft ( ) ) ; break ; case "right" : System . out . print ( ca. alignRight ( ) ) ; break ; case "center" : System . out . print ( ca. alignCenter ( ) ) ; break ; default : System . err . println ( String . format ( "Error! Unknown alignment: '%s'" , alignment ) ) ; break ; } } } \ No newline at end of file diff --git a/rosetta/file8.js b/rosetta/file8.js new file mode 100644 index 0000000..625020b --- /dev/null +++ b/rosetta/file8.js @@ -0,0 +1 @@ +function ambRun ( func ) { var choices = [ ] ; var index ;   function amb ( values ) { if ( values. length == 0 ) { fail ( ) ; } if ( index == choices. length ) { choices. push ( { i : 0 , count : values. length } ) ; } var choice = choices [ index ++ ] ; return values [ choice. i ] ; }   function fail ( ) { throw fail ; }   while ( true ) { try { index = 0 ; return func ( amb , fail ) ; } catch ( e ) { if ( e != fail ) { throw e ; } var choice ; while ( ( choice = choices. pop ( ) ) && ++ choice. i == choice. count ) { } if ( choice == undefined ) { return undefined ; } choices. push ( choice ) ; } } }   ambRun ( function ( amb , fail ) { function linked ( s1 , s2 ) { return s1. slice ( - 1 ) == s2. slice ( 0 , 1 ) ; }   var w1 = amb ( [ "the" , "that" , "a" ] ) ; var w2 = amb ( [ "frog" , "elephant" , "thing" ] ) ; if ( ! linked ( w1 , w2 ) ) fail ( ) ;   var w3 = amb ( [ "walked" , "treaded" , "grows" ] ) ; if ( ! linked ( w2 , w3 ) ) fail ( ) ;   var w4 = amb ( [ "slowly" , "quickly" ] ) ; if ( ! linked ( w3 , w4 ) ) fail ( ) ;   return [ w1 , w2 , w3 , w4 ] . join ( ' ' ) ; } ) ; // "that thing grows slowly" \ No newline at end of file diff --git a/rosetta/file8.ocaml b/rosetta/file8.ocaml new file mode 100644 index 0000000..c913c14 --- /dev/null +++ b/rosetta/file8.ocaml @@ -0,0 +1 @@ +let set_1 = [ "the" ; "that" ; "a" ] let set_2 = [ "frog" ; "elephant" ; "thing" ] let set_3 = [ "walked" ; "treaded" ; "grows" ] let set_4 = [ "slowly" ; "quickly" ]   let combs ll = let rec aux acc = function | [ ] -> ( List . map List . rev acc ) | hd :: tl -> let acc = List . fold_left ( fun _ac l -> List . fold_left ( fun _ac v -> ( v :: l ) :: _ac ) _ac hd ) [ ] acc in aux acc tl in aux [ [ ] ] ll   let last s = s . [ pred ( String . length s ) ] let joined a b = ( last a = b . [ 0 ] )   let rec test = function | a :: b :: tl -> ( joined a b ) && ( test ( b :: tl ) ) | _ -> true   let print_set set = List . iter ( Printf . printf " %s" ) set ; print_newline ( ) ; ;;   let ( ) = let sets = combs [ set_1 ; set_2 ; set_3 ; set_4 ] in let sets = List . filter test sets in List . iter print_set sets ; ;; \ No newline at end of file diff --git a/rosetta/file8.perl b/rosetta/file8.perl new file mode 100644 index 0000000..04fb642 --- /dev/null +++ b/rosetta/file8.perl @@ -0,0 +1 @@ +#! /usr/bin/perl   use strict ; use Image :: Imlib2 ;   my $img = Image :: Imlib2 -> load ( "Unfilledcirc.jpg" ) ; $img -> set_color ( 0 , 255 , 0 , 255 ) ; $img -> fill ( 100 , 100 ) ; $img -> save ( "filledcirc.jpg" ) ; exit 0 ; \ No newline at end of file diff --git a/rosetta/file8.php b/rosetta/file8.php new file mode 100644 index 0000000..729cd3e --- /dev/null +++ b/rosetta/file8.php @@ -0,0 +1 @@ + STR_PAD_RIGHT , 'R' => STR_PAD_LEFT , 'C' => STR_PAD_BOTH ) ;   /** Justify columns of textual tabular input where the record separator is the newline and the field separator is a 'dollar' character. justification can be L, R, or C; (Left, Right, or Centered).   Return the justified output as a string */ function aligner ( $str , $justification = 'L' ) { global $j2justtype ; assert ( array_key_exists ( $justification , $j2justtype ) ) ; $justtype = $j2justtype [ $justification ] ;   $fieldsbyrow = array ( ) ; foreach ( explode ( " \n " , $str ) as $line ) $fieldsbyrow [ ] = explode ( '$' , $line ) ; $maxfields = max ( array_map ( 'count' , $fieldsbyrow ) ) ;   foreach ( range ( 0 , $maxfields - 1 ) as $col ) { $maxwidth = 0 ; foreach ( $fieldsbyrow as $fields ) $maxwidth = max ( $maxwidth , strlen ( $fields [ $col ] ) ) ; foreach ( $fieldsbyrow as & $fields ) $fields [ $col ] = str_pad ( $fields [ $col ] , $maxwidth , ' ' , $justtype ) ; unset ( $fields ) ; // see http://bugs.php.net/29992 } $result = '' ; foreach ( $fieldsbyrow as $fields ) $result .= implode ( ' ' , $fields ) . " \n " ; return $result ; }   $textinfile = '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 ( array ( 'L' , 'R' , 'C' ) as $j ) echo aligner ( $textinfile , $j ) ;   ?> \ No newline at end of file diff --git a/rosetta/file8.py b/rosetta/file8.py new file mode 100644 index 0000000..a6a4d9e --- /dev/null +++ b/rosetta/file8.py @@ -0,0 +1 @@ +# With help from http://netpbm.sourceforge.net/doc/ppm.html   # String masquerading as ppm file (version P3) import io   ppmtxt = '''P3 # feep.ppm 4 4 15 0 0 0 0 0 0 0 0 0 15 0 15 0 0 0 0 15 7 0 0 0 0 0 0 0 0 0 0 0 0 0 15 7 0 0 0 15 0 15 0 0 0 0 0 0 0 0 0 '''     def tokenize ( f ) : for line in f: if line [ 0 ] != '#' : for t in line. split ( ) : yield t   def ppmp3tobitmap ( f ) : t = tokenize ( f ) nexttoken = lambda  : next ( t ) assert 'P3' == nexttoken ( ) , 'Wrong filetype' width , height , maxval = ( int ( nexttoken ( ) ) for i in range ( 3 ) ) bitmap = Bitmap ( width , height , Colour ( 0 , 0 , 0 ) ) for h in range ( height- 1 , - 1 , - 1 ) : for w in range ( 0 , width ) : bitmap. set ( w , h , Colour ( * ( int ( nexttoken ( ) ) for i in range ( 3 ) ) ) )   return bitmap   print ( 'Original Colour PPM file' ) print ( ppmtxt ) ppmfile = io. StringIO ( ppmtxt ) bitmap = ppmp3tobitmap ( ppmfile ) print ( 'Grey PPM:' ) bitmap. togreyscale ( ) ppmfileout = io. StringIO ( '' ) bitmap. writeppmp3 ( ppmfileout ) print ( ppmfileout. getvalue ( ) )     ''' The print statements above produce the following output:   Original Colour PPM file P3 # feep.ppm 4 4 15 0 0 0 0 0 0 0 0 0 15 0 15 0 0 0 0 15 7 0 0 0 0 0 0 0 0 0 0 0 0 0 15 7 0 0 0 15 0 15 0 0 0 0 0 0 0 0 0   Grey PPM: P3 # generated from Bitmap.writeppmp3 4 4 11 0 0 0 0 0 0 0 0 0 4 4 4 0 0 0 11 11 11 0 0 0 0 0 0 0 0 0 0 0 0 11 11 11 0 0 0 4 4 4 0 0 0 0 0 0 0 0 0   ''' \ No newline at end of file diff --git a/rosetta/file8.rb b/rosetta/file8.rb new file mode 100644 index 0000000..5a72210 --- /dev/null +++ b/rosetta/file8.rb @@ -0,0 +1 @@ +# direct   def factorial ( n ) ( 1 .. n ) . reduce ( : * ) end   def catalan_direct ( n ) factorial ( 2 * n ) / ( factorial ( n + 1 ) * factorial ( n ) ) end   # recursive   def catalan_rec1 ( n ) return 1 if n == 0 ( 0 .. n - 1 ) . inject ( 0 ) { | sum, i | sum + catalan_rec1 ( i ) * catalan_rec1 ( n - 1 - i ) } end   def catalan_rec2 ( n ) return 1 if n == 0 2 * ( 2 * n - 1 ) * catalan_rec2 ( n - 1 ) / ( n + 1 ) end   # performance and results   require 'benchmark' require 'memoize' include Memoize   Benchmark . bm ( 10 ) do | b | b. report ( 'forget' ) { 16 . times { | n | [ n, catalan_direct ( n ) , catalan_rec1 ( n ) , catalan_rec2 ( n ) ] } } b. report ( 'memoized' ) { memoize :factorial memoize :catalan_direct memoize :catalan_rec1 memoize :catalan_rec2 16 . times { | n | [ n, catalan_direct ( n ) , catalan_rec1 ( n ) , catalan_rec2 ( n ) ] } } end   16 . times { | n | p [ n, catalan_direct ( n ) , catalan_rec1 ( n ) , catalan_rec2 ( n ) ] } \ No newline at end of file diff --git a/rosetta/file8.scala b/rosetta/file8.scala new file mode 100644 index 0000000..794a43b --- /dev/null +++ b/rosetta/file8.scala @@ -0,0 +1 @@ +// Fibonacci Sequence (begining with 1,1): 1 1 2 3 5 8 13 21 34 55 ... val fibs : Stream [ BigInt ] = { def series ( i : BigInt,j : BigInt ) : Stream [ BigInt ] = i #:: series ( j, i+j ) ; series ( 1 , 0 ) . tail . tail }     /** * Given a numeric sequence, return the distribution of the most-signicant-digit * as expected by Benford's Law and then by actual distribution. */ def benford [ N : Numeric ] ( data : Seq [ N ] ) : Map [ Int, ( Double,Double ) ] = {   import scala. math . _   val maxSize = 10000000 // An arbitrary size to avoid problems with endless streams   val size = ( data. take ( maxSize ) ) . size . toDouble   val distribution = data. take ( maxSize ) . groupBy ( _ . toString . head . toString . toInt ) . map { case ( d,l ) => ( d - > l. size ) }   ( for ( i < - ( 1 to 9 ) ) yield { ( i - > ( log10 ( 1D + 1D / i ) , ( distribution ( i ) / size ) ) ) } ) . toMap }   { println ( "Fibonacci Sequence (size=1000): 1 1 2 3 5 8 13 21 34 55 ... \n " ) println ( "%9s %9s %9s" . format ( "Actual" , "Expected" , "Deviation" ) )   benford ( fibs. take ( 1000 ) ) . toList . sorted foreach { case ( k, v ) => println ( "%d: %5.2f%% | %5.2f%% | %5.4f%%" . format ( k,v. _ 2 * 100 ,v. _ 1 * 100 ,math. abs ( v. _ 2-v. _ 1 ) * 100 ) ) } } \ No newline at end of file diff --git a/rosetta/file8.ss b/rosetta/file8.ss new file mode 100644 index 0000000..c506a9b --- /dev/null +++ b/rosetta/file8.ss @@ -0,0 +1 @@ +( define ( A m n ) ( cond ( ( = m 0 ) ( + n 1 ) ) ( ( = n 0 ) ( A ( - m 1 ) 1 ) ) ( else ( A ( - m 1 ) ( A m ( - n 1 ) ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file8.tcl b/rosetta/file8.tcl new file mode 100644 index 0000000..b65e906 --- /dev/null +++ b/rosetta/file8.tcl @@ -0,0 +1 @@ +puts [ exec ls ] \ No newline at end of file diff --git a/rosetta/file9.clojure b/rosetta/file9.clojure new file mode 100644 index 0000000..b044799 --- /dev/null +++ b/rosetta/file9.clojure @@ -0,0 +1 @@ +  ( ns rosettacode . align - columns ( : require [ clojure . contrib . string : as str ] ) )   ( def data "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." )   ( def table ( map # ( str / split # " \$ " % ) ( str / split - lines data ) ) )   ( defn col - width [ n table ] ( reduce max ( map # ( try ( count ( nth % n ) ) ( catch Exception _ 0 ) ) table ) ) ) ( defn spaces [ n ] ( str / repeat n " " ) ) ( defn add - padding "if the string is too big turncate it, else return a string with padding" [ string width justification ] ( if ( >= ( count string ) width ) ( str / take width string ) ( let [ pad - len ( int ( - width ( count string ) ) ) ;we don't want rationals half - pad - len ( int ( / pad - len 2 ) ) ] ( case justification  : right ( str ( spaces pad - len ) string )  : left ( str string ( spaces pad - len ) )  : center ( str ( spaces half - pad - len ) string ( spaces ( - pad - len half - pad - len ) ) ) ) ) ) )   ( defn aligned - table "get the width of each column, then generate a new table with propper padding for eath item" ( [ table justification ] ( let [ col - widths ( map # ( + 2 ( col - width % table ) ) ( range ( count ( first table ) ) ) ) ] ( map ( fn [ row ] ( map # ( add - padding % 1 % 2 justification ) row col - widths ) ) table ) ) ) )   ( defn print - table [ table ] ( do ( println ) ( print ( str / join "" ( flatten ( interleave table ( repeat " \n " ) ) ) ) ) ) )   ( print - table ( aligned - table table : center ) )   \ No newline at end of file diff --git a/rosetta/file9.hs b/rosetta/file9.hs new file mode 100644 index 0000000..0298cf3 --- /dev/null +++ b/rosetta/file9.hs @@ -0,0 +1 @@ +module Bitmap . Line ( line ) where   import Bitmap import Control . Monad import Control . Monad . ST import qualified Data . STRef   var = Data . STRef . newSTRef get = Data . STRef . readSTRef mutate = Data . STRef . modifySTRef   line :: Color c => Image s c -> Pixel -> Pixel -> c -> ST s ( ) line i ( Pixel ( xa , ya ) ) ( Pixel ( xb , yb ) ) c = do yV <- var y1 errorV <- var $ deltax ` div ` 2 forM _ [ x1 .. x2 ] ( \x -> do y <- get yV setPix i ( Pixel $ if steep then ( y , x ) else ( x , y ) ) c mutate errorV $ subtract deltay error <- get errorV when ( error < 0 ) ( do mutate yV ( + ystep ) mutate errorV ( + deltax ) ) ) where steep = abs ( yb - ya ) > abs ( xb - xa ) ( xa ', ya' , xb ', yb' ) = if steep then ( ya , xa , yb , xb ) else ( xa , ya , xb , yb ) ( x1 , y1 , x2 , y2 ) = if xa ' > xb' then ( xb ', yb' , xa ', ya' ) else ( xa ', ya' , xb ', yb' ) deltax = x2 - x1 deltay = abs $ y2 - y1 ystep = if y1 < y2 then 1 else - 1 \ No newline at end of file diff --git a/rosetta/file9.java b/rosetta/file9.java new file mode 100644 index 0000000..6a792be --- /dev/null +++ b/rosetta/file9.java @@ -0,0 +1 @@ +import java.io.IOException ; import java.nio.charset.StandardCharsets ; import java.nio.file.Files ; import java.nio.file.Paths ; import java.util.ArrayList ; import java.util.List ;   import org.apache.commons.lang3.StringUtils ;   /** * Aligns fields into columns, separated by "|" */ public class ColumnAligner { private List < String [ ] > words = new ArrayList <> ( ) ; private int columns = 0 ; private List < Integer > columnWidths = new ArrayList <> ( ) ;   /** * Initialize columns aligner from lines in a single string * * @param s * lines in a single string. Empty string does form a column. */ public ColumnAligner ( String s ) { String [ ] lines = s. split ( " \\ n" ) ; for ( String line : lines ) { processInputLine ( line ) ; } }   /** * Initialize columns aligner from lines in a list of strings * * @param lines * lines in a single string. Empty string does form a column. */ public ColumnAligner ( List < String > lines ) { for ( String line : lines ) { processInputLine ( line ) ; } }   private void processInputLine ( String line ) { String [ ] lineWords = line. split ( " \\ $" ) ; words. add ( lineWords ) ; columns = Math . max ( columns, lineWords. length ) ; for ( int i = 0 ; i < lineWords. length ; i ++ ) { String word = lineWords [ i ] ; if ( i >= columnWidths. size ( ) ) { columnWidths. add ( word. length ( ) ) ; } else { columnWidths. set ( i, Math . max ( columnWidths. get ( i ) , word. length ( ) ) ) ; } } }   interface AlignFunction { String align ( String s, int length ) ; }   /** * Left-align all columns * * @return Lines, terminated by "\n" of columns, separated by "|" */ public String alignLeft ( ) { return align ( new AlignFunction ( ) { @Override public String align ( String s, int length ) { return StringUtils. rightPad ( s, length ) ; } } ) ; }   /** * Right-align all columns * * @return Lines, terminated by "\n" of columns, separated by "|" */ public String alignRight ( ) { return align ( new AlignFunction ( ) { @Override public String align ( String s, int length ) { return StringUtils. leftPad ( s, length ) ; } } ) ; }   /** * Center-align all columns * * @return Lines, terminated by "\n" of columns, separated by "|" */ public String alignCenter ( ) { return align ( new AlignFunction ( ) { @Override public String align ( String s, int length ) { return StringUtils. center ( s, length ) ; } } ) ; }   private String align ( AlignFunction a ) { StringBuilder result = new StringBuilder ( ) ; for ( String [ ] lineWords : words ) { for ( int i = 0 ; i < lineWords. length ; i ++ ) { String word = lineWords [ i ] ; if ( i == 0 ) { result. append ( "|" ) ; } result. append ( a. align ( word, columnWidths. get ( i ) ) + "|" ) ; } result. append ( " \n " ) ; } return result. toString ( ) ; }   public static void main ( String args [ ] ) throws IOException { if ( args. length < 1 ) { System . out . println ( "Usage: ColumnAligner file [left|right|center]" ) ; return ; } String filePath = args [ 0 ] ; String alignment = "left" ; if ( args. length >= 2 ) { alignment = args [ 1 ] ; } ColumnAligner ca = new ColumnAligner ( Files. readAllLines ( Paths. get ( filePath ) , StandardCharsets. UTF_8 ) ) ; switch ( alignment ) { case "left" : System . out . print ( ca. alignLeft ( ) ) ; break ; case "right" : System . out . print ( ca. alignRight ( ) ) ; break ; case "center" : System . out . print ( ca. alignCenter ( ) ) ; break ; default : System . err . println ( String . format ( "Error! Unknown alignment: '%s'" , alignment ) ) ; break ; } } } \ No newline at end of file diff --git a/rosetta/file9.js b/rosetta/file9.js new file mode 100644 index 0000000..ae74a83 --- /dev/null +++ b/rosetta/file9.js @@ -0,0 +1 @@ +function fibo ( n ) { if ( n < 0 ) throw "Argument cannot be negative" ; else return ( function ( n ) { if ( n < 2 ) return 1 ; else return arguments. callee ( n - 1 ) + arguments. callee ( n - 2 ) ; } ) ( n ) ; } \ No newline at end of file diff --git a/rosetta/file9.ocaml b/rosetta/file9.ocaml new file mode 100644 index 0000000..32ac878 --- /dev/null +++ b/rosetta/file9.ocaml @@ -0,0 +1 @@ +let sort_chars s = let r = String . copy s in for i = 0 to ( String . length r ) - 2 do for j = i + 1 to ( String . length r ) - 1 do if r . [ i ] > r . [ j ] then begin let tmp = r . [ i ] in r . [ i ] <- r . [ j ] ; r . [ j ] <- tmp ; end done done ; ( r )   let deranged ( s1, s2 ) = let len1 = String . length s1 and len2 = String . length s2 in if len1 <> len2 then false else try for i = 0 to pred len1 do if s1 . [ i ] = s2 . [ i ] then raise Exit done ; true with Exit -> false   let pairs_of_list lst = let rec aux acc = function | [ ] -> acc | x :: xs -> aux ( List . fold_left ( fun acc y -> ( x,y ) :: acc ) acc xs ) xs in aux [ ] lst   let ( ) = let h = Hashtbl . create 3571 in let ic = open_in "unixdict.txt" in try while true do let word = input_line ic in let key = sort_chars word in let l = try Hashtbl . find h key with Not_found -> [ ] in Hashtbl . replace h key ( word :: l ) ; done with End_of_file -> close_in ic ; let lst = Hashtbl . fold ( fun _ lw acc -> if List . length lw < 2 then acc else lw :: acc ) h [ ] in let lst = List . fold_left ( fun acc anagrams -> let pairs = pairs_of_list anagrams in ( List . filter deranged pairs ) @ acc ) [ ] lst in let res, _ = List . fold_left ( fun ( res, n ) ( w1, w2 ) -> let len = String . length w1 in match Pervasives . compare len n with | 0 -> ( ( w1, w2 ) :: res, n ) | 1 -> ( [ w1, w2 ] , len ) | _ -> ( res, n ) ) ( [ ] , 0 ) lst in List . iter ( fun ( w1, w2 ) -> Printf . printf "%s, %s\n" w1 w2 ) res \ No newline at end of file diff --git a/rosetta/file9.perl b/rosetta/file9.perl new file mode 100644 index 0000000..04fb642 --- /dev/null +++ b/rosetta/file9.perl @@ -0,0 +1 @@ +#! /usr/bin/perl   use strict ; use Image :: Imlib2 ;   my $img = Image :: Imlib2 -> load ( "Unfilledcirc.jpg" ) ; $img -> set_color ( 0 , 255 , 0 , 255 ) ; $img -> fill ( 100 , 100 ) ; $img -> save ( "filledcirc.jpg" ) ; exit 0 ; \ No newline at end of file diff --git a/rosetta/file9.php b/rosetta/file9.php new file mode 100644 index 0000000..729cd3e --- /dev/null +++ b/rosetta/file9.php @@ -0,0 +1 @@ + STR_PAD_RIGHT , 'R' => STR_PAD_LEFT , 'C' => STR_PAD_BOTH ) ;   /** Justify columns of textual tabular input where the record separator is the newline and the field separator is a 'dollar' character. justification can be L, R, or C; (Left, Right, or Centered).   Return the justified output as a string */ function aligner ( $str , $justification = 'L' ) { global $j2justtype ; assert ( array_key_exists ( $justification , $j2justtype ) ) ; $justtype = $j2justtype [ $justification ] ;   $fieldsbyrow = array ( ) ; foreach ( explode ( " \n " , $str ) as $line ) $fieldsbyrow [ ] = explode ( '$' , $line ) ; $maxfields = max ( array_map ( 'count' , $fieldsbyrow ) ) ;   foreach ( range ( 0 , $maxfields - 1 ) as $col ) { $maxwidth = 0 ; foreach ( $fieldsbyrow as $fields ) $maxwidth = max ( $maxwidth , strlen ( $fields [ $col ] ) ) ; foreach ( $fieldsbyrow as & $fields ) $fields [ $col ] = str_pad ( $fields [ $col ] , $maxwidth , ' ' , $justtype ) ; unset ( $fields ) ; // see http://bugs.php.net/29992 } $result = '' ; foreach ( $fieldsbyrow as $fields ) $result .= implode ( ' ' , $fields ) . " \n " ; return $result ; }   $textinfile = '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 ( array ( 'L' , 'R' , 'C' ) as $j ) echo aligner ( $textinfile , $j ) ;   ?> \ No newline at end of file diff --git a/rosetta/file9.py b/rosetta/file9.py new file mode 100644 index 0000000..2ca9a95 --- /dev/null +++ b/rosetta/file9.py @@ -0,0 +1 @@ +>>> import calendar >>> help ( calendar . prcal ) Help on method pryear in module calendar :   pryear ( self , theyear , w = 0 , l = 0 , c = 6 , m = 3 ) method of calendar . TextCalendar instance Print a years calendar .   >>> calendar . prcal ( 1969 ) 1969   January February March Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9 13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16 20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23 27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30 31   April May June Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 4 1 7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8 14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15 21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22 28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29 30   July August September Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7 7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14 14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21 21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28 28 29 30 31 25 26 27 28 29 30 31 29 30   October November December Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 1 2 1 2 3 4 5 6 7 6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14 13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21 20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28 27 28 29 30 31 24 25 26 27 28 29 30 29 30 31   >>> print ( '1234567890' * 8 ) 12345678901234567890123456789012345678901234567890123456789012345678901234567890 >>> \ No newline at end of file diff --git a/rosetta/file9.rb b/rosetta/file9.rb new file mode 100644 index 0000000..4e9c4bc --- /dev/null +++ b/rosetta/file9.rb @@ -0,0 +1 @@ +# sum: p ( 1 .. 10 ) . inject ( : + ) # smallest number divisible by all numbers from 1 to 20: p ( 1 .. 20 ) . inject ( :lcm ) #lcm: lowest common multiple   \ No newline at end of file diff --git a/rosetta/file9.scala b/rosetta/file9.scala new file mode 100644 index 0000000..e1e346f --- /dev/null +++ b/rosetta/file9.scala @@ -0,0 +1 @@ +def binarySearch [ A <% Ordered [ A ] ] ( a : IndexedSeq [ A ] , v : A ) = { def recurse ( low : Int, high : Int ) : Option [ Int ] = ( low + high ) / 2 match { case _ if high < low => None case mid if a ( mid ) > v => recurse ( low, mid - 1 ) case mid if a ( mid ) < v => recurse ( mid + 1 , high ) case mid => Some ( mid ) } recurse ( 0 , a. size - 1 ) } \ No newline at end of file diff --git a/rosetta/file9.ss b/rosetta/file9.ss new file mode 100644 index 0000000..c506a9b --- /dev/null +++ b/rosetta/file9.ss @@ -0,0 +1 @@ +( define ( A m n ) ( cond ( ( = m 0 ) ( + n 1 ) ) ( ( = n 0 ) ( A ( - m 1 ) 1 ) ) ( else ( A ( - m 1 ) ( A m ( - n 1 ) ) ) ) ) ) \ No newline at end of file diff --git a/rosetta/file9.tcl b/rosetta/file9.tcl new file mode 100644 index 0000000..f24ec5a --- /dev/null +++ b/rosetta/file9.tcl @@ -0,0 +1 @@ +package require Tcl 8.6   proc examine { filename } { global cmds set RE "(?:^| \[ \[ \{ \] ) \[ \\ w:. \] +" set f [ open $filename ] while { [ gets $f line ] > = 0 } { set line [ string trim $line ] if { $line eq "" || [ string match "#*" $line ] } { continue } foreach cmd [ regexp -all -inline $RE $line ] { incr cmds ( [ string trim $cmd " \{ \[ " ] ) } } close $f }   # Parse each file on the command line foreach filename $argv { examine $filename } # Get the command list in order of frequency set cmdinfo [ lsort -stride 2 -index 1 -integer -decreasing [ array get cmds ] ] # Print the top 10 (two list items per entry, so 0-19, not 0-9) foreach { cmd count } [ lrange $cmdinfo 0 19 ] { puts [ format "%-20s%d" $cmd $count ] } \ No newline at end of file