Example #1
0
	def insert_stats(self):
		list = self.get_stats_list()
		if list:
			row = [None] * 6
			self.clist.clear()
			self.clist.freeze()
			for func in list:
				cc,nc,tt,ct,callers = self.stats.stats[func]
				row[0] = `nc`
				if nc != cc:
					row[0] = row[0] + '/' + `cc`
				row[1] = fpformat.fix(tt, 3)
				if nc == 0:
					row[2] = ''
				else:
					row[2] = fpformat.fix(tt/nc, 3)
				row[3] = fpformat.fix(ct, 3)
				if cc == 0:
					row[4] = ''
				else:
					row[4] = fpformat.fix(ct/cc, 3)
				file,line,name = func
				row[5] = file + ":" + `line` + "(" + name + \
					 ")"
				self.clist.append(row)
			self.clist.thaw()
Example #2
0
def getPosStr(orgPos):
    worldSize = bf2.gameLogic.getWorldSize()
    scale = [512.0 / worldSize[0], 1, 512.0 / worldSize[1]]
    pos = [orgPos[0] * scale[0], orgPos[1] * scale[1], orgPos[2] * scale[2]]
    res = str(fpformat.fix(pos[0], 3)) + "," + str(fpformat.fix(
        pos[1], 3)) + "," + str(fpformat.fix(pos[2], 3))
    return res
Example #3
0
def paintFunc(color='red', width=2):
    count = 200
    delta = abs(float((b0 - a0)) / count)
    x = a0
    ymax = F(x)
    ymin = F(x)
    while x < b0:
        if ymax < F(x): ymax = F(x)
        if ymin > F(x): ymin = F(x)
        x += delta
    labelYmax.configure(text=fpformat.fix(ymax, 1))
    labelYmin.configure(text=fpformat.fix(ymin, 1))
    kx = canvasWidth / abs(float(b0 - a0))
    ky = canvasHeight / abs(float(ymax - ymin))
    x = a0
    c.create_line(10,
                  canvasHeight,
                  canvasWidth,
                  canvasHeight,
                  width=2,
                  arrow=LAST)
    c.create_line(10, canvasHeight, 10, 0, width=2, arrow=LAST)
    #print '-'*60
    while x < b0:
        #print kx*(x-a0)+10, canvasHeight - ky*(F(x)-ymin), kx*((x-a0)+delta)+10,canvasHeight-ky*(F(x+delta)-ymin)
        c.create_line(kx * (x - a0) + 10,
                      canvasHeight - ky * (F(x) - ymin),
                      kx * ((x - a0) + delta) + 10,
                      canvasHeight - ky * (F(x + delta) - ymin),
                      width=width,
                      fill=color)
        x += delta
Example #4
0
def getPosStr(orgPos):
    worldSize = bf2.gameLogic.getWorldSize()
    scale = [512.0 / worldSize[0], 1, 512.0 / worldSize[1]]
    # 	scale = [1, 1, 1]
    pos = [orgPos[0] * scale[0], orgPos[1] * scale[1], orgPos[2] * scale[2]]
    res = str(fpformat.fix(pos[0], 3)) + "," + str(fpformat.fix(pos[1], 3)) + "," + str(fpformat.fix(pos[2], 3))
    return res
Example #5
0
def writeHtml(url, file, level, username, password):
    # Write out a HTML help document
    output = 0
    divs = 0
    response = urlOpenWithRetry(url, 30, 3, 1.1, username, password)
    for line in response.text.splitlines(True):
        if '<body>' in line:
            output = 1
            divs = 1
            continue
        if output == 1:
            for i in range(5, 0, -1):
                tmp = '<h' + fpformat.fix(i, 0) + ' '
                replace = '<h' + fpformat.fix(i + level, 0) + ' '
                if tmp in line:
                    line = re.sub(tmp, replace, line)
                tmp = '</h' + fpformat.fix(i, 0) + '>'
                replace = '</h' + fpformat.fix(i + level, 0) + '>'
                if tmp in line:
                    line = re.sub(tmp, replace, line)
            refs = re.findall('<a class="wiki" href="/trac/sa/wiki/([A-Za-z0-9]+)">', line);
            for ref in refs:
                references[ref] = 1
            if '</body>' in line:
                output = 0
            else:
                file.write(line)
    file.write("")
Example #6
0
def getFunction():
    global function, a0, b0
    function = 'функция: ' + func.formula
    function += 'interval: ' + fpformat.fix(
        (float(a0)), 2) + ' - ' + fpformat.fix(str(float(b0)), 2)
    function += '   eps= ' + str(eps)
    return function
Example #7
0
def stats(results, optimal=None):
    sum, notfound, worst = first_stats(results)
    avg = sum / len(results)
    varianza = fsum([(x - avg) ** 2 for x in results]) / len(results)
    scarto = fpformat.fix(sqrt(varianza), 2)
    valori = set(results)
    frequenze = dict(zip(valori, [results.count(v) for v in valori]))
    sorted_frequenze = sorted(frequenze, key=frequenze.get, reverse=True)
    sorted_frequenze = sorted_frequenze[:10]
    if optimal:
        opt_sum, opt_nf, opt_worst = first_stats(optimal)
        opt_avg = opt_sum / len(optimal)
        opt_scarto = fpformat.fix(sqrt(fsum([(x - opt_avg) ** 2 for x in optimal]) / len(optimal)), 2)
        ratio_avg = avg / opt_avg
        ratio_worst = worst / opt_worst
        ratio_scarto = fpformat.fix((float(scarto) / float(opt_scarto)), 2)

    print "-------------------------------------------------"
    print "Statistiche:\t\t\t\tOffline\tOnline\tRapporto"
    print "Numero di test eseguiti:\t\t " + str(len(results)) + "\t" + str(len(optimal))
#    print "Carburante esaurito:\t\t\t " + str(notfound)
    print "Caso peggiore:\t\t\t\t " + str(worst) + "\t" + str(opt_worst) + "\t" + str(ratio_worst)
    print "Media aritmetica dei risultati:\t\t " + str(avg) + "\t" + str(opt_avg) + "\t" + str(ratio_avg)
    print "Scarto quadratico medio:\t\t " + str(scarto) + "\t" + str(opt_scarto) + "\t" + str(ratio_scarto)
    print "I dieci risultati piu' riscontrati:"
    print "Costo:\tOttenuto:\tSotto la media?"
    for el in sorted_frequenze:
        sotto = "media"
        if el < avg:
            sotto = "si"
        elif el > avg:
            sotto = "no"
        print str(el) + "\t" + str(frequenze[el]) + "\t\t" + sotto
Example #8
0
 def insert_stats(self):
     list = self.get_stats_list()
     if list:
         row = [None] * 6
         model = self.list.get_model()
         for func in list:
             cc,nc,tt,ct,callers = self.stats.stats[func]
             row[0] = `nc`
             if nc != cc:
                 row[0] = row[0] + '/' + `cc`
             row[1] = fpformat.fix(tt, 3)
             if nc == 0:
                 row[2] = ''
             else:
                 row[2] = fpformat.fix(tt/nc, 3)
             row[3] = fpformat.fix(ct, 3)
             if cc == 0:
                 row[4] = ''
             else:
                 row[4] = fpformat.fix(ct/cc, 3)
             file,line,name = func
             row[5] = file + ":" + `line` + "(" + name + \
                      ")"
             self.list.get_model().append(row)
     return
