Exemplo n.º 1
0
def create_program_summary(program):
	summary = "%s, %s - %s\n\n%s" % (
		IDS_TODAY_LABEL if common.is_time_today(program.start_time) else common.get_date(program.start_time),
		common.get_time(program.start_time),
		common.get_time(program.start_time + program.duration),
		create_summary(program))
	return summary
Exemplo n.º 2
0
def create_program_summary(program):
    summary = "%s, %s - %s\n\n%s" % (IDS_TODAY_LABEL if common.is_time_today(
        program.start_time) else common.get_date(program.start_time),
                                     common.get_time(program.start_time),
                                     common.get_time(program.start_time +
                                                     program.duration),
                                     create_summary(program))
    return summary
Exemplo n.º 3
0
def run_method_agents(method, agents):
    grin_method = common.get_method('grin')
    berlang_method = common.get_method('berlang')

    xs = []
    ys = []
    ys2 = []
    ys3 = []
    for agent in agents:
        print('prog:{}'.format(agent), end='\r')
        ys.append(common.test_progressive(agent, 'U', 1, 0.5)['wait'])
        print('grin:{}'.format(agent), end='\r')
        ys2.append(grin_method(0.03, agent, 'U', 1, 0.5)['wait'])
        print('berlang:{}'.format(agent), end='\r')
        ys3.append(berlang_method(0.03, agent, 'U', 1, 0.5)['wait'])
        xs.append(agent)
        plt.clf()
        plt.plot(xs, ys, xs, ys2, xs, ys3)
        plt.legend(('Progressive wait ratio', 'Grin wait ratio', 'B-Erlang wait ratio'))
        plt.xlabel('Agent number')
        plt.ylabel('Ratio')
        plt.grid(True)
        plt.title('Methods ' + ' perfomance with different agent numbers')
        plt.savefig(common.get_time() + 'agents_' + 'compare' + '_file.png')
    print('\n')
Exemplo n.º 4
0
def loghandler():
    '''日志处理函数'''

    global Log
    global GameLog

    print('服务器日志启动')
    while True:
        sleep(10)  # 间隔多长时间记录一次
        path = os.getcwd() + LOG_PATH + '/{}'\
            .format(get_time()[:10])
        if not os.path.exists(path):
            os.mkdir(path)
        if Log:
            print(Log)
            with open(path + '/log.txt', 'a') as f:
                logwrite = Log
                Log = Log[len(logwrite):]
                for line in logwrite:
                    f.write(line + '\n')
        if GameLog:
            print(GameLog)
            with open(path + '/gamelog.txt', 'a') as f2:
                gamelogwrite = GameLog
                GameLog = []
                for line in gamelogwrite:
                    f2.write(line + '\n')
Exemplo n.º 5
0
 def __init__(self, paras):
     """
     连接到指定的mongodb数据库
     """
     self._db = get_mongodb_client(paras)[DB]
     self.time_dict = get_time()
     self.infl_scale = 0
Exemplo n.º 6
0
def run_method_critical(method, criticals):
    method_run = common.get_method(method)
    xs = []
    ys = []
    ys2 = []
    ys3 = []
    ys4 = []
    ys5 = []
    for critical in criticals:
        print('Running with critical:{}'.format(critical))
        res = method_run(critical, 20, 'U', 1, 0.5)
        xs.append(critical)
        ys.append(res['abandon'])
        ys2.append(res['wait'])
        ys3.append(0.03)
        ys4.append(common.test_progressive(20, 'U', 1, 0.5)['wait'])
        ys5.append(res['limited'])
        print(critical, end='\r')

        plt.clf()
        plt.plot(xs, ys, xs, ys2, xs, ys3, xs, ys4, xs, ys5)
        plt.legend(('Abandon ratio', 'Wait ratio', '0.03 ratio',
                    'Progressive wait ratio', 'Progressive limited ratio'))
        plt.xlabel('Critical value')
        plt.ylabel('Ratio')
        plt.grid(True)
        plt.title(
            common.get_nice_name(method) +
            ' perfomance with different critical values')

    plt.savefig(common.get_time() + 'critical_' + method + '_file.png')
    print('\n')
