예제 #1
0
def final_submission():
    files = {'small': 303, 'medium': 303, 'large': 400}
    for size in files:
        for i in range(files[size]):
            prefix = size + '-' + str(i + 1)
            filename = './inputs/' + prefix + '.in'
            outputname = './outputs/' + prefix + '.out'
            print("processing " + filename)
            adj_list, vertices_list = parse(filename)
            process(vertices_list, adj_list, outputname)
예제 #2
0
def main():
    queue_url = argv[1] if len(argv) > 1 else None
    if queue_url is None:
        print(f"Invalid argument {queue_url}")
        exit(1)
    info("Start Consuming Queue " + queue_url)
    queue = sqs.Queue(queue_url)
    while True:
        for message in queue.receive_messages():
            try:
                process(message)
            except Exception as e:
                error(e)
            finally:
                message.delete()
예제 #3
0
def calc_map(opt, video_scores, video_names, groundtruth_dir, iou_thresholds):
  """Get mAP (action) for IoU 0.1, 0.3 and 0.5."""
  activity_threshold = 0.4
  num_videos = len(video_scores)
  video_files = [name + '.txt' for name in video_names]

  v_props = []
  for i in range(num_videos):
    # video_name = video_names[i]
    scores = video_scores[i]
    segments = get_segments(scores, activity_threshold)

    prop = []
    for segment in segments:
      start, end, cls, score = segment
      # start, end are indices of clips. Transform to frame index.
      start_index = start * opt.step_size * opt.downsample
      end_index = (
          (end - 1) * opt.step_size + opt.n_frames) * opt.downsample - 1
      prop.append([cls, start_index, end_index, score, video_files[i]])
    v_props.append(prop)

  # Run evaluation on different IoU thresholds.
  mean_aps = []
  for iou in iou_thresholds:
    mean_ap = process(v_props, video_files, groundtruth_dir, iou)
    mean_aps.append(mean_ap)
  return mean_aps
def test_thing(data):
    result = process(data[0], data[1])
    expected = AutoInsuranceAction(data[2], data[3], data[4], data[5])
    assert(expected.premium_increase == result.premium_increase)
    assert(expected.warning_letter_enum == result.warning_letter_enum)
    assert(expected.is_policy_canceled == result.is_policy_canceled)
    assert(expected.is_error == result.is_error)
예제 #5
0
    def test_Payment(self):

        handler = process()
        handler.request = Request({
            'REQUEST_METHOD': 'get',
            'PATH_INFO': '/process',
            })
        handler.response = Response()
        handler.get()
        self.assertEqual(200, handler.response.status)
예제 #6
0
def main(file_path, *octave):
	csv_path = hum_csv_path + process(file_path.replace("\\","/"))
	hum = Hum(csv_path)
	if len(octave) > 0:
		matches = hum.get_matches(float(octave[0]))
	else:
		matches = hum.get_matches()
	print "Best"
	for x in xrange(0,len(matches)):
		song = matches[x]
		print str(x+1) + ". " + title_from_path(song[0])
예제 #7
0
    def test_Payment(self):

        handler = process()
        handler.request = Request({
            'REQUEST_METHOD': 'post',
            'PATH_INFO': '/process',
            })
        handler.response = Response()
        
        self.assertEqual(200, handler.response.status)
        test = Player.newPlayer(Player(key_name='*****@*****.**'),'*****@*****.**',10,10,10,40,20,0,0)
        test.put()
예제 #8
0
    def forward(self, filename, save_weight=False, pretrained_weight=None):
        X, Y, character, idx2chr, chr2idx, X_modified, Y_modified = process(filename)
        model = self.build(X_modified.shape[1], X_modified.shape[2],Y_modified.shape[1])

        if pretrained_weight is not None:
            model.load_weights(pretrained_weight)
        else:
            model.fit(X_modified, Y_modified, epochs=self.epochs, batch_size=self.batch_size)
        
        if save_weight:
            model.sample_weights('poem_generator_weight.h5')
        
        return model