def writeHtml(url, file, level, username, password):
    # Write out a HTML help document
    output = 0
    divs = 0
    response = urlOpenWithRetry(url, 30, 3, 1.1, username, password)
    for line in response.text.splitlines(True):
        # Remove all the annoying paragraph symbols.
        line = line.replace("&para;", "");
        if '<body>' in line:
            output = 1
            divs = 1
            continue
        if output == 1:
            for i in range(5, 0, -1):
                tmp = '<h' + fpformat.fix(i, 0) + ' '
                replace = '<h' + fpformat.fix(i + level, 0) + ' '
                if tmp in line:
                    line = re.sub(tmp, replace, line)
                tmp = '</h' + fpformat.fix(i, 0) + '>'
                replace = '</h' + fpformat.fix(i + level, 0) + '>'
                if tmp in line:
                    line = re.sub(tmp, replace, line)
            refs = re.findall('<a class="wiki" href="/trac/sa/wiki/([A-Za-z0-9]+)">', line);
            for ref in refs:
                references[ref] = 1
            if '</body>' in line:
                output = 0
            else:
                file.write(line)
    file.write("")
Example #10
0
def main():
    for j in range(len(data_sets)):
        dataset, attributes, target = import_dataset_csv(
            data_sets[j], target_positions[j])
        '''
        print "-------inizio dataset-----"
        print dataset
        print "------------"
        print attributi
        print "------------"
        print target
        print "------------"
        '''
        start = timer()
        end = timer()
        print(end - start)
        accuracy_train = []
        accuracy_validation = []
        accuracy_pruning_train = []
        accuracy_pruning_validation = []
        time = []
        pruning_time = []
        for i in range(0, len(percentages)):
            sys.stdout.write(
                "\r{0}".format("Analisi dataset:\"" + str(data_sets[j]) +
                               "\", Percentuale training:" +
                               str(percentages[i] * 100) + "%"))
            sys.stdout.flush()
            #TEST SENZA PRUNING
            start = timer()
            tmp = test(dataset, attributes, target, percentages[i],
                       num_test[j], 0)  #0 sta per senza pruning
            end = timer()
            accuracy_train.append(tmp[0])
            accuracy_validation.append(tmp[1])
            time.append(fpformat.fix((end - start), 4))

            #TEST PRUNING
            start = timer()
            tmp_pruning = test(dataset, attributes, target, percentages[i],
                               num_test[j], 1)  #1 sta per pruning
            end = timer()
            accuracy_pruning_train.append(tmp_pruning[0])
            accuracy_pruning_validation.append(tmp_pruning[1])
            pruning_time.append(fpformat.fix((end - start), 4))

        #OUTPUT PROGRAMMA
        create_plot(data_sets[j], percentages, accuracy_train,
                    accuracy_validation, 0)
        create_plot(data_sets[j], percentages, accuracy_pruning_train,
                    accuracy_pruning_validation, 1)
        plot_comparation(data_sets[j], percentages, accuracy_validation,
                         accuracy_pruning_validation)
        print " con numero di test per percentuale = " + str(num_test[j])
        print "Tempi esecuzione senza pruning:" + str(time)
        print "Tempi esecuzione con pruning:" + str(pruning_time)
        print "Percentuali di apprendimento:" + str(percentages)
        print "Accuratezza senza pruning:" + str(accuracy_validation)
        print "Accuratezza con pruning:" + str(accuracy_pruning_validation)
Example #11
0
def format_pos(bf2_object):
    if bf2_object:
        pos = bf2_object.getPosition()
        rot = bf2_object.getRotation()
        if pos and len(pos) == 3 and rot and len(rot) == 3:
            return (fpformat.fix(pos[0], 1) + ',' + fpformat.fix(pos[1], 1) +
                    ',' + fpformat.fix(pos[2], 1) + ',' +
                    fpformat.fix(rot[0], 1))
    return None
Example #12
0
def calc_support_resistance(symbol,
                            timeframe='day',
                            template_graph_conf="/tmp/graph.conf"):
    """
    计算阻力位和支撑位(轴心交易),使用周和月的
    日线图用 周的,周线图用 月的
    """
    graph_conf = None
    base_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
    conf_dir = "%s/conf" % (base_dir)
    if timeframe == "day":
        graph_conf = "%s/graph_template_%s.conf" % (conf_dir, timeframe)
        timeframe = "week"
    elif timeframe == "week":
        graph_conf = "%s/graph_template_%s.conf" % (conf_dir, timeframe)
        timeframe = "month"

    symbol = symbol.upper()
    cmd = "cd /home/hua.fu/geniustrader/Scripts;./display_indicator.pl --last-record --tight --timeframe=%s I:PP %s|grep -P '\[\d+[-/]\d+\]'" % (
        timeframe, symbol)
    #print "DEBUG indicator_cmd = %s" % cmd
    (status, output) = commands.getstatusoutput(cmd)
    if status != 0:
        return False
    pivot_data = output.split("=")[1].split("\t")[1:]
    #print "pivot_data = %s" % pivot_data
    fd = open(graph_conf)
    source_line = fd.readlines()
    replace_content = []
    fd.close()
    for line in source_line:
        #print line
        myrep = None
        if line.find('CenterPrice') != -1:
            myrep = line.replace('CenterPrice', fpformat.fix(pivot_data[0], 2))
        if line.find('FirstSupport') != -1:
            myrep = line.replace('FirstSupport',
                                 fpformat.fix(pivot_data[1], 2))
        if line.find('SecondSupport') != -1:
            myrep = line.replace('SecondSupport',
                                 fpformat.fix(pivot_data[2], 2))
        if line.find('FirstResistance') != -1:
            myrep = line.replace('FirstResistance',
                                 fpformat.fix(pivot_data[3], 2))
        if line.find('SecondResistance') != -1:
            myrep = line.replace('SecondResistance',
                                 fpformat.fix(pivot_data[4], 2))
        if myrep:
            replace_content.append(myrep)
        else:
            replace_content.append(line)

    tmp_file = template_graph_conf
    fd = open(tmp_file, "w")
    fd.writelines(replace_content)
    fd.close()
    return True
Example #13
0
def impri(m):
    print "\n"
    print "\t||" + ("\t" * (len(m[0]) + 1)) + "||"
    for i in range(len(m)):
        print "\t||\t",
        for j in range(len(m[0])):
            print fpformat.fix(m[i][j],2),"\t",
        print "||"
        print "\t||" + ("\t" * (len(m[0]) + 1)) + "||"
    print "\n"
Example #14
0
    def __get_sequences (self):
        """Get user sequences"""
#        stmt = """select sequence_name, min_value, max_value, increment_by, cycle_flag, order_flag, cache_size
#                      from user_sequences"""
        stmt = self._prepareStatement(OracleCatalog['sequences'])
        sequences = {}
        print "get sequences"
        for name, min_value, max_value, step, cycled, ordered, cache_size in self.__query(stmt):
            sequences[name] = fpformat.fix(min_value,0), str(max_value), fpformat.fix(step,0), cycled, ordered, fpformat.fix(cache_size,0)
        return sequences
Example #15
0
def format_pos(bf2_object):
    if bf2_object:
        pos = bf2_object.getPosition()
        rot = bf2_object.getRotation()
        if pos and len(pos) == 3 and rot and len(rot) == 3:
            return (fpformat.fix(pos[0], 1) + ','
                    + fpformat.fix(pos[1], 1) + ','
                    + fpformat.fix(pos[2], 1) + ','
                    + fpformat.fix(rot[0], 1))
    return None
