def lineStart(self): if self.main_empty() and self.line_empty(): try: # pass calc = Calculator(self.massa, self.diam, self.sech, self.modul, self.tklr, self.mdrn, self.temp, self.height, self.rg.checkedId(), #land - тип местности int(self.ui.spinVet.text()), #vet - район по ветру int(self.ui.spinGol.text())) #gol - район по гололеду self.lineResult = calc.lineCalc(self.lenLine, self.strLine, self.angleLine) if self.lineResult.line_warning: msg_supp = QtWidgets.QMessageBox() msg_supp.setWindowTitle('Превышена максимально - допустимая нагрузка') msg_supp.setText('Для данного пролета требуется кабель с большей максимально - допустимой нагрузкой') msg_supp.setIcon(msg_supp.Warning) msg_supp.exec() # self.updateLineUI(Hf, Hkl, Sf, Skl) self.updateLineUI() except: msg_ls = QtWidgets.QMessageBox() msg_ls.setWindowTitle('Некорректные данные для расчета!') msg_ls.setText('Проверьте корректность исходных данных') msg_ls.setIcon(msg_ls.Warning) msg_ls.exec()
def pillarStart(self): if self.main_empty() and self.pillar_empty(): try: # pass calc = Calculator(self.massa, self.diam, self.sech, self.modul, self.tklr, self.mdrn, self.temp, self.height, self.rg.checkedId(), # land - тип местности int(self.ui.spinVet.text()), # vet - район по ветру int(self.ui.spinGol.text())) # gol - район по гололеду # результат в экземпляре класса self.pillResult = calc.pillarCalc(self.lenLeftpillar, self.strLeftpillar, self.lenRightpillar, self.strRightpillar, self.anglepillar) self.updatePillarUI() except: msg_ls = QtWidgets.QMessageBox() msg_ls.setWindowTitle('Некорректные данные для расчета!') msg_ls.setText('Проверьте корректность исходных данных') msg_ls.setIcon(msg_ls.Warning)
def draw_gini_and_cr3(): t1 = time.time() paper_city_tuple_list = DBConnector.get_city_paper_tuple_list() t2 = time.time() print('Load tuple list, cost {0} secs.'.format(str(round(t2 - t1, 3)))) ginis, cr3s = [], [] for i in range(1997, 2018): t1 = time.time() sid_list = DBConnector.get_sid_list_from_cnki_main_by_year(i) year_list = list( filter(lambda o: o[1] in sid_list, paper_city_tuple_list)) paper_city_list = [] for item in year_list: paper_city_list.append(item[2]) ginis.append(Calculator.get_gini_index(paper_city_list)) cr3s.append(Calculator.get_cr3(paper_city_list)) t2 = time.time() print('Finish Year {0}, cost time: {1} secs.'.format( str(i), str(round(t2 - t1, 3)))) x = range(1997, 2018) plt.xlabel('Year') plt.ylabel('Value') plt.xticks(range(1997, 2018, 1), rotation=45) plt.ylim((0.0, 1.0)) plt.yticks(np.arange(0.0, 1.0, step=0.1)) plt.plot(x, ginis, 'o-', label='Gini Index') plt.plot(x, cr3s, '^-m', label='CR3') plt.legend(loc='upper right') plt.show() year = 1997 for item in ginis: print(str(year) + ':' + str(item)) year = year + 1
class MainScreen(GridLayout): def __init__(self, **kwargs): super(MainScreen, self).__init__(**kwargs) txt_inpt = ObjectProperty(None) print(self.txt_inpt.text) self.buffer = "" self.calc = Calculator() def update_label(self, value): if (value == "CE"): self.buffer = "" self.txt_inpt.text = self.buffer self.txt_inpt.texture_update() elif (value == "C"): self.buffer = self.buffer[:len(self.buffer) - 1] self.txt_inpt.text = self.buffer self.txt_inpt.texture_update() else: self.buffer += value self.txt_inpt.text = self.buffer self.txt_inpt.texture_update() def do_calculate(self, input): self.calc.parser(input) self.txt_inpt.text = self.calc.M1 self.txt_inpt.texture_update() self.buffer = self.calc.M1
class TestCal: def setup_class(self): print("setup") self.calc = Calculator() def teardown_class(self): print("teardown") def setup(self): print("开始计算") def teardown(self): print("结束计算") @pytest.mark.parametrize('a,b,expect', [ [1, 1, 2], [0.1, 0.1, 0.2], [1000, 1000, 2000], [0, 1000, 1000] ], ids=['int1', 'float', 'bignum', 'zeronum']) def test_add(self, a, b, expect): assert expect == self.calc.add(a, b) @pytest.mark.parametrize('a,b,expect',[ [1, 1, 1], [0.1, 0.1, 1], [1000, 1000, 1], [0, 1000, 0], [1, 0, 0] ], ids=['int1', 'float', 'bignum', 'zeronum', 'error']) def test_del(self, a, b, expect): try: assert expect == self.calc.div(a, b) except: print("这里有个异常")
def main(): window = make_window() display = make_display(window) label = make_label(window) buttons = make_buttons(window) calculator = Calculator(window, label, display, buttons) calculator.start()
def main(): description = "Cleans up old backups to leave more room on the backup server." \ "\n\nE.g. python cleaner.py -p /path/to/archive -o 3:4 7:7." \ "\n\nThe example provided will keep an archive from every 4th day if it's more than 3 days old" \ " and archive every 7 days if it's more than a week old." \ "\n\nThe format of backups this script takes is BACKUP_SET-VERSION." parser = argparse.ArgumentParser( description=description, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('-p', '--root-path', type=str, required=True, help='The root path of your backups.') parser.add_argument( '-o', '--options', type=str, required=True, nargs='*', help='Your age threshold and desired interval size separated by a colon' ) parser.add_argument('-f', '--force', action='store_true', help='Automatically confirms that you want to delete.') args = parser.parse_args() calc = Calculator(args.root_path, args.options, args.force) calc.calculate() cleaner = Cleaner(calc) cleaner.clean()
def classesProbabilities(self,summaries, input): probs = {} gaus = Calculator(formula=Gaussian) for index,values in summaries.items(): probs[index] = 1 for i in range(len(values)): mean, stdev = values[i] x = input[i] probs[index] *= gaus.calculate([x, mean, stdev]) return probs
def classesProbabilities(self, summaries, input): probs = {} gaus = Calculator(formula=Gaussian) for index, values in summaries.items(): probs[index] = 1 for i in range(len(values)): mean, stdev = values[i] x = input[i] probs[index] *= gaus.calculate([x, mean, stdev]) return probs
def __init__(self,daily_savings, days_until_grad, income_bracket,amount_saved =0): self.User = Calculator(amount_saved,daily_savings, days_until_grad, income_bracket) self.NeedList = GoalList([], self.User.calculate_need_percent()) self.WantList = GoalList([], 1 - self.User.calculate_need_percent())
def formatting_sample(request): #sample logging logging.error("testing debug log") calc = Calculator() calc.add(2) print("calculated:" + str(calc.get_current())) s = 'The crappy persons name is %(suz)s and %(sup)s' % {"sup": "crappy", "suz": "crappppp"} print s return http.HttpResponse(s)
def test_subtract(self): self.assertEqual(Calculator.subtract(2, 2), 0) self.assertEqual(Calculator.subtract(-2, -2), 0) self.assertEqual(Calculator.subtract(2, -2), 4) self.assertEqual(Calculator.subtract(2.2, 2.2), 0) try: result = Calculator.subtract("string1", "string2") except: Exception pass else: self.fail('subtract() accepts strings as input')
def test_add(self): self.assertEqual(Calculator.add(2, 2), 4) self.assertEqual(Calculator.add(-2, -2), -4) self.assertEqual(Calculator.add(2, -2), 0) self.assertEqual(Calculator.add(2.2, 2.2), 4.4) try: result = Calculator.add("string1", "string2") except: Exception pass else: self.fail('add() accepts strings as input')
def Separate(self): Graph = c.GetDistance(self.Spec_g, th=5) Graph_i = c.GetInclinations(Graph) self.phonemes = [] ### phonemes : list of namedtuple('phoneme', [point, UV, pcm_start, pcm_end]) for i in range(len(self.UV_list)): if self.UV_list[i].UV == 'U': # UV_list[i].start : end 에서 무조건 하나 가져옴 point = self.GetPointFromRange(Graph, self.UV_list[i].start, self.UV_list[i].end) temp = namedtuple('phoneme', ['point', 'UV', 'pcm_start', 'pcm_end']) temp.point = point temp.UV = 'U' self.phonemes.append(temp) elif self.UV_list[i].UV == 'V': # graph for문 돌면서 0인 구간 중 가운뎃값 가져옴 points = self.GetAllZeroPointFromRange(Graph, self.UV_list[i].start, self.UV_list[i].end) if points==[]: convexes = c.GetConvex_range(Graph_i, self.UV_list[i].start, self.UV_list[i].end) if len(convexes)>0: minindex = convexes[0] minvalue = Graph[convexes[0]] for j in range(len(convexes)): if minvalue > Graph[convexes[j]]: minvalue = Graph[convexes[j]] minindex = convexes[j] points.append(minindex) for j in range(len(points)): temp = namedtuple('phoneme', ['point', 'UV', 'pcm_start', 'pcm_end']) temp.point = points[j] temp.UV = 'V' self.phonemes.append(temp) ### PostTreat : calculate p_start, p_end for i in range(len(self.phonemes)): f_start = Framing.Index_frame_to_origin(self.phonemes[i].point, self.frame_size, self.interval) f_end = f_start + 2 * self.frame_size - self.interval f_range = (f_start - f_end) sectlen = int(0.05 * self.sample_rate) p_start = f_start - int((sectlen - f_range) / 2) + 650 if p_start < 0: p_start = 0 p_end = p_start + sectlen if p_end >= len(self.pcmValue): p_end = len(self.pcmValue) - 1 p_start = p_end - sectlen self.phonemes[i].pcm_start = p_start self.phonemes[i].pcm_end = p_end
def loadData(self): gg = self.GGdoubleSpinBox.value() tg = self.TGdoubleSpinBox.value() pg = self.PGspinBox.value() deg = self.DEGdoubleSpinBox.value() neg = self.NEGspinBox.value() nky = self.NKYspinBox.value() lg = self.LGdoubleSpinBox.value() sg = self.SGdoubleSpinBox.value() fg = self.FGdoubleSpinBox.value() feg = self.FEGdoubleSpinBox.value() mg = self.MGdoubleSpinBox.value() gb = self.GBdoubleSpinBox.value() tb = self.TBdoubleSpinBox.value() pb = self.PBspinBox.value() deb = self.DEBdoubleSpinBox.value() neb = self.NEBspinBox.value() nke = self.NKEspinBox.value() lb = self.LBdoubleSpinBox.value() sb = self.SBdoubleSpinBox.value() fb = self.FBdoubleSpinBox.value() mb = self.MBdoubleSpinBox.value() me = self.MEdoubleSpinBox.value() betact = self.BETACTdoubleSpinBox.value() hpg = self.HPGdoubleSpinBox.value() fpg = self.FPGdoubleSpinBox.value() hn = self.HNdoubleSpinBox.value() cped1 = self.CPED1comboBox.currentIndex() + 1 cped2 = self.CPED2comboBox.currentIndex() + 1 matep = self.MATEPcomboBox.currentIndex() + 1 count = self.getCountPasses() self.__calc = Calculator.Calculator(gg, tg, pg, deg, neg, nky, lg, sg, fg, feg, mg, gb, tb, pb, deb, neb, nke, \ lb, sb, fb, mb, me, betact, hpg, fpg, hn, cped1, cped2, matep, count)
def DoProcess(self, filename): self.Settings(filename) if not self.file_valid: return 0 self.Spec = c.Spectrogram(self.pcm_framed, self.sample_rate) self.Mark_Empty() self.Mark_UV() self.Check_Empty_UV() self.UV_list = self.UV_Section() self.g = filters.gaussian_filter1d(c.GetInclinations_abs(filters.gaussian_filter1d(self.frame_LE,0.1)),2.5) self.g_inc = c.GetInclinations(self.g) self.Separate() self.Make_dataset() return len(self.phonemes)
def Mark_UV(self): Spect = self.Spec ### 무게중심 y가 max의 10%이상이면 유성음 ### centerY = c.GetCenterOfMass(Spect,'y') th_center = max(centerY)/10 for i in range(len(self.frame_table)): if centerY[i] > th_center: self.frame_table[i].UV = 3 else: if not self.frame_table[i].Empty: self.frame_table[i].UV = 2 ### 180 이상인 것들이 12개 이상 있으면 유성음 ### th_max = 180 for i in range(len(Spect)): count = 0 for j in range(len(Spect[i])): if Spect[i][j]> th_max: count += 1 if count > self.frame_size / 40: self.frame_table[i].UV = 3 ### max가 1000 이상인 프레임은 유성음 ### for i in range(len(self.frame_table)): if self.maxes[i] > 1000: self.frame_table[i].UV = 3
def main(): root = Tk() cal = Calculator(root) c = input('Do you want to train the network (y/n) ') if c == 'y': cal.network.train() root.mainloop()
def calculate(self,event): for child in self.GetParent().GetParent().GetParent().bottomwindow.GetChildren(): child.Destroy() a = storage.loadSAccts() b = storage.loadLoans() nameS = BeautifulSoup(self.combo_box_1.GetValue()) nameL = BeautifulSoup(self.combo_box_2.GetValue()) text = "" monthly = self.inputTxt3.GetValue() M = self.inputTxt2.GetValue() for i in a: if BeautifulSoup(i.n) == nameS: for j in b: if BeautifulSoup(j.name) == nameL: val = Calculator.compareLS(j, i,float(monthly), int(M)) if isinstance(val, Savings.Savings): text = BeautifulSoup(i.n) else: text = BeautifulSoup(j.name) #text = "Hagstaedara er fyrir notanda ad greida upphaed \n" + monthly + " inn a "+ BeautifulSoup(j.name).encode('ascii') +" i" + M +" manudi,\n\'hagstaedara\' telst vera meiri eignir ad "+M + " manudum loknum" if text != "": first= unicode(BeautifulSoup("Hagstæðara er að greiða upphæð ")) M1 = unicode(BeautifulSoup(M)) amount = locale.currency(int(monthly), grouping = True) monthly1 = unicode(BeautifulSoup(amount)) second = unicode(BeautifulSoup("\ninn á ")) third = unicode(BeautifulSoup(" í ")) fourth = unicode(BeautifulSoup(" mánuði.")) text = unicode(text) someInfo = wx.StaticText(self.GetParent().GetParent().GetParent().bottomwindow,-1,first+monthly1+second+text+third+M1+fourth,pos=(15,10),size=(800,200)) someInfo.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.NORMAL, 0, "PT Sans")) someInfo.SetForegroundColour("blue")
def validate_grades(grades, grades_are_valid, all_grades_are_present): # Calculate Grades & Output Results (IF VALID) if grades_are_valid: if all_grades_are_present: final_grade, final_letter_grade, category_averages = Calculator.calculate_grade( grades, category_grade_weights, category_num_items) # Formats Final Grade Output message = "Percentage: {:.2f}".format(final_grade).rstrip( '0').rstrip('.') message += " %\nLetter Grade: " + final_letter_grade + "\n\n" for x in range(0, len(category_averages)): message += "Average '" + category_names[ x] + "' score was {:.2f}".format( category_averages[x]).rstrip('0').rstrip('.') message += " %\n" messagebox.showinfo(title="Final Grade", message=message) else: current_grade, current_letter_grade, new_desired_grade_list, unachievable_grade_list, percentage_graded, percentage_not_graded, needed_grade_avgs \ = Calculator.calculate_current_grade(grades, category_grade_weights, category_num_items) # Formats Current Grade Output message = "Percentage: {:.2f}".format(current_grade).rstrip( '0').rstrip('.') message += " %\nLetter Grade: " + current_letter_grade + "\n\n" for x in range(0, len(unachievable_grade_list)): message += "Not enough remaining points to get a '" + Calculator.assign_letter_grade( unachievable_grade_list[x]) + "' ({:.2f}".format( unachievable_grade_list[x]).rstrip('0').rstrip('.') message += " %)\n" for x in range(0, len(needed_grade_avgs)): message += "Need avg of {:.2f}".format( needed_grade_avgs[x]).rstrip('0').rstrip('.') message += " % on remaining items to get a '" + Calculator.assign_letter_grade( new_desired_grade_list[x]) + "' ({:.2f}".format( new_desired_grade_list[x]).rstrip('0').rstrip('.') message += " %)\n" if len(unachievable_grade_list) == 0 and len( needed_grade_avgs) == 0: message += "Congratulations!\nYou will receive an 'A' whether you complete the remaining assignments or not\n" message += "\nPercent of points allotted: {:.2f}".format( percentage_graded * 100).rstrip('0').rstrip('.') message += " %\nPercent of points remaining: {:.2f}".format( percentage_not_graded * 100).rstrip('0').rstrip('.') message += " %\n" messagebox.showinfo(title="Current Grade", message=message)
def initcalc_class(): print("setup") calc = Calculator() yield calc print("teardown")
def LessThanSix(calc, ops): print(calc[1]) if calc[1] == ops[0]: result = Calculator.Addition(calc[0], calc[2]) print("Add", result) elif calc[1] == ops[1]: result = Calculator.Subtraction(calc[0], calc[2]) print("Sub", result) elif calc[1] == ops[2]: result = Calculator.Multiplication(calc[0], calc[2]) print("Mult", result) elif calc[1] == ops[3]: result = Calculator.Division(calc[0], calc[2]) print("Div", result) else: print("404 Jutsu Not found nani ") return result
def __init__(self, img_v, width, height): self._u = img_v[:] self.u = img_v[:] self.width = width self.height = height self.v = Calculator.dotD(img_v, width, height) self.w = self.v[:] self.gamma = Const.gamma
def deserialize_calculator(calculatorDat): calc_data = json.loads(calculatorDat)[0] return Calculator.Calculator(calc_data['amount_saved'], calc_data['daily_savings'], calc_data['days_until_grad'], calc_data['income_bracket'], calc_data['max_money_needed'], calc_data['min_money_needed'])
def Framing_pcm(self): self.pcm_framed=Framing.Framing(self.pcm, self.frame_size, self.interval) self.frame_table=[] for i in range(len(self.pcm_framed)): temp=namedtuple('Status', ['Empty', 'UV']) temp.Empty=False temp.UV=0 self.frame_table.append(temp) self.frame_LE=c.Log_Energy(self.pcm_framed)
def updateU(self): sub = [self.v[i] - self.w[i] for i in range(len(self.v))] d = Calculator.dotDT(sub, self.width, self.height) d = [x / self.gamma for x in d] d = [self._u[i] + d[i] for i in range(len(self._u))] d = np.fft.fft2(np.matrix(d)) f = np.fft.rfft( np.diag([x for x in range(6 * self.width * self.height)])) u = list(np.dot(d, f)) self.u = [x for x in u]
def BTNEquals(self): #Passes the information to the calculator module self.ids.input.text = "" a = Calculator.SingularMethod(self.ids.result.text) #A to list b = list(str(a)) print(b) a = a.strip() self.ids.input.text = str(a) print(a)
def exec_calculate(): payload = request.json operate = Calculator.Calculator(payload) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) task = asyncio.ensure_future(operate.start()) result = loop.run_until_complete(task) loop.close() result = json.loads(json.dumps(result, default=obj_to_dict)) return result, result['code']
def SerializeEnergyConsumption(self, circuit): calculator = Calculator.Calculator(circuit) energyConsumption = calculator.CalculateActualEnergyConsumption( circuit) result = self.SerializeOpenTag("ul") self.depth += 1 result += f'Energy Consumption = {(energyConsumption)} kW' self.depth -= 1 result += self.SerializeCloseTag("ul") return result
def buttonClicked(self): if self.display.text() == 'Error!': self.display.setText('') button = self.sender() key = button.text() if key == '=': try: result = str(eval(self.display.text())) except: result = 'Error!' self.display.setText(result) elif key == 'C': self.display.clear() elif key == constantList[0]: self.display.setText(self.display.text() + '3.141592') elif key == constantList[1]: self.display.setText(self.display.text() + '3E+8') elif key == constantList[2]: self.display.setText(self.display.text() + '340') elif key == constantList[3]: self.display.setText(self.display.text() + '1.5E+8') elif key == functionList[0]: n = self.display.text() value = Calculator.factorial(n) self.display.setText(str(value)) elif key == functionList[1]: n = self.display.text() value = Calculator.decToBin(n) self.display.setText(str(value)) elif key == functionList[2]: n = self.display.text() value = Calculator.binToDec(n) self.display.setText(str(value)) elif key == functionList[3]: n = self.display.text() value = Calculator.decToRoman(n) self.display.setText(str(value)) else: self.display.setText(self.display.text() + key)
class Manager: def __init__(self,daily_savings, days_until_grad, income_bracket,amount_saved =0): self.User = Calculator(amount_saved,daily_savings, days_until_grad, income_bracket) self.NeedList = GoalList([], self.User.calculate_need_percent()) self.WantList = GoalList([], 1 - self.User.calculate_need_percent()) def update(self): self.NeedList.goal_list_percent = self.User.calculate_need_percent() self.WantList.goal_list_percent = 1 - self.User.calculate_need_percent() self.NeedList.make_payment(self.User.daily_savings) self.WantList.make_payment(self.User.daily_savings)
def updateV(self): d = Calculator.dotD(self.u, self.width, self.height) d = [d[i] - self.w[i] for i in range(len(d))] l1 = np.sum([np.abs(x) for x in d]) if l1 > Const.alpha: d.sort(reverse=True) i = Const.alpha while i < len(d): d[i] = 0 i += 1 self.v = d[:]
def summarize(self, dataset): mean = Calculator(formula=Mean) stdev = Calculator(formula=STdev) result = [(mean.calculate(data), stdev.calculate(data)) for data in zip(*dataset)] del result[-1] return result
def calculate(self,event): for child in self.GetParent().GetParent().GetParent().bottomwindow.GetChildren(): child.Destroy() savings = storage.loadSAccts() text = "Hagstæðasti sparnaðarreikningur af öllum reikningum:\n" monthly = self.inputTxt1.GetValue() m = self.inputTxt2.GetValue() M = self.inputTxt3.GetValue() S = Calculator.compareAllSavings(savings,float(monthly),int(m),int(M)) someInfo1 = wx.StaticText(self.GetParent().GetParent().GetParent().bottomwindow, -1,text,pos=(15,10),size=(800,20)) someInfo2 = wx.StaticText(self.GetParent().GetParent().GetParent().bottomwindow, -1,str(S),pos=(15,29),size=(800,200)) someInfo1.SetFont(wx.Font(11, wx.SWISS, wx.NORMAL, wx.BOLD)) someInfo2.SetFont(wx.Font(11, wx.SWISS, wx.NORMAL, wx.NORMAL)) someInfo1.SetForegroundColour("black") someInfo2.SetForegroundColour("blue")
def test_resta(self): my_calc = Calculator(2, -3) self.assertEqual(my_calc.resta(), 5)
canvas.create_line(ox+d, oy-5, ox+d, oy+5, fill="red") # Axes canvas.create_line(0, 300, 600, 300, fill="red") canvas.create_line(300, 0, 300, 600, fill="red") # Control region canvas.create_rectangle(0, 600, 600, 700, fill="gray75") print("Parsing expression...") RPNqueue = Parser.parseMathExpression("sin((x+y)/pi)") print("Finished parsing expression.") validEquation = False if RPNqueue is not None: validEquation = Calculator.checkValid(RPNqueue) if validEquation: lineradius = linesize / 2 for j in range(-9, 10): for i in range(-9, 10): value = Calculator.evaluate(RPNqueue, i, j) angle = 0 # Ensure that the value is a number if not math.isnan(value): # If the value is infinite, set the slope to vertical if math.isinf(value): if value > 0: angle = math.pi / 2 else: angle = 3 * math.pi / 2
def test_resta(self): cal = Calculator(2, 3) self.assertEqual(-1, cal.resta())
def test_multiplicacion(self): cal = Calculator(2, 3) self.assertEqual(6, cal.multiplicacion())
def summarize(self,dataset): mean = Calculator(formula=Mean) stdev = Calculator(formula=STdev) result = [(mean.calculate(data), stdev.calculate(data)) for data in zip(*dataset)] del result[-1] return result
def test_suma(self): cal = Calculator(2, 3) self.assertEqual(5, cal.suma()) cal = Calculator(7, 3) self.assertEqual(10, cal.suma())
def test_division(self): my_calc = Calculator(2, 4) self.assertEqual(my_calc.division(), 0.5)
def test_calculate(self): for expression, result in self.results: evaluated = Calculator.calculate(expression) self.assertEqual(result, evaluated)
def test_suma(self): my_calc = Calculator(2, 4) self.assertEqual(my_calc.suma(), 6)
def test_division(self): cal = Calculator(6, 3) self.assertEqual(2, cal.division())
def test_multiplicacion(self): my_calc = Calculator(2, 3) self.assertEqual(my_calc.multiplicacion(), 6)
def run(self): print "Started the program..." # Start the training print "Started training from the training data..." asl = [] awl = [] asw = [] psw30 = [] juk30 = [] difficulty = {} difficulty_scores = [] lines = open('manual_difficulty_scores').readlines() print "Reading the manual difficulty levels given to training data..." for line in lines: if line == '\n': break line = str(line).split(':') difficulty[line[0]] = int(line[1]) # Create output directory try: stat(self.output_directory) except: mkdir(self.output_directory) print "Writing stats of training data to " + self.output_directory + "\stats_training.csv..." # Write to output file output_file = open(path.join(self.output_directory, 'stats_training.csv'), 'w+') output_file.write("\"Filename\";\"ASL\";\"AWL\";\"ASW\";\"PSW30\";\"JUK30\"\n") print "Calculating English Readability indices for training data..." print "Added them to " + self.output_directory + "\english_index_training.csv..." english_index_file = open(path.join(self.output_directory, 'english_index_training.csv'), 'w+') english_index_file.write("\"Filename\";" "\"Automatic Readability Index\";" "\"Gunning Fog Index\";" "\"Smog Index\";" "\"Flesch Reading Ease\";" "\"Flesch Kincaid Grade Level\";" "\"Coleman Liau Index\"\n") # Walk through all files in tree for (dir_path, _, file_names) in walk(self.input_train_directory): for filename in file_names: test_file = path.join(dir_path, filename) # The index calculator c = Calculator(test_file) # The parser p = c.parser if difficulty.has_key(test_file): difficulty_scores.append(difficulty[test_file]) asl.append(p.average_sentence_length()) awl.append(p.average_word_length()) asw.append(p.average_syllable_per_word()) psw30.append(p.number_of_polysyllables_per_30_words()) juk30.append(p.number_of_jukthakshar_per_30_words()) # The output line output_line = "\"" + str(test_file) \ + "\";\"" \ + str(p.average_sentence_length())\ + "\";\"" \ + str(p.average_word_length())\ + "\";\"" \ + str(p.average_syllable_per_word()) \ + "\";\"" \ + str(p.number_of_polysyllables_per_30_words()) \ + "\";\""\ + str(p.number_of_jukthakshar_per_30_words())\ + "\"\n" output_file.write(output_line) english_index_output_line = "\"" + str(test_file) \ + "\";\"" \ + str(c.automated_readability_index())\ + "\";\"" \ + str(c.gunning_fog_index())\ + "\";\"" \ + str(c.smog_index()) \ + "\";\""\ + str(c.flesch_reading_ease()) \ + "\";\"" \ + str(c.flesch_kincaid_grade_level()) \ + "\";\""\ + str(c.coleman_liau_index())\ + "\"\n" english_index_file.write(english_index_output_line) output_file.close() english_index_file.close() # Generate the index print "Generating the custom index using Correlation and Linear Regression..." g = Generator(asl, awl, asw, psw30, juk30, difficulty_scores, self.output_directory) g.generate() # Stop the training # Start testing # Write to output file print "Start testing on testing data..." print "Calculating stats for testing data..." print "Writing stats to " + self.output_directory + "\stats_testing.csv..." output_file = open(path.join(self.output_directory, 'stats_testing.csv'), 'w+') output_file.write("\"Filename\";\"ASL\";\"AWL\";\"ASW\";\"PSW30\";\"JUK30\"\n") print "Calculating English Indices on testing data..." print "Applying our custom formula to testing data..." print "Output written to " + self.output_directory + "\index_testing.csv..." index_file = open(path.join(self.output_directory, 'index_testing.csv'), 'w+') index_file.write("\"Filename\";" "\"Generated Index Value\";" "\"Automatic Readability Index\";" "\"Gunning Fog Index\";" "\"Smog Index\";" "\"Flesch Reading Ease\";" "\"Flesch Kincaid Grade Level\";" "\"Coleman Liau Index\"\n") # Walk through all files in tree for (dir_path, _, file_names) in walk(self.input_test_directory): for filename in file_names: test_file = path.join(dir_path, filename) # The index calculator c = Calculator(test_file) index = g.custom_index(test_file) # The parser p = c.parser # The output line output_line = "\"" + str(test_file) \ + "\";\"" \ + str(p.average_sentence_length())\ + "\";\"" \ + str(p.average_word_length())\ + "\";\"" \ + str(p.average_syllable_per_word()) \ + "\";\"" \ + str(p.number_of_polysyllables_per_30_words()) \ + "\";\""\ + str(p.number_of_jukthakshar_per_30_words())\ + "\"\n" output_file.write(output_line) index_output_line = "\"" \ + str(test_file) \ + "\";\"" \ + str(index) \ + "\";\"" \ + str(c.automated_readability_index())\ + "\";\"" \ + str(c.gunning_fog_index())\ + "\";\"" \ + str(c.smog_index()) \ + "\";\""\ + str(c.flesch_reading_ease()) \ + "\";\"" \ + str(c.flesch_kincaid_grade_level()) \ + "\";\""\ + str(c.coleman_liau_index())\ + "\"\n" index_file.write(index_output_line) output_file.close() index_file.close() print "End testing..." # Stop testing