Exemplo n.º 7
0
def build_graph(lemma_cmd, proof_cmds):
    lemma_name = lemma_name_from_statement(getAddBody(lemma_cmd))
    graph = ProofGraph(getAddBody(lemma_cmd))
    next_node_id = 1
    states = [(get_id(lemma_cmd), graph.start_node)]
    state_map = {}
    for cmd in proof_cmds:
        if isAdd(cmd):
            most_recent_state, most_recent_node = states[-1]
            if shouldFilterCommand(cmd):
                state_map[get_id(cmd)] = most_recent_state
                continue
            states.append((get_id(cmd),
                           graph.mkNode(sanitizeTactic(getAddBody(cmd)),
                                        datetime.fromtimestamp(get_time(cmd)),
                                        most_recent_node)))
            next_node_id += 1
            if isFinishingProofCmd(getAddBody(cmd)):
                for statenum, node in states:
                    graph.setNodeColor(node, "blue")
        if isFailed(cmd):
            most_recent_state, most_recent_node = states[-1]
            graph.setNodeColor(most_recent_node, "red")
        if isCancel(cmd):
            cancel_dest = getCancelDest(cmd)
            cancel_dest = state_map.get(cancel_dest, cancel_dest)
            while len(states) > 0 and states[-1][0] != cancel_dest:
                states.pop()
            assert len(states) > 0
    if not os.path.exists("graphs"):
        os.mkdir("graphs")
    graph_filename = "graphs/" + lemma_name + ".svg"
    graph.draw(graph_filename)
    return graph
Exemplo n.º 8
0
def run_method_busy(busies):
    grin_method = common.get_method('grin')
    berlang_method = common.get_method('berlang')

    xs = []
    ys = []
    ys2 = []
    ys3 = []
    for busy in busies:
        print('prog:{}'.format(busy), end='\r')
        ys.append(common.test_progressive(20, 'U', 1, busy)['wait'])
        print('grin:{}'.format(busy), end='\r')
        ys2.append(grin_method(0.03, 20, 'U', 1, busy)['wait'])
        print('berlang:{}'.format(busy), end='\r')
        ys3.append(berlang_method(0.03, 20, 'U', 1, busy)['wait'])
        xs.append(busy)
        plt.clf()
        plt.plot(xs, ys, xs, ys2, xs, ys3)
        plt.legend(('Progressive wait ratio', 'Grin wait ratio', 'B-Erlang wait ratio'))
        plt.xlabel('busy ratio')
        plt.ylabel('Ratio')
        plt.grid(True)
        plt.title('Methods ' + 'perfomance with different busy ratios')
        plt.savefig(common.get_time() + 'busy' + 'compare'+ 'busy' + '_file.png')
    print('\n')
Exemplo n.º 9
0
 def set_frame(self, index, force = False):
     if not force:
         self.next_frame = index
         return
     if self.frame:
         self.frame.destroy()
     self.frame = FRAMES[index](self)
     self.current_time = get_time()
Exemplo n.º 10
0
def get_class_parameters(kwarg):
    ret = {'attrs': []}
    for key in ('rsc', 'fsc', 'usc'):
        if key in kwarg:
            ret['attrs'].append(['TCA_HFSC_%s' % key.upper(),
                                 {'m1': get_rate(kwarg[key].get('m1', 0)),
                                  'd': get_time(kwarg[key].get('d', 0)),
                                  'm2':get_rate(kwarg[key].get('m2', 0))}])
    return ret
Exemplo n.º 11
0
 def update_loop(self):
     try:
         if self.next_frame is not None:
             self.set_frame(self.next_frame, True)
             self.next_frame = None
             return
         self.loop_count += 1
         current_time = get_time()
         dt = current_time - self.current_time
         self.current_time = current_time
         self.audio.update(dt)
         self.make_update(dt)
     except:
         import traceback
         traceback.print_exc()
         self.exit()