Example #16
0
def update_db(db_cursor,cx,stock_list):
    """ update db from json file """
    # del data from db
    sql_cmd = "delete from stock"
    db_cursor.execute(sql_cmd)
    cx.commit()
    # insert db
    for stock_dict in stock_list:
        # determin record is already in db or not
        stock_exchange = stock_dict['exchange']
        stock_symbol = stock_dict['symbol']
        stock_title = stock_dict['title']
        note = stock_filter(stock_dict)
        if not note: continue
        #print stock_dict
        #stock_roi_ttm = stock_dict['ReturnOnInvestmentTTM'].replace(",","")
        stock_roi_ttm = stock_dict['ReturnOnInvestmentYear'].replace(",","")
        #stock_volume = stock_dict['Volume'].replace(",","") 
        #stock_avg_volume = stock_dict['AverageVolume'].replace(",","")
        stock_volume = "0"
        stock_avg_volume = "0"
        stock_price = stock_dict['QuoteLast'] 
        stock_50_avg = stock_dict['Price50DayAverage'] 
        stock_200_avg = stock_dict['Price200DayAverage'] 
        stock_eps = stock_dict['EPS'] 
        stock_bps = stock_dict['BookValuePerShareYear']
        #stock_dps = stock_dict['DividendPerShare'] 
        stock_dps = stock_dict['DividendYield'] #股息收益率 
        #stock_epsgrowthrate = stock_dict['EPSGrowthRate5Years']
        #stock_revenuegrowthrate = stock_dict['RevenueGrowthRate5Years']
        stock_cashpershare = stock_dict['CashPerShareYear']
        stock_debt2equity = stock_dict['TotalDebtToEquityYear'].replace(",","")
        stock_ldebt2equity = stock_dict['LTDebtToEquityYear'].replace(",","")
        stock_debt2asset = stock_dict['TotalDebtToAssetsYear']
        stock_earning_yield = 0
        stock_bps_yield = 0
        stock_cash_yield = 0
        if Decimal(stock_price) != 0:
            # 收益率 eps / price
            stock_earning_yield = fpformat.fix((float(stock_eps) / float(stock_price)),4)
            # 净资产比率  bps / price
            stock_bps_yield = fpformat.fix((float(stock_bps) / float(stock_price)),4)
            #stock_bps_yield = stock_dps
            # 现金流价格比率
            stock_cash_yield = fpformat.fix((float(stock_cashpershare) / float(stock_price)),4)


        sql_cmd = 'insert into stock values(NULL,"%s","%s","%s",%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,"%s")' % (stock_exchange,stock_title,stock_symbol,stock_price,stock_50_avg,stock_200_avg,stock_volume,stock_avg_volume,stock_eps,stock_bps,stock_dps,stock_roi_ttm,stock_earning_yield,stock_bps_yield,stock_cashpershare,stock_cash_yield,stock_debt2equity,stock_ldebt2equity,stock_debt2asset,note)
        try:
            db_cursor.execute(sql_cmd)
            cx.commit()
        except Exception,e:
            print "sql_cmd = " + sql_cmd
            print "%s : Error = %s" % (stock_symbol,e)
            sys.exit()
Example #17
0
    def start(self, screen):
        MATRIX_SIZE = self.get_matrix_size(screen)
        optimal_file = "OPTIMAL-" + str(MATRIX_SIZE) + ".result"
        RIDOTTI = True if self.get_param("Calcoli ridotti? [s/N]", screen, True) == 115 else False
        INPUTFILE = self.get_file("File da cui prendere i risultati per i calcoli ('Nessun file' per eseguire i calcoli)", screen, MATRIX_SIZE)
        OUTPUTFILE = self.get_file("File in cui salvare i risultati ('Nessun file' per non salvare)", screen, MATRIX_SIZE)
        try:
            f = open(optimal_file, 'r')
            optimal = [int(x) for x in f.readlines()]
            f.close()
            self.get_param("Trovato file con i risultati dell'algoritmo ottimale! (" + optimal_file + ")", screen, True)
        except:
            optimal = self.tests(MATRIX_SIZE, screen, knowledge=True, reduxed=RIDOTTI)
            self.save_results(optimal, optimal_file, screen)
        if not INPUTFILE == "":
            try:
                f = open(INPUTFILE, 'r')
                results = [int(x) for x in f.readlines()]
                f.close()
                self.get_param("Calcolo le statistiche dal file " + INPUTFILE, screen, True)
            except:
                self.get_param("File non trovato! Rieseguo i test", screen, True)
                results = self.tests(MATRIX_SIZE, screen, knowledge=False, reduxed=RIDOTTI)
        else:
            results = self.tests(MATRIX_SIZE, screen, knowledge=False, reduxed=RIDOTTI)
        if OUTPUTFILE:
            self.save_results(results, OUTPUTFILE, screen)

        not_found, worst, avg, scarto, frequenze, sorted_frequenze = self.stats(results)
        opt_not_found, opt_worst, opt_avg, opt_scarto, opt_frequenze, opt_sorted_frequenze = self.stats(optimal)
        ratio_avg = fpformat.fix(float(avg) / float(opt_avg), 2)
        ratio_worst = fpformat.fix(float(worst) / float(opt_worst), 2)
        ratio_scarto = fpformat.fix((float(scarto) / float(opt_scarto)), 2)
        screen.clear()
        screen.border(0)
        screen.addstr(2, 2, "Statistiche:\t\t\t\tOffline\t\tOnline\t\tRapporto")
        screen.addstr(4, 2, "Numero di test eseguiti:\t\t " + str(len(results)) + "\t\t" + str(len(optimal)))
        screen.addstr(6, 2, "Carburante esaurito:\t\t\t " + str(not_found) + "\t\t" + str(opt_not_found))
        screen.addstr(8, 2, "Caso peggiore:\t\t\t " + str(worst) + "\t\t" + str(opt_worst) + "\t\t" + str(ratio_worst))
        screen.addstr(10, 2, "Media aritmetica dei risultati:\t " + str(avg) + "\t\t" + str(opt_avg) + "\t\t" + str(ratio_avg))
        screen.addstr(12, 2, "Scarto quadratico medio:\t\t " + str(scarto) + "\t\t" + str(opt_scarto) + "\t\t" + str(ratio_scarto))
        screen.addstr(14, 1, "-" * (screen.getmaxyx()[1] - 2))
        screen.addstr(16, 2, "I dieci risultati piu' riscontrati nell'algoritmo non ottimale:")
        screen.addstr(18, 2, "Costo:\tOttenuto:\tSotto la media?")
        cnt = 20
        for el in sorted_frequenze:
            sotto = "media"
            if el < avg:
                sotto = "si"
            elif el > avg:
                sotto = "no"
            screen.addstr(cnt, 2, str(el) + "\t\t" + str(frequenze[el]) + "\t\t" + sotto)
            cnt += 2
        screen.addstr(cnt, 2, "Premere q per uscire")
        self.close(screen)