예제 #9
0
 def generate(self, number,save_weight=False, pretrained_weight=None,  filename = 'chanda.txt'):
     model  = Model(self.epochs, self.batch_size)
     generate_model = model.forward(filename, save_weight=False, pretrained_weight=None)
     
     X, Y, characters, idx2chr, chr2idx, X_modified, Y_modified = process(filename)
     string_mapped = X[number]
     full_string = [idx2chr[value] for value in string_mapped]
     for i in range(400):
         x = np.reshape(string_mapped,(1,len(string_mapped), 1))
         x = x / float(len(characters))
         pred_index = np.argmax(generate_model.predict(x, verbose=0))
         seq = [idx2chr[value] for value in string_mapped]
         full_string.append(idx2chr[pred_index])
         string_mapped.append(pred_index)
         string_mapped = string_mapped[1:len(string_mapped)]
     
     return ''.join(full_string)
예제 #10
0
 def create(self, args):
     """create a new process"""
     args[1] = int(args[1])
     proc = process()
     self.cur_pid = self.get_pid()
     proc.id = self.cur_pid
     proc.status['type'] = 'ready_a'
     proc.creation_tree['parent'] = self.cur_proc
     proc.creation_tree['child'] = []
     proc.name = args[0]
     proc.priority = args[1]
     if self.cur_proc:
         self.cur_proc.creation_tree['child'].append(proc)
     else: proc.creation_tree['parent'] = None
     self.proc_list[proc.id] = proc
     self.ready_a_q.push(proc)
     print "process %s created with priority %d\n" % \
           (proc.name, proc.priority)
     self.schedule()
예제 #11
0
    def process(self) :
      if self.pfilee==0 :
        self.projetfile=self.T+ os.sep +u"tmp.idv"
        self.pfilee=1
        self.saveprojet()
        self.pfilee=0
      else :
        self.saveprojet()
      k=0
      while k<self.timeline.columnCount() :
        self.timeline.cellWidget(0,k).export2ppm(self.T+ os.sep +u"img_"+unicode(k)+u".ppm",self.imgwidthF,self.imgheightF,self.imgwidth,self.imgheight)
        k+=1

      self.prc=process(self.data,self,self.verifsformats[5][self.outputfileformat.currentIndex()],self.imgformat,self.parent)

      if self.prc.err==0 :
        self.showprog=ShowProgress(self,self.prc.totimage)
        self.showprog.show()

        self.prc.start()
        self.connect(self.prc,SIGNAL("image"),self.displayProcessImg)
        self.connect(self.prc,SIGNAL("frame"),self.infoFrame)
        self.connect(self.prc,SIGNAL("text"),self.infoProgress)
예제 #12
0
파일: main.py 프로젝트: mpett/narwhal_game
clock = pygame.time.Clock()
background = pygame.image.load("images/underwater_background/background2.png")
narwhal1 = Narwhal(0, SCREENHEIGHT - 90, "images/single_narwhal.png", 7)
helmetfish = HelmetFish(30, 100, "images/helmetfish.png")
FPS = 24
total_frames = 0
# Colors
clr1 = (123, 23, 34)
clr2 = (55, 233, 12)
clr3 = (25, 44, 123)
changing_color = 0

# Main loop
while True:
    # Processes
    process(narwhal1, FPS, total_frames)
    # Logic
    narwhal1.motion(SCREENWIDTH)
    HelmetFish.movement(SCREENWIDTH)
    Projectile.movement()
    HelmetFish.update_all(SCREENWIDTH, SCREENHEIGHT)
    collisions()
    total_frames += 1
    #Draw
    screen.blit(background, (0, 0))
    BaseClass.all_sprites.draw(screen)
    Projectile.List.draw(screen)
    # Flip y-axis
    pygame.display.flip()
    # Clock
    clock.tick(FPS)