Exemplo n.º 12
0
def run_method_ratios(dist, ratios):
    grin_method = common.get_method('grin')
    berlang_method = common.get_method('berlang')

    xs = []
    ys = []
    ys2 = []
    ys3 = []
    for ratio in ratios:
        print('prog:{}'.format(ratio), end='\r')
        ys.append(common.test_progressive(20, dist, ratio, 0.5)['wait'])
        print('grin:{}'.format(ratio), end='\r')
        ys2.append(grin_method(0.03, 20, dist, ratio, 0.5)['wait'])
        print('berlang:{}'.format(ratio), end='\r')
        ys3.append(berlang_method(0.03, 20, dist, ratio, 0.5)['wait'])
        xs.append(ratio)
        plt.clf()
        plt.plot(xs, ys, xs, ys2, xs, ys3)
        plt.legend(('Progressive wait ratio', 'Grin wait ratio',
                    'B-Erlang wait ratio'))
        plt.ylabel('Ratio')
        plt.grid(True)
        if (dist == 'E'):
            plt.xlabel('service to setup lambda ratio')
            name = 'exponentially'
            plt.title(
                'Perfomance with different service to setup lambda ratio.\nBoth distributed '
                + name + '.')
        else:
            plt.xlabel('service to setup ratio')
            name = 'uniformly'
            plt.title(
                'Perfomance with different service to setup ratio.\nBoth distributed '
                + name + '.')

        plt.savefig(common.get_time() + 'dist' + 'compare' + name +
                    '_file.png')
    print('\n')
Exemplo n.º 13
0
import logging
import os
from common import get_time

# 初始化日志默认配置
LOG_PATH = '/log'
path = os.getcwd() + LOG_PATH + '/{}'.format(get_time()[:10])
if not os.path.exists(path):
    os.mkdir(path)
fmt = '%(asctime)s %(levelname)s Line:%(lineno)s==>%(message)s'
logging.basicConfig(
    filename=path + '/game.log',  # 日志输出文件
    level=logging.DEBUG,  # 日志写入级别
    datefmt='%Y-%m-%d %H:%M:%S',  # 时间格式
    format=fmt)  # 日志写入格式
Exemplo n.º 14
0
def create_program_title(program, is_record, is_series_record, is_conflicting):
	title = "%s  %s" % (common.get_time(program.start_time), create_recording_title(program, is_record, is_series_record, is_conflicting))
	return title
 def get_save_path(self):
     return config.local_storage_path + common.get_time(
     ) + os.sep, common.get_time() + os.sep
Exemplo n.º 16
0
def _get_log_path():
    return config.log_path + common.get_time() + '_flask.log'
Exemplo n.º 17
0
 def __init__(self, paras):
     self._db = get_mongodb_client(paras)[DB]
     self.time_dict = get_time()
     self._coll_app_comts = self._db['app_comments']
     self._coll_app_det = self._db['app_detail']
     self._coll_app_bd = self._db['app_bangdan']
Exemplo n.º 18
0
def get_commands(logdir, user, session_label):
    with open(f"{logdir}/{user}-sessions/{session_label}",
              'r') as session_file:
        return sorted([loads(line) for line in session_file.readlines()],
                      key=lambda cmd: get_time(cmd))
Exemplo n.º 19
0
import unittest
from HTMLTestReportCN import HTMLTestRunner
from common import get_time, REPORTPATH

datetime = get_time()
tests = unittest.defaultTestLoader.discover('')
f = open(REPORTPATH + '/' + '接口' + datetime + '.html', 'wb')
runner = HTMLTestRunner(stream=f, title='接口自动化测试报告', tester='linlin')
runner.run(tests)
f.close()
Exemplo n.º 20
0
 def except_deal(self, user):
     self.Log.append(get_time() + '用户退出' + user.user_name)
     self.deal_quit(user, self)
     pass
Exemplo n.º 21
0
def simulate(sim_data):
    scrip    = sim_data['SC']
    trans    = sim_data['TP']
    capt     = sim_data['CP']
    sl       = sim_data['SL']
    tar1     = sim_data['T1']
    tar2     = sim_data['T2']
    start    = sim_data['TS']
    end_time = sim_data['EN']
    sim_name = sim_data['NM']
    sim_type = sim_data['ST']
    str_id   = sim_data['ID']
    data     = sim_data['DATA']
    sl_val  = 0
    t1_val  = 0
    t2_val  = 0
    t1_vol  = 0
    t2_vol  = 0
    vol     = 0
    results = {}
    entry   = 0
    status  = ""
    end     = c.get_timestamp(c.get_only_date(start)+" "+end_time)
    sim_id  = c.gen_id("sim_tracker","sim_id")
    
    c.pr("I","Starting simulation for [SIM ID -> "+sim_id+"] [Scrip -> "+scrip +"] [Type -> "+sim_type+"] [Transaction -> "+trans+"] [Entry Point ->  "+c.get_date(start)+"] [Capital -> "+str(capt)+"] [T1 -> "+str(tar1)+"%] [T2 -> "+str(tar2)+"%] [SL -> "+str(sl)+"%]",1)
    #Step 1 Load the Scrip
   
    #data  = c.fetch_scrip_data(scrip,start,end)
    #data  = c.fetch_scrip_cache(cdata,start,end)
    tkeys = list(data.keys())
    tkeys.sort()
    tctr = 0
    for tk in tkeys:
        if tk == start:
            break
        else:
            tctr += 1
    tkeys = tkeys[tctr:]
    #Step 2 Take entry at the entry point at average price of first data candle
    entry   = tkeys[0]
    ep_data = data[tkeys[0]]
    #Removing key which corresponds to EP
      
    tkeys.pop(0)
    avg_ent = round((ep_data['open'] + ep_data['close'] + ep_data['high'] + ep_data['low'])/4,1)
    #Step 3 Calulate the volume which can be undertaken
    vol = math.floor(capt/avg_ent)
    #Step 4 Calculate SL/T1/T2 after entry
    if trans == "SELL":
        sl_val =  round(avg_ent + (round((avg_ent * sl),1)),1)
        t1_val =  round(avg_ent - (round((avg_ent * tar1),1)),1)
        t2_val =  round(avg_ent - (round((avg_ent * tar2),1)),1)
    
    if trans == "BUY":
        sl_val =  round(avg_ent - (round((avg_ent * sl),1)),1)
        t1_val =  round(avg_ent + (round((avg_ent * tar1),1)),1)
        t2_val =  round(avg_ent + (round((avg_ent * tar2),1)),1)

    #Calculate Volume split
    t1_vol = math.ceil(vol * 0.7)
    t2_vol = vol - t1_vol
    
    #Step 4.1 Record the simulation data in DB
    sim_query = "INSERT INTO sim_tracker VALUES ('"+sim_id+"','"+str_id+"','"+scrip+"','"+sim_type+"','"+trans+"',"+str(capt)+","+str(tar1)+","+str(tar2)+","+str(sl)+","+str(t1_vol)+","+str(t2_vol)+",'"+start+"','"+end+"')"
    s.execQuery(sim_query)
    #c.pr("I","First Candle [Open "+str(ep_data['open'])+"] [Low "+str(ep_data['low'])+"] [High "+str(ep_data['high'])+"] [Close "+str(ep_data['close'])+"]",1)
    c.pr("I","[EP AVG(OLHC) "+str(avg_ent)+"] [SL "+str(sl_val)+"] [T1 "+str(t1_val)+"] [T2 "+str(t2_val)+"] [Vol "+str(vol)+"] [T1 Vol "+str(t1_vol)+"] [T2 Vol "+str(t2_vol)+"]" ,1)

    #Step 5 Loop through time keys and check for condition
    for key in tkeys:
        #Check if there is volume to sell
        if vol:
            ep_data = data[key]
            avg_prc = round((ep_data['open'] + ep_data['close'] + ep_data['high'] + ep_data['low'])/4,1)
            if trans == "SELL":
                #Check if this did hit SL
                if sl_val >= avg_prc:
                    if t1_vol:
                        if avg_prc <= t1_val:
                            #c.pr("I","Volume Is At "+str(vol)+" On "+c.get_time(key)+" AVG Price "+str(avg_prc)+ " T1 Hit -> Yes" ,1)
                            results[key]       = {}
                            results[key]['EN'] = avg_ent
                            results[key]['EX'] = avg_prc
                            results[key]['VL'] = t1_vol
                            results[key]['ST'] = "T1H"
                            vol                = vol - t1_vol
                            t1_vol             = 0
                            
                    if t1_vol == 0 and t2_vol:
                        if avg_prc <= t2_val:
                            #c.pr("I","Volume Is At "+str(vol)+" On "+c.get_time(key)+" AVG Price "+str(avg_prc)+ " T2 Hit -> Yes" ,1)
                            if key in results:
                                results[key]['VL']  += t2_vol
                                results[key]['ST']  = "T2H"
                                vol                 = vol - t2_vol 
                                t2_vol              = 0
                            else:
                                results[key]       = {}
                                results[key]['EN'] = avg_ent
                                results[key]['EX'] = avg_prc
                                results[key]['VL'] = t2_vol
                                results[key]['ST'] = "T2H"
                                vol                = vol - t2_vol 
                                t2_vol             = 0    
                              
                else:  
                    #c.pr("I","Volume Is At "+str(vol)+" On "+c.get_time(key)+" AVG Price "+str(avg_prc)+ " SL Hit -> Yes" ,1)
                    results[key]       = {}
                    results[key]['EN'] = avg_ent
                    results[key]['EX'] = avg_prc
                    results[key]['VL'] = vol
                    results[key]['ST'] = "SLH"
                    vol                = 0
            #exit()
            if trans == "BUY":
                if sl_val <= avg_prc:
                    if t1_vol:
                        if avg_prc >= t1_val:
                            #c.pr("I","Volume Is At "+str(vol)+" On "+c.get_time(key)+" AVG Price "+str(avg_prc)+ " T1 Hit -> Yes" ,1)
                            results[key]       = {}
                            results[key]['EN'] = avg_ent
                            results[key]['EX'] = avg_prc
                            results[key]['VL'] = t1_vol
                            results[key]['ST'] = "T1H"
                            vol                = vol - t1_vol
                            t1_vol             = 0
                            
                    if t1_vol == 0 and t2_vol:
                        if avg_prc >= t2_val:
                            #c.pr("I","Volume Is At "+str(vol)+" On "+c.get_time(key)+" AVG Price "+str(avg_prc)+ " T2 Hit -> Yes" ,1)
                            if key in results:
                                
                                results[key]['VL']  += t2_vol
                                results[key]['ST']  = "T2H"
                                vol                 = vol - t2_vol 
                                t2_vol              = 0
                            else:
                                results[key]       = {}
                                results[key]['EN'] = avg_ent
                                results[key]['EX'] = avg_prc
                                results[key]['VL'] = t2_vol
                                results[key]['ST'] = "T2H"
                                vol                = vol - t2_vol 
                                t2_vol             = 0    
                              
                else:  
                    #c.pr("I","Volume Is At "+str(vol)+" On "+c.get_time(key)+" AVG Price "+str(avg_prc)+ " SL Hit -> Yes" ,1)
                    results[key]       = {}
                    results[key]['EN'] = avg_ent
                    results[key]['EX'] = avg_prc
                    results[key]['VL'] = vol
                    results[key]['ST'] = "SLH"
                    vol                = 0

        else:
            c.pr("I","Ending Simulations As Volume is 0",1)
            break   

    #If the volume is still there at 3:10 square off at 3:10
    if vol:
        #c.pr("I","Squaring of Position At 03:10 PM",1)
        ed_data = data[key]
        avg_ext = round((ed_data['open'] + ed_data['close'] + ed_data['high'] + ed_data['low'])/4,1)
        results[key]       = {}
        results[key]['EN'] = avg_ent
        results[key]['EX'] = avg_ext
        results[key]['VL'] = vol
        results[key]['ST'] = "SQF"

    #Step 6. Display Result
    c.pr("I","Simulation Resuts",1)
    for res in results:
        PL = 0
        if trans == "BUY":
            PL = round(((results[res]['EX'] - results[res]['EN']) * results[res]['VL']),1)
        if trans == "SELL":
            PL = round(((results[res]['EN'] - results[res]['EX']) * results[res]['VL']),1)

        c.pr("I","[ET -> "+c.get_time(entry)+"] [EP -> "+str(results[res]['EN'])+"] [ET -> "+c.get_time(res)+"] [XP -> "+str(results[res]['EX'])+"] [Volume -> "+str(results[res]['VL'])+"] [P/L -> "+str(PL)+"] [Status -> "+results[res]['ST']+"]",1)
        res_query = "INSERT INTO sim_results VALUES ('"+sim_id+"',"+str(start)+","+res+","+str(results[res]['EN'])+","+str(results[res]['EX'])+","+str(results[res]['VL'])+","+str(PL)+",'"+results[res]['ST']+"')"
        s.execQuery(res_query)
    c.pr("I","--------------------------------------------------------",1)
    return