Example #18
0
def formatRetrunValue(key, cfgExceptionData):
	if cfgExceptionData.has_key('recommended'):
		if type(cfgExceptionData['value']) is float:
			return "%s = %s \t" % (key, fpformat.fix(cfgExceptionData['value'], 2))
		else:
			return "%s = %s \t" % (key, str(cfgExceptionData['value']))
	else:
		if type(cfgExceptionData['value']) is float:
			return "%s = %s \t" % (key, fpformat.fix(cfgExceptionData['value'], 2))
		else:
			return "%s = %s \t" % (key, str(cfgExceptionData['value']))
Example #19
0
def runDisEMBLpipeline():
    try:
        smooth_frame = 8
        peak_frame = 8
        join_frame = 4
        fold_coils = 1.2
        fold_hotloops = 1.4
        fold_rem465 = 1.2
        mode = 'scores'
        try:
            file = open(sys.argv[1], 'r')
        except:
            mode = 'default'
    except:
        print '\nDisEMBL.py sequence_file \n'
        print 'A default run would be: ./DisEMBL.py fasta_file'
        raise SystemExit
    #db = sys.stdin
    parser = Fasta.RecordParser()
    iterator = Fasta.Iterator(file, parser)
    while 1:
        try:
            cur_record = iterator.next()
            sequence = upper(cur_record.sequence)
            # Run NN
            COILS_raw, HOTLOOPS_raw, REM465_raw = JensenNet(sequence)
            # Run Savitzky-Golay
            REM465_smooth = SavitzkyGolay(smooth_frame, 0, REM465_raw)
            COILS_smooth = SavitzkyGolay(smooth_frame, 0, COILS_raw)
            HOTLOOPS_smooth = SavitzkyGolay(smooth_frame, 0, HOTLOOPS_raw)

            sys.stdout.write('> ' + cur_record.title + '\n')
            sys.stdout.write('# COILS ')
            reportSlicesTXT(
                getSlices(COILS_smooth, fold_coils, join_frame, peak_frame,
                          0.43), sequence)
            sys.stdout.write('# REM465 ')
            reportSlicesTXT(
                getSlices(REM465_smooth, fold_rem465, join_frame, peak_frame,
                          0.50), sequence)
            sys.stdout.write('# HOTLOOPS ')
            reportSlicesTXT(
                getSlices(HOTLOOPS_smooth, fold_hotloops, join_frame,
                          peak_frame, 0.086), sequence)
            sys.stdout.write('# RESIDUE COILS REM465 HOTLOOPS\n')
            for i in range(len(REM465_smooth)):
                sys.stdout.write(sequence[i] + '\t' +
                                 fpformat.fix(COILS_smooth[i], 5) + '\t' +
                                 fpformat.fix(REM465_smooth[i], 5) + '\t' +
                                 fpformat.fix(HOTLOOPS_smooth[i], 5) + '\n')
        except AttributeError:
            break
    file.close()
    return
Example #20
0
def displayTime(screen, time):
    global endtime, laptime
    str = string.rjust(fpformat.fix(float(laptime) / 1000, 2), 6)
    str2 = string.rjust(fpformat.fix(float(time) / 1000, 2), 6)
    globals.font12x9.blit(str2, screen, (2, 0.5), 80)
    if endtime != 0:
        t = pygame.time.get_ticks() - endtime
        if t > 3000:
            endtime = 0
        globals.font12x9.center("TIME:" + str, screen, 19)
        globals.font12x9.center("              ", screen, 19,
                                int(255 * (float(t) / 3000)))
Example #21
0
def calc_support_resistance(symbol, timeframe="day", template_graph_conf="/tmp/graph.conf"):
    """
    计算阻力位和支撑位(轴心交易),使用周和月的
    日线图用 周的,周线图用 月的
    """
    graph_conf = None
    base_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
    conf_dir = "%s/conf" % (base_dir)
    if timeframe == "day":
        graph_conf = "%s/graph_template_%s.conf" % (conf_dir, timeframe)
        timeframe = "week"
    elif timeframe == "week":
        graph_conf = "%s/graph_template_%s.conf" % (conf_dir, timeframe)
        timeframe = "month"

    symbol = symbol.upper()
    cmd = (
        "cd /home/hua.fu/geniustrader/Scripts;./display_indicator.pl --last-record --tight --timeframe=%s I:PP %s|grep -P '\[\d+[-/]\d+\]'"
        % (timeframe, symbol)
    )
    # print "DEBUG indicator_cmd = %s" % cmd
    (status, output) = commands.getstatusoutput(cmd)
    if status != 0:
        return False
    pivot_data = output.split("=")[1].split("\t")[1:]
    # print "pivot_data = %s" % pivot_data
    fd = open(graph_conf)
    source_line = fd.readlines()
    replace_content = []
    fd.close()
    for line in source_line:
        # print line
        myrep = None
        if line.find("CenterPrice") != -1:
            myrep = line.replace("CenterPrice", fpformat.fix(pivot_data[0], 2))
        if line.find("FirstSupport") != -1:
            myrep = line.replace("FirstSupport", fpformat.fix(pivot_data[1], 2))
        if line.find("SecondSupport") != -1:
            myrep = line.replace("SecondSupport", fpformat.fix(pivot_data[2], 2))
        if line.find("FirstResistance") != -1:
            myrep = line.replace("FirstResistance", fpformat.fix(pivot_data[3], 2))
        if line.find("SecondResistance") != -1:
            myrep = line.replace("SecondResistance", fpformat.fix(pivot_data[4], 2))
        if myrep:
            replace_content.append(myrep)
        else:
            replace_content.append(line)

    tmp_file = template_graph_conf
    fd = open(tmp_file, "w")
    fd.writelines(replace_content)
    fd.close()
    return True
Example #22
0
def make_test():

    optimal_file = "OPTIMAL-" + str(MATRIX_SIZE) + ".txt"
    try:
        f = open(optimal_file, 'r')
        optimal = [int(x) for x in f.readlines()]
        f.close()
        print "--------------------------------------------------------------------------------------"
        print "Trovato file con i risultati dell'algoritmo ottimale!\nNon verranno eseguiti nuovamente i test!"
        print "(se vuoi rieseguire i test, cancella il file " + optimal_file + ")"
    except:
        optimal = tests(MATRIX_SIZE, knowledge=True, reduxed=RIDOTTI)
        save_results(optimal, optimal_file)
    if INPUTFILE:
        try:
            f = open(INPUTFILE, 'r')
            results = [int(x) for x in f.readlines()]
            f.close()
            print "--------------------------------------------------------------------------------------"
            print "Calcolo le statistiche dal file " + INPUTFILE
        except:
            print "--------------------------------------------------------------------------------------"
            print "File non trovato! Rieseguo i test"
            results = tests(MATRIX_SIZE, knowledge=False, reduxed=RIDOTTI)
    else:
        results = tests(MATRIX_SIZE, knowledge=False, reduxed=RIDOTTI)
    if OUTPUTFILE:
        save_results(results, OUTPUTFILE)

    not_found, worst, avg, scarto, frequenze, sorted_frequenze = stats(results)
    opt_not_found, opt_worst, opt_avg, opt_scarto, opt_frequenze, opt_sorted_frequenze = stats(optimal)
    ratio_avg = fpformat.fix(float(avg) / float(opt_avg), 2)
    ratio_worst = fpformat.fix(float(worst) / float(opt_worst), 2)
    ratio_scarto = fpformat.fix((float(scarto) / float(opt_scarto)), 2)

    print "--------------------------------------------------------------------------------------"
    print "|Statistiche:\t\t\t\tOffline\t\tOnline\t\tRapporto"
    print "|Numero di test eseguiti:\t\t " + str(len(results)) + "\t\t" + str(len(optimal))
    print "|Carburante esaurito:\t\t\t " + str(not_found) + "\t\t" + str(opt_not_found)
    print "|Caso peggiore:\t\t\t\t " + str(worst) + "\t\t" + str(opt_worst) + "\t\t" + str(ratio_worst)
    print "|Media aritmetica dei risultati:\t\t " + str(avg) + "\t\t" + str(opt_avg) + "\t\t" + str(ratio_avg)
    print "|Scarto quadratico medio:\t\t " + str(scarto) + "\t\t" + str(opt_scarto) + "\t\t" + str(ratio_scarto)
    print "--------------------------------------------------------------------------------------"
    print "I dieci risultati piu' riscontrati nell'algoritmo non ottimale:"
    print "Costo:\tOttenuto:\tSotto la media?"
    for el in sorted_frequenze:
        sotto = "media"
        if el < avg:
            sotto = "si"
        elif el > avg:
            sotto = "no"
        print str(el) + "\t" + str(frequenze[el]) + "\t\t" + sotto
