Best Python code snippet using slash
flappydot.py
Source:flappydot.py  
1from gamelib import Sprite, GameApp, Text2import tkinter as tk3import random4if __name__ != "__main__":5    from PIL import Image, ImageTk6CANVAS_WIDTH = None7CANVAS_HEIGHT = None8GRAVITY = 0.79JUMP_VELOCITY = -1010STARTING_VELOCITY = -1011# Game Speed12DO_INCREASE_SPEED_RELATED_TO_SCORE = True13INIT_PIPE_REFRESH_RATE = 2014INIT_PIPE_SPEED = 315PIPE_SPEED_STEP = 116MAX_PIPE_SPEED = 10017PIPE_REFRESH_RATE_STEP = 118DIFICULTY_STEP = 519# > Development Feature <20DEV_ENV = False21DEATH_MECHANISM = True22SCORE_PER_PIPE = 123class PillarPair(Sprite):24    def init_element(self):25        self.is_started = True26        self.scored = False27    def start(self):28        self.is_started = True29    def stop(self):30        self.is_started = False31    def update(self, pipe_speed):32        if self.is_started:33            self.x -= pipe_speed34    def state_scored(self):35        if self.x <= (CANVAS_WIDTH//2 - 80):36            self.scored = False37        elif self.dot_passed():38            self.scored = True39    def is_out_of_screen(self):40        return self.x < -(0.05*CANVAS_WIDTH)41    def reset_position(self):42        self.x = CANVAS_WIDTH + 0.05*(CANVAS_WIDTH)43    def random_height(self):44        self.y = random.randint(0.25*CANVAS_HEIGHT,45                                CANVAS_HEIGHT-0.25*CANVAS_HEIGHT)46    def dot_passed(self):47        return CANVAS_WIDTH//2-20 < self.x < CANVAS_WIDTH//2+20 and self.is_started and not self.scored48    def is_hit(self, dot):49        assert type(50            dot) == Dot, "The dot param must be the instance of Dot object"51        dot_x_front = dot.x + 2052        dot_y_top = dot.y + 2053        dot_y_bottom = dot.y - 2054        return (dot_x_front >= self.x - 40 and dot_x_front <= self.x + 40) and \55            (dot_y_top < self.y - 100 or dot_y_top > self.y +56             100 or dot_y_bottom < self.y - 100 or dot_y_bottom > self.y + 100)57class Dot(Sprite):58    def init_element(self):59        self.vy = STARTING_VELOCITY60        self.is_started = False61        self.facing_angle = 062        if DEV_ENV:63            self.hit_box = self.canvas.create_rectangle(64                self.x - 20, self.y - 20, self.x + 20, self.y+20,65                width=1, dash=(4, 2))66    def init_canvas_object(self):67        self.image = Image.open(self.image_filename)68        self.image = self.image.rotate(0)69        self.tk_image = ImageTk.PhotoImage(self.image)70        self.canvas_object_id = self.canvas.create_image(71            self.x,72            self.y,73            image=self.tk_image)74    def update(self):75        if self.is_started and self.y <= CANVAS_HEIGHT - 20:76            self.y += self.vy77            self.vy += GRAVITY78            self.facing_angle -= 479            self.canvas.delete(self.canvas_object_id)80            self.tk_image = ImageTk.PhotoImage(81                self.image.rotate(self.facing_angle))82            self.canvas_object_id = self.canvas.create_image(83                self.x,84                self.y,85                image=self.tk_image)86            if DEV_ENV:87                self.canvas.coords(self.hit_box, self.x - 20,88                                   self.y - 20, self.x + 20, self.y+20)89    def start(self):90        self.is_started = True91    def stop(self):92        self.is_started = False93    def jump(self):94        self.facing_angle = 4095        self.vy = JUMP_VELOCITY96    def is_out_of_screen(self):97        return self.y > CANVAS_HEIGHT-40 or self.y < 098class Background(Sprite):99    def init_canvas_object(self):100        self.x += CANVAS_WIDTH/2101        self.image = Image.open(self.image_filename)102        self.image = self.image.resize(103            (CANVAS_WIDTH*2, CANVAS_HEIGHT), Image.ANTIALIAS)104        self.tk_image = ImageTk.PhotoImage(self.image)105        self.canvas_object_id = self.canvas.create_image(106            self.x,107            self.y,108            image=self.tk_image)109    def init_element(self):110        self.is_started = False111    def start(self):112        self.is_started = True113    def stop(self):114        self.is_started = False115    def reset_position(self):116        self.x = CANVAS_WIDTH117    def update(self):118        if self.is_started:119            self.x -= 3120    def is_out_of_screen(self):121        return self.x < 0122class TextImage(Sprite):123    pass124class Title(TextImage):125    def init_element(self):126        self.status = False127        self.is_done = False128    def move_in(self):129        if self.y <= CANVAS_HEIGHT*0.25:130            self.y += 2131    def move_out(self):132        if self.y < CANVAS_HEIGHT*2:133            self.y += 10134    def done(self):135        self.status = True136class FlappyGame(GameApp):137    def init_game(self):138        # For updating the CANVAS_HEIGHT and CANVAS_WIDTH in the global scope.139        global CANVAS_HEIGHT, CANVAS_WIDTH140        CANVAS_WIDTH = self.canvas_width141        CANVAS_HEIGHT = self.canvas_height142        self.create_background()143        self.score = 0144        self.create_title()145        self.spacebar_status = True146        self.intro = True147        self.move_in_title()148        self.create_sprites()149        self.is_started = False150        self.is_gameover = False151        self.pipe_refresh_rate = INIT_PIPE_REFRESH_RATE152        self.pipe_speed = INIT_PIPE_SPEED153        self.update_pipe()154        if self.title.is_done:155            self.show_press_spacebar()156    def create_title(self):157        self.title = Title(158            self, "images/intro/title.png", CANVAS_WIDTH//2, 0-CANVAS_HEIGHT*0.1)159    def create_sprites(self):160        self.dot = Dot(self, 'images/dot.png',161                       CANVAS_WIDTH // 2, CANVAS_HEIGHT // 2)162        self.elements.append(self.dot)163    def create_pillar(self):164        self.pillar_pair = PillarPair(165            self, 'images/pillar-pair.png', CANVAS_WIDTH+0.05*CANVAS_WIDTH, CANVAS_HEIGHT//2)166        self.pillar_pair.random_height()167        self.elements.append(self.pillar_pair)168    def create_background(self):169        self.background = Background(170            self, 'images/background.png', CANVAS_WIDTH/2, CANVAS_HEIGHT / 2)171    def check_pillar_onscreen(self):172        if len(self.elements) > 1 and len(self.elements[1:]) != 4 and self.elements[-1].x <= CANVAS_WIDTH-0.275*CANVAS_WIDTH+0.05*CANVAS_WIDTH:173            self.create_pillar()174    def add_score(self):175        self.score += SCORE_PER_PIPE176        if DO_INCREASE_SPEED_RELATED_TO_SCORE:177            self.calculate_speed()178    def displayed_score(self):179        self.score_image_list = []180        for i in range(len(str(self.score))):181            image_name = 'images/number/'+str(self.score)[i]+'.png'182            position = CANVAS_WIDTH/(3*(len(str(self.score)) + 1))183            self.score_image_list.append(184                TextImage(self, image_name, CANVAS_WIDTH/3 + position*(i+1), CANVAS_HEIGHT*0.1))185    def calculate_speed(self):186        if self.score % DIFICULTY_STEP == 0 and self.score != 0:187            if self.pipe_speed < MAX_PIPE_SPEED:188                self.pipe_speed += PIPE_SPEED_STEP189            if self.pipe_refresh_rate > 1:190                self.pipe_refresh_rate -= PIPE_REFRESH_RATE_STEP191    def spacebar_start(self):192        self.spacebar_status = True193    def spacebar_stop(self):194        self.spacebar_status = False195    def space_on(self):196        if not self.spacebar_status:197            return198        self.spacebar = Title(199            self, "images/intro/spacebar0.png", CANVAS_WIDTH//2, CANVAS_HEIGHT - CANVAS_HEIGHT*0.15)200        self.spacebar.render()201        self.after(800, self.space_off)202    def space_off(self):203        if not self.spacebar_status:204            return205        self.spacebar = Title(206            self, "images/intro/spacebar1.png", CANVAS_WIDTH//2, CANVAS_HEIGHT - CANVAS_HEIGHT*0.15)207        self.spacebar.render()208        self.after(100, self.space_on)209    def show_press_spacebar(self):210        self.spacebar_status = True211        self.press_start = Title(212            self, "images/intro/press-start.png", CANVAS_WIDTH//2, CANVAS_HEIGHT-CANVAS_HEIGHT*0.2)213        self.press_start.render()214        self.spacebar_loop()215    def spacebar_loop(self):216        self.space_on()217    def delete_spacebar(self):218        self.canvas.delete(f"{self.spacebar.canvas_object_id}")219        self.canvas.delete(f"{self.press_start.canvas_object_id}")220    def move_in_title(self):221        if self.title.y == CANVAS_HEIGHT*0.25:222            self.title.is_done = True223            self.show_press_spacebar()224            return225        self.title.move_in()226        self.title.render()227        self.after(10, self.move_in_title)228    def move_out_title(self):229        if self.title.y > CANVAS_HEIGHT*1.5:230            self.title.status = True231            self.title.is_done = True232            return233        self.title.move_out()234        self.title.render()235        self.after(1, self.move_out_title)236    def gameover_popup(self):237        self.youlose = TextImage(238            self, "images/gameover.png", CANVAS_WIDTH//2, CANVAS_HEIGHT//2)239        self.youlose.render()240    def update_pipe(self):241        if self.is_started:242            for element in self.elements[1:]:243                element.update(self.pipe_speed)244                element.render()245            self.background.update()246            self.background.render()247            self.post_update()248        if not self.is_gameover:249            self.after(self.pipe_refresh_rate, self.update_pipe)250    def update_bird(self):251        if self.is_started or self.is_gameover:252            self.dot.update()253            self.dot.render()254        self.after(10, self.update_bird)255    def start(self):256        """For something that need to always be updated257        """258        self.update_bird()259    def animate(self):260        # animate method has been deprecated. Due to the animation shaking issue261        # Using update_bird() and update_pipe to update element instead262        pass263    def post_update(self):264        # Check if the dot is falling out from the screen265        if self.dot.is_out_of_screen() and DEATH_MECHANISM:266            self.gameover_popup()267            # Change game state to gameover268            self.is_started = False269            self.is_gameover = True270            # Stop every eliments271            for element in self.elements[1:]:272                element.stop()273            self.background.stop()274        self.check_pillar_onscreen()275        if self.background.is_out_of_screen():276            self.background.reset_position()277        for element in self.elements[1:]:278            if element.is_hit(self.dot) and DEATH_MECHANISM:279                self.gameover_popup()280                self.is_gameover = True281                self.is_started = False282            if element.dot_passed() and self.is_started:283                self.add_score()284                self.displayed_score()285            element.state_scored()286            if element.is_out_of_screen():287                element.reset_position()288                element.random_height()289    def on_key_pressed(self, event):290        if event.keysym == "space" and self.title.is_done:291            if not self.title.status:292                self.move_out_title()293                self.delete_spacebar()294            if not self.is_started and not self.is_gameover:295                self.create_pillar()296                self.displayed_score()297                self.is_started = True298                self.background.start()299                self.dot.start()300                self.spacebar_stop()301                self.delete_spacebar()302                return303            if self.is_gameover:304                return305            self.dot.jump()306        if event.keysym == "r" and self.is_gameover:307            # R button press to reset game when gameover.308            for item in self.elements:309                self.canvas.delete(item.canvas_object_id)310            self.elements = []311            self.init_game()312            return313if __name__ == "__main__":...timer.py
Source:timer.py  
1from time import perf_counter2from timer_py.printer import Printer3from timer_py.utils import format_time4class Timer:5    def __init__(self, tag: str = 'timer.py', format: str = '%02d:%02d:%02d.%s',6                 ms_digits: int = 3, color: str = 'green', start: bool = False):7        self.time_data = []8        self.is_started = False9        self.start_time = None10        self.format = format11        self.ms_digits = ms_digits12        self.color = color13        self.printer = Printer(tag)14        if start:15            self.start()16    def start(self, tag: str = None):17        if tag is not None:18            self.printer.set_tag(tag)19        if self.is_started:20            self.printer.error('Timer already started')21        else:22            self.start_time = perf_counter()23            self.is_started = True24        return self25    def pause(self) -> None:26        if self.is_started:27            elapsed = perf_counter() - self.start_time28            self.is_started = False29            self.time_data.append(elapsed)30        elif len(self.time_data) == 0:31            self.printer.error('Timer not started')32        else:33            self.printer.error('Timer already paused')34    def resume(self) -> None:35        if self.is_started:36            self.printer.error('Timer already started')37        elif len(self.time_data) == 0:38            self.printer.error('Timer not started')39        else:40            self.start_time = perf_counter()41            self.is_started = True42    def restart(self):43        self.start_time = perf_counter()44        self.time_data = []45        self.is_started = True46    def elapsed(self, tag: str = None, print: bool = True) -> float:47        if not self.is_started and len(self.time_data) == 0:48            self.printer.error('Timer not started')49            return 050        else:51            elapsed = perf_counter() - self.start_time if self.is_started else 052            total_time = sum(self.time_data) + elapsed53            formatted_time = format_time(total_time, self.ms_digits, self.format)54            if print:55                self.printer.info(formatted_time, tag)56            return total_time57    def set_tag(self, tag: str) -> None:58        self.printer.set_tag(tag)59    def stop(self, tag: str = None, print: bool = True) -> float:60        total_time = self.elapsed(tag, print)61        self.time_data = []62        self.is_started = False...tomcat_opt.py
Source:tomcat_opt.py  
1#!/usr/bin/python2# -*- coding:utf-8 -*-3import os4import commands5def status(ip,port):6    if not ip or not port:7        return False;8    command = ('(sleep 2;) | telnet %s ' % (ip))+ port +' | grep \"\\^]\" | wc -l';9    #print 'prepare run command: %s' % command10    # ç´æ¥è°ç¨è¿åç³»ç»çè¿åå¼ 0 æ¯æå ä¼é»å¡11    # is_started = os.system(command);12    is_started = commands.getoutput(command);13    #is_started = commands.getstatusoutput(command);14    #is_started = is_started.replace("\r\n","#")15    #print 'run result: %s' % is_started;16    print 'Server IP: %s, Port: %s, Status: %s.' % (ip, port, 'opened' if is_started.endswith('1') else 'closed');17    return is_started.endswith('1');18def opt(ssh_opt,catalina_home,cmd):19    command = 'ssh '+ ssh_opt +' \'sh '+ catalina_home +'/bin/catalina.sh '+cmd+'\''20    print 'prepare run command: %s' % command21    st = commands.getoutput(command);22    print 'run result: %s' % st;23    pass24if __name__ == '__main__':25    #opt('-p 2222 yxgly@10.100.142.93','/app/demome-cxf-1','stop -force')26    opt('-p 2222 yxgly@10.100.142.93','/app/demome-cxf-1','start')...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