예제 #13
0
    def run(self):

        while True:
            process(self, self.fish, self.FPS, self.total_frames, self.play_frames)
            self.screen.blit(self.background, (0, 0))
            position = pygame.mouse.get_pos()

            if self.state == FISH_PLAYING:
                if LEVEL == 1 :
                    self.background = pygame.image.load("images/Level1-3.jpg")
                elif LEVEL >= 3 and LEVEL < 5:
                    self.background = pygame.image.load("images/Level3-5.jpg")
                elif LEVEL >= 5 and LEVEL <= 9:
                    self.background = pygame.image.load("images/Level5-9.jpg")
                elif LEVEL == 10:
                    self.background = pygame.image.load("images/Level10.jpg")

                self.fish.motion(self.fish, SCREENWIDTH, SCREENHEIGHT)
                Shark.update_all(SCREENWIDTH, SCREENHEIGHT)
                Bag.update_all(SCREENWIDTH, SCREENHEIGHT)
                Jellyfish.update_all(SCREENWIDTH, SCREENHEIGHT)
                Pellet.update_all(SCREENWIDTH, SCREENHEIGHT)
                spawn(self, self.FPS, self.total_frames)
                collisions(self)
                # jelly_collisions(self)
                BaseClass.allsprites.draw(self.screen)
                FishProjectile.List.draw(self.screen)
                FishProjectile.movement()
                # print self.score
                # show_cleanup(self, "%s" % (self.kills))
                # show_cleanup_left(self, "Cleanups to Next Level")
                show_level(self, "%s" % (LEVEL))
                show_lives(self, "Lives: ")
                show_level_text(self, "LEVEL: ")
                #create our fancy text renderer
                bigfont = pygame.font.Font(None, 60)
                white = 255, 255, 255
                renderer = TextProgress(bigfont, "Next Level", white, (40, 40, 40))
                text = renderer.render(0)
                progress = (self.kills/float(LEVEL+3)) * 120
                text = renderer.render(progress)
                self.screen.blit(text, (0, 0))

            elif self.state == FISH_IN_WATER:
                show_message(self, "PRESS the Button to START", 30, "MIDDLE")
                Button.Button1.update_display(self.screen, (107,142,35), (SCREENWIDTH - 200) / 2, (SCREENHEIGHT + 100) / 2 , 200,    50,    0,        "Try Again?", (255,255,255))

            elif self.state == START_SCREEN:
                show_message(self, "KOI", 200, "TOP_MIDDLE_TOP")
                Button.Button1.update_display(self.screen, (107,142,35), (SCREENWIDTH - 300) / 2, (SCREENHEIGHT) / 2 , 300,    75,    0,        "Start Game", (255,255,255))
                Button.instructions.update_display(self.screen, (100,149,237), (SCREENWIDTH - 450) / 2, (SCREENHEIGHT + 450) / 2, 200,    50,    0,        "Tutorial", (255,255,255))
                Button.credits.update_display(self.screen, (100,149,237), (SCREENWIDTH + 50) / 2, (SCREENHEIGHT + 450) / 2 , 200,    50,    0,        "Credits", (255,255,255))

            elif self.state == FISH_GAME_OVER:
                show_message(self, "GAME OVER",50, "MIDDLE")
                Button.Button1.update_display(self.screen, (230,52,35), (SCREENWIDTH - 200) / 2, (SCREENHEIGHT + 100) / 2 , 200,    50,    0,        "Try Again?", (255,255,255))
                self.background = pygame.image.load("images/background.jpg")

            elif self.state == CREDITS:
                show_message(self, "Team Ant Informatics 125" , 40,  "TOP_MIDDLE_CENTER")
                show_names(self, "Ian McNicol", 30, 225)
                show_names(self, "Delian Petrov", 30, 250)
                show_names(self, "Christina Ryder", 30, 275)
                show_names(self, "Brian Wance", 30, 300)
                Button.back.update_display(self.screen, (102,205,170), (SCREENWIDTH - 200) / 2, (SCREENHEIGHT + 100) / 2 , 200,    50,    0,        "Back", (255,255,255))

            elif self.state == INSTRUCTIONS:
                show_message(self, "You Have 3 Lives", 30,"TOP_MIDDLE_TOP")
                show_message(self, "Destroy the Trash to Level Up", 30,"TOP_MIDDLE_TOP2")
                show_message(self, "Pick up Pebbles and CLICK to shoot them at Trash", 30,"TOP_MIDDLE_CENTER")
                show_message(self, "Reach Level 10 to win the game", 30,"TOP_MIDDLE_BOTTOM")
                Button.back.update_display(self.screen, (102,205,170), (SCREENWIDTH - 200) / 2, (SCREENHEIGHT + 100) / 2 , 200,    50,    0,        "Back", (255,255,255))

            elif LEVEL == 10:
                self.state = FISH_WON
                show_message(self, "YOU WON! PRESS ENTER TO PLAY AGAIN", 30, "BOTTOM_MIDDLE")
            # LOGIC
            # Logic is movement, functions, etc

            self.total_frames += 1
            # LOGIC
  


            #screen.blit(img_goldfish, (100,100) ) # renders image on the screen at spot 100 X 100
            BaseClass.allsprites.draw(self.screen)  # list of everything being drawn on the screen
            pygame.display.flip()  # ensures everything is being drawn on the screen
            #DRAW

            self.clock.tick(self.FPS)
