Advertisement
Guest User

Untitled

a guest
Jul 5th, 2015
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.85 KB | None | 0 0
  1. from random import *
  2. from DataBaseConnection import DataBaseConnection
  3. import json
  4. import os, sys
  5.  
  6. class VariationAlgorithm:
  7.    
  8.     def __init__(self, nameOfTask, idPattern):
  9.         directoryPath = r'/home/luka/Desktop/Tasks'
  10.         self.nameOfTask = nameOfTask
  11.         self.idPattern = idPattern
  12.         self.DirectoryPath = directoryPath + '/' + self.nameOfTask
  13.         self.DictionariesPath = self.DirectoryPath + '/Dictionaries'
  14.         self.PatternPath = self.DirectoryPath + '/Pattern'
  15.         self.GenerationPath = self.DirectoryPath + '/Generation'
  16.        
  17.     def prepareDirectory(self): ##Called first to setup enviroment for generating new generations
  18.         if not os.path.exists(self.DirectoryPath):
  19.             os.makedirs(self.DirectoryPath)
  20.             os.makedirs(self.DictionariesPath)
  21.             os.makedirs(self.PatternPath)
  22.             os.makedirs(self.GenerationPath)
  23.            
  24.         else:
  25.             print("Directory already exists!")
  26.  
  27.         newCountFilePath = self.DirectoryPath + '/CountOfTasks.txt' ##count of generations
  28.         newAnswerCountPath = self.DirectoryPath + '/AnswerCount.txt'##count of answers (1,4)
  29.        
  30.         writeCount = open(newCountFilePath, 'w+')
  31.         writeCount.write('0')
  32.         writeCount.close()
  33.  
  34.         writeAnswerCount = open(newAnswerCountPath, 'w+')
  35.         writeAnswerCount.write('')
  36.         writeAnswerCount.close()
  37.        
  38.  
  39.     def createNewDictionary(self, variables): ##Creating new dict (pairs of generated variables and math variables) - .json
  40.         orderNumber = self.orderNumber()
  41.         DictionaryPath = self.DictionariesPath + '/Dictionary' + str(orderNumber) + '.json'
  42.  
  43.         with open(DictionaryPath, 'w') as writeFile:
  44.             json.dump(variables, writeFile)
  45.  
  46.         countPath = self.DirectoryPath + '/CountOfTasks.txt'
  47.         countWrite = open(countPath, 'w')
  48.         countWrite.write(str(orderNumber + 1))
  49.         countWrite.close()
  50.        
  51.     def checkDictionary(self, variables): ##Checking if same generation exists
  52.         countOfTasks = self.orderNumber()
  53.        
  54.         for dictNumber in range(countOfTasks):
  55.             dictPath = self.DictionariesPath + '/Dictionary' + str(dictNumber) + '.json'
  56.  
  57.             with open(dictPath) as readFile:
  58.                 dictionary = json.load(readFile)
  59.  
  60.             intersection = set(variables.items() & dictionary.items())
  61.             return not(len(intersection) == len(variables))
  62.        
  63.     def matchLatexPattern(self, variables, typeOfMatching): ##Matching latex pattern with generated variables
  64.         latexPath = self.PatternPath + '/LatexPattern' + typeOfMatching + '.txt'
  65.         latexPattern = open(latexPath,'r+')
  66.         rows = latexPattern.readlines()
  67.         writeRow = ""
  68.        
  69.         for row in rows:
  70.             if row[0] == '/':
  71.                 writeRow += '<p>' + row.rstrip() + '<p><br>' + '\n'
  72.                 continue
  73.            
  74.             temporaryRow=""
  75.             splitedRow = row.split(" ")
  76.  
  77.             for i in range(len(splitedRow)):
  78.                 if splitedRow[i] in variables:
  79.                     temporaryRow += str(variables[splitedRow[i]])
  80.                 else:
  81.                     temporaryRow += splitedRow[i]
  82.             writeRow += '<p>' + temporaryRow.rstrip() + '<p><br>' + '\n'
  83.  
  84.         taskText = self.filterVariation(writeRow)
  85.         self.saveVariation(taskText, typeOfMatching)
  86.         latexPattern.close()
  87.        
  88.     def filterVariation(self, stringTask): ## Filtering needless expressions
  89.         tempString = ""
  90.         for i in range(len(stringTask)):
  91.             if stringTask[i] == '1' and stringTask[i+1] == 'x':
  92.                 continue
  93.             if stringTask[i] == '/':
  94.                 continue
  95.             else:
  96.                 tempString += stringTask[i]
  97.         return tempString
  98.  
  99.     def orderNumber(self): ##Returning number of generated tasks
  100.         countPath = self.DirectoryPath + '/CountOfTasks.txt'
  101.         countRead = open(countPath, 'r')
  102.         orderNumber = int(countRead.read())
  103.         countRead.close()
  104.         return orderNumber
  105.      
  106.     def saveVariation(self, variation, typeOfSaving): ##Saving new generation - .txt
  107.         orderNumber = self.orderNumber()
  108.  
  109.         newVariationDirectoryPath = self.GenerationPath + '/' + 'Variation' + str(orderNumber)
  110.         os.makedir(newVariationDirectoryPath)
  111.        
  112.         newVariationPath = self.newVariationDirectoryPath +  '/' + typeOfSaving + '.txt'
  113.            
  114.         writeVariation = open(newVariationPath, 'w')
  115.         writeVariation.write(variation)
  116.         writeVariation.close()
  117.        
  118.     def divide(self, dividend, divisor): ##Preventing dividing with zero
  119.         return dividend == 0 or divisor == 0
  120.  
  121.     def deleteVariations(self):
  122.         connection = DataBaseConnection()
  123.  
  124.         #removing variations and answers from DB
  125.         cursorDelete = connection.getCursor()
  126.         queryDelete = "DELETE FROM variation WHERE id_pattern_fk = %s"
  127.         cursorDelete.execute(queryDelete, (self.idPattern))
  128.         cursorDelete.close()
  129.  
  130.         cursorDeleteAnswers = conection.getCursor()
  131.         queryDeleteAnswers = "DELETE FROM variation_answer WHERE id_pattern_fk = %s"
  132.         cursorDeleteAnswers.execute(queryDeleteAnswers, (self.idPattern))
  133.         cursorDelete.close()
  134.        
  135.         ##removing Variation
  136.         os.remove(self.GenerationPath)
  137.         os.remove(self.DictionariesPath)
  138.         os.remove(self.PatternPath)
  139.  
  140.         ##reseting countOfTasks to 0
  141.         countPath = self.DirectoryPath + '/CountOfTasks.txt'
  142.         countReset = open(countPath, 'w')
  143.         countReset.write('0')
  144.         countReset.close()
  145.        
  146.     def commitVariations(self):
  147.         connection = DataBaseConnection()
  148.  
  149.         cursorSetImplemented = connection.getCursor()
  150.         querySetImplemented = "UPDATE pattern SET is_implemented_pattern = %s WHERE id_pattern = %s"
  151.         cursorSetImplemented.execute(querySetImplemented, (1, self.idPattern))
  152.        
  153.         numberOfVariations = self.orderNumber()
  154.        
  155.         for i in range(numberOfVariations):
  156.             stepByStepPath = self.GenerationPath + '/' + 'Variation' + str(i) + '/' + 'StepByStep.txt'
  157.             taskPath = self.GenerationPath + '/' + 'Variation' + str(i) + '/' + 'Task.txt'
  158.  
  159.             stepByStepRead = open(stepByStepPath, 'r')
  160.             stepByStepVariation = stepByStepRead.read()
  161.             stepByStepRead.close()
  162.  
  163.             taskRead = open(taskPath, 'r')
  164.             taskVariation = taskRead.read()
  165.             taskRead.close()
  166.  
  167.             commitCursor = connection.getCursor()
  168.             queryCommit = "INSERT INTO variation (id_pattern_fk, task_variation, stepbystep_variation) VALUES(%s, %s, %s)"
  169.             commitCursor.execute(queryCommit, (self.idPattern, taskVariation, stepByStepVariation))
  170.             commitCursor.close()
  171.  
  172.             ##dodaj za rjesenja, sub/super, weight
  173.  
  174.     def pullPattern(self): ##getting pattern's info
  175.         connection = DataBaseConnection()
  176.  
  177.         cursorPull = connection.getDictCursor()
  178.         query = "SELECT * FROM pattern WHERE id_pattern = %s"
  179.         cursorPull.execute(query, (self.idPattern))
  180.  
  181.         result = cursorPull.fetchone()
  182.  
  183.         stepByStepPattern = result['stepbystep_pattern']
  184.         taskPattern = result['task_pattern']
  185.         variablesAndConditions = result['variables_and_conditions_pattern']
  186.         subCategory = result['subcategory_pattern']
  187.         superCategory = result['supercategory_pattern']
  188.         weight = result['weight_pattern']
  189.         remark = reuslt['remark_pattern']
  190.        
  191.        
  192.         newStepByStepPatternPath = self.PatternPath + '/LatexPatternStepByStep.txt'
  193.         newTaskPatternPath = self.PatternPath + '/LatexPatternTask.txt'
  194.         newVariablesAndConditionsPath = self.PatternPath + '/VariablesAndConditions.txt'
  195.         newSubCategoryPatternPath = self.PatternPath + '/SubCategory.txt'
  196.         newSuperCategoryPatternPath = self.PatternPath + '/SuperCategory.txt'
  197.         newWeightPatternPath = self.PatternPath + '/Weight.txt'
  198.         newRemarkPatternPath = self.PatternPath + '/Remark.txt'
  199.  
  200.        
  201.         writeStepByStepPattern = open(newStepByStepPatternPath, 'w+')
  202.         writeStepByStepPattern.write(stepByStepPattern)
  203.         writeStepByStepPattern.close()
  204.        
  205.         writeTaskPattern = open(newTaskPatternPath, 'w+')
  206.         writeTaskPattern.write(taskPattern)
  207.         writeTaskPattern.close()
  208.  
  209.         writeVariablesAndConditions = open(newVariablesAndConditionsPatternPath, 'w+')
  210.         writeVariablesAndConditions.write(variablesAndConditions)
  211.         writeVariablesAndConditions.close()
  212.  
  213.         writeSubCategory = open(newSubCategorypatternPath, 'w+')
  214.         writeSubCategory.write(subCategory)
  215.         writeSubCategory.close()
  216.  
  217.         writeSuperCategory = open(newSubCategoryPatternPath, 'w+')
  218.         writeSubCategory.write(subCategory)
  219.         writeSubCategory.close()
  220.  
  221.         writeWeight = open(newWeightPatternPath, 'w+')
  222.         writeWeight.write(weight)
  223.         writeWeight.close()
  224.  
  225.         writeRemark = open(newRemarkPatternPath, 'w+')
  226.         writeRemark.write(remark)
  227.         writeRemar.close()
  228.        
  229.  
  230.         cursorGetCountOfAnswers = connection.getDictCursor()
  231.         queryGetCountOfAnswers = "SELECT COUNT(*) as count FROM pattern_answer WHERE id_pattern_fk = %id"
  232.         cursorGetCountOfAnswers.execute(queryGetCountOfAnswers,(self.idPattern))
  233.  
  234.         resultCountOfAnswers = cursorGetCountOfAnswers.fetch()
  235.  
  236.         answerCount = resultCountOfAnswers['count']
  237.         answerCountPath = self.DirectoryPath + '/AnswerCount.txt'
  238.  
  239.         writeAnswerCount = open(nswerCountPath, 'w')
  240.         writeAnswerCount.write(answerCount)
  241.         writeAnswerCount.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement