Форум сайта python.su
CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, 'heavylift': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': os.path.join(BASE_DIR, 'django_cache'), } }
@cache_page(60 * 60) def user_data_view(request): cache1 = caches['default'] #Прирывниваем легкий кеш к cache1 cache2 = caches['heavylift'] #Прирывниваем тяжёлый кеш к cache2 cache1.set('my_key', 'Идёт подготовка данных') #Получаем данные из "легкого" кеша, или None (если он пуст) if cache1.get('my_key', None) == None: #Если "легкий" кеш пуст, проверяем heavylift #Получаем данные из "тяжёлого" кеша, или None (если он пуст) if cache2.get('heavylift', None) == None: #Если "тяжёлый" кеш пуст, запускаем асинхронную задачу. Что если он не пуст? #Запуск асинхронной задачи else: #Если "легкий" кеш не пуст - прекращаем работу return
from multiprocessing import Process, Queue, Value import time def fact(q,i1,i2,progr): #print ("i1=",i1," i2=",i2) m=1 for i in range(i1+1,i2+1): m=i*m progr.value=100*(i-i1)//(i2-i1) #print(progr.value) q.put(m) print("exit i1,i2",i1,i2) if __name__ == '__main__': n=35000 k=9 start_time = time.time() q = Queue() progr=[Value('d', 0.0)] * k p=[Process(target=fact,name='{}'.format(i),args=(q,n*i//k,n*(i+1)//k,progr[i],)) for i in range(k)] for x in p: x.start() #for x in p: x.join(0.1) while any(( x.is_alive() for x in p )): time.sleep(1) sum1=0 for x in progr: sum1=sum1+x.value print("progress=",sum1/k) print([(x.is_alive(),x.name) for x in p]) print([x.value for x in progr]) .... res=1 while not q.empty(): res=res*q.get() print("time=",time.time()-start_time) #print(res) ....
<svg viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg" id="svg" height="100%" width="100%"> <text font-family="{font}" font-size="{size}" id="user_text">{text}</text> </svg>
let text = document.getElementById("user_text"); let box = text.getBBox(); let w = box.width; let h = box.height;
import pygame pygame.init() name = "Best Game Ever" logo = pygame.image.load('logo.png') disp_width=1000 #Размер дисплея disp_height=600 player_walk_left = [pygame.image.load('walk left/left1.png'), pygame.image.load('walk left/left2.png'), pygame.image.load('walk left/left3.png'), pygame.image.load('walk left/left4.png')] player_walk_right = [pygame.image.load('walk right/right1.png'), pygame.image.load('walk right/right2.png'), pygame.image.load('walk right/right3.png'), pygame.image.load('walk right/right4.png')] player_stand_right = [pygame.image.load('stand/right1.png'), pygame.image.load('stand/right2.png'), pygame.image.load('stand/right3.png'), pygame.image.load('stand/right4.png')] player_stand_left = [pygame.image.load('stand/left1.png'), pygame.image.load('stand/left2.png'), pygame.image.load('stand/left3.png'), pygame.image.load('stand/left4.png')] disp = pygame.display.set_mode((disp_width, disp_height)) pygame.display.set_caption(name) pygame.display.set_icon(logo) frame = pygame.time.Clock() class player(object): def __init__(self, player_x, player_y, width, height): self.player_x = player_x self.player_y = player_y self.width = width self.height = height self.player_speed = 5 self.jump = False self.left = False self.right = False self.anim_count = 0 self.jump_dist = 7 self.direct = 1 self.stand_right = True self.stand_left = False def draw(self, disp): if self.anim_count + 1 >= 16: self.anim_count = 0 if self.left: disp.blit(player_walk_left[self.anim_count//4], (self.player_x,self.player_y)) self.anim_count += 1 elif self.right: disp.blit(player_walk_right[self.anim_count//4], (self.player_x,self.player_y)) self.anim_count +=1 else: if self.direct == 1: disp.blit(player_stand_right[self.anim_count//4], (self.player_x,self.player_y)) self.anim_count +=1 else: disp.blit(player_stand_left[self.anim_count//4], (self.player_x,self.player_y)) self.anim_count +=1 class fireball_one(object): fb_left = [pygame.image.load('fireball/fb1.png'), pygame.image.load('fireball/fb2.png'), pygame.image.load('fireball/fb3.png'), pygame.image.load('fireball/fb4.png'), pygame.image.load('fireball/fb5.png'), pygame.image.load('fireball/fb6.png'), pygame.image.load('fireball/fb7.png')] def __init__(self, player_x, player_y, facing): self.player_x = player_x self.player_y = player_y self.facing = facing self.fb_vel = 8 * facing def draw(self, disp): for fireball in fireballs: self.move() self.anim_count = 0 if self.anim_count + 1 >= 27: self.anim_count = 0 if self.facing == 1: disp.blit(self.fb_left[self.anim_count//7], (self.player_x,self.player_y)) self.anim_count += 1 else: disp.blit(self.fb_left[self.anim_count//7], (self.player_x,self.player_y)) self.anim_count += 1 def move(self): for fireball in fireballs: if fireball.player_x < 500 and fireball.player_x > 0: fireball.player_x += fireball.fb_vel # Moves the bullet by its vel else: fireballs.pop(fireballs.index(fireball)) self.anim_count = 0 def redrawGameWindow(): disp.blit(pygame.image.load('backgroung.png'), (0,0)) cat.draw(disp) for fireball in fireballs: fireball.draw(disp) pygame.display.update() cat = player(50, 500, 50, 50) run = True #Для включенного состояния игры fireballs = [] while run: frame.tick(30) for events in pygame.event.get(): if events.type == pygame.QUIT: #Выход из игры run = False keys = pygame.key.get_pressed() if keys[pygame.K_f]: if cat.direct == -1: facing = -1 else: facing = 1 if len(fireballs) < 10: fireballs.append(fireball_one(round(cat.player_x + cat.width//2), round(cat.player_y + cat.height//2), facing)) # This will create a bullet starting at the middle of the character if keys[pygame.K_LEFT] or keys[pygame.K_a]: if cat.player_x > 5: cat.direct = -1 cat.player_x -= cat.player_speed cat.left = True cat.right = False cat.stand_left = False cat.stand_right = False elif keys[pygame.K_RIGHT] or keys[pygame.K_d]: if cat.player_x < 970: cat.direct = 1 cat.player_x += cat.player_speed cat.left = False cat.right = True cat.stand_left = False cat.stand_right = False else: if cat.direct == -1: cat.stand_left = False elif cat.direct == 1: cat.stand_right = False cat.left = False cat.right = False if not(cat.jump): if keys[pygame.K_SPACE]: cat.jump = True else: if cat.jump_dist >= -7: if cat.jump_dist < 0: cat.player_y += (cat.jump_dist ** 2) / 3 else: cat.player_y -= (cat.jump_dist ** 2) / 3 cat.jump_dist -= 1 else: cat.jump = False cat.jump_dist = 7 redrawGameWindow() pygame.quit()
import wx import wx.html2 html_string = """ <!DOCTYPE htm> <html> <head> <title>Hello World!</title> </head> <body> <svg viewBox="0 0 192 192" xmlns="http://www.w3.org/2000/svg" id="svg" height="100%" width="100%"> <rect transform="translate(64,128)" width="27" height="64" stroke-width=".5" fill="#ff0" stroke="#000" id="rect"/> <text font-family="monospace" font-size="16" transform="translate(64,141)" id="tsvg">Test Text</text> </svg> <script type="text/javascript"> var text = document.getElementById('tsvg'); alert(text); // ok var tw = text.getComputedTextLength(); alert(tw); // no var box = text.getBBox(); var w = box.width; var h = box.height; alert(w+" "+ h); // no </script> </body> </html> """ class MyBrowser(wx.Dialog): def __init__(self, *args, **kwds): wx.Dialog.__init__(self, *args, **kwds) sizer = wx.BoxSizer(wx.VERTICAL) self.browser = wx.html2.WebView.New(self) sizer.Add(self.browser, 1, wx.EXPAND, 10) self.SetSizer(sizer) self.SetSize((700, 700)) if __name__ == '__main__': app = wx.App() dialog = MyBrowser(None, -1) dialog.browser.SetPage(html_string, '') dialog.Show() app.MainLoop()
import sys import cv2 as cv import numpy as np from collections import Counter from glob import glob def main(argv): ## [load] default_file = 'opencv_frame_6.png' filename = argv[0] if len(argv) > 0 else default_file sum = 0 # Loads an image src = cv.imread(cv.samples.findFile(filename), cv.IMREAD_COLOR) # Check if image is loaded fine if src is None: print ('Error opening image!') print ('Usage: hough_circle.py [image_name -- default ' + default_file + '] \n') return -1 ## [load] ## [convert_to_gray] # Convert it to gray gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY) ## [convert_to_gray] ## [reduce_noise] # Reduce the noise to avoid false circle detection gray = cv.medianBlur(gray, 5) ## [reduce_noise] ## [houghcircles] rows = gray.shape[0] circles = cv.HoughCircles(gray, cv.HOUGH_GRADIENT, 1, rows / 15, param1=100, param2=28, minRadius=59, maxRadius=130) circles1 = cv.HoughCircles(gray, cv.HOUGH_GRADIENT, 1, rows / 21, param1=150, param2=28, minRadius=1, maxRadius=50)## [houghcircles] ## [draw] if circles is not None: circles = np.uint16(np.around(circles)).astype("int") color_red = (0,0,255) for i in circles[0, :]: center = (i[0], i[1]) # circle center cv.circle(src, center, 1, (0, 100, 100), 3) # circle outline radius = i[2] cv.circle(src, center,radius,(255, 0, 255), 3) if circles1 is not None: circles1 = np.uint16(np.around(circles1)).astype("int") color_red = (0,0,255) for i in circles1[0, :]: center = (i[0], i[1]) # circle center cv.circle(src, center, 1, (0, 100, 100), 3) # circle outline radius = i[2] cv.circle(src, center, radius, (255, 0, 255), 3) ## [draw] ## [display] cv.imshow("detected circles", src) print (circles) print (circles1) #print (len(circles[0])) #print (len(circles1[0])) cv.waitKey(0) ## [display] return 0 if __name__ == "__main__": main(sys.argv[1:])
import wx import threading import time class GameWindow(wx.App): class __DrawThread(threading.Thread): def __init__(self, redraw_win): threading.Thread.__init__(self) self.stopped = False self.redraw_win = redraw_win self.start() def run(self): while self.stopped is not True: self.repaint() time.sleep(0.01) def repaint(self): dc = wx.ClientDC(self.redraw_win) dc.Clear() class __ComponentUpdateThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.stopped = False self.start() def run(self): pass class __EvtHandlerThread(threading.Thread): def __init__(self, panel): threading.Thread.__init__(self) self.stopped = False self.panel = panel self.start() def run(self): self.panel.Bind(wx.EVT_KEY_DOWN, self.on_keyboard_down) def on_keyboard_down(self, e): print (e.GetKeyCode()) self.panel.Unbind(wx.EVT_KEY_DOWN) self.panel.Bind(wx.EVT_KEY_DOWN, self.on_keyboard_down) def __init__(self, title="Lucky Project", size=(600, 600)): wx.App.__init__(self) self.__frame__ = wx.Frame(parent=None, title=title, size=size) self.__panel__ = wx.Panel(parent=self.__frame__) self.__frame__.Bind(wx.EVT_CLOSE, self.__on_close) self.__frame__.Center() self.__frame__.Show() self.__repaint_thread = self.__DrawThread(self.__panel__) self.__component_update_thread = self.__ComponentUpdateThread() self.__evt_handler_thread = self.__EvtHandlerThread(self.__panel__) self.MainLoop() def __on_close(self, e): self.__frame__.Destroy() self.__repaint_thread.stopped = True self.__component_update_thread.stopped = True self.__evt_handler_thread.stopped = True win = GameWindow()