Exemplo n.º 22
0
def create_program_title(program, is_record, is_series_record, is_conflicting):
    title = "%s  %s" % (common.get_time(program.start_time),
                        create_recording_title(program, is_record,
                                               is_series_record,
                                               is_conflicting))
    return title
Exemplo n.º 23
0
def main():
  parser = argparse.ArgumentParser(description='Run synthesis experiment.')
  parser.add_argument('-n', type=int, help='Number of repetitions', default=10)
  parser.add_argument('--filter', type=str, help='Filter which experiments to run', default="")
  parser.add_argument('--exclude', type=str, help='Exclude some experiments', default="")
  parser.add_argument('--exp_name', type=str, help='Name of this experiment', default="")
  parser.add_argument('--args', type=str, help='Arguments to be passed to mimic', default="")
  parser.add_argument('--metric', type=str, help='Which metric should be used during search?  Comma-separated list', default="0")

  global argv
  argv = parser.parse_args()

  workdir = os.path.abspath(os.path.dirname(__file__) + "/../tests")
  n = argv.n

  metrics = map(lambda x: int(x), argv.metric.split(","))

  global base_command
  if argv.args != "":
    base_command = base_command + " " + argv.args

  fncs = parse_functions(workdir, argv.filter, argv.exclude)

  # create a directory to store information
  global out
  out = workdir + "/out"
  if not os.path.exists(out):
    os.mkdir(out)
  timefordir = common.get_time(True)
  out = out + "/" + timefordir
  if argv.exp_name != "":
    out = out + "_" + argv.exp_name
  if os.path.exists(out):
    print "ERROR, out directory exists already: " + out
    sys.exit(1)
  os.mkdir(out)
  logfile = out + "/readme.txt"

  # run the experiment
  tasks = []
  c = 0
  print ""
  for f, i, m in [(f, i, m) for f in fncs for i in range(n) for m in metrics]:
    tasks.append((c, f, i, m))
    c += 1
  shuffle(tasks) # shuffle tasks
  results = []
  print "Running experiment..."
  def get_details():
    s = ""
    s += "  function(s):        %d" % len(fncs)
    s += "\n  repetitions:        %d" % n
    s += "\n  output directory:   %s" % out[out.find("/tests/")+1:]
    return s
  print get_details()
  common.fprint(logfile, "Arguments: " + " ".join(sys.argv) + "\n")
  common.fprinta(logfile, "Time: " + common.get_time() + "\n")
  common.fprinta(logfile, get_details() + "\n" + line + "\n")
  print line
  stat = status.get_status()
  stat.set_message("Running experiment...")
  stat.init_progress(len(tasks))
  for c, f, i, m in tasks:
    stat.writeln("Running mimic for %s..." % (f.shortname))
    res = run.mimic(f, metric=m, cleanup=0)
    stat.writeln("  done in %.2f seconds and %d searches" % (res.total_time, res.total_searches))
    stat.inc_progress(force_update=True)
    results.append(res)
    jn = cPickle.dumps(results)
    common.fprint(out + "/result.pickle", jn)
  stat.end_progress()
  print line
  print "Finished experiment:"
  print get_details()
  common.fprinta(logfile, "Time: " + common.get_time() + "\n")