예제 #14
0
def test_should_increase_with_no_letter_at_26():
    actual = process(0, 26)
    expected = AutoInsuranceAction(25, WarningLetterEnum.NONE, False, False)
    assert (expected == actual)
                            # print(inner_message["params"]["request"]["url"].split("//",1)[1].split("/",1)[0])
                            data["url"] = inner_message["params"]["request"]["url"].split("//",1)[1].split("/",1)[0]
                        except IndexError:
                            pass

                        data["param-timestamp"] = inner_message["params"]["timestamp"]

                        # rawdata["documentURL"] = inner_message["params"]["request"]['documentURL']
                        # rawdata['type'] = inner_message["params"]["request"]['type']

                        writer.writerow(data)

                    elif(inner_message['method']=="Network.dataReceived"):
                        data["timestamp"] = entry["timestamp"]
                        data["requestId"] = inner_message["params"]["requestId"]
                        data["method"] = inner_message["method"]
                        data['dataLength'] = inner_message["params"]['dataLength']
                        data['encodedDataLength'] = inner_message["params"]['encodedDataLength']
                        data["param-timestamp"] = inner_message["params"]["timestamp"]

                        writer.writerow(data)

            # for browser in driver.get_log('browser'):
            #     print(browser)

            driver.quit()

if __name__ == "__main__":
    main(mode=sys.argv[1], network=sys.argv[2], iterations=sys.argv[3])
    process(sys.argv[1], sys.argv[2])
예제 #16
0
def test_should_error_under_15():
    actual = process(0, 15)
    expected = AutoInsuranceAction(-1, WarningLetterEnum.NONE, False, True)
    assert (expected == actual)
예제 #17
0
def test_should_error_above_85_years():
    actual = process(0, 90)
    expected = AutoInsuranceAction(-1, WarningLetterEnum.NONE, False, True)
    assert (expected == actual)
예제 #18
0
    "delete":
    lambda args: deleteRow(currentDB, args[1], args[2]),
    "select":
    lambda args: search(currentDB, args[2], args[1], args[3], args[4], args[5]
                        ),
    "import":
    lambda args: importExcel(currentDB, args[1], args[2])
}