Example #23
0
    def test_failing_values(self):
        # Now for 'unreasonable n and d'
        self.assertEquals(fix(1.0, 1000), '1.'+('0'*1000))
        self.assertEquals(sci("1"+('0'*1000), 0), '1e+1000')

        # This behavior is inconsistent.  sci raises an exception; fix doesn't.
        yacht = "Throatwobbler Mangrove"
        self.assertEquals(fix(yacht, 10), yacht)
        try:
            sci(yacht, 10)
        except NotANumber:
            pass
        else:
            self.fail("No exception on non-numeric sci")
Example #24
0
    def test_failing_values(self):
        # Now for 'unreasonable n and d'
        self.assertEquals(fix(1.0, 1000), '1.' + ('0' * 1000))
        self.assertEquals(sci("1" + ('0' * 1000), 0), '1e+1000')

        # This behavior is inconsistent.  sci raises an exception; fix doesn't.
        yacht = "Throatwobbler Mangrove"
        self.assertEquals(fix(yacht, 10), yacht)
        try:
            sci(yacht, 10)
        except NotANumber:
            pass
        else:
            self.fail("No exception on non-numeric sci")
Example #25
0
    def checkFix(self, n, digits):
        result = fix(n, digits)
        if isinstance(n, StringType):
            n = repr(n)
        expected = "%.*f" % (digits, float(n))

        self.assertEquals(result, expected)
Example #26
0
    def checkFix(self, n, digits):
        result = fix(n, digits)
        if isinstance(n, StringType):
            n = repr(n)
        expected = "%.*f" % (digits, float(n))

        self.assertEquals(result, expected)
def cigar_parsing(q_name, q_len, cigar_data, value, r_name):
    mm = 0
    i = 0
    d = 0
    for item in cigar_data:
        if item[0] == 0:
            mm += item[1]
        elif item[0] == 1:
            i += item[1]
        elif item[0] == 2:
            d += item[1]
    align_len = mm + i + d
    query_aligned_len = float( mm + i )
    if query_aligned_len / q_len >= 0.7:
        if align_len != 0 and value >= 0:
            identity_percentage = ((align_len - value) / align_len) * 100
            if identity_percentage >= 93:
                evaluated_data = [q_name, r_name, fpformat.fix( identity_percentage, 2 ), str( value )]
                if align.is_read1:
                    evaluated_data.append( "r1\n" )
                elif align.is_read2:
                    evaluated_data.append( "r2\n" )
                return evaluated_data
            else:
                return None
Example #28
0
def cigar_parsing(q_name, q_len, cigar_data, value, r_name):
    mm = 0
    i = 0
    d = 0
    for item in cigar_data:
        if item[0] == 0:
            mm += item[1]
        elif item[0] == 1:
            i += item[1]
        elif item[0] == 2:
            d += item[1]
    align_len = mm + i + d
    query_aligned_len = float(mm + i)
    if query_aligned_len / q_len >= 0.7:
        if align_len != 0 and value >= 0:
            identity_percentage = ((align_len - value) / align_len) * 100
            if identity_percentage >= 93:
                evaluated_data = [
                    q_name, r_name,
                    fpformat.fix(identity_percentage, 2),
                    str(value)
                ]
                if align.is_read1:
                    evaluated_data.append("r1\n")
                elif align.is_read2:
                    evaluated_data.append("r2\n")
                return evaluated_data
            else:
                return None
Example #29
0
def writeEps():
    global epsCurrent, eps, labelEps
    if epsCurrent <= eps:
        fg = 'green'
    else:
        fg = 'red'
    labelEps.configure( text='интервал неопр.:' + fpformat.fix(float(epsCurrent),6), fg = fg)
Example #30
0
def onExitVehicle(player, vehicle):
    if player == None:
        return
    rootVehicle = bf2.objectManager.getRootParent(vehicle)
    vehicleType = getVehicleType(rootVehicle.templateName)
    playerTeam = str(player.getTeam())

    if vehicleType == VEHICLE_TYPE_SOLDIER:
        pass
    else:
        timeInVehicle = 0
        if player.fa.enterTemplate == rootVehicle.templateName:
            timeInVehicle = date() - player.fa.enterAt
        timeString = wallString()
        logfile.write(
            "EXIT PlayerName="
            + player.getName()
            + " PlayerTeam="
            + playerTeam
            + " VehicleName="
            + rootVehicle.templateName
            + " VehicleTime="
            + str(fpformat.fix(timeInVehicle, 1))
            + " Time="
            + timeString
            + "\n"
        )

    player.fa.enterAt = 0

    logfile.flush()
    return
Example #31
0
def solve(points, tour, currentDist):
    startTime = int(time.time())
    print("points: " + str(len(tour)) + " start tour" + str(tour))
    step = 0
    offset = lambda x: 1 if x == 1 else 0
    while True:
        # The best opt and distance.
        startStepTime = int(time.time())
        bestDist = currentDist
        bestThreeOpt = None
        tries = 0
        for i in range(1, len(tour) - 3):  
            for j in range(i + 1, len(tour) - 2):
                for k in range(j + 2, len(tour) - offset(i)):
                    #print("i: %d, j: %d, j+1: %d, k:%d" % (i, j, j +1, k))
                    tries += 1 
                    threeOpt = getBestThreeOpt(points, tour, currentDist, i, j, k)
                    if threeOpt.getEndDist() < bestDist:
                        bestDist = threeOpt.getEndDist()
                        bestThreeOpt = threeOpt
        step += 1
        utils.dprint("step: " + str(step) + ", tries: " + str(tries) + ", time: " + fpformat.fix(time.time() - startStepTime, 3))
        if bestDist == currentDist:
            # If no more improvement we are at a local minima and are done.
            print("no more improvement")
            break
        # Perform the opt.
        bestThreeOpt.swap();
        currentDist = bestDist
        if  int(time.time()) - startTime > maxTimeToRun:
            # Out of time, return the best we've got.
            print("out of time")
            break
    print("end tour" + str(tour))
    return 0, bestDist, tour
