class TestReferences: def __init__(self, docsdir, refsdir): self._docsdir = docsdir self._refsdir = refsdir self._skipped = get_skipped_tests(docsdir) self._test = Test() self.config = Config() self.printer = get_printer() try: os.makedirs(self._refsdir) except OSError as e: if e.errno != errno.EEXIST: raise except: raise def create_refs_for_file(self, filename, n_doc = 1, total_docs = 1): if filename in self._skipped: self.printer.print_default("Skipping test '%s' (%d/%d)" % (os.path.join(self._docsdir, filename), n_doc, total_docs)) return refs_path = os.path.join(self._refsdir, filename) try: os.makedirs(refs_path) except OSError as e: if e.errno != errno.EEXIST: raise except: raise doc_path = os.path.join(self._docsdir, filename) if not self.config.force and self._test.has_results(refs_path): self.printer.print_default("Results found, skipping '%s' (%d/%d)" % (doc_path, n_doc, total_docs)) return self.printer.printout_ln("Creating refs for '%s' (%d/%d)" % (doc_path, n_doc, total_docs)) if self._test.create_refs(doc_path, refs_path): self._test.create_checksums(refs_path, self.config.checksums_only) def create_refs(self): docs, total_docs = get_document_paths_from_dir(self._docsdir) n_doc = 0 for doc in docs: n_doc += 1 self.create_refs_for_file(doc, n_doc, total_docs)
def train(self): print "[INFO] Training .." grad_history = np.zeros(self.num_parameters) theta = self.theta_init # Loop over epochs for epochid in range(self.max_epochs): # create a shuffled copy of the data X_shuffled = random.sample(self.X_train, self.num_data) # reset grad history per each epoch grad_history = np.zeros(self.num_parameters) # Loop over batches for batch_id in range(self.num_batches): start_i = batch_id * self.batch_size end_i = (batch_id+1) * self.batch_size if end_i + self.batch_size > self.num_data: end_i = self.num_data X_batch = X_shuffled[start_i:end_i] theta, grad_history = self.trainOneBatch( theta, X_batch, grad_history, batch_id) print "Finished epoch %d." % epochid # Save the model at every 5 epochs if epochid % self.epoch_save_freq == 0: filename = "optResult-RNTN-" + \ time.strftime("%Y%m%d-%H%M%S") + "-epoch-" + str(epochid) with open(filename, 'wb') as output: pickle.dump(theta, output, -1) # Evaluate on train, test set testObj_train = Test(self.dictionary, self.X_train) tree_accuracy_train, root_accuracy_train = testObj_train.test(theta) print "[Train accuracy] tree: %.2f, root: %.2f" %\ (tree_accuracy_train, root_accuracy_train) # Test on test data testObj_test = Test(self.dictionary, self.X_test) tree_accuracy_test, root_accuracy_test = testObj_test.test(theta) print "[Test accuracy] tree: %.2f, root: %.2f" %\ (tree_accuracy_test, root_accuracy_test) sys.stdout.flush() return theta
def __init__(self, docsdir, refsdir): self._docsdir = docsdir self._refsdir = refsdir self._skipped = get_skipped_tests(docsdir) self._test = Test() self.config = Config() self.printer = get_printer() try: os.makedirs(self._refsdir) except OSError as e: if e.errno != errno.EEXIST: raise except: raise
def __init__(self, docsdir, refsdir, outdir): self._docsdir = docsdir self._refsdir = refsdir self._outdir = outdir self._skipped = get_skipped_tests(docsdir) self._test = Test() self.config = Config() self.printer = get_printer() # Results self._n_tests = 0 self._n_passed = 0 self._failed = [] self._crashed = [] self._failed_status_error = [] self._stderr = [] try: os.makedirs(self._outdir); except OSError as e: if e.errno != errno.EEXIST: raise except: raise
# https://www.codewars.com/kata/a-wolf-in-sheeps-clothing/train/python from Test import Test def warn_the_sheep(queue): if (queue[-1] == 'wolf'): return 'Pls go away and stop eating my sheep' else: return 'Oi! Sheep number {}! You are about to be eaten by a wolf!'.format( len(queue) - (queue.index('wolf') + 1)) test = Test() test.assert_equals( warn_the_sheep([ 'sheep', 'sheep', 'sheep', 'sheep', 'sheep', 'wolf', 'sheep', 'sheep' ]), 'Oi! Sheep number 2! You are about to be eaten by a wolf!') test.assert_equals( warn_the_sheep( ['sheep', 'wolf', 'sheep', 'sheep', 'sheep', 'sheep', 'sheep']), 'Oi! Sheep number 5! You are about to be eaten by a wolf!') test.assert_equals( warn_the_sheep( ['wolf', 'sheep', 'sheep', 'sheep', 'sheep', 'sheep', 'sheep']), 'Oi! Sheep number 6! You are about to be eaten by a wolf!') test.assert_equals(warn_the_sheep(['sheep', 'wolf', 'sheep']), 'Oi! Sheep number 1! You are about to be eaten by a wolf!') test.assert_equals(warn_the_sheep(['sheep', 'sheep', 'wolf']), 'Pls go away and stop eating my sheep')
from Test import Test, Test as test ''' Implement a function which convert the given boolean value into its string representation. Note: Only valid inputs will be given. ''' def boolean_to_string(b): return f'{b}' test.assert_equals(boolean_to_string(True), "True") test.assert_equals(boolean_to_string(False), "False")
def __init__(self, dock): Test.__init__(self, "Test modules", dock)
# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Copyright 2015 Ozge Lule([email protected]), # Esref Ozturk([email protected]) from socket import * from json import * from Test import Test test = Test() s1 = socket(AF_INET, SOCK_STREAM) s1.connect(("0.0.0.0", 20000)) data = test.send(s1, '{"op":"start","params":["single","None","None"]}') data = loads(data) gameid = data['gameid'] print gameid test.send(s1, '{"op":"play","params":["setdepth",%d]}' % (1,)) test.send(s1, '{"op":"play","params":["nextmove","%s","%s"]}' % ('White', 'e2 e4')) test.send(s1, '{"op":"play","params":["changemode","%s"]}' % ('multi',))
# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Copyright 2015 Ozge Lule([email protected]), # Esref Ozturk([email protected]) from socket import * from Test import Test test = Test() s1 = socket(AF_INET, SOCK_STREAM) s1.connect(("0.0.0.0", 20000)) test.send(s1, '{"op":"start","params":["single","easy","None"]}') test.send(s1, '{"op":"play","params":["setdepth","1"]}') test.send(s1, '{"op":"play","params":["nextmove","%s","%s"]}' % ('White', 'e2 e4')) test.send(s1, '{"op":"play","params":["save","%s"]}' % 'pgnfile') test.send(s1, '{"op":"play","params":["history"]}') test.send(s1, '{"op":"play","params":["quit"]}') s2 = socket(AF_INET, SOCK_STREAM) s2.connect(("0.0.0.0", 20000))
def setUp(self): """Call before every test case.""" self.parser = Parser() self.test = Test()
def __init__(self): self.name = "LogTest" Test.__init__(self)
rep = map(lambda x: x in pair[1], pair[0]) if any(rep) == False: max_length = max(max_length, len(pair[1]) * len(pair[0])) return max_length def maxProduct_v2(words: List[str]) -> int: iterations = 0 max_length = 0 s = set() for w1 in words: for w2 in words: if w1 is w2 or (w1, w2) in s or (w2, w1) in s: continue iterations += 1 rep = map(lambda x: x in w2, w1) if any(rep) == False: max_length = max(max_length, len(w1) * len(w2)) s.add((w1, w2)) return max_length def maxProduct_v3(words: List[str]) -> int: pass Test.assert_equals(maxProduct(["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]), 16) Test.assert_equals(maxProduct(["a", "ab", "abc", "d", "cd", "bcd", "abcd"]), 4) Test.assert_equals(maxProduct(["a", "aa", "aaa", "aaaa"]), 0)
def __init__(self, dock): self.exe = config.exe1 self.wmclass = config.wmclass1 self.desktop_file = config.desktop_file1 Test.__init__(self, "Test launcher", dock)
from Test import Test, Test as test ''' Trolls are attacking your comment section! A common way to deal with this situation is to remove all of the vowels from the trolls' comments, neutralizing the threat. Your task is to write a function that takes a string and return a new string with all vowels removed. For example, the string "This website is for losers LOL!" would become "Ths wbst s fr lsrs LL!". Note: for this kata y isn't considered a vowel. ''' def disemvowel(string): return ''.join(x for x in string if x.lower() not in ('a','e','i','o','u')) def disemvowel(string): return ''.join(x for x in string if x.lower() not in ('aeiou')) def disemvowel(string): return string.translate(string.maketrans('','','aeiouAEIOU')) test.assert_equals(disemvowel("This website is for losers LOL!"), "Ths wbst s fr lsrs LL!")
from Test import Test, Test as test ''' You take your son to the forest to see the monkeys. You know that there are a certain number there (n), but your son is too young to just appreciate the full number, he has to start counting them from 1. As a good parent, you will sit and count with him. Given the number (n), populate an array with all numbers up to and including that number, but excluding zero. For example: monkeyCount(10) # --> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] monkeyCount(1) # --> [1] ''' def monkey_count(n): return [i for i in range(1, n + 1)] # Top solution def monkey_count(n): return range(1, n + 1) Test.describe("Basic tests") Test.assert_equals(monkey_count(5), [1, 2, 3, 4, 5]) Test.assert_equals(monkey_count(3), [1, 2, 3]) Test.assert_equals(monkey_count(9), [1, 2, 3, 4, 5, 6, 7, 8, 9]) Test.assert_equals(monkey_count(10), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) Test.assert_equals( monkey_count(20), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
persistence(999) => 4 # Because 9*9*9 = 729, 7*2*9 = 126, # 1*2*6 = 12, and finally 1*2 = 2. persistence(4) => 0 # Because 4 is already a one-digit number. persistence(39) # returns 3, because 3*9=27, 2*7=14, 1*4=4 # and 4 has only one digit persistence(999) # returns 4, because 9*9*9=729, 7*2*9=126, # 1*2*6=12, and finally 1*2=2 persistence(4) # returns 0, because 4 is already a one-digit number ''' def persistence(n): count = 0 while len(str(n)) > 1: prod = 1 for i in str(n): prod *= int(i) n = prod count += 1 return count Test.assert_equals(persistence(39), 3) Test.assert_equals(persistence(4), 0) Test.assert_equals(persistence(25), 2) Test.assert_equals(persistence(999), 4)
def __init__(self): self.name = "LoggingTimerLogTimeTest" Test.__init__(self)
quoting=csv.QUOTE_ALL) raw_writer = csv.DictWriter(raw_output, fieldnames=raw_fieldnames, quoting=csv.QUOTE_ALL) # Write csv headers for both files summary_writer.writeheader() raw_writer.writeheader() company_count = 1 for name in company_names: endpoint = '/company?id={}&start_date=2018-01-01T00:00:00.000Z&end_date=2018-02-01T00:00:00.000Z&stats=name,fan_count,description,website,post_message,post_type,post_created_time,post_like_count,post_comment_count'.format( company_names[name]['fbid']) url = MOOSE_ROOT + endpoint t = Test(company_names[name]['code'], name, MOOSE_ROOT, endpoint) for run_count in range(1, NUM_RUNS + 1): print("COMPANY {}/{} | {} - RUN: {}/{} | {}".format( company_count, len(company_names), name, run_count, NUM_RUNS, endpoint)) r = requests.get(url) if r: # print(json.dumps(r.json(), indent=2)) t.responses.append(r) raw_writer.writerow(t.gen_response_row(r)) summary_writer.writerow(t.summarise(check_ok_status=False)) company_count += 1
def __init__(self, dock): self.mgr = 'Docks' self.dt = .2 # time to update the dock size Test.__init__(self, "Test Docks", dock)
from Test import Test, Test as test ''' Given an array of integers, return a new array with each value doubled. For example: [1, 2, 3] --> [2, 4, 6] For the beginner, try to use the map method - it comes in very handy quite a lot so is a good one to know. ''' def maps(a): return [i * 2 for i in a] test.describe("Sample tests") test.assert_equals(maps([1, 2, 3]), [2, 4, 6]) test.assert_equals(maps([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]) test.assert_equals(maps([]), [])
def instantiate_test(self, alignment, record): """ Create a test instance, populate the attributes, and append it to the test list :param alignment: :param record """ test = Test() pdb_id = ParseAlignment.get_alignment_pdb_id(alignment) chain_id = ParseAlignment.get_alignment_pdb_chain(alignment) # set the pdb_id test.set_pdb_id(pdb_id) # determine coverage & identity coverage, identity = ParseAlignment.coverage_and_identity(alignment, record) # set the test sequence test.set_sequence(pdb_id, chain_id) # set the coverage & identity values test.set_coverage(coverage) test.set_identity(identity) # get the experimental method test.set_expt_method() # parse the pdb and pull out the resolution test.set_resolution() # parse the pdb and pull ligand information test.set_ligands() self.test_list.append(test)
class TestReferences: def __init__(self, docsdir, refsdir): self._docsdir = docsdir self._refsdir = refsdir self._skipped = get_skipped_tests(docsdir) self._test = Test() self.config = Config() self.printer = get_printer() self._total_tests = 1 self._n_tests = 0 self._queue = Queue() self._lock = RLock() try: os.makedirs(self._refsdir) except OSError as e: if e.errno != errno.EEXIST: raise except: raise def create_refs_for_file(self, filename): if filename in self._skipped: with self._lock: self._n_tests += 1 self.printer.print_default("Skipping test '%s'" % (os.path.join(self._docsdir, filename))) return refs_path = os.path.join(self._refsdir, filename) try: os.makedirs(refs_path) except OSError as e: if e.errno != errno.EEXIST: raise except: raise doc_path = os.path.join(self._docsdir, filename) if not self.config.force and self._test.has_results(refs_path): with self._lock: self._n_tests += 1 self.printer.print_default("Results found, skipping '%s'" % doc_path) return if self._test.create_refs(doc_path, refs_path): self._test.create_checksums(refs_path, self.config.checksums_only) with self._lock: self._n_tests += 1 self.printer.printout_ln("[%d/%d] %s: done" % (self._n_tests, self._total_tests, doc_path)) def _worker_thread(self): while True: doc = self._queue.get() self.create_refs_for_file(doc) self._queue.task_done() def create_refs(self): docs, total_docs = get_document_paths_from_dir(self._docsdir) self._total_tests = total_docs self.printer.printout_ln('Found %d documents' % (total_docs)) self.printer.printout_ln('Process %d using %d worker threads' % (os.getpid(), self.config.threads)) self.printer.printout_ln() self.printer.printout('Spawning %d workers...' % (self.config.threads)) for n_thread in range(self.config.threads): thread = Thread(target=self._worker_thread) thread.daemon = True thread.start() for doc in docs: self._queue.put(doc) self._queue.join()
def main(): parser = Parser(True) # Tokenize the data parser.tokenize("src/europarl-v7.es-en.es") parser.tokenize("src/europarl-v7.es-en.en") parser.tokenize("src/europarl-v7.fr-en.en") parser.tokenize("src/europarl-v7.fr-en.fr") # Normalize the data parser.cleanse("data/europarl-v7.es-en.es.tok", "data/europarl-v7.es-en.en.tok") parser.cleanse("data/europarl-v7.fr-en.en.tok", "data/europarl-v7.fr-en.fr.tok") # Split data into train, tune, test sets parser.split_train_tune_test("data/europarl-v7.es-en.es.tok.cleansed", "data/europarl-v7.es-en.en.tok.cleansed", "data/europarl-v7.fr-en.en.tok.cleansed", "data/europarl-v7.fr-en.fr.tok.cleansed", .6, .2) parser.match("data/test/europarl-v7.es-en.es.tok.cleansed.test", "data/test/europarl-v7.es-en.en.tok.cleansed.test", "data/test/europarl-v7.fr-en.en.tok.cleansed.test", "data/test/europarl-v7.fr-en.fr.tok.cleansed.test") trainer = Train(True) # Build target language models trainer.build_language_models("data/train/europarl-v7.es-en.en.tok.cleansed.train") trainer.build_language_models("data/train/europarl-v7.fr-en.fr.tok.cleansed.train") # Train each leg of the translation system trainer.train("data/train/europarl-v7.es-en.es.tok.cleansed.train", "data/train/europarl-v7.es-en.en.tok.cleansed.train", "es-en.working") trainer.train("data/train/europarl-v7.fr-en.en.tok.cleansed.train", "data/train/europarl-v7.fr-en.fr.tok.cleansed.train", "en-fr.working") # Tune the system on held out data tuner = Tune(True) tuner.tune("data/tune/europarl-v7.es-en.es.tok.cleansed.tune", "data/tune/europarl-v7.es-en.en.tok.cleansed.tune", "es-en.working") tuner.tune("data/tune/europarl-v7.fr-en.en.tok.cleansed.tune", "data/tune/europarl-v7.fr-en.fr.tok.cleansed.tune", "en-fr.working") test = Test(True) # Run interactive translator server test.test_translator_interactive("es-en.working") test.test_translator_interactive("en-fr.working") # Score translation quality between pivot translations using held out test data test.test_translation_quality("data/test/europarl-v7.es-en.es.tok.cleansed.test", "data/test/europarl-v7.es-en.en.tok.cleansed.test", "es-en.working") test.test_translation_quality("data/test/europarl-v7.fr-en.en.tok.cleansed.test", "data/test/europarl-v7.fr-en.fr.tok.cleansed.test", "en-fr.working") # Run interactive translator on pivoting system test.test_pivoting_interactive("es-en.working", "en-fr.working") # Score translation quality on entire translation using matched test data test.test_pivoting_quality("data/test/europarl-v7.es-en.es.tok.cleansed.test.matched", "es-en.working", "data/test/europarl-v7.fr-en.fr.tok.cleansed.test.matched", "en-fr.working")
def get(self): lat = float(self.request.get('lat')) lon = float(self.request.get('lon')) newtests = Test.query(lat, lon) self.response.out.write(Utils.GqlEncoder().encode(newtests))
# This file is part of Checkmate. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Copyright 2015 Ozge Lule([email protected]), # Esref Ozturk([email protected]) from socket import * from Test import Test test = Test() s2 = socket(AF_INET, SOCK_STREAM) s2.connect(("0.0.0.0", 20000)) test.send(s2, '{"op":"connect", "color":"Black", "gameid":"%d"}' % 1) test.send(s2, '{"op":"kill"}')
def DTW(tf, nf): len_t = len(tf) #预存语音梅谱帧数 len_n = len(nf) #实时语音梅谱帧数 vector_len = len(tf[0]) #特征向量长度 #print(len_t,' ',vector_len) print("before:", len(tf), ',', len(nf), ',', vector_len) if len_t > len_n: for i in range(len_t - len_n): nf = np.append(nf, [nf[len_n - 1]], axis=0) len_n = len_t elif len_t < len_n: for i in range(len_n - len_t): tf = np.append(tf, [tf[len_t - 1]], axis=0) len_t = len_n D = CalculateDistance(0, 0, tf, nf, vector_len) #起点距离 #d = [] #d.append(D) i = 0 j = 0 #t =[1] #n = [1] #k = 0 #计数器,用来查看DTW的执行过程 max_size = 65535 min_size = 0 #print(len_t,',',len_n) while (i <= len_n - 1 and j <= len_t - 1): #if (j*2>=i and (2*(i-len_n+2)<=j-len_t+1) and i+1<len_n-1) : if (j * 2 >= i and (2 * (i - len_n + 2) <= j - len_t + 1) and i + 1 < len_n - 1): D1 = CalculateDistance(i + 1, j, tf, nf, vector_len) else: D1 = max_size #if (j<=2*i and (0.5*(i-len_n+1)>=(j-len_t+2)) and j+1 <len_n-1) : if (j <= 2 * i and (i - len_n >= 2 * j - 2 * len_t + 1) and j + 1 < len_n - 1): D2 = CalculateDistance(i, j + 1, tf, nf, vector_len) else: D2 = max_size if i + 1 <= len_n - 1 and j + 1 <= len_t - 1: #print(j+1) D3 = CalculateDistance(i + 1, j + 1, tf, nf, vector_len) min_size = min(D1, D2, D3) if min_size == D1: i = i + 1 elif min_size == D2: j = j + 1 elif min_size == D3: i = i + 1 j = j + 1 D = D + min_size Test.getCpu() #d.append(min_size) # k = k+1 #print(k,' ','( ',i,' ',j,' )' ) #x = [i for i in range(len(d))] #plt.plot(x,d,label="distance") #plt.legend() #plt.show() #print(D) return D
# Esref Ozturk([email protected]) from random import randint from Checkmate import Checkmate from Test import Test bookmodes = ["worst", "best", "random"] a = Checkmate(mode="multi") # Be sure to download and extract http://ftp.gnu.org/gnu/chess/book_1.00.pgn.gz a.addbook("book_1.00.pgn") a.enablebook(enable=True) dummy = Test() while not a.isfinished(): a.setbookmode(bookmodes[randint(0, 2)]) move = a.hint() if move: a.nextmove(a.currentplayer(), move) else: break dummy.show(a) a.quit()
from Test import Test, Test as test ''' We need a function that can transform a number into a string. What ways of achieving this do you know? Examples: number_to_string(123) /* returns '123' */ number_to_string(999) /* returns '999' */ ''' def number_to_string(num): return str(num) test.assert_equals(number_to_string(67), '67')
def __init__(self, dock): self.mgr = 'Icons' self.dt = .3 # time to update the dock size Test.__init__(self, "Test Icons", dock)
from Test import Test ''' Deoxyribonucleic acid (DNA) is a chemical found in the nucleus of cells and carries the "instructions" for the development and functioning of living organisms. If you want to know more http://en.wikipedia.org/wiki/DNA In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G". You have function with one side of the DNA (string, except for Haskell); you need to get the other complementary side. DNA strand is never empty or there is no DNA at all (again, except for Haskell). More similar exercise are found here http://rosalind.info/problems/list-view/ (source) DNA_strand ("ATTGC") # return "TAACG" DNA_strand ("GTAT") # return "CATA" ''' def DNA_strand(dna): d = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'} return ''.join([d[x] for x in dna]) # Top solution, use translate + maketrans def DNA_strand(dna): return dna.translate(str.maketrans("ATCG", "TAGC")) Test.assert_equals(DNA_strand("AAAA"), "TTTT", "String AAAA is") Test.assert_equals(DNA_strand("ATTGC"), "TAACG", "String ATTGC is") Test.assert_equals(DNA_strand("GTAT"), "CATA", "String GTAT is")
from Test import Test def array_plus_array(arr1,arr2): return sum(arr1 + arr2) Test.it("Basic test") Test.assert_equals(array_plus_array([1, 2, 3], [4, 5, 6]), 21) Test.assert_equals(array_plus_array([-1, -2, -3], [-4, -5, -6]), -21) Test.assert_equals(array_plus_array([0, 0, 0], [4, 5, 6]), 15) Test.assert_equals(array_plus_array([100, 200, 300], [400, 500, 600]), 2100)
from Core import Interface from Core.Granularity import GranularityTemporal from Core.Granularity import GranularityTimeInterval from Core.Enum_Type import Enum_Type from Metrics import MetricColumn from Metrics.MetricExpressions import MetricExpressionNullValue from Test import Test from Test.TestOperations import TestOperationMayor from Test.TestRepresentations import TestRepresentationPercentage from Test.TestService import TestService from Source.SourceBBDD import SourceHIVE from Metrics import MetricService #Test 1 column_metric_program = MetricExpressionNullValue(MetricColumn()) test_column_metric = Test(15, TestRepresentationPercentage(), TestOperationMayor(), column_metric_program) columns = [ Column('channel_id', Enum_Type.STRING, None), Column('slot', Enum_Type.STRING, None), Column('week', Enum_Type.STRING, None), Column('genre_id', Enum_Type.STRING, None), Column('duration', Enum_Type.STRING, None), Column('subgenre_id', Enum_Type.STRING, None), Column('user_id', Enum_Type.STRING, None), Column('program_id', Enum_Type.STRING, column_metric_program), Column('event_id', Enum_Type.STRING, None) ] granularity = GranularityTemporal(2018, 3, 0, 11, None, None, None, GranularityTimeInterval.DAY)
from Test import Test, Test as test ''' Your task is to create a function that does four basic mathematical operations. The function should take three arguments - operation(string/char), value1(number), value2(number). The function should return result of numbers after applying the chosen operation. Examples basic_op('+', 4, 7) # Output: 11 basic_op('-', 15, 18) # Output: -3 basic_op('*', 5, 5) # Output: 25 basic_op('/', 49, 7) # Output: 7 ''' def basic_op(operator, value1, value2): return eval(f'{value1} {operator} {value2}') # Similar def basic_op(operator, value1, value2): return eval("{}{}{}".format(value1, operator, value2)) Test.describe("Basic tests") Test.assert_equals(basic_op('+', 4, 7), 11) Test.assert_equals(basic_op('-', 15, 18), -3) Test.assert_equals(basic_op('*', 5, 5), 25) Test.assert_equals(basic_op('/', 49, 7), 7)
def main(): testing = Test() testing.testFunction() interface = getUIChoice() interface.menuInterface()
def main(fn): # data= pd.read_csv("../data/kddcup.data_10_percent_corrected", names=cols) data = pd.read_csv(fn, header=-1) # data= remove_missing(data) # data= impute_missing(data) data = impute_missing2(data) # Features to be used in classification features = [x for x in range(1, len(data.columns))] X = data[features] y = data[0] #h= TGaussianNB(X, y) #h.run() print("GaussianNB") h = Test(X, y, GaussianNB()) h.run() h.report(fn="../Report/results/cancer.gnb.cm.tex") s = Search(X, y, GaussianNB(), [{}]) s.search() s.report("../Report/results/cancer.gnb.tex") print("DTree neu") parameters = [{ 'criterion': ['gini', 'entropy'], 'max_features': ['auto', 'sqrt', 'log2'] }] s = Search(X, y, DTree(), parameters) s.search() s.report("../Report/results/cancer.dt.tex") h = Test(X, y, DTree(max_features='log2', criterion='gini', random_state=1234)) h.run() h.report(fn="../Report/results/cancer.dt.cm.tex") print("RF") parameters = [{ 'n_estimators': range(1, 15), 'criterion': ['gini', 'entropy'], 'max_features': ['auto', 'sqrt', 'log2'] }] s = Search(X, y, RandomForestClassifier(), parameters) s.search() s.report("../Report/results/cancer.rf.tex", ) h = Test( X, y, RandomForestClassifier(n_estimators=6, criterion='gini', max_features='sqrt', random_state=1234)) h.run() h.report(fn="../Report/results/cancer.rf.cm.tex") parameters = [{ 'kernel': ['linear', 'sigmoid', 'rbf', 'poly'], 'C': [0.1, 1, 10, 11, 20] }] print("SVM") from sklearn import preprocessing X_scaled = preprocessing.scale(X) s = Search(X_scaled, y, SVC(), parameters) s.search() s.report("../Report/results/cancer.svm.tex") h = Test(X, y, SVC(C=11, kernel='poly')) h.run() h.report(fn="../Report/results/cancer.svm.cm.tex") print("KNeighborsClassifier") parameters = [{ 'n_neighbors': range(4, 8), 'weights': ['uniform', 'distance'], 'p': [1, 2] }] s = Search(X, y, KNeighborsClassifier(), parameters) s.search() s.report("../Report/results/cancer.knn.tex") h = Test(X, y, KNeighborsClassifier(n_neighbors=5, weights='uniform', p=2)) h.run() h.report(fn="../Report/results/cancer.knn.cm.tex")
from Test import Test as test ''' ASC Week 1 Challenge 4 (Medium #1) Write a function that converts any sentence into a V A P O R W A V E sentence. a V A P O R W A V E sentence converts all the letters into uppercase, and adds 2 spaces between each letter (or special character) to create this V A P O R W A V E effect. "Lets go to the movies" --> "L E T S G O T O T H E M O V I E S" "Why isn't my code working?" --> "W H Y I S N ' T M Y C O D E W O R K I N G ?" ''' def vaporcode(s): return ' '.join([l.upper() for l in s if l != ' ']) # Easier to read, more succinct def vaporcode(s): return " ".join(s.replace(" ", "").upper()) test.assert_equals(vaporcode("Lets go to the movies"), "L E T S G O T O T H E M O V I E S") test.assert_equals(vaporcode("Why isn't my code working?"), "W H Y I S N ' T M Y C O D E W O R K I N G ?")
from Test import Test, Test as test ''' You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this "outlier" N. Examples [2, 4, 0, 100, 4, 11, 2602, 36] Should return: 11 (the only odd number) [160, 3, 1719, 19, 11, 13, -21] Should return: 160 (the only even number) ''' # Store in nested lists # When both lists have items and one has more than 1 def find_outlier(integers): l = [[],[]] for i in integers: if i % 2 == 0: l[0].append(i) else: l[1].append(i) if len(l[1]) > 1 and len(l[0]) == 1: return l[0][0] elif len(l[0]) > 1 and len(l[1]) == 1: return l[1][0] test.assert_equals(find_outlier([2, 4, 6, 8, 10, 3]), 3) test.assert_equals(find_outlier([2, 4, 0, 100, 4, 11, 2602, 36]), 11) test.assert_equals(find_outlier([160, 3, 1719, 19, 11, 13, -21]), 160)
from Test import Test, Test as test ''' You get an array of numbers, return the sum of all of the positives ones. Example [1,-4,7,12] => 1 + 7 + 12 = 20 Note: if there is nothing to sum, the sum is default to 0. ''' def positive_sum(arr): return sum([x for x in arr if x > 0]) Test.describe("positive_sum") Test.it("works for some examples") Test.assert_equals(positive_sum([1, 2, 3, 4, 5]), 15) Test.assert_equals(positive_sum([1, -2, 3, 4, 5]), 13) Test.assert_equals(positive_sum([-1, 2, 3, 4, -5]), 9) Test.it("returns 0 when array is empty") Test.assert_equals(positive_sum([]), 0) Test.it("returns 0 when all elements are negative") Test.assert_equals(positive_sum([-1, -2, -3, -4, -5]), 0)
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Copyright 2015 Ozge Lule([email protected]), # Esref Ozturk([email protected]) from socket import * from Test import Test moves = [('White', 'e2 e4'), ('White', 'd1 f3'), ('White', 'f1 c4'), ('White', 'f3 f7')] test = Test() s1 = socket(AF_INET, SOCK_STREAM) s1.connect(("0.0.0.0", 20000)) test.send(s1, '{"op":"start" , "color":"White","params":["multi","None","None"]}') test.send(s1, '{"op":"play","params":["nextmove","%s","%s"]}' % moves[0]) test.send(s1, '{"op":"play","params":["nextmove","%s","%s"]}' % moves[1]) test.send(s1, '{"op":"play","params":["nextmove","%s","%s"]}' % moves[2]) test.send(s1, '{"op":"play","params":["nextmove","%s","%s"]}' % moves[3]) test.send(s1, '{"op":"kill"}')
# # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Copyright 2015 Ozge Lule([email protected]), # Esref Ozturk([email protected]) from socket import * from json import * from Test import Test moves = [('White', 'e2 e4'), ('Black', 'a7 a6'), ('White', 'd1 f3'), ('Black', 'a6 a5'), ('White', 'f1 c4'), ('Black', 'a5 a4'), ('White', 'f3 f7')] test = Test() s1 = socket(AF_INET, SOCK_STREAM) s1.connect(("0.0.0.0", 20000)) s2 = socket(AF_INET, SOCK_STREAM) s2.connect(("0.0.0.0", 20000)) data = test.send(s1, '{"op":"start" , "color":"White","params":["multi","None","None"]}') data = loads(data) gameid = data['gameid'] test.send(s2, '{"op":"connect" , "color":"Black","gameid":"%d"}' % gameid) test.send(s1, '{"op":"play","params":["nextmove","%s","%s"]}' % moves[0])
class SimpleTests(unittest.TestCase): def setUp(self): """Call before every test case.""" self.parser = Parser() self.test = Test() def testNormal1(self): cut=self.test test='''\ test squareError method <%squareError (%c1%,%c2%)%> returns <%double%>: param <%ArrayList<point>%> c1: dependsOn x1,x2,y1,y2: <% c1=new ArrayList(); c1.add(new Point(%x1%,%y1%)); c1.add(new Point(%x2%,%y2%)); %> out: returns >= (x1+y1) - (x2-y2) invalid 0: <%c1=null;%> out: throws <%.GetType().Name==NullReferenceException%> ''' cut.tokens=self.parser.test.parseString(test)[0] try: cut.populate().next() except StopIteration: pass else: self.fail('Why has execution stopped') assert self.test.test=="squareError",self.test.test def testNormal2(self): cut = self.test test="""\ test squareError method <%squareError (%c1%,%c2%)%>: param <%ArrayList<point>%> c1: dependsOn x1,x2,y1,y2: <% c1=new ArrayList(); c1.add(new Point(%x1%,%y1%)); c1.add(new Point(%x2%,%y2%)); %> out: returns >= (x1+y1) - (x2-y2) invalid 0: <%c1=null;%> out: throws <%.GetType().Name==NullReferenceException%> """ self.test.tokens=self.parser.test.parseString(test)[0] try: cut.populate().next() except StopIteration: pass else: self.fail('Why has execution stopped') assert self.test.method=="squareError (%c1%,%c2%)",self.test.method def testDefective1(self): test="""\ test squareError method <%squareError (%c1%,%c2%)%>: param <%ArrayList<point>%> c1: dependsOn x1,x2,y1,y2: <% c1=new ArrayList(); c1.add(new Point(%x1%,%y1%)); c1.add(new Point(%x2%,%y2%)); %> out: returns >= (x1+y1) - (x2-y2) invalid 0: <%c1=null;%> out: throws <%.GetType().Name==NullReferenceException%> param <%ArrayList<point>%> c1: dependsOn x1,x2,y1,y2: <% c1=new ArrayList(); c1.add(new Point(%x1%,%y1%)); c1.add(new Point(%x2%,%y2%)); %> out: returns >= (x1+y1) - (x2-y2) invalid 0: <%c1=null;%> out: throws <%.GetType().Name==NullReferenceException%> """ self.test.tokens=self.parser.test.parseString(test)[0] gen=self.test.populate() self.assertRaises(DuplicateDefinitionException,gen.next) def testInheritance1(self): cut=self.test test='''\ test squareError method <%squareError (%c1%,%c2%)%>: param x: valid 0: x==3 x==5 out: assert <% true %> param y(x) ''' self.test.tokens=self.parser.test.parseString(test)[0] try: cut.populate().next() except StopIteration: pass else: self.fail('Why has execution stopped') inp=cut.inputs['y'] assert isinstance(inp,Input) assert not inp.dependsOn assert inp.inherits assert len(inp.validPartitions)==1,len(inp.validPartitions) def testInheritance2(self): cut=self.test test='''\ test squareError method <%squareError (%c1%,%c2%)%>: param x: valid 0: x==3 x==5 out: assert <% true %> param z(x) param w(z): valid 0: w==3 w==5 w==1 out: assert <% true %> param y(x,w) ''' self.test.tokens=self.parser.test.parseString(test)[0] try: cut.populate().next() except StopIteration: pass else: self.fail('Why has execution stopped') inp=cut.inputs['y'] assert isinstance(inp,Input) assert not inp.dependsOn assert inp.inherits assert len(inp.validPartitions)==3,len(inp.validPartitions) def testInheritance3(self): cut=self.test test='''\ test squareError method <%squareError (%c1%,%c2%)%>: param x(w): valid 0: x==3 x==5 out: assert <% true %> param z(x) param w(z): valid 0: w==3 w==5 w==1 out: assert <% true %> param y(w) ''' self.test.tokens=self.parser.test.parseString(test)[0] self.assertRaises(CyclicReferenceException,cut.populate().next) def getExample(self): test='''\ invalid y: y==4 y<3 y>2 ''' tokens=LibraryParser().invalidPartition.parseString(test)[0] p=InheritedPartition(tokens) for x in p.populate(): pass return p def testInheritance4(self): cut=self.test test='''\ test squareError method <%squareError (%c1%,%c2%)%>: param x: valid 0(email): x==3 x==5 out: assert <% true %> param z(x) param w(z): valid 0: w==3 w==5 w==1 out: assert <% true %> param y(w) ''' self.test.tokens=self.parser.test.parseString(test)[0] f=False gen=cut.populate() try: typ,val=gen.next() assert typ=='inp',typ assert 'email' in val,val f=True gen.send(self.getExample()) except StopIteration: pass else: self.fail('Why has execution stopped') assert f inp=cut.inputs['y'] assert isinstance(inp,Input) assert not inp.dependsOn assert inp.inherits assert len(inp.validPartitions)==2,len(inp.validPartitions) def testInheritance5(self): cut=self.test test='''\ test squareError method <%squareError (%c1%,%c2%)%>: param x(w) ''' self.test.tokens=self.parser.test.parseString(test)[0] self.assertRaises(SemanticException,cut.populate().next) def testInheritance6(self): cut=self.test test='''\ test squareError method <%squareError (%c1%,%c2%)%>: param x(w) param w(f,r) param f: valid 0: f==4 param r(x) ''' self.test.tokens=self.parser.test.parseString(test)[0] self.assertRaises(CyclicReferenceException,cut.populate().next) def testInheritance7(self): cut=self.test test='''\ test squareError method <%squareError (%c1%,%c2%)%>: param x(w) param w(f,r) param f: valid 0: f==4 param r(): valid 0: w==5 ''' self.test.tokens=self.parser.test.parseString(test)[0] self.assertRaises(SemanticException,cut.populate().next) def checkIfDependant(self,order,inputDict): for i,name in enumerate(order): assert all((dep in order[:i]) for dep in inputDict[name].dependsOn) def testSortDependencies1(self): cut=self.test i1,i2,i3,i4,i5=Input(),Input(),Input(),Input(),Input() i1.name,i2.name,i3.name,i4.name,i5.name='i1','i2','i3','i4','i5' i1.dependsOn=['i2','i3','i4'] i5.dependsOn=['i1'] i4.dependsOn=['i2','i3'] i2.dependsOn=['i3'] cut.inputs={'i1':i1,'i2':i2,'i3':i3,'i4':i4,'i5':i5} order=cut.sortDependencies() assert len(order)==5,len(order) self.checkIfDependant(order,cut.inputs) def testSortDependencies2(self): cut=self.test i1,i2,i3,i4,i5=Input(),Input(),Input(),Input(),Input() i1.name,i2.name,i3.name,i4.name,i5.name='i1','i2','i3','i4','i5' cut.inputs={'i1':i1,'i2':i2,'i3':i3,'i4':i4,'i5':i5} order=cut.sortDependencies() assert len(order)==5,len(order) self.checkIfDependant(order,cut.inputs) def testSortDependencies3(self): cut=self.test i1,i2,i3,i4,i5=Input(),Input(),Input(),Input(),Input() i1.name,i2.name,i3.name,i4.name,i5.name='i1','i2','i3','i4','i5' i1.dependsOn=['i2','i4'] i5.dependsOn=['i1'] i4.dependsOn=['i2','i3'] i2.dependsOn=['i3'] i3.dependsOn=['i5'] cut.inputs={'i1':i1,'i2':i2,'i3':i3,'i4':i4,'i5':i5} self.assertRaises(CyclicReferenceException,cut.sortDependencies) def testSortDependencies4(self): cut=self.test i1,i2,i3,i4,i5=Input(),Input(),Input(),Input(),Input() i1.name,i2.name,i3.name,i4.name,i5.name='i1','i2','i3','i4','i5' i1.dependsOn=['i2','i4'] i5.dependsOn=['i1'] i4.dependsOn=['i2','i3'] i2.dependsOn=['i3'] i3.dependsOn=['i7'] cut.inputs={'i1':i1,'i2':i2,'i3':i3,'i4':i4,'i5':i5} self.assertRaises(SemanticException,cut.sortDependencies) def testCombine1(self): test=self.combineN([1,2,3]) assert test==[[1],[2],[3]],test def testCombine2(self): test1=self.combineN([1,2,3],[4,5,6]) test2=self.test.combine2([1,2,3],[4,5,6],True) assert all(t1==t2 for t1,t2 in zip(test1,test2)) def testHorizontalGrowth1(self): cut=self.test suite=cut.combine2([TestCaseValue(index=i+1,variableName=0) for i in range(3)], [TestCaseValue(index=j+1,variableName=1) for j in range(3)],True) pi=cut.horizontalGrowth(suite,2,[3,3,1]) assert len(pi)==0,len(pi) assert all(TestCaseValue(index=1, variableName=2) in tc or TestCaseValue(index=None, variableName=2) in tc for tc in suite) def testHorizontalGrowth2(self): cut=self.test suite=cut.combine2([TestCaseValue(index=i+1,variableName=0) for i in range(3)], [TestCaseValue(index=j+1,variableName=1) for j in range(3)],True) pi=cut.horizontalGrowth(suite,2,[3,3,3]) assert len(pi)==2,len(pi) assert all(TestCaseValue(index=1, variableName=2) in tc or TestCaseValue(index=2, variableName=2) or TestCaseValue(index=3, variableName=2) in tc for tc in suite) def testVerticalGrowth1(self): cut=self.test suite=[] suite.append([TestCaseValue(index=1,variableName=0),TestCaseValue(index=1,variableName=1)]) suite.append([TestCaseValue(index=1,variableName=0),TestCaseValue(index=2,variableName=1)]) suite.append([TestCaseValue(index=2,variableName=0),TestCaseValue(index=1,variableName=1)]) suite.append([TestCaseValue(index=None,variableName=0),TestCaseValue(index=2,variableName=1)]) pi=set([(TestCaseValue(index=2,variableName=0),TestCaseValue(index=2,variableName=1))]) cut.verticalGrowth(suite,pi) assert len(suite)==4,len(suite) assert len(pi)==0,len(pi) assert suite[3][1]==TestCaseValue(index=2,variableName=1),str(suite[3][1]) self.assertPairwiseCoverage(suite) def assertPairwiseCoverage(self,suite): vars=len(suite[0]) column=[[] for i in range(vars)] for tc in suite: for i in range(vars): column[i].append(tc[i]) #calculate whole pi pi=set() for i in range(vars): for c in range(i): pairs=self.test.combine2(set(column[c]),set(column[i])) intersections=set((p1,p2) for p1,p2 in pairs if p1.index!=None and p2.index!=None) pi.update(intersections) #start removing pairs from pi for i in range(vars): for c in range(i): pairs=set(pair for pair in zip(column[c],column[i])) pi.difference_update(pairs) assert len(pi)==0,len(pi) def combineN (self, *args): '''Combines the first list (as argument) with subsequent lists''' #This method is a bit too much memory hungry due to its recursive nature and can be optimised. Speed is ok. if len(args)==0: return for i,ls in enumerate(args[0]): if not isinstance(ls,list): args[0][i]=[ls] if len(args)==1: for ls in args[0]: ls[0]=copy.copy(ls[0]) return args[0] res=[] for ls in args[0]: #combine with args[1] for c in args[1]: temp=copy.copy(ls) temp.append(copy.copy(c)) res.append(temp) return self.combineN(res,*args[2:]) def testAssertPairwiseCoverage1(self): cut=self.test suite=cut.combine2([TestCaseValue(index=i+1,variableName=0) for i in range(3)], [TestCaseValue(index=j+1,variableName=1) for j in range(3)],True) self.assertPairwiseCoverage(suite) def testAssertPairwiseCoverage2(self): cut=self.test suite=self.combineN([TestCaseValue(index=i+1,variableName=0) for i in range(3)], [TestCaseValue(index=j+1,variableName=1) for j in range(3)], [TestCaseValue(index=j+1,variableName=2) for j in range(2)]) self.assertPairwiseCoverage(suite) def testGetPairwiseSuite1(self): suite=self.test.getPairwiseSuite([2,2,3]) self.assertPairwiseCoverage(suite) def testGetPairwiseSuite2(self): '''testing with a large test suite''' suite=self.test.getPairwiseSuite([2,2,3,4,5,6,1]) self.assertPairwiseCoverage(suite) def testGetPairwiseSuite3(self): '''testing with a shallow test suite''' suite=self.test.getPairwiseSuite([1,1,1,1,1,1,1,1,1,1]) assert len(suite)==1,len(suite) self.assertPairwiseCoverage(suite) def testGetPairwiseSuite4(self): '''testing with a too short test suite''' suite=self.test.getPairwiseSuite([1]) assert len(suite)==1,len(suite) self.assertPairwiseCoverage(suite) def testGetPairwiseSuite5(self): '''testing with a very large test suite''' suite=self.test.getPairwiseSuite([10,2,10,4,5,20,1]) self.assertPairwiseCoverage(suite) def testGetPairwiseSuite6(self): '''testing with an incrementally larger test suite''' suite=self.test.getPairwiseSuite([1,1,5,10,60]) self.assertPairwiseCoverage(suite) def testgetBCInvalidSuite(self): '''testing base choice combination strategy''' suite=self.test.getBCInvalidSuite([2,0,0,3,2]) assert len(suite)==7,len(suite) #check there is only 1 negative no. assert all(len([None for v in tc if v.index<0])==1 for tc in suite) #check that all other nos are 0 assert all(len([None for v in tc if v.index==0])==len(tc)-1 for tc in suite) #-----------------------------------------Integration tests-----------------------------------------# def testGetTestSuite1(self): '''Simple test suite generation''' cut=self.test test='''\ test xihaga method <% boq (%a%)%> returns <% int %>: param c: valid 0: c==3 c==4 param b(c) param a: dependsOn b,c: a==b+c out: returns>3 valid 0: a==1 ''' cut.tokens=self.parser.test.parseString(test)[0] gen=cut.populate() try: gen.next() except StopIteration: pass else: self.fail('Why has execution stopped') suite=cut.getTestSuite() values=[tc[3].value for tc in suite] assert values==[6,1,1,8],values def testGetTestSuite2(self): '''Saved test suite generation''' cut=self.test with open('prog.stdl') as f: cut.tokens=self.parser.test.parseString(f.read())[0] gen=cut.populate() try: gen.next() except StopIteration: pass else: self.fail('Why has execution stopped') suite=cut.getTestSuite() assert len(suite)==6,len(suite) def testGetInvalidTestSuite1(self): '''Testing an invalid test suite only''' cut=self.test test='''\ test xihaga method <% boq (%a%)%> returns <% int %>: param c: valid 0: c>3 c<7 out: assert <%true%> error: assert <%false%> param b(c) ''' cut.tokens=self.parser.test.parseString(test)[0] gen=cut.populate() try: gen.next() except StopIteration: pass else: self.fail('Why has execution stopped') suite=cut.getTestSuite(valid=0,invalid='bc') assert len(suite)==4,len(suite) for check in (tc[0] for tc in suite): assert isinstance(check,PartitionCheck) checkItems=check.getCheckItems({}) for checkItem in checkItems: assert isinstance(checkItem,PartitionCheckItem) assert checkItem.value=='false',checkItems.value
def __init__(self, dock): Test.__init__(self, "Test separator icon", dock)
def __init__(self, dock): self.test_file='/tmp/cairo-dock-test' Test.__init__(self, "Test custom launcher", dock)
async3secSegments=Segmentation("None",periodSync=False,sizeType="fixed",frameSizeMs=3000.0,hopSizeMs=1000.0) segStrategies=[async2secSegments,async3secSegments] #Define features to be used /定義要使用的功能 features=[] for featName in ['SubEnv']:#other options: 'MFCC','MelSpec'/其他選項:'MFCC','MelSpec' for segType in segStrategies: for timeDim in [32,64]: for freqDim in [16]: features.append(Feature(featName,[timeDim,freqDim],"frame",segType,involveDelta=False)) #Define data specifications for this database/定義此數據庫的數據規範 data=Data(dbaName,dataFolder,featureFolder,features,useBalancedData,splitRatios,info) #Defining NN model with a name. /用名稱定義NN模型。 # Implementation is in models.py. Feel free to add your own models and /實現在models.py中。 # test by just changing the name here/您可以在此處更改名稱,隨意添加自己的模型並進行測試 modelNames=['uocSeq1','uocSeq2'] #Running random split and testing several times (1/testSetPercentage)/運行隨機拆分和測試幾次(1 / testSetPercentage) # ex: if test set is 20%, tests will be repeated 5 times/例如:如果測試組為20%,測試將被重複5次 numExperiments=int(1/splitRatios[-1]) for i in range(numExperiments): for modelName in modelNames: #Define test specifications and run/定義測試規範並運行 singleTest=Test(modelName,data,resultsFolder,batch_size=128,num_epochs=50) #Run the tests: outputs will be put in the results folder/運行測試:輸出將被放入結果文件夾中 singleTest.run() #Cleaning this test sessions' intermediate files/清理此測試會話的中間文件 cleanFilesOfPrevSess([dataFolder])
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Copyright 2015 Ozge Lule([email protected]), # Esref Ozturk([email protected]) from socket import * from Test import Test moves = [('Black', 'a7 a6'), ('Black', 'a6 a5'), ('Black', 'a5 a4')] test = Test() s2 = socket(AF_INET, SOCK_STREAM) s2.connect(("0.0.0.0", 20000)) gameid = 1 test.send(s2, '{"op":"connect" , "color":"Black","gameid":"%d"}' % gameid) test.send(s2, '{"op":"play","params":["nextmove","%s","%s"]}' % moves[0]) test.send(s2, '{"op":"play","params":["nextmove","%s","%s"]}' % moves[1]) test.send(s2, '{"op":"play","params":["nextmove","%s","%s"]}' % moves[2]) test.send(s2, '{"op":"kill"}')
# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Copyright 2015 Ozge Lule([email protected]), # Esref Ozturk([email protected]) from Checkmate import Checkmate from Test import Test dummy = Test() a = Checkmate(mode='multi') a.nextmove('White', 'e2 e4') a.nextmove('Black', 'a7 a6') dummy.show(a) a.undo() a.nextmove('Black', 'a7 a5') dummy.show(a) a.quit()
# # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Copyright 2015 Ozge Lule([email protected]), # Esref Ozturk([email protected]) from random import randint from socket import * from json import * from Test import Test bookmodes = ['worst', 'best', 'random'] test = Test() s1 = socket(AF_INET, SOCK_STREAM) s1.connect(("0.0.0.0", 20000)) s2 = socket(AF_INET, SOCK_STREAM) s2.connect(("0.0.0.0", 20000)) data = test.send(s1, '{"op":"start", "color":"White","params":["multi","None","None"]}') data = loads(data) gameid = data['gameid'] test.send(s2, '{"op":"connect" , "color":"Black","gameid":"%d"}' % gameid) # Be sure to download and extract http://ftp.gnu.org/gnu/chess/book_1.00.pgn.gz
stepsize = 0.001 while vUpdate > 100 and uCnt < outLoop: uCnt += 1 p_array = {} innerUpdate = inLoop Member_array, Cost_array, update2 = lr_solver_MC( TupleSet_array, Pos_array, Neg_array, Cost_array, Benefit_array, Member_array, b, Cost_Prior_array, A_MC_x, A_MC_y, innerUpdate, stepsize) Benefit_array, Cost_array, update1 = lr_solver_BC( TupleSet_array, Pos_array, Neg_array, Cost_array, Benefit_array, Member_array, b, A_BC_x, A_BC_y, innerUpdate, stepsize) print "Update ", uCnt, update1, update2 # Store the Model newAUC_score = Test(Cost_array, Benefit_array, Member_array, uCnt, f, TestData) if newAUC_score > Best_AUPR: Best_AUPR = newAUC_score Store(Cost_array, Benefit_array, Member_array, uCnt, f) Predict(Cost_array, Benefit_array, Member_array) print "new AUC score, AUC = ", Best_AUPR
__author__ = 'nitinpasumarthy' from Test import Test trainfilepath = './data/entrain.txt' testfilepath = './data/entest.txt' outfilepath = './data/predictedtags.txt' tester = Test(trainfilepath, testfilepath, outfilepath) print("error_rate = {}".format(tester.error_rate(outfilepath, testfilepath))) print('Done')
def fit(self, data, test_split=True, test_portion=0.1, search_parameter_space=False): lr_bu = self.lr_bu lr_bi = self.lr_bi lr_pu = self.lr_pu lr_qi = self.lr_qi lr_yj = self.lr_yj reg_bu = self.reg_bu reg_bi = self.reg_bi reg_pu = self.reg_pu reg_qi = self.reg_qi reg_yj = self.reg_yj if not search_parameter_space: self.test_split = test_split self.__set_data(data, test_portion) print('Initializing features for Users and Items...') initial = initializer(self.user_ids, self.item_ids, self.initialization_method, self.n_latent, self.init_mean, self.init_std) self.pu, self.qi = initial.initialize_latent_vectors( initalization_method='normal') _, self.yj = initial.initialize_latent_vectors( initalization_method='normal') self.bu = dict([(key, 0) for key in self.train_data_user_ids]) self.bi = dict([(key, 0) for key in self.train_data_item_ids]) if not self.biased: global_mean = 0 else: global_mean = self.all_ratings_in_train / len(self.train_data) for current_epoch in range(self.n_epochs): if self.verbose: print(" processing epoch {}".format(current_epoch)) for u, i, r in self.train_data: # items rated by u self.Iu = [items for items in self.user_existing_ratings[u]] self.sqrt_Iu = np.sqrt(len(self.Iu)) # implicit feedback self.u_impl_fdb = np.zeros(self.n_latent, np.double) for j in self.Iu: for f in range(self.n_latent): self.u_impl_fdb[f] += self.yj[j][f] / self.sqrt_Iu # compute current error dot = 0 for f in range(self.n_latent): dot += self.qi[i][f] * (self.pu[u][f] + self.u_impl_fdb[f]) err = r - (global_mean + self.bu[u] + self.bi[i] + dot) # update biases self.bu[u] += lr_bu * (err - reg_bu * self.bu[u]) self.bi[i] += lr_bi * (err - reg_bi * self.bi[i]) # update factors for f in range(self.n_latent): puf = self.pu[u][f] qif = self.qi[i][f] self.pu[u][f] += lr_pu * (err * qif - reg_pu * puf) self.qi[i][f] += lr_qi * (err * puf - reg_qi * qif) for j in self.Iu: self.yj[j][f] += lr_yj * (err * qif / self.sqrt_Iu - reg_yj * self.yj[j][f]) # Calculate errors #error_counter += 1 train_error = Test.rmse_error(self.train_data, self.pu, self.qi) # Show error to Client if self.test_split: test_error = Test.rmse_error(self.test_data, self.pu, self.qi) print( 'Epoch Number: {}/{} Training RMSE: {:.2f} Test RMSE: {}'. format(current_epoch + 1, self.n_epochs, train_error, test_error)) else: print('Epoch Number: {}/{} Training RMSE: {:.2f}'.format( current_epoch + 1, self.n_epochs, train_error)) self.bu = self.bu self.bi = self.bi self.pu = self.pu self.qi = self.qi self.yj = self.yj
def fit(self, data, test_split=True, test_portion=0.1, search_parameter_space=False): if not search_parameter_space: self.test_split = test_split self.__set_data(data, test_portion) print('Initializing features for Users and Items...') initial = initializer(self.user_ids, self.item_ids, self.initialization_method, self.n_latent, 0, 0) user_features, item_features = initial.initialize_latent_vectors() bu = dict([(key, 0) for key in self.train_data_user_ids]) bi = dict([(key, 0) for key in self.train_data_item_ids]) if not self.biased: global_mean = 0 else: global_mean = self.all_ratings_in_train / len(self.train_data) for current_epoch in range(self.n_epochs): if self.verbose: print("Processing epoch {}".format(current_epoch)) # (re)initialize nums and denoms to zero self.user_num = dict([(key, np.zeros(self.n_latent)) for key in self.train_data_user_ids]) self.user_denom = dict([(key, np.zeros(self.n_latent)) for key in self.train_data_user_ids]) self.item_num = dict([(key, np.zeros(self.n_latent)) for key in self.train_data_item_ids]) self.item_denom = dict([(key, np.zeros(self.n_latent)) for key in self.train_data_item_ids]) for u, i, r in self.train_data: # compute current estimation and error dot = 0 # <q_i, p_u> for f in range(self.n_latent): dot += user_features[u][f] * item_features[i][f] est = global_mean + bu[u] + bi[i] + dot err = r - est # Update biases if self.biased: bu[u] += self.lr_bu * (err - self.reg_bu * bu[u]) bi[i] += self.lr_bi * (err - self.reg_bi * bi[i]) # Compute numerators and denominators for f in range(self.n_latent): self.user_num[u][f] += item_features[i][f] * r self.user_denom[u][f] += item_features[i][f] * est self.item_num[i][f] += user_features[u][f] * r self.item_denom[i][f] += user_features[u][f] * est # Update user factors for u in self.train_data_user_ids: n_ratings = self.user_n_ratings[u] for f in range(self.n_latent): self.user_denom[u][ f] += n_ratings * self.reg_user_features * user_features[ u][f] user_features[u][ f] *= self.user_num[u][f] / self.user_denom[u][f] # Update item factors for i in self.train_data_item_ids: n_ratings = self.item_n_ratings[i] for f in range(self.n_latent): self.item_denom[i][ f] += n_ratings * self.reg_item_features * item_features[ i][f] item_features[i][ f] *= self.item_num[i][f] / self.item_denom[i][f] # Calculate errors #error_counter += 1 train_error = Test.rmse_error(self.train_data, user_features, item_features) # Show error to Client if self.test_split: test_error = Test.rmse_error(self.test_data, user_features, item_features) print( 'Epoch Number: {}/{} Training RMSE: {:.2f} Test RMSE: {}'. format(current_epoch + 1, self.n_epochs, train_error, test_error)) else: print('Epoch Number: {}/{} Training RMSE: {:.2f}'.format( current_epoch + 1, self.n_epochs, train_error)) self.bu = bu self.bi = bi self.user_features = user_features self.item_features = item_features
def __init__(self, dock): self.name1 = 'xxx' self.name2 = 'yyy' Test.__init__(self, "Test stack icon", dock)
def fit(self, data, test_split=True, test_portion=0.1, search_parameter_space=False): # Set train_data, test_data, user_ids etc. if search parameter is False # If True, this lets us search parameter space with the same train-test split if not search_parameter_space: self.test_split = test_split self.__set_data(data, test_portion) # Initialization print('Initializing features for Users and Items...') initial = initializer(self.user_ids, self.item_ids, self.initialization_method, self.n_latent, self.init_mean, self.init_std) self.user_features, self.item_features = initial.initialize_latent_vectors( ) # Training print('Starting training...') error_counter = 0 for epoch in range(self.max_epoch): # updating user and item features for user, item, rating in self.train_data: error = rating - \ np.dot(self.user_features[user], self.item_features[item]) # Use temp to update each item and user feature in sync. temp = self.user_features[user] # Update user and item feature for each user, item and rating pair self.user_features[user] += self.learning_rate * \ (error * self.item_features[item] - self.regularization * self.user_features[user]) self.item_features[item] += self.learning_rate * \ (error * temp - self.regularization * self.item_features[item]) # Calculate errors error_counter += 1 train_error = Test.rmse_error(self.train_data, self.user_features, self.item_features) # Show error to Client if self.test_split: test_error = Test.rmse_error(self.test_data, self.user_features, self.item_features) print( 'Epoch Number: {}/{} Training RMSE: {:.2f} Test RMSE: {}'. format(epoch + 1, self.max_epoch, train_error, test_error)) else: print('Epoch Number: {}/{} Training RMSE: {:.2f}'.format( epoch + 1, self.max_epoch, train_error)) # Save best features depending on test_error if self.test_split and test_error < self.min_test_error: self.min_test_error = test_error self.best_user_features = copy.deepcopy(self.user_features) self.best_item_features = copy.deepcopy(self.item_features) error_counter = 0 # Save best features if test data is False elif not self.test_split and train_error < self.min_train_error: self.min_train_error = train_error self.best_user_features = copy.deepcopy(self.user_features) self.best_item_features = copy.deepcopy(self.item_features) # Break if test_error didn't improve for the last n rounds and early stopping is true if self.early_stopping and error_counter >= self.early_stopping: print( "Test error didn't get lower for the last {} epochs. Training is stopped." .format(error_counter)) print('Best test error is: {:.2f}. Best features are saved.'. format(self.min_test_error)) break print('Training has ended...') self.user_features = copy.deepcopy(self.best_user_features) self.item_features = copy.deepcopy(self.best_item_features)
def __init__(self, dock): self.exe = config.exe self.wmclass = config.wmclass self.desktop_file = config.desktop_file Test.__init__(self, "Test taskbar", dock)
def main(self): """ Data parsing/processing section""" # parse input data strip=Parse(self.input) parsed_data=strip.getStripText() # Parse input data need_compress_catagory=strip.getNeedCompreeCatagory() # Check which catagories need group grouped_data=strip.getGroupedParsedData() # Group data """ Cuboid construction section """ #Create cuboid division_factor=3 min_sup=len(grouped_data)/division_factor # Iceberg condition cuboid=Cuboid(strip.getRowConuter(), min_sup) oneDimensionTable=cuboid.getOneDimensionTable() # Conduct 1-D aggregate compressedBaseTable=cuboid.getCompressedBaseTable(grouped_data, need_compress_catagory) # Construct compressed base table """ Star tree/table construction section""" #Construct star tree and star table s_t=Cubing(compressedBaseTable) root=s_t.starCubing() #s_t.constructStarTree() """ Test/Output section """ # test results t=Test() t.testParsedData(parsed_data) # Test if parsed data is correct t.testNeedCompressCatagory(need_compress_catagory) # Test which catagory needs compress t.testGroupedParsedData(grouped_data) # Test grouped data t.testOneDimensionAggregatation(oneDimensionTable,need_compress_catagory, min_sup) # Test 1-D aggregation t.testCompressedBaseTable(compressedBaseTable) # Test node-ordered compressed base table t.testStarTree(root,0,s_t.count,'')
# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Copyright 2015 Ozge Lule([email protected]), # Esref Ozturk([email protected]) from socket import * from json import * from Test import Test test = Test() s1 = socket(AF_INET, SOCK_STREAM) s1.connect(("0.0.0.0", 20000)) s2 = socket(AF_INET, SOCK_STREAM) s2.connect(("0.0.0.0", 20000)) data = test.send(s1, '{"op":"start","params":["single","easy","None"]}') data = loads(data) gameid = data['gameid'] test.send(s1, '{"op":"play","params":["setdepth","1"]}') test.send(s1, '{"op":"play","params":["nextmove","%s","%s"]}' % ('White', 'e2 e4')) test.send(s1, '{"op":"exit"}')
from Test import Test, Test as test ''' Deoxyribonucleic acid, DNA is the primary information storage molecule in biological systems. It is composed of four nucleic acid bases Guanine ('G'), Cytosine ('C'), Adenine ('A'), and Thymine ('T'). Ribonucleic acid, RNA, is the primary messenger molecule in cells. RNA differs slightly from DNA its chemical structure and contains no Thymine. In RNA Thymine is replaced by another nucleic acid Uracil ('U'). Create a function which translates a given DNA string into RNA. For example: "GCAT" => "GCAU" The input string can be of arbitrary length - in particular, it may be empty. All input is guaranteed to be valid, i.e. each input string will only ever consist of 'G', 'C', 'A' and/or 'T'. ''' def dna_to_rna(dna): return ''.join(['U' if x == 'T' else x for x in dna]) # Top one def DNAtoRNA(dna): return dna.replace('T', 'U') test.assert_equals(dna_to_rna("TTTT"), "UUUU") test.assert_equals(dna_to_rna("GCAT"), "GCAU") test.assert_equals(dna_to_rna("GACCGCCGCC"), "GACCGCCGCC")
def __init__(self): Test.__init__(self) self._numObjects = 64 self._numThreads = [1, 2, 4, 8, 16, 32] self._numReads = 32
Task: Your task is to write a function which returns the sum of following series upto nth term(parameter). Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +... Rules: You need to round the answer to 2 decimal places and return it as String. If the given value is 0 then it should return 0.00 You will only be given Natural Numbers as arguments. Examples: SeriesSum(1) => 1 = "1.00" SeriesSum(2) => 1 + 1/4 = "1.25" SeriesSum(5) => 1 + 1/4 + 1/7 + 1/10 + 1/13 = "1.57" NOTE: In PHP the function is called series_sum(). ''' def series_sum(n): total = 0 count = 1 for num in range(1, n + 1): total += 1 / count count += 3 return format(total, '.2f') Test.assert_equals(series_sum(1), "1.00") Test.assert_equals(series_sum(2), "1.25") Test.assert_equals(series_sum(3), "1.39")