if __name__ == "__main__":
    about()
    command = ""
    while command != "\q":
        print(currentDB + ">>>", end="")
        command = input().lower()
        if command == "\q":
            print("goodbye")
            exit()
        elif command == "help":
            helpuser()
        elif command == "\\a":
            showdbs()
        elif command == "\\t":
            showtables()
        else:
            operation = process(command)
            print(operation)
            backInfo = functions[operation[0]](operation)
            print(backInfo)
            '''except Exception as e:print(e)'''
예제 #19
0
 def requires(self):
     return process(is_local=self.is_local,
                    reg=self.reg,
                    dict_param=self.dict_param)
예제 #20
0
 def requires(self):
     return [
         process(is_local=self.is_local, reg=self.reg, dict_param=i)
         for i in self.list_cv
     ]
예제 #21
0
pygame.init()
SCREENWIDTH, SCREENHEIGHT = 640, 360
screen = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT), 0, 32)
clock = pygame.time.Clock()
FPS = 25
total_frames = 0

background = pygame.image.load("images/forest.jpg")
bug = Bug(0, SCREENHEIGHT - 40, "images/bug.png")

# ---------- Main Program Loop (All of the Drawing and other main Stuff!) ---------
while True:

    pygame.display.set_caption('Fly Swatter - XanonDevelopment')

    process(bug, FPS, total_frames)
    #PROCESSES

    #LOGIC
    bug.motion(SCREENWIDTH, SCREENHEIGHT)
    Fly.update_all(SCREENWIDTH, SCREENHEIGHT)
    BugProjectile.movement()
    total_frames += 1
    #Code Bellow randomises background color, Commented as is pretty useless.
    #i += 1
    #if i > 255:
    #	i %= 255

    #LOGIC

    #DRAW
예제 #22
0
                           save="./output_images/undistort_example")

    # Create channel plot of the test images
    plot_channels(images)

    # Create the white feature tuning plot
    plot_white_feature(images)

    # Create the yellow feature tuning plots
    plot_yellow_feature(images, tuning="h")
    plot_yellow_feature(images, tuning="s")
    plot_yellow_feature(images, tuning="v")

    # Create the yellow feature tuning plot
    plot_sobel_feature(images, tuning="thresh_min")
    plot_sobel_feature(images, tuning="iterations")

    # Create the feature composition images
    plot_feature(images)

    # Create perspective transformation plots
    plot_perspective_transform(images[0:-1:2], mtx, dist, ROI_SRC, ROI_DST)

    # Create the main pipeline plot
    plot_pipeline(images)

    # Process one of the test images
    img = mpimg.imread("./test_images/test2.jpg")
    processed_img = process(img)
    plot_process_example(processed_img, f"output_images/test2_processed.jpg")
예제 #23
0
from game.base import *
from process import *

pygame.init()

SCREENWIDTH, SCREENHEIGHT = 640, 360
screen = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT), 0, 32)

clock = pygame.time.Clock()
FPS = 25

bug = Bug(0, SCREENHEIGHT - 40, 40, 40, "game/images/bug.png")

while True:
    #PROCESSES
    process(bug)
    #PROCESSES
    #LOGIC
    bug.motion(SCREENWIDTH, SCREENHEIGHT)
    #LOGIC
    #DRAW
    screen.fill((0, 0, 0))
    BaseClass.allsprites.draw(screen)
    pygame.display.flip()
    #DRAW

    clock.tick(FPS)
예제 #24
0
def test_should_increase_with_letter1_at_16_and_1_claim():
    actual = process(1, 16)
    expected = AutoInsuranceAction(100, WarningLetterEnum.LTR1, False, False)
    assert (expected == actual)
예제 #25
0
from pathlib import Path
from process import *
from labels import *
from labelling import *
from output import *

audio_file_path = 'Input/commercial_mono.wav'
wav_fpath = Path(audio_file_path)
cont_embeds, wav_splits = process(wav_fpath)
labels = labels(cont_embeds)
labelling = create_labelling(labels, wav_splits)
output = output(labelling)
예제 #26
0
파일: main.py 프로젝트: yash19970/Midge
import pygame, sys
from pygame.locals import *
from classes import *
from process import *

