def _formatSoughtInformation(fraction, outputMethod): numerator = fraction.getNumerator() denominator = fraction.getDenominator() involvedSymbolList = denominator.getSymbolList() coefficientMap = QuantumCounter.QuantumCounter() coefficientMap.createCoefficientMap(involvedSymbolList) coefficientNumber = 0 numCoefficients = 2**len(involvedSymbolList) while (coefficientNumber < numCoefficients): numeratorCopy = Relation.Relation() numeratorCopy.copyFrom(numerator) numeratorCopy.insertArguments(coefficientMap) currentNumerator = numeratorCopy.evaluate() denominatorCopy = Relation.Relation() denominatorCopy.copyFrom(denominator) denominatorCopy.insertArguments(coefficientMap) currentDenominator = denominatorCopy.evaluate() if (currentNumerator == 0 and currentDenominator == 0): outputMethod("0/0{0}".format(coefficientMap.toString())) elif (currentNumerator == 1 and currentDenominator == 1): outputMethod("1{0}".format(coefficientMap.toString())) elif (currentNumerator == 1 and currentDenominator == 0): outputMethod("1/0{0}".format(coefficientMap.toString())) # else the coefficient is naught (0/1), and does not need to # be printed coefficientMap.increment() coefficientNumber += 1
def make_relation(self, rname, num_tuple, range_A, range_B, v): """ Randomly produce the relation relation """ data = [] integers = [] for i in range(num_tuple): value_A, value_B = random.randint(range_A[0], range_A[1]), random.randint(range_B[0], range_B[1]) integers += [value_A, value_B] data += [value_A] + [value_B] if value_A == v: print(value_A, value_B) relation = Relation(rname=rname, info={'A': 4, 'B': 4}, data=data, num_tuple=num_tuple) ts = [] for i in range(0, len(integers) - 1, 2): ts.append([integers[i], integers[i + 1]]) def take_first(elem): return elem[0] ts.sort(key=take_first) f = open('./tsdata_' + rname.lower() + '.txt', 'w') for tsdata in ts: value_1 = tsdata[0] value_2 = tsdata[1] f.write(str(value_1) + " " + str(value_2) + "\n") print(rname, ts) # save the record in the buffer # num_block: The number of num_block needed to store the relation # tuple_per_block: The number of tuples in one block # write a block to the hard disk in each iteration num_block = num_tuple * relation.byte_per_tuple // self.blk_size tuple_per_block = self.blk_size // relation.byte_per_tuple relation.tuple_per_block = tuple_per_block relation.num_block = num_block for i in range(num_block): attribute_per_block = tuple_per_block * len(relation.attributes) d_start = i * attribute_per_block # fetch a block of data d_end = d_start + attribute_per_block - 1 blk_data = data[d_start:d_end + 1] if self.buffer.is_full(): # apply for a block to store self.buffer.free_buffer() blk = self.buffer.get_new_block() start = blk * self.blk_size * 8 # write data to the block integer-wise for datum in blk_data: datum = '{0:b}'.format(datum) zeros = '0' * (32 - len(datum)) datum = zeros + datum for j in range(32): # write an integer bit-by-bit self.buffer.data[start + j] = datum[j] start += 32 addr = 'relation_' + relation.rname.lower() + '_{index}'.format(index=i) # write the data to the disk self.buffer.write_blk_to_disk(blk, addr) self.relations[rname] = relation
def _isRelationPseudoValid(relationConstructor): isValid = Relation._areAllCharactersLegal(relationConstructor) if (isValid): isValid = Relation._areCombinationsLegal(relationConstructor) if (isValid): isValid = Relation._isNestingLegal(relationConstructor) if (isValid): isValid = Relation._areNumbersLegal(relationConstructor) return isValid
def Naming(self): txt_name = self.entry_name.get().replace(" ", "") txt_attributes = self.entry_attributes.get().replace(" ", "") txt_keys = self.entry_keys.get().replace(" ", "") txt_fds = self.entry_fds.get().replace(" ", "") relationObject = Relation() relationObject.Name = txt_name relationObject.Attributes = txt_attributes.split(",")
def __init__(this, aggregate, soughtDevelopment, quantumCounter, numIterations): this.aggregate = aggregate this.finishedProcessing = False this.productWith0 = Relation.Relation("1") this.productWith1 = Relation.Relation("1") this.quantumCounter = quantumCounter this.remainingIterations = numIterations this.soughtDevelopment = soughtDevelopment
def runCLI(): interface = Interface.Interface(print) userWishesToExit = False print("Running PLE, welcome!") print("Press the return key twice to quit.") while (not userWishesToExit): command = input("\n1. Add a fact" "\n2. Delete a fact" "\n3. Show a list of facts " "\n4. Request a solution\n>>> ") if (command == "1"): # add constructor = input("Enter the fact to add:\n>>> ") constructor = _transpose(constructor) fact = Relation.Relation(constructor) interface.addFact(fact) elif (command == "2"): # delete rawInput = input("Enter the fact number to delete:\n>>> ") try: factNumberToDelete = int(rawInput) - 1 interface.deleteFact(factNumberToDelete) except Exception as error: print("Could not delete fact.") elif (command == "3"): # show list (in transposed form) factList = interface.getFactList() factNumber = 0 numFacts = len(factList) while (factNumber < numFacts): currentFactStr = factList[factNumber].data print("{0} -> {1}".format(factNumber + 1, currentFactStr)) factNumber += 1 if (numFacts == 0): print("There are no facts.") elif (command == "4"): # request solution request = Relation.Relation(input("Enter the request:\n>>> ")) if (request.isValid()): interface.setRequest(request) handler = interface.generateProcessor() handler() response = interface.retrieveResponse() _formatSoughtInformation(response, print) else: print("The request is malformed.") elif (command == ""): userWishesToExit = True else: print("Did not recognise command.")
class Algorithms(object): def __init__(self): self._relation = Relation(ATTRIBUTES, FDS) def _attribute_closure(attrs): """ attrs: AttributSet returns: AttributeSet that contains all derived attributes """ result = copy.deepcopy(attrs) tmp = set() # halt when no more attributes are added while result.attrs() != tmp: tmp = result.attrs() for fd in self._relation.fds(): if fd.lhs().issubset(result.attrs()): # if A->B and A in attrs, add B to attrs result.union(fd.lhs()) return result def is_super_key(self, keyA, keyB): """ keyA: AttributeSet keyB: AttributeSet check whether keyA is a super key of keyB """ return self._attribute_closure(keyB) == keyA
def add_fds(self): str_name = self.name['text'] if str_name != '-': realtion_object = self.relationList[self.relationList.index( Relation(str_name))] fd_gui = FdGui(self.root, self.entry_fds, realtion_object, self.schema) self.root.wait_window(fd_gui.top)
def go(this): while (this.remainingIterations > 0): fullDevelopmentCopy = Relation.Relation() fullDevelopmentCopy.copyFrom(this.aggregate) fullDevelopmentCopy.insertArguments(this.quantumCounter) soughtDevelopmentCopy = Relation.Relation() soughtDevelopmentCopy.copyFrom(this.soughtDevelopment) soughtDevelopmentCopy.insertArguments(this.quantumCounter) coefficient = soughtDevelopmentCopy.evaluate() if (coefficient == 0): this.productWith0 = (this.productWith0 * fullDevelopmentCopy) else: this.productWith1 = (this.productWith1 * fullDevelopmentCopy) this.quantumCounter.increment() this.remainingIterations -= 1 this.finishedProcessing = True
def again(self): again = tkinter.messagebox.askquestion("단칸방 플레이스", "추천한 맛집이 마음에 드시나요?") if again == 'yes': againRe = tkinter.messagebox.askquestion("단칸방 플레이스", "추천한 맛집으로 예약하시겠습니까?") # 추천한 맛집을 예약하는 윈도우 창으로 넘어가게 된다. if againRe == 'yes': Relation() else: self.finish() else: self.finish()
def appTaco(self): again = tkinter.messagebox.askquestion("단칸방 플레이스", "추천한 맛집이 마음에 드시나요?", parent = self.taco) if again == 'yes': againRe = tkinter.messagebox.askquestion("단칸방 플레이스", "추천한 맛집으로 예약하시겠습니까?", parent = self.taco) if againRe == 'yes': Relation() else: self.finish() else: self.againTaco()
def appBeef(self): again = tkinter.messagebox.askquestion("단칸방 플레이스", "추천한 맛집이 마음에 드시나요?", parent = self.beef) if again == 'yes': againRe = tkinter.messagebox.askquestion("단칸방 플레이스", "추천한 맛집으로 예약하시겠습니까?", parent = self.beef) if againRe == 'yes': r = Relation() print(r.strName.get()) else: self.finish() else: self.againBeef()
def getSymbolList(this, relationConstructor): relationConstructor = runCLI._transpose(relationConstructor) isValidToCheckSymbols = _isRelationPseudoValid(relationConstructor) if (isValidToCheckSymbols): relation = Relation.Relation(relationConstructor) symbolList = relation.getSymbolList() this.evalJavaScript("Python.register = {0};".format( str(symbolList))) else: # calling Relation.getSymbolList would throw an error this.evalJavaScript("Python.register = [];")
def again( self ): # 두 번째로 추천한 맛집이 마음에 드는지를 파악하는 메시지 창으로 세 개의 맛집이 agian()를 가리키고 있기 때문에 parent를 사용하지 않았다. again = tkinter.messagebox.askquestion("단칸방 플레이스", "추천한 맛집이 마음에 드시나요?") if again == 'yes': # 추천한 맛집이 마음에 들 경우는 againRe = tkinter.messagebox.askquestion( "단칸방 플레이스", "추천한 맛집으로 예약하시겠습니까?") # 추천한 맛집을 예약하는 창으로 넘어가게 된다. if againRe == 'yes': Relation() else: # 예약하고 싶지 않을 경우에는, 프로그램을 종료한다. self.finish() else: # 추천한 맛집 마음에 들지 않을 때에는, 프로그램을 종료한다. self.finish()
def onClick(self, event): item = self.tree.identify('item', event.x, event.y) if "ROOT" in self.tree.item(item, "value"): #self.tree.item(item, open=True) columns = self.tree.get_children(item)[0] keys = self.tree.get_children(item)[1] str_name = self.tree.item(item, "text") self.current_relation = copy.deepcopy( self.relationList[self.relationList.index(Relation(str_name))]) self.name['text'] = self.current_relation attributes_str = '' for column in self.current_relation.Attributes: attributes_str += column.Name + ", " self.attributes['text'] = attributes_str[:-2] keys_str = '' for key in self.current_relation.Keys: key_str = '' for attribute in key.Attributes: key_str += attribute.Name + '.' keys_str += key_str[:-1] + ", " self.keys['text'] = keys_str[:-2] fds_str = '' for fd in self.current_relation.FDs: fds_str += str(fd) + ', ' fds_str = fds_str[:-2] self.entry_fds.config(state=NORMAL) self.entry_fds.delete(0, END) self.entry_fds.insert(0, fds_str) if len(self.current_relation.Keys) == 0: self.automatic_keys_var.set(1) self.chk_automatic_keys.configure(state="disabled") else: self.chk_automatic_keys.configure(state="normal") self.automatic_keys_var.set(0) ''' #self.entry_fds.delete(0.0, END) ''' self.compute_normal_form.state(["!disabled"]) self.btn_export_xml.state(["!disabled"]) self.specify_fds.state(["!disabled"])
def request(this, requestStr): requestRelation = Relation.Relation(requestStr) if (requestRelation.isValid()): GInterface.setRequest(requestRelation) handler = GInterface.generateProcessor() handler() response = GInterface.retrieveResponse() constituentList = [] runCLI._formatSoughtInformation(response, constituentList.append) # the constituentList array can be abbreviated at this # point by the general rule [0][1] + [0](1 - [1]) = [0], # but it is not a feature required for full # functionality # transfer constituents to JavaScript front-end constituentNumber = 0 numConstituents = len(constituentList) while (constituentNumber < numConstituents): currentConstituent = constituentList[constituentNumber] isConstituentInfinite = False if (len(currentConstituent) > 1): isConstituentInfinite = (currentConstituent[0] == '1' and currentConstituent[1] == '/') # the truth of this implies that the constituent # has a coefficient 1/0 if (isConstituentInfinite): this.evalJavaScript("Python.cacheInf[Python.cac" "heInf.length] = \"{0}\";".format( currentConstituent)) else: this.evalJavaScript( "Python.cache[Python.cache." "length] = \"{0}\";".format(currentConstituent)) constituentNumber += 1 this.evalJavaScript("Python.onProcessorFinish();") # empty GInterface numFacts = len(GInterface.getFactList()) while (numFacts != 0): GInterface.deleteFact(0) numFacts = len(GInterface.getFactList()) else: this.processError("Failed to set request: request is ma" "lformed.")
def getFactAggregation(this): optimisedFactList = []; for fact in this.factList: optimisedFact = Relation.Relation(); optimisedFact.copyFrom(fact); optimisedFact.optimise(); optimisedFactList.append(optimisedFact); UNITY = Relation.Relation('1'); aggregate = Relation.Relation('0'); factNumber = 0; numFacts = len(optimisedFactList); while (factNumber < numFacts): priorFactNumber = 0; productOfPriorFacts = Relation.Relation('1'); while (priorFactNumber < factNumber): productOfPriorFacts = productOfPriorFacts * (UNITY - optimisedFactList[priorFactNumber]); priorFactNumber += 1; currentFact = optimisedFactList[factNumber]; aggregate += currentFact * productOfPriorFacts; factNumber += 1; aggregate.optimise(); return aggregate;
def appSteak( self ): # 스테이크 맛집이 마음에 드는지를 파악하는 메시지 창으로, parent를 주어 메시지 창이 열리는 곳을 지정해 주었다. again = tkinter.messagebox.askquestion("단칸방 플레이스", "추천한 맛집이 마음에 드시나요?", parent=self.steak) if again == 'yes': # 추천한 맛집이 마음에 들 경우는 againRe = tkinter.messagebox.askquestion( "단칸방 플레이스", "추천한 맛집으로 예약하시겠습니까?", parent=self.steak) # 추천한 맛집을 예약하는 창으로 넘어가게 된다. if againRe == 'yes': r = Relation() print(r.strName.get()) else: # 예약하고 싶지 않을 경우에는, 프로그램을 종료한다. self.finish() else: # 추천한 맛집 마음에 들지 않을 때에는, 다시 한 번 더 추천해 준다. self.againSteak()
def xmlProcessSchemes(self): relationList = [] for relation in self.root: relObj=Relation.Relation() relObj.Name = self.getRelationName(relation) for columns in self.getColumns(relation): attribute_object = Attribute(columns) relObj.Attributes.append(attribute_object) relObj.Keys = self.getKyes(relation) relObj.FDs = self.getFunctionalDependencies(relation) #attribute_object = Attribute() #attribute_object.Name = columns['name'] relationList.append(relObj) return relationList
def isValid(this, relationConstructor): relationConstructor = runCLI._transpose(relationConstructor) relation = Relation.Relation(relationConstructor) isValidToCheckSymbols = _isRelationPseudoValid(relationConstructor) if (isValidToCheckSymbols): symbolList = relation.getSymbolList() if (len(symbolList) > 0 and max(symbolList) > LARGEST_SYMBOL): this.evalJavaScript("Python.register = false;") elif (len(symbolList) > MAX_RELATION_SYMBOLS_FOR_TESTING): this.evalJavaScript("Python.register = \"maybe\";") else: isRelationValid = relation.isValid() # this test completes the suite internal to # Relation.isValid() if (isRelationValid): this.evalJavaScript("Python.register = true;") else: this.evalJavaScript("Python.register = false;") else: this.evalJavaScript("Python.register = false;")
def outPutXls(self, suggests): tables = [] datas = [] for _suggest in suggests: datas.append([_suggest['title']]) for _item in _suggest['array']: datas.append([ _item['date'], _item['code'], NameList.getName(_item['code']), _item['wir'], _item['price'], _item['operatePrice'], str(_item['percent']) + '%' ]) if _suggest['relation']: funds = RLN.getRelation(_item['code']) for _fund in funds: datas.append(['', _fund['code'], _fund['name']]) datas.append(['']) tables.append({'name': 'Stock', 'data': datas}) XlsHelper('result.xls').create(tables)
def __init__(self): self._relation = Relation(ATTRIBUTES, FDS)
def testProcessor(): # test all methods: __init__, go, hasFinished, getProductWith0 and # getProductWith1. # group 1 aggregate1 = Relation.Relation("[0](1 - [1]) + [1](1 - [0])") soughtDevelopment1 = Relation.Relation("[0]") quantumCounter1 = QuantumCounter.QuantumCounter() quantumCounter1.createCoefficientMap(soughtDevelopment1.getSymbolList()) processor1 = Processor.Processor(aggregate1, soughtDevelopment1, quantumCounter1, 2) processor1.go() assert (processor1.getProductWith0() == Relation.Relation("[1]")) assert (processor1.getProductWith1() == Relation.Relation("1-[1]")) # group 2 aggregate2_3 = Relation.Relation("[0](1 - [1])[4] + (1 - [4])[5][1]" "(1 - [0])") soughtDevelopment2_3 = Relation.Relation("[0][1](1 - [5])") quantumCounter2 = QuantumCounter.QuantumCounter() quantumCounter2.createCoefficientMap(soughtDevelopment2_3.getSymbolList()) processor2 = Processor.Processor(aggregate2_3, soughtDevelopment2_3, quantumCounter2, 5) assert (processor2.hasFinished() == False) processor2.go() assert (processor2.hasFinished() == True) quantumCounter3 = QuantumCounter.QuantumCounter() quantumCounter3.createCoefficientMap(soughtDevelopment2_3.getSymbolList()) quantumCounter3.add(5) processor3 = Processor.Processor(aggregate2_3, soughtDevelopment2_3, quantumCounter3, 3) assert (processor3.hasFinished() == False) processor3.go() assert (processor3.hasFinished() == True) productWith0For2_3 = (processor2.getProductWith0() * processor3.getProductWith0()) assert (productWith0For2_3 == Relation.Relation("0")) productWith1For2_3 = (processor2.getProductWith1() * processor3.getProductWith1()) assert (productWith1For2_3 == Relation.Relation("0")) # group 3 aggregate4_5 = Relation.Relation("[2](1 - [3]) + (1 - [2])([3][4] +" "(1 - [3])(1 - [4]))") soughtDevelopment4_5 = Relation.Relation("[2](1 - [3])[5] + (1 - [5" "])[2](1 - [3]) + [3](1 - [2])") quantumCounter4 = QuantumCounter.QuantumCounter() quantumCounter4.createCoefficientMap(soughtDevelopment4_5.getSymbolList()) processor4 = Processor.Processor(aggregate4_5, soughtDevelopment4_5, quantumCounter4, 4) processor4.go() quantumCounter5 = QuantumCounter.QuantumCounter() quantumCounter5.createCoefficientMap(soughtDevelopment4_5.getSymbolList()) quantumCounter5.add(4) processor5 = Processor.Processor(aggregate4_5, soughtDevelopment4_5, quantumCounter5, 4) processor5.go() productWith0For4_5 = (processor4.getProductWith0() * processor5.getProductWith0()) assert (productWith0For4_5 == Relation.Relation("0")) productWith1For4_5 = (processor4.getProductWith1() * processor5.getProductWith1()) assert (productWith1For4_5 == Relation.Relation("[4]"))
from Geothon import * import Relation as R triangle('A', 'B', 'C') segment('A', 'B').extendTo(point('D'), segment('A', 'C').getLength()) segment('C', 'B').extendTo(point('E'), segment('A', 'C').getLength()) segment('B', 'A').extendTo(point('F'), segment('C', 'B').getLength()) segment('C', 'A').extendTo(point('G'), segment('C', 'B').getLength()) segment('B', 'C').extendTo(point('H'), segment('A', 'B').getLength()) segment('A', 'C').extendTo(point('I'), segment('A', 'B').getLength()) circle('O').fromThreePoints(point('D'), point('E'), point('F')) assert (segment('B', 'D').getLength() == segment('B', 'E').getLength()) assert (segment('A', 'F').getLength() == segment('A', 'G').getLength()) assert (segment('C', 'H').getLength() == segment('C', 'I').getLength()) assert (R.concyclic(point('D'), point('E'), point('F'), point('G'), point('H'), point('I'))) show()
def testInterface(): # test constructor __init__, getFactList, addFact, and deleteFact errorList = [] interface1 = Interface.Interface(errorList.append) assert (interface1.getFactList() == []) relation1 = Relation.Relation("1") interface1.addFact(relation1) assert (interface1.getFactList() == [relation1]) relation2 = Relation.Relation("0") interface1.addFact(relation2) assert (interface1.getFactList() == [relation1, relation2]) relation3 = Relation.Relation("[0]") interface1.addFact(relation3) assert (interface1.getFactList() == [relation1, relation2, relation3]) assert (len(errorList) == 0) interface1.deleteFact(-1) assert (interface1.getFactList() == [relation1, relation2, relation3]) assert (len(errorList) == 1) interface1.deleteFact(0) assert (interface1.getFactList() == [relation2, relation3]) interface1.deleteFact(1) assert (interface1.getFactList() == [relation2]) interface1.deleteFact(1) assert (interface1.getFactList() == [relation2]) assert (len(errorList) == 2) relation4 = Relation.Relation("2") interface1.addFact(relation4) assert (interface1.getFactList() == [relation2]) assert (len(errorList) == 3) # testing setRequest, and getRequest interface1.setRequest(relation4) assert (len(errorList) == 4) request = interface1.getRequest() assert (request == None) assert (len(errorList) == 5) relation5 = Relation.Relation("[1]") interface1.setRequest(relation5) request = interface1.getRequest() assert (request == relation5) assert (len(errorList) == 5) errorList.clear() # testing generateProcessor, and retrieveSoughtInformation interface2 = Interface.Interface(errorList.append) interface2.retrieveResponse() assert (len(errorList) == 1) interface2.generateProcessor() assert (len(errorList) == 2) interface2.addFact(Relation.Relation("1")) interface2.setRequest(Relation.Relation("1")) interface2.generateProcessor() assert (len(errorList) == 2) interface2.generateProcessor() assert (len(errorList) == 2) errorList.clear() interface3 = Interface.Interface(errorList.append) handler = interface3.generateProcessor() assert (handler == None) assert (len(errorList) == 1) interface3.addFact(Relation.Relation("[1]")) interface3.setRequest(Relation.Relation("[1]")) handler = interface3.generateProcessor() assert (len(errorList) == 1) assert (handler != None) interface3.retrieveResponse() assert (len(errorList) == 2) handler() interface3.retrieveResponse() quaesitum = interface3.retrieveResponse() assert (len(errorList) == 2) assert (quaesitum.getNumerator().evaluate() / quaesitum.getDenominator().evaluate() == 0) errorList.clear() interface3 = Interface.Interface(errorList.append) interface3.addFact(Relation.Relation("[1](1 - [0])")) interface3.addFact(Relation.Relation("[0](1 - [1])")) interface3.setRequest(Relation.Relation("[1]")) quaesitum = interface3.retrieveResponse() assert (len(errorList) == 1) handler = interface3.generateProcessor() quaesitum = interface3.retrieveResponse() assert (quaesitum == None) assert (len(errorList) == 2) handler() quaesitum = interface3.retrieveResponse() assert (quaesitum != None) assert (len(errorList) == 2)
def addFact(this, relationConstructor): relationConstructor = runCLI._transpose(relationConstructor) factRelation = Relation.Relation(relationConstructor) GInterface.addFact(factRelation)
def testRelation(): # test helper function _areAllCharactersLegal assert (Relation._areAllCharactersLegal("") == True) assert (Relation._areAllCharactersLegal(" ") == True) assert (Relation._areAllCharactersLegal("1 0 + -") == True) assert (Relation._areAllCharactersLegal("012345678911 [") == True) assert (Relation._areAllCharactersLegal("[]1( )") == True) assert (Relation._areAllCharactersLegal(",") == False) assert (Relation._areAllCharactersLegal(". ") == False) assert (Relation._areAllCharactersLegal("13 16 22 4 19 a") == False) assert (Relation._areAllCharactersLegal("`") == False) assert (Relation._areAllCharactersLegal("*") == False) assert (Relation._areAllCharactersLegal("/ 9001") == False) # test helper function _areCombinationsLegal assert (Relation._areCombinationsLegal("") == False) assert (Relation._areCombinationsLegal(" + ") == False) assert (Relation._areCombinationsLegal(")-") == False) assert (Relation._areCombinationsLegal("(12) -") == False) assert (Relation._areCombinationsLegal("(144)- ") == False) assert (Relation._areCombinationsLegal("(1) (9)") == False) assert (Relation._areCombinationsLegal("(4) 2") == False) assert (Relation._areCombinationsLegal("2 [1]") == False) assert (Relation._areCombinationsLegal("(1]+ 3") == False) assert (Relation._areCombinationsLegal("2 [1]") == False) assert (Relation._areCombinationsLegal("[") == False) assert (Relation._areCombinationsLegal("]") == False) assert (Relation._areCombinationsLegal("[1)") == False) assert (Relation._areCombinationsLegal("(1 2)") == False) assert (Relation._areCombinationsLegal("[3 1]") == False) assert (Relation._areCombinationsLegal("( )(12)") == False) assert (Relation._areCombinationsLegal("()") == False) assert (Relation._areCombinationsLegal("[12]") == True) assert (Relation._areCombinationsLegal("[123456789](0)") == True) assert (Relation._areCombinationsLegal("1 + 1") == True) assert (Relation._areCombinationsLegal("2+n") == True) assert (Relation._areCombinationsLegal("n+(5)") == True) assert (Relation._areCombinationsLegal("[5]+(((n)))") == True) assert (Relation._areCombinationsLegal("((1+((1)(( n)))))") == True) # test helper function _areNumbersLegal assert (Relation._areNumbersLegal("") == True) assert (Relation._areNumbersLegal("tortilla") == True) assert (Relation._areNumbersLegal("0 1-- 2, three 1007") == True) assert (Relation._areNumbersLegal("007") == False) assert (Relation._areNumbersLegal("0*0*1") == True) assert (Relation._areNumbersLegal("00 12") == False) assert (Relation._areNumbersLegal("100000 600001") == True) # test helper function _isNestingLegal assert (Relation._isNestingLegal("") == True) assert (Relation._isNestingLegal("()") == True) assert (Relation._isNestingLegal(" ") == True) assert (Relation._isNestingLegal(" ( ( ) ) ") == True) assert (Relation._isNestingLegal("(a(x)+) (]") == True) assert (Relation._isNestingLegal("([[1()]()[2]])") == True) assert (Relation._isNestingLegal("(()()") == False) assert (Relation._isNestingLegal(")( )( ") == False) assert (Relation._isNestingLegal(")(())(") == False) assert (Relation._isNestingLegal("(a)v)") == False) # test helper function _recursivelyReplace assert (Relation._recursivelyReplace("ab", "a", "b") == "bb") assert (Relation._recursivelyReplace("ab", "ab", "ab") == "ab") assert (Relation._recursivelyReplace("23232323", "2323", "23") == "23") assert (Relation._recursivelyReplace("110111101 10011111111", "11", "1") == "10101 1001") assert (Relation._recursivelyReplace("", "a", "cd") == "") assert (Relation._recursivelyReplace("", "", "l") == "") assert (Relation._recursivelyReplace("", "n", "") == "") assert (Relation._recursivelyReplace("x", "", "") == "x") # test test-helper function, _areArraysEqual assert (_areArraysEqual([0], [1]) == False) assert (_areArraysEqual([1, 2], [1]) == False) assert (_areArraysEqual([1, 2, 3, 4], [1, 3, 2, 4]) == True) assert (_areArraysEqual([0, 0], [1]) == False) assert (_areArraysEqual([0, 199], [199, 0]) == True) assert (_areArraysEqual([], []) == True) assert (_areArraysEqual([12], []) == False) assert (_areArraysEqual([12, 13, 13], [13, 12, 12]) == False) assert (_areArraysEqual([12, 13, 13], [13, 12, 12]) == False) assert (_areArraysEqual([1, 2, 3, 55, 102, 1042, 4, 16], [1, 2, 3, 55, 1042, 102, 4, 16]) == True) assert (_areArraysEqual([1, 2, 3, 55, 102, 1043, 4, 16], [1, 2, 3, 55, 1042, 102, 4, 16]) == False) # test getSymbolList relation1 = Relation.Relation("[1] + [0](1 - [1])") symbolsInRelation1 = relation1.getSymbolList() assert (_areArraysEqual(symbolsInRelation1, [0, 1])) relation2 = Relation.Relation("1") symbolsInRelation2 = relation2.getSymbolList() assert (_areArraysEqual(symbolsInRelation2, [])) relation3 = Relation.Relation("0 + [1]") symbolsInRelation3 = relation3.getSymbolList() assert (_areArraysEqual(symbolsInRelation3, [1])) relation4 = Relation.Relation("0 + [5](1 - [2])(1 - [4][7])") symbolsInRelation4 = relation4.getSymbolList() assert (_areArraysEqual(symbolsInRelation4, [2, 4, 5, 7])) relation5 = Relation.Relation("(1 - [3])([12] + [15](1 - [12]))") symbolsInRelation5 = relation5.getSymbolList() assert (_areArraysEqual(symbolsInRelation5, [3, 12, 15])) relation6 = Relation.Relation("[1][2][100] + [9001][1](1 - [2])(1 -" " [100])") symbolsInRelation6 = relation6.getSymbolList() assert (_areArraysEqual(symbolsInRelation6, [1, 2, 100, 9001])) # test evaluate relation7 = Relation.Relation("1") assert (relation7.evaluate() == 1) relation8 = Relation.Relation("0") assert (relation8.evaluate() == 0) relation9 = Relation.Relation("(0)(1)") assert (relation9.evaluate() == 0) relation10 = Relation.Relation("(0)(1) + 1 + (0)(1 - (1))") assert (relation10.evaluate() == 1) relation11 = Relation.Relation("(1)(1)(0) + (1)(1 - (1))(1 - ((0)(1" "))) + (1 - (1))(1 - (1))") assert (relation11.evaluate() == 0) relation12 = Relation.Relation("(0)(1 - (0)) + (0)(1 - (1)) + (1)(" "1 - (0))(1 - (1 - (1)))") assert (relation12.evaluate() == 1) # test insertArguments, "==" operator __eq__, copyFrom, and the "!=" # comparator __ne__ quantumCounter13 = QuantumCounter.QuantumCounter([1, 0]) relation13 = Relation.Relation("[1]") relation13.insertArguments(quantumCounter13) assert (relation13.evaluate() == 0) quantumCounter14 = QuantumCounter.QuantumCounter([0, 0]) relation14 = Relation.Relation("[0] + [0](1 - [1])") relation14.insertArguments(quantumCounter14) assert (relation14.evaluate() == 0) quantumCounter15 = QuantumCounter.QuantumCounter([1]) relation15 = Relation.Relation("[0](1 - [1]) + [1](1 - [0])") relation15.insertArguments(quantumCounter15) relation16 = Relation.Relation("(1 - [1])") assert ((relation15 == relation16) == True) assert ((relation15 != relation16) == False) relation16Copy = Relation.Relation() relation16Copy.copyFrom(relation16) assert (relation16 == relation16Copy) relation17 = Relation.Relation("[4]") relation18 = Relation.Relation("0") assert ((relation17 == relation18) == False) assert ((relation17 != relation18) == True) quantumCounter17 = QuantumCounter.QuantumCounter([1, 0, -1, 0, 0]) relation17.insertArguments(quantumCounter17) assert ((relation17 == relation18) == True) assert ((relation17 != relation18) == False) assert ((relation17 == relation17) == True) assert ((relation17 != relation17) == False) assert ((relation18 == relation18) == True) assert ((relation18 != relation18) == False) relation17Copy = Relation.Relation() relation17Copy.copyFrom(relation17) assert (relation17 == relation17Copy) relation19 = Relation.Relation("1") relation20 = Relation.Relation( "[2][1][111] + (1 - [2])[111](1 - [1" "]) + (0)(1 - [6]) + [1][2](1 - [111]) + (1 - [1])(1 - [111]) +" " [1][111](1 - [2]) + [2][111](1 - [1]) + 0 + [1](1 - [111])(1 " "- [2])") relation21 = Relation.Relation( "[2][1][111] + (1 - [2])[111](1 - [1" "]) + (0)(1 - [6]) + [1][2](1 - [111]) + (1 - [1])(1 - [111]) +" " [1][111](1 - [2]) + [2][111](1 - [1]) + 0 + [1](1 - [111])(1 " "- [1])") assert ((relation19 == relation20) == True) assert ((relation19 != relation20) == False) assert ((relation20 == relation21) == False) assert ((relation20 != relation21) == True) relation22 = Relation.Relation("[4][0][1] + (1 - [0])[1](1 - [4])") quantumCounter22 = QuantumCounter.QuantumCounter( ['v', 'v', 'v', 'v', 1, 'v', 1]) relation23 = Relation.Relation("(1)[0][1] + (1 - [0])[1](1 - (1))") assert ((relation22 == relation23) == False) relation22.insertArguments(quantumCounter22) assert (relation22 == relation23) relation24 = Relation.Relation() relation24.copyFrom(relation22) assert (relation23 == relation24) relation25 = Relation.Relation("0 + [1](1 - [2])(1 - [0][3])") relation26 = Relation.Relation() relation26.copyFrom(relation25) relation27 = Relation.Relation() relation27.copyFrom(relation26) assert (relation25 == relation26) assert (relation25 == relation27) assert ((relation26 != relation27) == False) quantumCounter25 = QuantumCounter.QuantumCounter([]) relation25.insertArguments(quantumCounter25) assert (relation25 == relation26) quantumCounter26 = QuantumCounter.QuantumCounter(["1"]) relation26.insertArguments(quantumCounter26) assert (relation25 == relation26) assert (relation26 == relation27) quantumCounter27 = QuantumCounter.QuantumCounter([0, 1, 0, 1]) relation27.insertArguments(quantumCounter27) assert (relation27.evaluate() == 1) # test the "*" operator __mul__ relation28 = Relation.Relation("[0]") relation29 = Relation.Relation("[0]") relation30 = relation28 * relation29 assert (relation28 * relation29 == relation28) assert (relation28 * relation29 == relation29) relation31 = Relation.Relation("[1]") relation32 = relation31 * relation30 relation33 = relation30 * relation31 relation34 = Relation.Relation("[0][1]") assert (relation32 == relation33) assert (relation34 == relation33) assert (relation34 == relation32) assert (relation34 != relation28) relation35 = Relation.Relation("[0] + [1](1 - [0])") relation36 = Relation.Relation("0") relation37 = Relation.Relation("1") relation38 = Relation.Relation("(0) + ((([1])))") relation39 = Relation.Relation("([1])") assert (relation35 * relation36 == relation36) assert (relation35 != relation36) assert (relation35 * relation35 == relation35) assert (relation35 * relation37 == relation35) assert (relation37 * relation35 == relation35) assert (relation36 * relation37 == relation36) assert (relation36 * relation38 == relation36) assert (relation37 * relation38 == relation38) assert (relation38 * relation38 == relation38) assert (relation35 * relation38 == relation39) assert (relation38 * relation35 == relation39) assert (relation38 * relation39 == relation39) # test eliminateSymbol relation39 = Relation.Relation("[0]") relation39.eliminateSymbol(0) assert (relation39.evaluate() == 0) relation40 = Relation.Relation("[0](1 - [1]) + (1 - [0])(1 - [1])") relation40.eliminateSymbol(1) relation41 = Relation.Relation("0") assert (relation40 == relation41) relation42 = Relation.Relation("[9](1 - [1]) + [9][1](1 - [2][3])") relation42.eliminateSymbol(1) relation43 = Relation.Relation("[9](1 - [2][3])") assert (relation42 == relation43) relation44 = Relation.Relation("0") relation44.eliminateSymbol(5) assert (relation44.evaluate() == 0) relation45 = Relation.Relation("[10][2][3] + [10](1 - [2])(1 - [3])" " + (1 - [10])(1 - [2])") relation46 = Relation.Relation("(1 - [2])(1 - [3])") relation45.eliminateSymbol(10) assert (relation45 == relation46) # test the binary "+" operator __add__ relation46 = Relation.Relation("0") relation47 = Relation.Relation("1") relation48 = Relation.Relation("[2]") relation49 = Relation.Relation("(1 - [2])") assert (relation46 + relation46 == relation46) assert (relation46 + relation47 == relation47) assert (relation48 + relation49 + relation46 == relation47) relation50 = Relation.Relation("[12][11]") relation51 = Relation.Relation("(1 - [12])[11][4]") relation52 = Relation.Relation("(1 - [12])[11](1 - [4])") relation53 = Relation.Relation("(1 - [12])[11]") relation54 = Relation.Relation("[11]") assert (relation50 + relation51 + relation52 == relation54) assert (relation52 + relation50 + relation51 == relation54) assert (relation53 == relation51 + relation52) assert (relation54 == relation50 + relation53) relation55 = Relation.Relation("[102](1 - [0])") relation56 = Relation.Relation("[0](1 - [1][102])") relation57 = Relation.Relation("[102](1 - [0])(1 - [1]) + [102](1 -" " [0])[1] + [0](1 - [1][102])") relation58 = Relation.Relation("[102](1 - [0])(1 - [4]) + [102](1 -" " [0])[1] + [0](1 - [1][102])") assert (relation55 + relation56 == relation57) assert (relation55 + relation56 != relation58) # test binary "-" operator __sub__ relation57 = Relation.Relation("[102]") relation58 = Relation.Relation("(1 - [102])") relation59 = Relation.Relation("0") relation60 = Relation.Relation("1") assert (relation57 - relation57 == relation59) assert (relation60 - relation57 == relation58) assert (relation60 - relation58 == relation57) assert (relation60 - (relation60 - relation58) == relation58) assert (relation60 - (relation60 - relation57) == relation57) relation61 = Relation.Relation("[3](1 - [4]) + (1 - [3])[4]") relation62 = Relation.Relation("[12]([3][4] + (1 - [3])(1 - [4])) +" " (1 - [12])([3][4] + (1 - [3])(1 - [4]))") relation63 = Relation.Relation("1") assert (relation63 - relation61 == relation62) assert (relation63 - relation62 == relation61) relation64 = Relation.Relation("[0][1](1 - [2])[4] + (1 - [4])") relation65 = Relation.Relation("(1 - [4])") relation66 = Relation.Relation("[0][1](1 - [2])[4]") assert (relation64 - relation65 == relation66) assert (relation64 - relation66 == relation65) # test isValid, optimise relation67 = Relation.Relation("0") relation67Copy = Relation.Relation() relation67Copy.copyFrom(relation67) relation67Copy.optimise() assert (relation67.isValid() == True) assert (relation67 == relation67Copy) relation68 = Relation.Relation("1") relation68Copy = Relation.Relation() relation68Copy.copyFrom(relation68) relation68Copy.optimise() assert (relation68.isValid() == True) assert (relation68 == relation68Copy) relation69 = Relation.Relation("(1) + 0") relation69Copy = Relation.Relation() relation69Copy.copyFrom(relation69) relation69Copy.optimise() assert (relation69.isValid() == True) assert (relation69 == relation69Copy) relation70 = Relation.Relation("(1)(1)") relation70Copy = Relation.Relation() relation70Copy.copyFrom(relation70) relation70Copy.optimise() assert (relation70.isValid() == True) assert (relation70 == relation70Copy) relation71 = Relation.Relation("(((1)))(0)") relation71Copy = Relation.Relation() relation71Copy.copyFrom(relation71) relation71Copy.optimise() assert (relation71.isValid() == True) assert (relation71 == relation71Copy) relation72 = Relation.Relation("(((1)))(0) - (0)") relation72Copy = Relation.Relation() relation72Copy.copyFrom(relation72) relation72Copy.optimise() assert (relation72.isValid() == True) assert (relation72 == relation72Copy) relation73 = Relation.Relation("[0]") relation73Copy = Relation.Relation() relation73Copy.copyFrom(relation73) relation73Copy.optimise() assert (relation73.isValid() == True) assert (relation73 == relation73Copy) relation74 = Relation.Relation("[10]") relation74Copy = Relation.Relation() relation74Copy.copyFrom(relation74) relation74Copy.optimise() assert (relation74.isValid() == True) assert (relation74 == relation74Copy) relation75 = Relation.Relation("[104]") relation75Copy = Relation.Relation() relation75Copy.copyFrom(relation75) relation75Copy.optimise() assert (relation75.isValid() == True) assert (relation75 == relation75Copy) relation76 = Relation.Relation("1 - [99]") relation76Copy = Relation.Relation() relation76Copy.copyFrom(relation76) relation76Copy.optimise() assert (relation76.isValid() == True) assert (relation76 == relation76Copy) relation77 = Relation.Relation("1 - [13][12]") relation77Copy = Relation.Relation() relation77Copy.copyFrom(relation77) relation77Copy.optimise() assert (relation77.isValid() == True) assert (relation77 == relation77Copy) relation78 = Relation.Relation("(1 - [13][1])[13]") relation78Copy = Relation.Relation() relation78Copy.copyFrom(relation78) relation78Copy.optimise() assert (relation78.isValid() == True) assert (relation78 == relation78Copy) relation79 = Relation.Relation("[0] + (1 - [0])[1]") relation79Copy = Relation.Relation() relation79Copy.copyFrom(relation79) relation79Copy.optimise() assert (relation79.isValid() == True) assert (relation79 == relation79Copy) relation80 = Relation.Relation("[0](1 - [2]) + (1 - [0])[1](1 - [2]" " + [2])") relation80Copy = Relation.Relation() relation80Copy.copyFrom(relation80) relation80Copy.optimise() assert (relation80.isValid() == True) assert (relation80 == relation80Copy) relation81 = Relation.Relation(" 0 ") relation81Copy = Relation.Relation() relation81Copy.copyFrom(relation81) relation81Copy.optimise() assert (relation81.isValid() == True) assert (relation81 == relation81Copy) relation82 = Relation.Relation(" ( 1 )+ 0") relation82Copy = Relation.Relation() relation82Copy.copyFrom(relation82) relation82Copy.optimise() assert (relation82.isValid() == True) assert (relation82 == relation82Copy) relation83 = Relation.Relation("1 + (0)(1)") relation83Copy = Relation.Relation() relation83Copy.copyFrom(relation83) relation83Copy.optimise() assert (relation83.isValid() == True) assert (relation83 == relation83Copy) relation84 = Relation.Relation( " " " " " [0] " " " " " " + (1 - [0]) " " ") relation84Copy = Relation.Relation() relation84Copy.copyFrom(relation84) relation84Copy.optimise() assert (relation84.isValid() == True) assert (relation84 == relation84Copy) relation85 = Relation.Relation("(( ([0])))([0])+(1-" "[0])") relation85Copy = Relation.Relation() relation85Copy.copyFrom(relation85) relation85Copy.optimise() assert (relation85.isValid() == True) assert (relation85 == relation85Copy) relation86 = Relation.Relation("[0][2] - 0 - ([2][0][1] - [1])") relation86Copy = Relation.Relation() relation86Copy.copyFrom(relation86) relation86Copy.optimise() assert (relation86.isValid() == True) assert (relation86 == relation86Copy) relation87 = Relation.Relation("-1") assert (relation87.isValid() == False) relation88 = Relation.Relation("-2") assert (relation88.isValid() == False) relation89 = Relation.Relation("2") assert (relation89.isValid() == False) relation90 = Relation.Relation("[0] + [1]") assert (relation90.isValid() == False) relation91 = Relation.Relation("[0] + [0]") assert (relation91.isValid() == False) relation92 = Relation.Relation("") assert (relation92.isValid() == False) relation93 = Relation.Relation("0.0") assert (relation93.isValid() == False) relation94 = Relation.Relation("all men are mortals") assert (relation94.isValid() == False) relation95 = Relation.Relation("((1)") assert (relation95.isValid() == False) relation96 = Relation.Relation("2(1)") assert (relation96.isValid() == False) relation97 = Relation.Relation("[ 0]") assert (relation97.isValid() == False) relation98 = Relation.Relation("[10 2]") assert (relation98.isValid() == False) relation99 = Relation.Relation("[2 ]") assert (relation99.isValid() == False) relation100 = Relation.Relation("[2+1]") assert (relation100.isValid() == False) relation101 = Relation.Relation("[12] + ()(1 - [12])") assert (relation101.isValid() == False) relation102 = Relation.Relation("[12] + (1(1) 1)") assert (relation102.isValid() == False) relation103 = Relation.Relation("[])") assert (relation103.isValid() == False) relation104 = Relation.Relation("[-1])") assert (relation104.isValid() == False) relation105 = Relation.Relation("[00]") assert (relation105.isValid() == False) relation106 = Relation.Relation("00") assert (relation106.isValid() == False) relation107 = Relation.Relation("[01]") assert (relation107.isValid() == False) relation108 = Relation.Relation("+") assert (relation108.isValid() == False) relation109 = Relation.Relation("-") assert (relation109.isValid() == False) relation110 = Relation.Relation("[12]a") assert (relation110.isValid() == False) relation111 = Relation.Relation("[12] + b") assert (relation111.isValid() == False) relation112 = Relation.Relation("[12] + ") assert (relation112.isValid() == False) relation113 = Relation.Relation("1 +*") assert (relation113.isValid() == False) relation114 = Relation.Relation("(1)*(1)") assert (relation114.isValid() == False) relation115 = Relation.Relation("[") assert (relation115.isValid() == False) relation116 = Relation.Relation(")") assert (relation116.isValid() == False) relation117 = Relation.Relation("([1)]") assert (relation117.isValid() == False) relation118 = Relation.Relation("1 - [13][3] )") assert (relation118.isValid() == False) relation119 = Relation.Relation("(1) (1)") assert (relation119.isValid() == False) relation120 = Relation.Relation("9 / 9") assert (relation120.isValid() == False) relation121 = Relation.Relation("1/1") assert (relation121.isValid() == False) relation122 = Relation.Relation("[1] + (1 - [1.])") assert (relation122.isValid() == False) relation123 = Relation.Relation("[1] + l (1 - [1])") assert (relation123.isValid() == False) relation124 = Relation.Relation("{1 + 0}") assert (relation124.isValid() == False) relation125 = Relation.Relation("shredded lettuce") assert (relation125.isValid() == False) relation126 = Relation.Relation("\"\"") assert (relation126.isValid() == False) relation127 = Relation.Relation("assert(False)") assert (relation127.isValid() == False) relation128 = Relation.Relation("eval(assert(False))") assert (relation128.isValid() == False) relation129 = Relation.Relation("1 + 0^1") assert (relation129.isValid() == False) relation130 = Relation.Relation("1 -- 0") assert (relation130.isValid() == False) relation131 = Relation.Relation("0 +- 0") assert (relation131.isValid() == False) relation132 = Relation.Relation("0 +- 1") assert (relation132.isValid() == False) relation133 = Relation.Relation("(((((((1))))) )") assert (relation133.isValid() == False) relation134 = Relation.Relation("0\t") assert (relation134.isValid() == False) relation135 = Relation.Relation("0 0") assert (relation135.isValid() == False) relation136 = Relation.Relation("0 0") assert (relation136.isValid() == False) relation137 = Relation.Relation("1[0]") assert (relation137.isValid() == False) relation138 = Relation.Relation("-[0]") assert (relation138.isValid() == False) relation139 = Relation.Relation("[0][1] + [0](1 - [1]) + (1-[0])[1] " "+ (1-[0])(1 - [1]) + [2](1 - [1])") assert (relation139.isValid() == False) relation140 = Relation.Relation("((([0]) + (1 - [0])) + 1(0))") assert (relation140.isValid() == False) relation141 = Relation.Relation(")1(") assert (relation141.isValid() == False) relation142 = Relation.Relation("]4[") assert (relation142.isValid() == False) relation143 = Relation.Relation("[6] -(") assert (relation143.isValid() == False) relation144 = Relation.Relation("1(1 - [1])") assert (relation144.isValid() == False) relation145 = Relation.Relation("(1 - [1])1") assert (relation145.isValid() == False)
class ManualGui: def __init__(self, master): frame = Frame(master, borderwidth=5) frame.grid(column=0, row=0, columnspan=2, rowspan=5) self._frame = frame labelframe = LabelFrame(frame, text="Relation Information: ") labelframe.grid(row=2, column=2, columnspan=3, ipadx=100, padx=20, pady=5, sticky='wn') frm_name = Frame(labelframe) frm_name.pack(side='left', anchor='nw', padx=25, pady=10) lbl_name = Label(frm_name, text="Name:") lbl_name.pack(anchor='w', pady=3) lbl_attributes = Label(frm_name, text="Attributes:") lbl_attributes.pack(anchor='w', pady=3) lbl_automatic_keys = Label(frm_name, text="Automatically Compute Keys:") lbl_automatic_keys.pack(anchor='nw', pady=3) lbl_keys = Label(frm_name, text="Keys:") lbl_keys.pack(anchor='w', pady=3) lbl_fds = Label(frm_name, text="Functional Dependencies:") lbl_fds.pack(anchor='nw', pady=2) frm_attributes = Frame(labelframe, pady=10) frm_attributes.pack(side='left', anchor='w') #self.name = Label(frm_attributes, text="-", font = "-weight bold") self.entry_name = Entry(frm_attributes, width=100) self.entry_name.pack(anchor='w', pady=5) self.entry_name.insert(0, "R") self.entry_attributes = Entry(frm_attributes, width=100) self.entry_attributes.pack(anchor='w', pady=5) self.entry_attributes.insert(0, "A, B, C, D, E") self.automatic_keys_var = IntVar() #self.automatic_keys_var.set(1) self.chk_automatic_keys = Checkbutton(frm_attributes, text="", command=self.onChecked, variable=self.automatic_keys_var) self.chk_automatic_keys.pack(anchor='w', pady=1) self.entry_keys = Entry(frm_attributes, width=100) self.entry_keys.pack(anchor='w', pady=5) self.entry_keys.insert(0, "A.B, B.C") self.entry_fds = Entry(frm_attributes, width=100) self.entry_fds.pack(anchor='w') self.entry_fds.insert(0, "A.B -> C.D, C -> A.D.E, B -> D.E, D -> E") self.compute_normal_form = ttk.Button( frm_attributes, text="Normalize Relation", command=self.compute_normal_form_clicked, width=25) self.compute_normal_form.pack(side='left', anchor='w', pady=1) self.compute_normal_form = ttk.Button(frm_attributes, text="Clear fields", command=self.clear_fields, width=25) self.compute_normal_form.pack(anchor='w', pady=1, padx=5) nb = ttk.Notebook(frame, name='normalization', height=350, width=870) nb.grid(row=3, column=2, columnspan=3, padx=20, pady=10, sticky='wne') self._create_report_tab(nb) self._create_ddl_tab(nb) self._create_dml_tab(nb) self._create_drop_ddl_tab(nb) #self._create_text_tab(nb) self.current_relation = None ''' self.RelationInfo= Label(frame,text="Relation Info:", font=13) self.RelationInfo.grid(row=0, sticky=NW) self.label_1= Label(frame,text="Name") self.label_1.grid(row=2, sticky=E) self.label_2= Label(frame,text="Attributes") self.label_2.grid(row=3, sticky=E) self.label_3= Label(frame,text="Keys") self.label_3.grid(row=4, sticky=E) self.label_4= Label(frame,text="FDs") self.label_4.grid(row=5, sticky=E) self.entry_name= Entry(frame,width=50) self.entry_name.grid(row=2,column=1) self.entry_attributes= Entry(frame,width=50) self.entry_attributes.grid(row=3,column=1) self.entry_keys= Entry(frame,width=50) self.entry_keys.grid(row=4,column=1) self.entry_fds= Entry(frame,width=50) self.entry_fds.grid(row=5,column=1) self.NormResult= Label(frame,text="Normalization Result:", font=15) self.NormResult.grid(row=10, sticky=E) self.Result= Text (frame,width=60,tabs=10) self.Result.grid(row=11,column=1) self.buttonBrowse = Button(frame, text="Compute Normal Form", command=self.Naming, height=2, width=20) self.buttonBrowse.grid(row=9, column=0) # Name = self.entry_1.get() # Attributes = self.entry_2.get() # Keys = self.entry_3.get() # FDs = self.entry_4.get() # def printName(self): # print("Compute Normal Form") ''' def Naming(self): txt_name = self.entry_name.get().replace(" ", "") txt_attributes = self.entry_attributes.get().replace(" ", "") txt_keys = self.entry_keys.get().replace(" ", "") txt_fds = self.entry_fds.get().replace(" ", "") relationObject = Relation() relationObject.Name = txt_name relationObject.Attributes = txt_attributes.split(",") def processNormForm(self): Name = self.entry_1.get() Attributes = self.entry_2.get() Keys = self.entry_3.get() FDs = self.entry_4.get() def onChecked(self): if self.automatic_keys_var.get(): messagebox.showinfo( "Automatically Compute Keys", "Keys will be automatically computed from the specified FDs.\nIf no key found, the basic key (U->U) will be considered" ) #self.preserve_dependency.config(text='(BCNF is not guarantied)') self.entry_keys.config(state=DISABLED) else: self.entry_keys.config(state=NORMAL) def compute_normal_form_clicked(self): # Filling FDs from GUI try: txt_name = self.entry_name.get().replace(" ", "") txt_attributes = self.entry_attributes.get().replace(" ", "") txt_keys = self.entry_keys.get().replace(" ", "") txt_fds = self.entry_fds.get().replace(" ", "") self.current_relation = Relation() self.current_relation.Name = txt_name for att in txt_attributes.split(','): self.current_relation.Attributes.append(Attribute(att)) fds_list = [] for txt_fd in txt_fds.split(','): txt_lhs_rhs = txt_fd.split('->') lhs_attributes = txt_lhs_rhs[0].split('.') rhs_attributes = txt_lhs_rhs[1].split('.') fd_object = FunctionalDependency() for attribute in lhs_attributes: attribute_object = self.current_relation.Attributes[ self.current_relation.Attributes.index( Attribute(attribute))] fd_object.leftHandSide.append(attribute_object) for attribute in rhs_attributes: attribute_object = self.current_relation.Attributes[ self.current_relation.Attributes.index( Attribute(attribute))] fd_object.rightHandSide.append(attribute_object) fds_list.append(fd_object) self.current_relation.FDs = fds_list if self.automatic_keys_var.get(): # automatic keys computation self.current_relation.compute_candidate_keys() keys_str = '' for key in self.current_relation.Keys: key_str = '' for attribute in key.Attributes: key_str += attribute.Name + '.' keys_str += key_str[:-1] + ", " self.entry_keys.insert(0, keys_str) else: for txt_key in txt_keys.split(","): key_object = Key() for att in txt_key.split("."): key_object.Attributes.append(Attribute(att)) self.current_relation.Keys.append(key_object) self.current_relation.computeNormalForm() self.current_relation.decompose() self.txt_result.delete(0.0, END) #self.txt_result.insert(5.0, relationObject.Name + ":\n") #self.txt_result.insert(5.0, relationObject.NormalForm) self.txt_result.insert(0.0, self.current_relation.print_report()) self.txt_ddl.delete(0.0, END) self.txt_ddl.insert( 0.0, str(self.current_relation.buildCreateTableScript())) self.txt_dml.delete(0.0, END) self.txt_dml.insert(0.0, str(self.current_relation.buildDmlScript())) self.txt_ddl_drop.delete(0.0, END) self.txt_ddl_drop.insert( 0.0, str(self.current_relation.buildDropTableClause())) except Exception as ex: messagebox.showerror( "Error", "An error occurred during normalization.\n Please, make sure that all fields are in correct format" ) def _create_report_tab(self, nb): # frame to hold contentx frame2 = ttk.Frame(nb, name='report') frame = ttk.Frame(frame2) frame.pack(fill=BOTH, expand=Y, padx=10, pady=10) self.txt_result = Text(frame, wrap=WORD, width=40, height=10) vscroll = ttk.Scrollbar(frame, orient=VERTICAL, command=self.txt_result.yview) self.txt_result['yscroll'] = vscroll.set vscroll.pack(side=RIGHT, fill=Y) self.txt_result.pack(fill=BOTH, expand=Y) self.btn_export_xml = ttk.Button(frame2, text='Export to XML', underline=0, command=self.btn_export_xml_clicked) self.btn_export_xml.pack(side='left', padx=10, pady=10, anchor='sw') # add to notebook (underline = index for short-cut character) nb.add(frame2, text='Normalization Proposal', underline=0, padding=2) def _create_ddl_tab(self, nb): # frame to hold contentx frame2 = ttk.Frame(nb, name='ddl') frame = ttk.Frame(frame2) frame.pack(fill=BOTH, expand=Y, padx=10, pady=10) self.txt_ddl = Text(frame, wrap=WORD, width=40, height=10) vscroll = ttk.Scrollbar(frame, orient=VERTICAL, command=self.txt_ddl.yview) self.txt_ddl['yscroll'] = vscroll.set vscroll.pack(side=RIGHT, fill=Y) self.txt_ddl.pack(fill=BOTH, expand=Y) btn_save_ddl = ttk.Button(frame2, text='Save', underline=0, command=self.btn_save_ddl_clicked) btn_save_ddl.pack(side='left', padx=10, pady=10, anchor='sw') # add to notebook (underline = index for short-cut character) nb.add(frame2, text='DDL: Create New Tables', underline=0, padding=2) def _create_dml_tab(self, nb): # frame to hold contentx frame2 = ttk.Frame(nb, name='dml') frame = ttk.Frame(frame2) frame.pack(fill=BOTH, expand=Y, padx=10, pady=10) self.txt_dml = Text(frame, wrap=WORD, width=40, height=10) vscroll = ttk.Scrollbar(frame, orient=VERTICAL, command=self.txt_dml.yview) self.txt_dml['yscroll'] = vscroll.set vscroll.pack(side=RIGHT, fill=Y) self.txt_dml.pack(fill=BOTH, expand=Y) btn_save_dml = ttk.Button(frame2, text='Save', underline=0, command=self.btn_save_dml_clicked) btn_save_dml.pack(side='left', padx=10, pady=10, anchor='sw') # add to notebook (underline = index for short-cut character) nb.add(frame2, text='DML: Data Migration', underline=0, padding=2) def _create_drop_ddl_tab(self, nb): # frame to hold contentx frame2 = ttk.Frame(nb, name='drop_ddl') frame = ttk.Frame(frame2) frame.pack(fill=BOTH, expand=Y, padx=10, pady=10) self.txt_ddl_drop = Text(frame, wrap=WORD, width=40, height=10) vscroll = ttk.Scrollbar(frame, orient=VERTICAL, command=self.txt_ddl_drop.yview) self.txt_ddl_drop['yscroll'] = vscroll.set vscroll.pack(side=RIGHT, fill=Y) self.txt_ddl_drop.pack(fill=BOTH, expand=Y) btn_save_ddl_drop = ttk.Button(frame2, text='Save', underline=0, command=self.btn_save_ddl_drop_clicked) btn_save_ddl_drop.pack(side='left', padx=10, pady=10, anchor='sw') # add to notebook (underline = index for short-cut character) nb.add(frame2, text='DDL: Drop Old Tables', underline=0, padding=2) def btn_export_xml_clicked(self): if self.current_relation: f = filedialog.asksaveasfilename(title="Export to XML...", defaultextension=".xml") if f == '': return rxml = xmlReader.XmlReader('schema.xml') rxml.xmlCompleteStructure([self.current_relation], f) def btn_save_ddl_clicked(self): script = str(self.txt_ddl.get(1.0, END)) self.save_file(script) def btn_save_dml_clicked(self): script = str(self.txt_dml.get(1.0, END)) self.save_file(script) def btn_save_ddl_drop_clicked(self): script = str(self.txt_ddl_drop.get(1.0, END)) self.save_file(script) def save_file(self, text2save): f = filedialog.asksaveasfile(mode='w', defaultextension=".sql") if f is None: return f.write(text2save) f.close() def clear_fields(self): self.entry_name.delete(0, END) self.entry_attributes.delete(0, END) self.entry_fds.delete(0, END) self.automatic_keys_var.set(0) self.entry_keys.config(state=NORMAL) self.entry_keys.delete(0, END)
def compute_normal_form_clicked(self): # Filling FDs from GUI try: txt_name = self.entry_name.get().replace(" ", "") txt_attributes = self.entry_attributes.get().replace(" ", "") txt_keys = self.entry_keys.get().replace(" ", "") txt_fds = self.entry_fds.get().replace(" ", "") self.current_relation = Relation() self.current_relation.Name = txt_name for att in txt_attributes.split(','): self.current_relation.Attributes.append(Attribute(att)) fds_list = [] for txt_fd in txt_fds.split(','): txt_lhs_rhs = txt_fd.split('->') lhs_attributes = txt_lhs_rhs[0].split('.') rhs_attributes = txt_lhs_rhs[1].split('.') fd_object = FunctionalDependency() for attribute in lhs_attributes: attribute_object = self.current_relation.Attributes[ self.current_relation.Attributes.index( Attribute(attribute))] fd_object.leftHandSide.append(attribute_object) for attribute in rhs_attributes: attribute_object = self.current_relation.Attributes[ self.current_relation.Attributes.index( Attribute(attribute))] fd_object.rightHandSide.append(attribute_object) fds_list.append(fd_object) self.current_relation.FDs = fds_list if self.automatic_keys_var.get(): # automatic keys computation self.current_relation.compute_candidate_keys() keys_str = '' for key in self.current_relation.Keys: key_str = '' for attribute in key.Attributes: key_str += attribute.Name + '.' keys_str += key_str[:-1] + ", " self.entry_keys.insert(0, keys_str) else: for txt_key in txt_keys.split(","): key_object = Key() for att in txt_key.split("."): key_object.Attributes.append(Attribute(att)) self.current_relation.Keys.append(key_object) self.current_relation.computeNormalForm() self.current_relation.decompose() self.txt_result.delete(0.0, END) #self.txt_result.insert(5.0, relationObject.Name + ":\n") #self.txt_result.insert(5.0, relationObject.NormalForm) self.txt_result.insert(0.0, self.current_relation.print_report()) self.txt_ddl.delete(0.0, END) self.txt_ddl.insert( 0.0, str(self.current_relation.buildCreateTableScript())) self.txt_dml.delete(0.0, END) self.txt_dml.insert(0.0, str(self.current_relation.buildDmlScript())) self.txt_ddl_drop.delete(0.0, END) self.txt_ddl_drop.insert( 0.0, str(self.current_relation.buildDropTableClause())) except Exception as ex: messagebox.showerror( "Error", "An error occurred during normalization.\n Please, make sure that all fields are in correct format" )
def testFactDatabase(): # test constructor __init__, appendFact, and getFactList factDatabase1 = FactDatabase.FactDatabase() assert (factDatabase1.getFactList() == []) relation1 = Relation.Relation("[0]") successStateAdd1 = factDatabase1.appendFact(relation1) assert (successStateAdd1 == True) assert (factDatabase1.getFactList()[0] == relation1) assert (len(factDatabase1.getFactList()) == 1) relation2 = Relation.Relation("[0] + 1") successStateAdd2 = factDatabase1.appendFact(relation2) assert (successStateAdd2 == False) assert (factDatabase1.getFactList()[0] == relation1) assert (len(factDatabase1.getFactList()) == 1) relation3 = Relation.Relation("[0] + (1 - [0])[12]") successStateAdd3 = factDatabase1.appendFact(relation3) assert (successStateAdd3 == True) assert (factDatabase1.getFactList()[0] == relation1) assert (factDatabase1.getFactList()[1] == relation3) assert (len(factDatabase1.getFactList()) == 2) successStateAdd4 = factDatabase1.appendFact("pulled pork") assert (successStateAdd4 == False) assert (factDatabase1.getFactList()[0] == relation1) assert (factDatabase1.getFactList()[1] == relation3) assert (len(factDatabase1.getFactList()) == 2) relation5 = Relation.Relation("[12](1 - [5]) + [5](1 - [12])[0]") successStateAdd5 = factDatabase1.appendFact(relation5) assert (successStateAdd5 == True) assert (factDatabase1.getFactList()[0] == relation1) assert (factDatabase1.getFactList()[1] == relation3) assert (factDatabase1.getFactList()[2] == relation5) assert (len(factDatabase1.getFactList()) == 3) # test deleteFact factDatabase2 = FactDatabase.FactDatabase() successStateDelete1 = factDatabase2.deleteFact(0) assert (successStateDelete1 == False) successStateDelete2 = factDatabase2.deleteFact(1) assert (successStateDelete2 == False) successStateDelete3 = factDatabase2.deleteFact(-1) assert (successStateDelete3 == False) relation6 = Relation.Relation("[1][2](1 - [3])") factDatabase2.appendFact(relation6) successStateDelete4 = factDatabase2.deleteFact(0) assert (successStateDelete4 == True) assert (len(factDatabase2.getFactList()) == 0) relation7 = Relation.Relation("[1][8] + (1 - [1])(1 - [8])") factDatabase2.appendFact(relation7) relation8 = Relation.Relation("[1][2] + [2](1 - [8])(1 - [1])") factDatabase2.appendFact(relation8) relation9 = Relation.Relation("[2](1 - [3]) + [4][3](1 - [2])") factDatabase2.appendFact(relation9) relation10 = Relation.Relation("0") factDatabase2.appendFact(relation10) successStateDelete5 = factDatabase2.deleteFact(4) assert (successStateDelete5 == False) successStateDelete6 = factDatabase2.deleteFact(0) assert (successStateDelete6 == True) factList1 = factDatabase2.getFactList() assert (factList1[0] == relation8) assert (factList1[1] == relation9) assert (factList1[2] == relation10) assert (len(factList1) == 3) successStateDelete7 = factDatabase2.deleteFact(1) assert (successStateDelete7 == True) factList2 = factDatabase2.getFactList() assert (factList2[0] == relation8) assert (factList2[1] == relation10) assert (len(factList2) == 2) successStateDelete8 = factDatabase2.deleteFact(1) assert (successStateDelete8 == True) factList3 = factDatabase2.getFactList() assert (factList3[0] == relation8) assert (len(factList3) == 1) # test getFactAggregation factDatabase3 = FactDatabase.FactDatabase() relation11 = Relation.Relation("[0]") factDatabase3.appendFact(relation11) assert (factDatabase3.getFactAggregation() == relation11) relation12 = Relation.Relation("[1]") factDatabase3.appendFact(relation12) relation13 = Relation.Relation("[1] + [0](1 - [1])") assert (factDatabase3.getFactAggregation() == relation13) relation14 = Relation.Relation("(1 - [2][3])") factDatabase3.appendFact(relation14) relation15 = Relation.Relation("[0] + [1](1 - [0]) + (1 - [2][3])(1" " - [1])(1 - [0])") assert (factDatabase3.getFactAggregation() == relation15) relation16 = Relation.Relation("[3] + (1 - [3])(1 - [2])") factDatabase3.appendFact(relation16) relation17 = Relation.Relation("[0] + [1](1 - [0]) + (1 - [1])(1 - " "[0])") assert (factDatabase3.getFactAggregation() == relation17) factDatabase4 = FactDatabase.FactDatabase() relation18 = Relation.Relation("0") assert (factDatabase4.getFactAggregation() == relation18)