Example #32
0
 def getTotal(self, ano):
     """
     """
     if self.dados:
         total_universo = 0
         total_registro = 0
         total_taxa = 0
         for i in self.dados:
             if i['ano'] == ano:
                 try:
                     total_universo += int(i['universo'])
                     total_registro += int(i['qtd_ocorrencias'])
                 except:
                     pass
         if total_universo and total_registro:
             total_taxa = ((total_registro + .0) /
                           (total_universo + .0)) * 100000
             total_taxa = fpformat.fix(total_taxa, 2)
         return {
             'total_registro': total_registro,
             'total_taxa': total_taxa,
             'total_universo': total_universo
         }
     else:
         return {}
Example #33
0
    def getInfo(self):
        """
        """
        results = self.catalog(portal_type="sinesp",
                               tipo=self.tipo,
                               sort_on='uf',
                               sort_order='ascending')
        anos = self.getAnos()
        uf = self.getUF()

        if results:
            for i in results:
                dic = {
                    'tipo': i.tipo,
                    'uf': i.uf,
                    'ano': i.ano,
                    'qtd_ocorrencias': i.qtd_ocorrencias,
                    'taxa': '',
                    'universo': i.universo
                }
                try:
                    valor = float(i.taxa)
                    dic['taxa'] = fpformat.fix(valor, 2)
                except:
                    dic['taxa'] = i.taxa
                self.dados.append(dic)
        pass
Example #34
0
 def show_simple(self, args):
     #print fpformat.fix(1.0*self.num_instrs*self.ticks_per_cycle/self.num_ticks, 2), fpformat.fix(1.0*self.xbar_accs*self.ticks_per_cycle/self.num_ticks, 2), fpformat.fix(1.0*(self.num_MC_rds+self.num_MC_wrs)*self.ticks_per_cycle/self.num_ticks, 2),fpformat.fix(100.0*self.num_MC_acts/(self.num_MC_rds+self.num_MC_wrs), 2) + '%'
     #print fpformat.fix(1.0*self.num_instrs*self.ticks_per_cycle/self.num_ticks, 2), fpformat.fix(100.0*self.num_MC_acts/(self.num_MC_rds+self.num_MC_wrs), 2), args
     # the last one in the below line has a hack at the end
     print self.md.mdparams['pts.mc.scheduling_policy'], self.md.mdparams[
         'pts.mc.vmd_page_sz'], self.md.mdparams[
             'pts.mc.num_cached_pages_per_bank'], self.num_instrs, self.num_MC_rds + self.num_MC_wrs, self.num_MC_acts, fpformat.fix(
                 1.0 * self.num_instrs * self.ticks_per_cycle /
                 self.num_ticks, 2), fpformat.fix(
                     100.0 * self.num_MC_acts /
                     (self.num_MC_rds + self.num_MC_wrs), 2), fpformat.fix(
                         100 * (self.num_MC_acts - self.num_MC_pres +
                                self.num_RBoL_hits + self.num_RBoL_misses) /
                         (self.num_MC_rds + self.num_MC_wrs + 1),
                         2), self.num_DRAM_pages
     sys.exit()
Example #35
0
def SavitzkyGolay(window, derivative, datalist):
    if len(datalist) < 2 * window:
        window = len(datalist) / 2
    elif window == 0:
        window = 1
    command = SG_bin + ' -V0 -D' + str(derivative) + ' -n' + str(
        window) + ',' + str(window)
    args = shlex.split(command)
    proc = subprocess.Popen(args,
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)

    stdin = proc.stdin
    stdout = proc.stdout
    stderr = proc.stderr

    for data in datalist:
        stdin.write( ` data ` + '\n')
    try:
        stdin.close()
    except:
        print stderr.readlines()
    results = stdout.readlines()
    stdout.close()
    SG_results = []
    for result in results:
        f = float(fpformat.fix(result, 6))
        if f < 0:
            SG_results.append(0)
        else:
            SG_results.append(f)
    return SG_results
Example #36
0
    def getInfo(self):
        """
        """
        results = self.catalog(portal_type="sinesp",
                               tipo=self.tipo,
                               sort_on='uf',
                               sort_order='ascending')
        anos = self.getAnos()
        uf = self.getUF()

        if results:
            for i in results:
                dic = {
                    'tipo': i.tipo,
                    'uf': i.uf,
                    'ano': i.ano,
                    'qtd_ocorrencias': i.qtd_ocorrencias,
                    'taxa': '',
                    'universo': i.universo
                }
                try:
                    valor = float(i.taxa)
                    dic['taxa'] = fpformat.fix(valor, 2)
                except:
                    dic['taxa'] = i.taxa
                self.dados.append(dic)
        pass
Example #37
0
File: mdi.py Project: phasis/phasis
 def CnvPMPZ(self, evt): # tenuto per retrocompatibilita' con la 0.9.7, poi da eliminare
     self.val = "0"
     if(evt!=""):
         vl = evt.replace(".","")
         val = vl.replace(",",".")
         self.val = fpformat.fix(val,cfg.cdecPZ)
         self.val = float(val)
Example #38
0
def solve(vertices, vertexCount):
    percent = vertexCount / 20
    if percent == 0:
        percent = 1
    
    colors = [-1 for i in range(vertexCount)]
    neighborColors = []
    maxColor = 0

    # Sort vertices in decreasing order of degree
    #vertices.sort(key = lambda vertex : len(vertex.neighbors), reverse = True)
    vertices.sort(key = lambda vertex : len(vertex.neighbors))
        
    i = 0
    start = time.time()
    for vertex in vertices:
        # Not colored, pick a color.
        colorToUse, maxColor = getNextColor(vertex, colors, neighborColors, maxColor)
        colors[vertex.id] = colorToUse
        if i % percent == 0:
            sys.stdout.write(fpformat.fix(time.time() - start, 3) + " ")
            start = time.time()
        i += 1
        
    sys.stdout.write("\n")
            
    return colors, maxColor, 0    
    
Example #39
0
	def fillData(self,data):
		try:
			item = self.map[data]
		except KeyError:
			item = self.map["err"]
			
		self.nameLabel.set_label(item.name)
		self.priceLabel.set_label(fpformat.fix(item.price,2)+" "+EURO_SYMBOL)
		self.caloriesLabel.set_label("("+str(item.kcal)+" kcal / "+str(item.joul)+" kJ)")
		vegString = "("
		if(item.vegan):
			vegString+="ja/"
		else:
			vegString+="nein/"
			
		if(item.veggie):
			vegString+="ja)"
		else:
			vegString+="nein)"
		self.veggyLabel.set_label(vegString)
		
		#show window
		self.window.set_keep_below(False)
		self.window.set_keep_above(True)
		
		#sleep
		time.sleep(TIMESHOWN_INSECONDS)
		
		#hide window
		self.window.set_keep_above(False)
		self.window.set_keep_below(True)
Example #40
0
    def SalvaLista(self):
        Rotinas = RotinasGlobais.Rotinas
        ConsSQL = ConsultasSQL.ConsSQL
        nQtd = self.lstLivros.GetCount()
        sCPF = self.edtCodigo.GetValue()
        sPrecoTotal = fpformat.fix(self.nPrecoTotal, 2)

        sDTHR = self.edtDtHrVenda.GetValue()
        sDataHora = Rotinas.ConverteDataHoraStr(sDTHR, True, "%m/%d/%Y",
                                                "%H:%M:%S")

        for nCont in range(0, nQtd):
            sISBN = self.slISBNs.col[nCont]

            Rotinas.AtualizaDados(
                Rotinas.gConexao,
                ConsSQL.Venda('I', sISBN, sCPF, sDataHora,
                              Rotinas.VirgulaParaPonto(sPrecoTotal, False),
                              ""))

            nQtdEstoque = int(self.slQtdEstoque.col[nCont])
            if nQtdEstoque > 0:
                nQtdEstoque = nQtdEstoque - 1
            sQtdEstoque = str(nQtdEstoque)
            Rotinas.AtualizaDados(
                Rotinas.gConexao,
                ConsSQL.Venda('U', sISBN, "", "", "", sQtdEstoque))

        return True