pygame.init()
SCREENWIDTH, SCREENHEIGHT = 640, 360
screen = pygame.display.set_mode( (SCREENWIDTH,SCREENHEIGHT) )
clock = pygame.time.Clock()
FPS = 24
totalFrames = 0 #keeps track of all the frames created.
background = pygame.image.load("forest.jpg")
bug = Bug(0,100,"bug.png")

#----MainProgramLoop---#

while True:  
	process(bug,FPS,totalFrames)	
	#LOGIC 
	bug.motion(SCREENWIDTH,SCREENHEIGHT)
	Fly.update_all(SCREENWIDTH,SCREENHEIGHT)
	BugProjectile.movement()
	totalFrames += 1
	#LOGIC
	#DRAW
	screen.blit(background, (0,0) )
	BaseClass.allsprites.draw(screen)  
	BugProjectile.List.draw(screen) 
	pygame.display.flip()
	#DRAW
	clock.tick(FPS)
예제 #27
0
파일: main.py 프로젝트: olliee/flyswatter
clock = pygame.time.Clock()
FPS = 25
total_frames = 0


background = pygame.image.load("images/forest.jpg")
bug = Bug(0, SCREENHEIGHT - 40, "images/bug.png")


# ---------- Main Program Loop (All of the Drawing and other main Stuff!) ---------
while True:
 
	pygame.display.set_caption('Fly Swatter - XanonDevelopment')


	process(bug, FPS, total_frames)
	#PROCESSES

	#LOGIC       
	bug.motion(SCREENWIDTH, SCREENHEIGHT)
	Fly.update_all(SCREENWIDTH, SCREENHEIGHT)
	BugProjectile.movement()
	total_frames += 1 
#Code Bellow randomises background color, Commented as is pretty useless.
	#i += 1
	#if i > 255:
	#	i %= 255

	
	#LOGIC
예제 #28
0
except:
    idfs_paragraphs = load_idfs('data/idfs_paragraphs.txt')
    idfs_questions = load_idfs('data/idfs_questions.txt')

sys.stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='utf8')
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8')
p = None
pn = None
qs = list()
qsn = list()
for line in sys.stdin:
    line = line.strip()
    tokens = line.split('\t')
    if tokens[1] != '':
        qsn.append(tokens[1])
        qs.append(tokens[2])
    else:
        if p is not None and len(qs) > 0:
            sys.stderr.write(str(pn) + '\t' + p + '\n')
            out = process(p, pn, qs, qsn, idfs_questions, idfs_paragraphs)
            for e in out:
                sys.stdout.write(e)
        pn = tokens[0]
        p = tokens[2]
        qs = list()
        qsn = list()
if p is not None and len(qs) > 0:
    out = process(p, pn, qs, qsn, idfs_questions, idfs_paragraphs)
    for e in out:
        sys.stdout.write(e)
예제 #29
0
                usage()
                sys.exit(1)

            continue

            # any switch we don't recognize, ignore

    # did they give us any files to process?
    if len(args) == 0:
        arglist = ['daily.log'] # use default
    else:
        arglist = args[:]       # or use what they give us

    # process input files:
    for inpfile in arglist:     # go through given files
        sysname, entries = process(inpfile)
        if sysname != None:
            allSystems[sysname] = entries

    print()

    # display list of systems we found:
    syslist = list(allSystems)
    if len(syslist) > 1:
        print('Systems:')
        for sysname in sorted(syslist):
            print("    " + sysname)

        print()

    # analyze the systems:
예제 #30
0
    "delete": lambda args: deleteRow(currentDB,args[1],args[2]),
    "select": lambda args: search(currentDB,args[2], args[1],args[3],args[4],args[5]),
    "import": lambda args: importExcel(currentDB,args[1],args[2])
}


if __name__ == "__main__":
    about()
    command = ""
    while command != "\q":
        print(currentDB+">>>", end="")
        command = input().lower()
        if command == "\q":
            print("goodbye")
            exit()
        elif command == "help":
            helpuser()
        elif command == "\\a":
            showdbs()
        elif command == "\\t":
            showtables()
        else:
            operation = process(command)
            print(operation)
            backInfo = functions[operation[0]](operation)
            print(backInfo)
            '''except Exception as e:print(e)'''



예제 #31
0
import pytest
from process import *

cases = [
    # claims, age, premium_increase, warning_letter_enum, is_policy_canceled, is_error
    [
        process(0, 15),
        AutoInsuranceAction(-1, WarningLetterEnum.NONE, False, True)
    ],
    [
        process(0, 16),
        AutoInsuranceAction(50, WarningLetterEnum.NONE, False, False)
    ],
    [
        process(0, 17),
        AutoInsuranceAction(50, WarningLetterEnum.NONE, False, False)
    ],
    [
        process(0, 25),
        AutoInsuranceAction(50, WarningLetterEnum.NONE, False, False)
    ],
    [
        process(0, 26),
        AutoInsuranceAction(25, WarningLetterEnum.NONE, False, False)
    ],
    [
        process(0, 27),
        AutoInsuranceAction(25, WarningLetterEnum.NONE, False, False)
    ],
    [
        process(0, 84),
예제 #32
0
import os
import sys
from process import *

img_, process_type, target_x, target_y = read_image(sys.argv)

processed_img = process(img_,
                        process_type=process_type,
                        target_x=target_x,
                        target_y=target_y)

save(processed_img, img_)
예제 #33
0
    def ws_thread_recv(self, ):
        while (self._run):
            compress_data = None
            try:
                compress_data = self._ws.recv()
            except Exception as e:
                logger.exception("receive data error: {}, data:{}".format(
                    e, compress_data))
                # log_config.output2ui("receive data error: {}, data:{}".format(e, compress_data), 4)
                # 如果已经关闭了,则不需要重连
                if self._run:
                    logger.warning("need reconnect..")
                    log_config.output2ui("need reconnect..", 2)
                    ret = self.ws_reconnect(resub=True)
                    #如查重连失败,则接收线程退出
                    if not ret:
                        logger.critical(
                            "-------reconnect failed. ws_thread_recv exit..")
                        log_config.output2ui(
                            "-------reconnect failed. ws_thread_recv exit..",
                            4)
                        log_config.output2ui("web socket 多次重连失败,请检查网络!", 8)
                        raise (Exception("web socket 多次重连失败,请检查网络!"))
                        break
                else:
                    logger.info("don't need reconnect, ws_thread_recv exit..")
                    log_config.output2ui(
                        "don't need reconnect, ws_thread_recv exit..")
                    return
                time.sleep(1)
                continue

            try:
                result = gzip.decompress(compress_data).decode('utf-8')
            except Exception as e:
                logger.exception("depress data error, e={}, data={}".format(
                    e, compress_data))
                # log_config.output2ui("depress data error, e={}, data={}".format(e, compress_data), 4)
                continue

            if "error" in result:
                logger.error(
                    "----------ERROR: receive data error. error response: \n {}"
                    .format(result))
                # log_config.output2ui("----------ERROR: receive data error. error response: \n {}".format(result), 3)
            # print("++ ws_thread_recv: {}".format(result))
            if "ping" in result:
                #处理ping消息
                pong_body = result.replace("ping", "pong")
                self._ws.send(pong_body)
            elif "subbed" in result:
                logger.info("+++SUB SUCCESSFULLY: {}".format(result))
                log_config.output2ui("+++SUB SUCCESSFULLY: {}".format(result))
            else:
                #处理订阅和请求响应
                res = eval(result)
                process = None
                channel = res.get("ch", "")
                if channel != "":
                    #处理订阅消息响应
                    if channel in self._sub_map.keys():
                        process = self._sub_map[channel]
                else:
                    #处理请求消息响应
                    rep = res.get("rep", "")
                    logger.info("REQ: response: {}".format(res))
                    if rep in self._req_map.keys():
                        process = self._req_map[rep]
                        self._req_map.pop(rep)

                #回调函数调用
                if process:
                    try:
                        process(res)
                    except Exception as e:
                        logger.exception(
                            "process {} catch exception.e={}".format(
                                channel, e))
                        log_config.output2ui(
                            "process {} catch exception.e={}".format(
                                channel, e), 4)
예제 #34
0
파일: spacio.py 프로젝트: thisisdevs/Spacio
        classes.period.sp = 1
        classes.period.kl = 0
        bug = Bug(0, 0, 'ship/f1.png')

    if classes.BugProjectile.fire:
        t = pygame.image.load('extras/shell.gif')
        for proj in classes.BugProjectile.List:
            proj.image = pygame.image.load('extras/shell.gif')
    elif not classes.BugProjectile.fire:
        t = pygame.image.load('extras/gun.gif')
        for proj in classes.BugProjectile.List:
            proj.image = pygame.image.load('extras/gun.gif')

    a = text_display(str(bug.score), white)

    l = process(bug, FPS, total_frames, screen)

    if l == 1:
        bug = Bug(0, 0, 'ship/f1.png')

    screen.blit(background, (0, 0))
    screen.blit(background1, (0, 0))
    screen.blit(a, SURFACER_a)

    screen.blit(k, SURFACER_k)
    screen.blit(gem, (SCREEN_WIDTH - 256 - 80 - 42, SCREEN_HEIGHT - 30))
    screen.blit(gem, (SCREEN_WIDTH - 256 - 80 - 210, SCREEN_HEIGHT - 30))

    if bug.blood == 1:
        screen.blit(times, (SCREEN_WIDTH - 35, 5))
        screen.blit(times, (SCREEN_WIDTH - 35 - 23, 5))
예제 #35
0
              
    

    if classes.BugProjectile.fire:
       t=pygame.image.load('extras/shell.gif')
       for proj in classes.BugProjectile.List:
            proj.image=pygame.image.load('extras/shell.gif')
    elif not classes.BugProjectile.fire:
       t=pygame.image.load('extras/gun.gif')
       for proj in classes.BugProjectile.List:
            proj.image=pygame.image.load('extras/gun.gif')
    

    a=text_display(str(bug.score),white)
    
    l=process(bug,FPS,total_frames,screen)
  
  
    if l==1:
        bug=Bug(0,0,'ship/f1.png')

    
    screen.blit(background,(0,0))
    screen.blit(background1,(0,0))
    screen.blit(a,SURFACER_a)
   
    screen.blit(k,SURFACER_k)
    screen.blit(gem,(SCREEN_WIDTH-256-80-42,SCREEN_HEIGHT-30))
    screen.blit(gem,(SCREEN_WIDTH-256-80-210,SCREEN_HEIGHT-30))

    if bug.blood==1:
예제 #36
0
# method for inserting every filepath in a directory into our db
def insert_directory_db(directory):
	filelist = os.listdir(directory)
	for f in filelist:
		# if the file is not a .csv, exclude
		if not ".csv" in f:
			continue
		# adjoin the original directory to the filepath
		path = directory + f
		insert_song_db(path.strip('\t\n\r'))
	db_session.commit()
	return

# remove the old database file
if os.path.isfile("finalproj.db"):
	os.remove("finalproj.db")

# initialize the database
init_db()

# populate 

# first, process each audio file into a .csv
process(folder_path, False)

# add each .csv to our db
# because the .csv files in song_csv_path are not deleted, 
# old .csv files will be kept in our database each time this script is called
insert_directory_db(song_csv_path)