Example #41
0
    def SalvaLista(self):
        nQtd = self.lstLivros.getNumItems()
        sCPF = self.edtCodigo.getText()
        sPrecoTotal = fpformat.fix(self.nPrecoTotal, 2)

        sDTHR = self.edtDtHrVenda.getText()
        sDataHora = self.Rotinas.ConverteDataHoraStr(sDTHR, True, "%m/%d/%Y",
                                                     "%H:%M:%S")

        for nCont in range(0, nQtd):
            sISBN = self.slISBNs.col[nCont]

            self.Rotinas.AtualizaDados(
                self.Rotinas.gConexao,
                self.ConsSQL.Venda(
                    'I', sISBN, sCPF, sDataHora,
                    self.Rotinas.VirgulaParaPonto(sPrecoTotal, False), ""))

            nQtdEstoque = int(self.slQtdEstoque.col[nCont])
            if nQtdEstoque > 0:
                nQtdEstoque = nQtdEstoque - 1

            sQtdEstoque = str(nQtdEstoque)
            self.Rotinas.AtualizaDados(
                self.Rotinas.gConexao,
                self.ConsSQL.Venda('U', sISBN, "", "", "", sQtdEstoque))

        return True
Example #42
0
def get_relative_point_position(coord_a, coord_b):
    # type: (Point, Point) -> (float, float, float)
    try:
        # get point b distance, azimuth and elevation relative point a
        ap = _location_to_point(coord_b)
        bp = _location_to_point(coord_a)

        distance_km = fix(0.001 * _target_distance(ap, bp), 10)
        br = _rotate_globe(coord_b, coord_a, bp['radius'])
        if br['z'] * br['z'] + br['y'] * br['y'] > 1.0e-06:
            theta = degrees(atan2(br['z'], br['y']))
            azimuth = 90.0 - theta
            if (azimuth < 0.0):
                azimuth += 360.0
            if (azimuth > 360.0):
                azimuth -= 360.0
        else:
            azimuth = 0.0

        bma = _normalize_vector_diff(ap, bp)
        if bma:
            bearing = 90.0 - degrees(
                acos(bma['x'] * bp['nx'] + bma['y'] * bp['ny'] +
                     bma['z'] * bp['nz']))
        else:
            bearing = 0.0
        return bearing, azimuth, distance_km
    except:
        pass
Example #43
0
	def generateErrorDetailsHTMLPage(self,error,fileName):
		"""Generate the HTML with the detail of a single error"""
		page=self.getHTMLHeader(error.getName())
		#Write the title of the page
		page=page+'<h1 align="center">Error of '+self.subsystemName+'::'+error.getName()+'</h1>\n'
		page=page+'<p align="center">Generated scanning the basedir <I>'+self.baseDir+'</I><BR>\n'
		page=page+'<FONT size="-1">Generated at '+self.startTime+'</FONT></P>'
		page=page+'<HR size="3" width="80%" align="center">\n'
		
		#Generate the table with the error details
		page=page+self.generateHTMLForDetailedError(error, '', '')
		
		page=page+'<H2>Info and errors</H2>'
		
		if self.testAndExampleErrors.count(error.getNumber())>0:
			page=page+'<P>This error is used for test/examples</P>'
		else:
			if self.outOfRangeErrors.count(error.getNumber())>0:
				page=page+'<P><FONT color="red">The error number is out of the allowed range for this subsystem</FONT></P>'
			else:
				page=page+'<P>The number is in the corrrect range</P>'
			if self.duplicatedErrors.count(error.getNumber())>0:
				page=page+'<P><FONT color="red">There is another error in this subsystem with the same number</FONT></P>'
			else:
				page=page+'<P>The error is not duplicated</P>'
		
		# Final infos
		page=page+'<BR><HR size="3" width="80%" align="center">\n'
		page=page+'<P><FONT size="-1">Subsystem scanned in '+fpformat.fix(self.endFloatTime-self.startFloatTime,3)+' seconds.</FONT></P>'
		
		page=page+self.getHTMLFooter()
		self.writeHTMLOnFile(page, fileName)
Example #44
0
	def generateErrorDetailsHTMLPage(self,error,fileName):
		"""Generate the HTML with the detail of a single error"""
		page=self.getHTMLHeader(error.getName())
		#Write the title of the page
		page=page+'<h1 align="center">Error of '+self.subsystemName+'::'+error.getName()+'</h1>\n'
		page=page+'<p align="center">Generated scanning the basedir <I>'+self.baseDir+'</I><BR>\n'
		page=page+'<FONT size="-1">Generated at '+self.startTime+'</FONT></P>'
		page=page+'<HR size="3" width="80%" align="center">\n'
		
		#Generate the table with the error details
		page=page+self.generateHTMLForDetailedError(error, '', '')
		
		page=page+'<H2>Info and errors</H2>'
		
		if self.testAndExampleErrors.count(error.getNumber())>0:
			page=page+'<P>This error is used for test/examples</P>'
		else:
			if self.outOfRangeErrors.count(error.getNumber())>0:
				page=page+'<P><FONT color="red">The error number is out of the allowed range for this subsystem</FONT></P>'
			else:
				page=page+'<P>The number is in the corrrect range</P>'
			if self.duplicatedErrors.count(error.getNumber())>0:
				page=page+'<P><FONT color="red">There is another error in this subsystem with the same number</FONT></P>'
			else:
				page=page+'<P>The error is not duplicated</P>'
		
		# Final infos
		page=page+'<BR><HR size="3" width="80%" align="center">\n'
		page=page+'<P><FONT size="-1">Subsystem scanned in '+fpformat.fix(self.endFloatTime-self.startFloatTime,3)+' seconds.</FONT></P>'
		
		page=page+self.getHTMLFooter()
		self.writeHTMLOnFile(page, fileName)
Example #45
0
def world_generator_with_knowledge(size, x_end, y_end):
    world = Graph(x_end, y_end)
    for i in range(size):
        for j in range(size):
            world.add_node_coord((i, j))
            world.change_weight((i, j), float(fpformat.fix(math.sqrt(math.fabs(pow((x_end - i), 2) + pow((y_end - j), 2))), 3)))
    world.change_weight((x_end, y_end), -1)
    return world
Example #46
0
def update_ingredient_price(sender, instance, raw, using, update_fields,
                            **kwargs):
    try:
        new_price = instance.price / float(instance.quanlity_of_bottle)
    except Exception as e:
        new_price = 0
    new_price = float(fpformat.fix(new_price, 2))
    instance.price_per_ml = new_price
Example #47
0
def world_generator(size, x_end, y_end, knowledge):
    # Controllo se si richiede un mondo con il knowledge degli stati o meno
    if knowledge:
        world = Graph(x_end, y_end)
        for i in range(size):
            for j in range(size):
                world.add_node_coord((i, j))
                world.change_weight((i, j), float(fpformat.fix(math.sqrt(math.fabs(pow((x_end - i), 2) + pow((y_end - j), 2))), 3)))
        world.change_weight((x_end, y_end), -1)
        return world
    else:
        matrix = [[0 for i in range(size)] for j in range(size)]
        for i in range(size):
            for j in range(size):
                matrix[i][j] = float(fpformat.fix(math.sqrt(math.fabs(pow((x_end - i), 2) + pow((y_end - j), 2))), 3))
        matrix[x_end][y_end] = -1
        return matrix
Example #48
0
def matrix_generator(size, startPoint, arrivePoint):
 matrix = [ [ 0 for i in range(size)] for j in range(size) ]
 for i in range(size):
  for j in range(size):
   matrix[i][j] = [fpformat.fix(math.sqrt(math.fabs(pow((arrivePoint[0] - i),2) + pow((arrivePoint[1] - j), 2))),3),"*"]
 matrix[startPoint[0]][startPoint[1]][1] = "S"
 matrix[arrivePoint[0]][arrivePoint[1]] = [-2.22,"A"]
 return matrix
Example #49
0
File: mdi.py Project: phasis/phasis
 def CnvPMPZ(
         self, evt
 ):  # tenuto per retrocompatibilita' con la 0.9.7, poi da eliminare
     self.val = "0"
     if (evt != ""):
         vl = evt.replace(".", "")
         val = vl.replace(",", ".")
         self.val = fpformat.fix(val, cfg.cdecPZ)
         self.val = float(val)
Example #50
0
def evalRow(row):
    """
    Finds and returns the housing and population densities
    for a given place along with the place's name.
    
    Density is given in feet per person.
    """
    if row["Population"] == '0':
        densityP = 0
    else:
        densityP = int(row["Land Area"])/int(row["Population"])
    
    if row["Housing Units"] == '0':
        densityH = 0
    else:
        densityH = int(row["Land Area"])/int(row["Housing Units"])
    
    return [row["Name"], fpformat.fix(densityP, 2), fpformat.fix(densityH, 2)]
def deg2str_hms(deg):
	deg = deg/15.0
	hour_temp = int(deg)
	str_hour = str(hour_temp)
	temp = (deg - int(deg))*3600.0
	min = int(temp/60)
	str_min = str(min)
	str_sec = str(fpformat.fix((deg*3600.0 - hour_temp*3600.0 - 60.0*min),2))
	final_str = str_hour.zfill(2)+":"+str_min.zfill(2)+":"+str_sec.zfill(5)
	return final_str
Example #52
0
File: mdi.py Project: phasis/phasis
 def CnvPM(self, evt): # tenuto per retrocompatibilita' con la 0.9.7, poi da eliminare
     self.val = "0"
     if evt=='FC' or evt=='E74' or evt=='E72' or evt=='20C' : evt = "0"
     #if evt=='FC': evt = 0
     if(evt!=""):  ####
         vl = evt.replace(".","")  ####
         val = vl.replace(",",".")  ####
         self.val = fpformat.fix(val,2)  ####
         #print '-'+ val + '-'
         #if val!="": 0
         self.val = float(val)  ####            
Example #53
0
 def getNumber(self, number, number_dec):
     numberInt = int(number)
     numberIntStr = self.__numberFormat(numberInt)
     numberFloat = float(number)
     numberFloatStr = fpformat.fix(numberFloat, number_dec)
     if string.find(numberFloatStr, ".") != -1:
         decStr = string.split(numberFloatStr, ".")[1]
         numberStr = numberIntStr + self.CommaSep + decStr
     else:
         numberStr = numberIntStr
     return numberStr
Example #54
0
def onDropKit(player, kit):
    timeInVehicle = 0
    if player.fa.spawnAt != 0:
        timeInVehicle = date() - player.fa.spawnAt
    timeString = wallString()
    playerTeam = str(player.getTeam())
    logfile.write("DROPKIT PlayerName=" + player.getName() + " PlayerTeam=" +
                  playerTeam + " PlayerKit=" + kit.templateName +
                  " PlayerKitTime=" + str(fpformat.fix(timeInVehicle, 1)) +
                  " Time=" + timeString + "\n")
    logfile.flush()
    return
Example #55
0
def DEBUG(str, stop=false):
    if not debug:
        return

    global _debug__
    _debug__ = _debug__ + 1
    print("\nDEBUG" + fpformat.fix(_debug__, 0))

    if stop:
        raw_input(str)
    else:
        print(str)
Example #56
0
def DEBUG(str, stop=false):
    if not debug:
        return

    global _debug__
    _debug__ = _debug__ + 1
    print("\nDEBUG" + fpformat.fix(_debug__, 0))
    
    if stop:
        raw_input(str)
    else:
        print(str)
Example #57
0
def JensenNet(sequence):
    outFile = tempfile.mktemp()
    inFile = tempfile.mktemp()
    open(inFile, 'w').write(sequence + '\n')
    system(NN_bin + '< ' + inFile + ' > ' + outFile)
    REM465 = []
    COILS = []
    HOTLOOPS = []
    resultsFile = open(outFile, 'r')
    results = resultsFile.readlines()
    resultsFile.close()
    for result in results:
        coil = float(fpformat.fix(split(result)[0], 6))
        COILS.append(coil)
        hotloop = float(fpformat.fix(split(result)[1], 6))
        HOTLOOPS.append(hotloop)
        rem465 = float(fpformat.fix(split(result)[2], 6))
        REM465.append(rem465)
    os.remove(inFile)
    os.remove(outFile)
    return COILS, HOTLOOPS, REM465
Example #58
0
def JensenNet(sequence):
    outFile = tempfile.mktemp()
    inFile= tempfile.mktemp()
    open(inFile,'w').write(sequence+'\n')
    system(NN_bin + '< ' + inFile +' > ' + outFile)
    REM465 = []
    COILS = []
    HOTLOOPS = []
    resultsFile = open(outFile,'r')
    results = resultsFile.readlines()
    resultsFile.close()
    for result in results:
        coil = float(fpformat.fix(split(result)[0],6))
        COILS.append(coil)
        hotloop = float(fpformat.fix(split(result)[1],6))
        HOTLOOPS.append(hotloop)
        rem465 = float(fpformat.fix(split(result)[2],6))
        REM465.append(rem465)
    os.remove(inFile)
    os.remove(outFile)
    return COILS, HOTLOOPS, REM465
Example #59
0
def infer_bg(distance_file, taxon, rank, outfolder):
    intra = []
    extra = []
    intra_str, extra_str = inclusion_set(rank)
    bg = None
    with gzip.open(distance_file) as a:
        for line in a:
            field = map(strip, line.split("\t"))
            if taxon in field and field[3] in intra_str:
                intra.append(float(field[2]))
            elif taxon in field and field[3] in extra_str:
                extra.append(float(field[2]))
    if len(extra) and len(intra):
        bg_mean = fpformat.fix(mean(extra) - mean(intra), 2)
        bg_diff = fpformat.fix(min(extra) - max(intra), 2)
        plot = plot_distance_dist(intra, extra, taxon, outfolder)
        bg = [bg_mean, bg_diff, plot]
    elif len(intra) == 0:
        bg = "No intra%s data" % rank
    elif len(extra) == 0:
        bg = "No extra%s data" % rank
    return bg