def _set_filename(self, value): if value is None or value == self._filename: return self._filename = value # construct uid as a key for Cache uid = '%s|%s|%s' % (self.filename, self._mipmap, 0) # in case of Image have been asked with keep_data # check the kv.image cache instead of texture. image = Cache.get('kv.image', uid) if image: # we found an image, yeah ! but reset the texture now. self.image = image self._texture = None self._img_iterate() return else: # if we already got a texture, it will be automatically reloaded. _texture = Cache.get('kv.texture', uid) if _texture: self._texture = _texture return # if image not already in cache then load tmpfilename = self._filename self.image = ImageLoader.load(self._filename, keep_data=self._keep_data, mipmap=self._mipmap) self._filename = tmpfilename # put the image into the cache if needed Cache.append('kv.image', uid, self.image)
def on_grade_submit(self): """ This method submits grade for current answer through server. :param self: It is for handling class structure. :return: It is boolean for grading other answers. """ self.ids["ico_status"].opacity = 0 if not self.ids["input_grade"].text.strip(): if self.ids["txt_auto_grade"].text.strip(" ")[2].strip(): grade = self.ids["txt_auto_grade"].text.split(" ")[2] else: self.ids["ico_status"].opacity = 1 return False else: grade = self.ids["input_grade"].text database_api.grade_answer(Cache.get("info", "token"), Cache.get("lect", "code"), int(self.question_no), Cache.get("lect", "std_nick"), int(grade) ) return True
def _set_filename(self, value): if value is None or value == self._filename: return self._filename = value # construct uid as a key for Cache uid = '%s|%s|%s' % (self.filename, self._mipmap, 0) keep_data = self._keep_data # in case of Image have been asked with keep_data # check the kv.image cache instead of texture. if keep_data: image = Cache.get('kv.image', uid) if image: # we found an image, yeah ! but reset the texture now. self.image = image self._texture = None self._img_iterate() return else: # if we already got a texture, it will be automatically reloaded. _texture = Cache.get('kv.texture', uid) if _texture: return # if image not already in cache then load tmpfilename = self._filename self.image = ImageLoader.load( self._filename, keep_data=self._keep_data, mipmap=self._mipmap) self._filename = tmpfilename # put the image into the cache if needed if keep_data: Cache.append('kv.image', uid, self.image)
def on_pic_select(self, widget_name, file_path, mouse_pos): """ This method uploads selected picture to server and updates related widgets on GUI. :param self: It is for handling class structure. :param widget_name: It is for handling file chooser input. :param file_path: It is path of selected file. :param mouse_pos: It is for handling file chooser input. :return: """ self.popup.dismiss() database_api.uploadProfilePic(Cache.get("info", "token"), Cache.get("info", "nick"), file_path[0] ) if round_image.update_image(): Cache.append("info", "pict", True ) pic = [self.ico_user_picture, self.ids["img_user_card"] ] for pp in pic: pp.source = "data/img/pic_user_current.png" pp.reload()
def on_pre_enter(self): self.sound_hit_low = SoundLoader.load('Sound/pong_hit_low.ogg') self.sound_goal = SoundLoader.load('Sound/goal.ogg') # ReCacheing settings players_count = Cache.get('settings', 'players') if players_count == None: players_count = 1 self.players_count = players_count # difficult = Cache.get('settings', 'difficult') if difficult == None: difficult = 1 self.difficult = difficult # start_ball_velocity = Cache.get('settings', 'start ball velocity') if start_ball_velocity == None: start_ball_velocity = 5 try: start_ball_velocity = float(start_ball_velocity) except Exception: start_ball_velocity = 5 # velocity_multiple = Cache.get('settings', 'velocity multiple') if velocity_multiple == None: velocity_multiple = 1.05 try: velocity_multiple = float(velocity_multiple) except Exception: velocity_multiple = 1.05 Cache.append('settings', 'players', players_count) Cache.append('settings', 'difficult', difficult) Cache.append('settings', 'start ball velocity', start_ball_velocity) Cache.append('settings', 'velocity multiple', velocity_multiple)
def on_pre_enter(self, *args): Functions.existbutton(self) data = list(student_info(Cache.get('user', 'login'))[0]) self.ids['user_name'].text = " ".join(data[0:2]) self.ids['user_id'].text = str(data[4]) if Cache.get("counter", "value") == None: Functions.Calendar(self, 2) else: Functions.Calendar(self, Cache.get("counter", "value"))
def _set_filename(self, value): #Logger.info('CoreImageOpenCV: value %s' % (value)) if value is None or value == self._filename: return self._filename = value # construct uid as a key for Cache if (self.res_width > 0) or (self.res_height > 0): uid = '%s|%d|%d|%s|%s' % (self.filename, self.res_width, self.res_height, self._mipmap, 0) else: uid = '%s|%s|%s' % (self.filename, self._mipmap, 0) # in case of Image have been asked with keep_data # check the kv.image cache instead of texture. image = Cache.get('kv.image', uid) if image: # we found an image, yeah ! but reset the texture now. self.image = image # if image.__class__ is core image then it's a texture # from atlas or other sources and has no data so skip if (image.__class__ != self.__class__ and not image.keep_data and self._keep_data): self.remove_from_cache() self._filename = '' self._set_filename(value) else: self._texture = None self._img_iterate() return else: # if we already got a texture, it will be automatically reloaded. _texture = Cache.get('kv.texture', uid) if _texture: self._texture = _texture return # if image not already in cache then load tmpfilename = self._filename #Logger.info('CoreImageOpenCV: set_filename %s' % (tmpfilename)) #Logger.info('CoreImageOpenCV: %d %d' % (self.res_width, self.res_height)) image = ImageLoader.load( self._filename, keep_data=self._keep_data, mipmap=self._mipmap, nocache=self._nocache, res_width=self.res_width, res_height=self.res_height, load_exif=self.load_exif) self._filename = tmpfilename # put the image into the cache if needed if isinstance(image, Texture): self._texture = image self._size = image.size else: self.image = image if not self._nocache: Cache.append('kv.image', uid, self.image)
def test_map_buy_success(self): self.set_app() _map = get_map_by_title('Default') menu_screen = ValidObject.menu_screen(self.sm.get_screen('menu')) self.assertEqual( menu_screen.get_label_by_text('No map').text, 'No map') self.assertEqual(_map.title, 'Default') self.assertTrue(LevelOne.buy(_map)) self.assertEqual(_map.title, Cache.get('map', 'title')) self.assertEqual(_map.level, Cache.get('map', 'level')) self.assertEqual(_map.map, Cache.get('map', 'map')) self.assertEqual(_map.total_way, Cache.get('map', 'total_way')) self.assertEqual(RM - int(_map.price), Cache.get('bike', 'rm'))
def update_image(): """ This method tries to get profile picture of user from server for rendering. :return: It is for declaring that user has profile picture. """ try: if database_api.getProfilePic(Cache.get("info", "token"), Cache.get("info", "nick")) == "Done": render_image() return True else: return False except: return False
def _set_filename(self, value): if value is None or value == self._filename: return self._filename = value # construct uid as a key for Cache uid = '%s|%s|%s' % (self.filename, self._mipmap, 0) # in case of Image have been asked with keep_data # check the kv.image cache instead of texture. image = Cache.get('kv.image', uid) if image: # we found an image, yeah ! but reset the texture now. self.image = image # if image.__class__ is core image then it's a texture # from atlas or other sources and has no data so skip if (image.__class__ != self.__class__ and not image.keep_data and self._keep_data): self.remove_from_cache() self._filename = '' self._set_filename(value) else: self._texture = None self._img_iterate() return else: # if we already got a texture, it will be automatically reloaded. _texture = Cache.get('kv.texture', uid) if _texture: self._texture = _texture return # if image not already in cache then load tmpfilename = self._filename image = ImageLoader.load(self._filename, keep_data=self._keep_data, mipmap=self._mipmap, nocache=self._nocache) self._filename = tmpfilename # put the image into the cache if needed if isinstance(image, Texture): self._texture = image self._size = image.size else: self.image = image if not self._nocache: Cache.append('kv.image', uid, self.image)
def get_history_rate(self, item, btc_amt, mintime, maxtime): def on_success(request, response): response = json.loads(response) try: hrate = response['bpi'][mintime] hrate = abs(btc_amt) * decimal.Decimal(hrate) Cache.append('history_rate', uid, hrate) except KeyError: hrate = 'not found' self.parent.set_history_rate(item, hrate) # Check local cache before getting data from remote exchange = 'coindesk' uid = '{}:{}'.format(exchange, mintime) hrate = Cache.get('history_rate', uid) if hrate: return hrate req = UrlRequest(url='https://api.coindesk.com/v1/bpi/historical' '/close.json?start={}&end={}' .format(mintime, maxtime) ,on_success=on_success, timeout=15) return None
def template(self, *args, **ctx): '''Create a specialized template using a specific context. .. versionadded:: 1.0.5 With template, you can construct custom widget from a kv lang definition by giving them a context. Check :ref:`Template usage <template_usage>`. ''' # Prevent naming clash with whatever the user might be putting into the # ctx as key. name = args[0] if not name in self.templates: raise Exception('Unknown <%s> template name' % name) baseclasses, defs, fn = self.templates[name] name, baseclasses key = '%s|%s' % (name, baseclasses) cls = Cache.get('kv.lang', key) if cls is None: rootwidgets = [] for basecls in baseclasses.split('+'): rootwidgets.append(Factory.get(basecls)) cls = ClassType(name, tuple(rootwidgets), {}) Cache.append('kv.lang', key, cls) widget = cls() self._push_widgets() self._push_ids() self.idmap = copy(global_idmap) self.idmap['root'] = widget self.idmap['ctx'] = QueryDict(ctx) self.build_item(widget, defs, is_rule=True) self._pop_ids() self._pop_widgets() return widget
def ToAtlas(oFileName): """ checks if a a picture is already availble in a atlas file :rtype: string :param cFileName oFileName: :return: Found FileName """ uRetFileName = oFileName.string oFnSkinPic = Globals.oTheScreen.oSkin.dSkinPics.get(uRetFileName) if not oFnSkinPic is None: uRetFileName = oFnSkinPic.string if Globals.bIgnoreAtlas: return uRetFileName uKey = os.path.splitext(os.path.basename(uRetFileName))[0] if uRetFileName.startswith(Globals.oPathSkin.string): oFn = Globals.oFnAtlasSkin elif uRetFileName.startswith( Globals.oDefinitionPathes.oPathDefinition.string): oFn = Globals.oDefinitionPathes.oFnDefinitionAtlas else: return uRetFileName oAtlas = Cache.get('kv.atlas', oFn.string) if oAtlas: if not oAtlas.textures.get(uKey) is None: return ToUnicode(u'atlas://' + oFn.string + u'/' + uKey) return uRetFileName
def resource_find(filename, use_cache=("KIVY_DOC_INCLUDE" not in os.environ)): '''Search for a resource in the list of paths. Use resource_add_path to add a custom path to the search. By default, results are cached for 60 seconds. This can be disabled using use_cache=False. .. versionchanged:: 2.1.0 `use_cache` parameter added and made True by default. ''' if not filename: return found_filename = None if use_cache: found_filename = Cache.get('kv.resourcefind', filename) if found_filename: return found_filename if filename[:8] == 'atlas://': found_filename = filename else: abspath_filename = abspath(filename) if exists(abspath_filename): found_filename = abspath(filename) else: for path in reversed(resource_paths): abspath_filename = abspath(join(path, filename)) if exists(abspath_filename): found_filename = abspath_filename break if not found_filename and filename.startswith("data:"): found_filename = filename if use_cache and found_filename: Cache.append('kv.resourcefind', filename, found_filename) return found_filename
def scan_qr(self, on_complete): dlg = Cache.get('electrum_widgets', 'QrScannerDialog') if not dlg: dlg = Factory.QrScannerDialog() Cache.append('electrum_widgets', 'QrScannerDialog', dlg) dlg.bind(on_complete=on_complete) dlg.open()
def image(self, filename, load_callback=None, post_callback=None, **kwargs): '''Load a image using loader. A Proxy image is returned with a loading image. :: img = Loader.image(filename) # img will be a ProxyImage. # You'll use it the same as an Image class. # Later, when the image is really loaded, # the loader will change the img.image property # to the new loaded image ''' data = Cache.get('kivy.loader', filename) if data not in (None, False): # found image, if data is not here, need to reload. return ProxyImage(data, loading_image=self.loading_image, loaded=True, **kwargs) client = ProxyImage(self.loading_image, loading_image=self.loading_image, **kwargs) self._client.append((filename, client)) if data is None: # if data is None, this is really the first time self._q_load.append((filename, load_callback, post_callback)) Cache.append('kivy.loader', filename, False) self._start_wanted = True self._trigger_update() else: # already queued for loading pass return client
def __init__(self, link="", tym="", **kwargs): super(RVC, self).__init__(**kwargs) app = App.get_running_app() data_matches = app.get_team_data(data_matches=Cache.get("tymy", "tymy_vysledky"), team="C-tým", matches=True) self.data = [{'text': str(values["souperi"]) + " - " + str(values["vysledek"])} for values in data_matches]
def go_back(self, *args): print('GO BACKKKK >>>>>>>') ViewControl.clear_widgets(self) # ViewControl().remove_widget(PostSplashLoading) l = '{}()'.format(MainV.screen_stack['sc_stack']['p']) print(MainV.screen_stack['sc_stack']['p']) print(MainV.screen_stack['sc_stack']['p'].parent) # print(Cache.print_usage()) # ViewControl.remove_widget(self, MainV.screen_stack['current']) # ViewControl.remove_widget(self, MainV.screen_stack['sc_stack']['p']) # print(ViewControl.children) # print(MainV.screen_stack['sc_stack']['p'].parent) # ViewControl.remove_widget(self, MainV.screen_stack['sc_stack']['p']) # print(ViewControl().children) # ViewControl().clear_widgets(self) # MainV.screen_stack['sc_stack']['p'].unbind() # ViewControl.clear_widgets(self) # for i in ViewControl.children: # print('this is i {}'.format(i)) print("sgasgsadg") # Clock.schedule_once(ViewControl.add_widget(self, Cache.get('mycache','objectid')),10) # MainV.screen_stack['sc_stack']['p'].parent.remove_widget(MainV.screen_stack['sc_stack']['p']) print(MainV.screen_stack['sc_stack']['p'].parent) print(MainV.screen_stack['sc_stack']['p']) # ViewControl.add_widget(self, MainV.screen_stack['sc_stack']['p']) ll = Label(text='test') # ViewControl.add_widget(self,PostSplashLoading()) # Clock.schedule_once(ViewControl.add_widget(self, ll), 3) ViewControl.add_widget(self, Cache.get('mycache', 'objectid'))
def populate(self): self._textures = [] if __debug__: Logger.trace("Image: %r, populate to textures (%d)" % (self.filename, len(self._data))) for count in xrange(len(self._data)): # first, check if a texture with the same name already exist in the # cache uid = "%s|%s|%s" % (self.filename, self._mipmap, count) texture = Cache.get("kv.texture", uid) # if not create it and append to the cache if texture is None: imagedata = self._data[count] texture = Texture.create_from_data(imagedata, mipmap=self._mipmap) if not self._nocache: Cache.append("kv.texture", uid, texture) if imagedata.flip_vertical: texture.flip_vertical() # set as our current texture self._textures.append(texture) # release data if ask if not self.keep_data: self._data[count].release_data()
def tile_draw(self, nx, ny, tx, ty, sx, sy, zoom, bound): '''Draw a specific tile on the screen. Return False if the tile is not yet available.''' # nx, ny = index of tile # tx, ty = real position on scatter # sx, sy = real size on scatter # pzoom = current zoom level image = self.tileserver.get(nx, bound-ny-1, zoom, self.maptype) if image in (None, False): return if not image.texture: Logger.exception('Returned image has no texture.') return if image.texture.wrap is None: image.texture.wrap = GL_CLAMP alpha = Cache.get('tileserver.tilesalpha', image.id) if alpha is None: alpha = 0 if image.loaded: # as soon as we have the image alpha += min(self._dt * 4, 1.0) # fade it in Cache.append('tileserver.tilesalpha', image.id, alpha) with self.canvas: Color(1, 1, 1, alpha) Rectangle(pos=(tx, ty), size=(sx, sy), texture=image.texture)
def template(self, *args, **ctx): '''Create a specialized template using a specific context. .. versionadded:: 1.0.5 With templates, you can construct custom widgets from a kv lang definition by giving them a context. Check :ref:`Template usage <template_usage>`. ''' # Prevent naming clash with whatever the user might be putting into the # ctx as key. name = args[0] if name not in self.templates: raise Exception('Unknown <%s> template name' % name) baseclasses, rule, fn = self.templates[name] key = '%s|%s' % (name, baseclasses) cls = Cache.get('kv.lang', key) if cls is None: rootwidgets = [] for basecls in baseclasses.split('+'): rootwidgets.append(Factory.get(basecls)) cls = type(name, tuple(rootwidgets), {}) Cache.append('kv.lang', key, cls) widget = cls() # in previous versions, ``ctx`` is passed as is as ``template_ctx`` # preventing widgets in it from be collected by the GC. This was # especially relevant to AccordionItem's title_template. proxy_ctx = {k: get_proxy(v) for k, v in ctx.items()} self._apply_rule(widget, rule, rule, template_ctx=proxy_ctx) return widget
def display_screen(self, next_screen, direction, track, *args, **kwargs): old_screen = None if isinstance(next_screen, str): screen = Cache.get('screens', next_screen) if screen is None or next_screen in SCREEN_BLACKLIST: screen = self._create_screen(next_screen, *args, **kwargs) else: screen.reload(*args, **kwargs) next_screen = screen if len(self.children) > 0: old_screen = self.children[0] if not direction: if len(self.list) > 0: next_screen = self.list.pop() next_screen.reload(*args, **kwargs) else: print("No more screens to backtrack.") return if old_screen is None: Refs.log(f'Display {next_screen.name}') else: Refs.log(f'{old_screen.name} → {next_screen.name}') if next_screen not in self.screens: self.add_widget(next_screen) self.current = next_screen.name if old_screen is not None: if old_screen.name == 'dungeon_battle' and old_screen.boss_encounter: Refs.log(f'Battle from boss encounter - Dont delete') return self.remove_widget(old_screen) if track and old_screen.name not in SCREEN_BLACKLIST: self.list.append(old_screen) if old_screen.name in SCREEN_BLACKLIST: Cache.remove('screens', old_screen)
def tile_draw(self, nx, ny, tx, ty, sx, sy, zoom, bound): '''Draw a specific tile on the screen. Return False if the tile is not yet available.''' # nx, ny = index of tile # tx, ty = real position on scatter # sx, sy = real size on scatter # pzoom = current zoom level image = self.tileserver.get(nx, bound - ny - 1, zoom, self.maptype) if image in (None, False): return if not image.texture: Logger.exception('Returned image has no texture.') return if image.texture.wrap is None: image.texture.wrap = GL_CLAMP alpha = Cache.get('tileserver.tilesalpha', image.id) if alpha is None: alpha = 0 if image.loaded: # as soon as we have the image alpha += min(self._dt * 4, 1.0) # fade it in Cache.append('tileserver.tilesalpha', image.id, alpha) with self.canvas: Color(1, 1, 1, alpha) Rectangle(pos=(tx, ty), size=(sx, sy), texture=image.texture)
def stop(self): Logger.debug("HMS: stop") client_token = Cache.get("HMS", "client_token") if client_token is not None: self._store.put("client_token", **client_token) Logger.debug("HMS: stop: put client_token in JsonStore")
def list_constants(self, shorten=True, show_indx=False): "List all env constants." consts = Cache.get(category='envcache', key='constants') if not consts: Logger.info("ENV: Building env constants list.") consts = [] i = 1 for k in sorted(self.env_dict.keys()): v = self.env_dict[k].strip() row = [] if show_indx: if shorten and len(v[:50]) > 50: row = (i, k,v[:50]) else: row = (k, v) consts.append(row) i += 1 # Cache constants Logger.info("ENV: Caching constants.") Cache.append(category='envcache', key='constants', obj=consts) else: Logger.info("ENV: Retrieved constants from cache.") return consts
def template(self, *args, **ctx): '''Create a specialized template using a specific context. .. versionadded:: 1.0.5 With template, you can construct custom widget from a kv lang definition by giving them a context. Check :ref:`Template usage <template_usage>`. ''' # Prevent naming clash with whatever the user might be putting into the # ctx as key. name = args[0] if name not in self.templates: raise Exception('Unknown <%s> template name' % name) baseclasses, rule, fn = self.templates[name] key = '%s|%s' % (name, baseclasses) cls = Cache.get('kv.lang', key) if cls is None: rootwidgets = [] for basecls in baseclasses.split('+'): rootwidgets.append(Factory.get(basecls)) cls = ClassType(name, tuple(rootwidgets), {}) Cache.append('kv.lang', key, cls) widget = cls() self._apply_rule(widget, rule, rule, template_ctx=ctx) return widget
def ToAtlas(uFileName): ''' checks if a a picture is already availble in a atlas file ''' uRetFileName = uFileName uFile=oORCA.oTheScreen.aSkinPics.get(uFileName) if not uFile is None: uRetFileName=uFile if oORCA.bIgnoreAtlas: return uRetFileName uKey=os.path.splitext(os.path.basename(uRetFileName))[0] if uRetFileName.startswith(oORCA.uSkinPath): uFn=oORCA.uAtlasSkinFile elif uRetFileName.startswith(oORCA.oDefinitionPathes.uDefinitionPath): uFn=oORCA.oDefinitionPathes.uDefinitionAtlasFile else: return uRetFileName oAtlas = Cache.get('kv.atlas', uFn) if oAtlas: if not oAtlas.textures.get(uKey) is None: return ToUnicode(u'atlas://'+uFn+u'/'+uKey) return uRetFileName
def populate(self): self._textures = [] if __debug__: Logger.trace('Image: %r, populate to textures (%d)' % (self.filename, len(self._data))) for count in range(len(self._data)): # first, check if a texture with the same name already exist in the # cache uid = '%s|%s|%s' % (self.filename, self._mipmap, count) texture = Cache.get('kv.texture', uid) # if not create it and append to the cache if texture is None: imagedata = self._data[count] imagedata.source = '{}{}|{}'.format( 'zip|' if self.filename.endswith('.zip') else '', self._nocache, uid) texture = Texture.create_from_data(imagedata, mipmap=self._mipmap) if not self._nocache: Cache.append('kv.texture', uid, texture) if imagedata.flip_vertical: texture.flip_vertical() # set as our current texture self._textures.append(texture) # release data if ask if not self.keep_data: self._data[count].release_data()
def populate(self): self._textures = [] fname = self.filename if __debug__: Logger.trace('Image: %r, populate to textures (%d)' % (fname, len(self._data))) for count in range(len(self._data)): # first, check if a texture with the same name already exist in the # cache chr = type(fname) uid = chr(u'%s|%d|%d') % (fname, self._mipmap, count) texture = Cache.get('kv.texture', uid) # if not create it and append to the cache if texture is None: imagedata = self._data[count] source = '{}{}|'.format( 'zip|' if fname.endswith('.zip') else '', self._nocache) imagedata.source = chr(source) + uid texture = Texture.create_from_data( imagedata, mipmap=self._mipmap) if not self._nocache: Cache.append('kv.texture', uid, texture) if imagedata.flip_vertical: texture.flip_vertical() # set as our current texture self._textures.append(texture) # release data if ask if not self.keep_data: self._data[count].release_data()
def populate(self): self._textures = [] if __debug__: Logger.trace('Image: %r, populate to textures (%d)' % (self.filename, len(self._data))) for count in xrange(len(self._data)): # first, check if a texture with the same name already exist in the # cache uid = '%s|%s|%s' % (self.filename, self._mipmap, count) texture = Cache.get('kv.texture', uid) # if not create it and append to the cache if texture is None: texture = Texture.create_from_data( self._data[count], mipmap=self._mipmap) Cache.append('kv.texture', uid, texture) # set as our current texture self._textures.append(texture) # release data if ask if not self.keep_data: self._data[count].release_data()
def populate(self): self._textures = [] if __debug__: Logger.trace('Image: %r, populate to textures (%d)' % (self.filename, len(self._data))) for count in xrange(len(self._data)): # first, check if a texture with the same name already exist in the # cache uid = '%s|%s|%s' % (self.filename, self._mipmap, count) texture = Cache.get('kv.texture', uid) # if not create it and append to the cache if texture is None: texture = Texture.create_from_data(self._data[count], mipmap=self._mipmap) Cache.append('kv.texture', uid, texture) # set as our current texture self._textures.append(texture) # release data if ask if not self.keep_data: self._data[count].release_data()
def on_time_add(self): """ This method adds extra time to exam duration through server. :param self: It is for handling class structure. :return: """ self.duration += 10 database_api.add_time_to_exam(Cache.get("info", "token"), Cache.get("lect", "code"), Cache.get("lect", "exam"), 10) self.ids["txt_duration_clock"].text = str(self.duration) duration_prev = self.ids["txt_info_duration"].text self.ids["txt_info_duration"].text = "{dur} mins".format( dur=int(duration_prev.split(" ")[0]) + 10)
def on_exam_finish_confirm(self, dt): """ This method changes exam's status to finished through server. :param self: It is for handling class structure. :param dt: It is for handling callback input. :return: It is for switching page back to lectures page. """ popup.dismiss() database_api.change_status_of_exam(Cache.get("info", "token"), Cache.get("lect", "code"), Cache.get("lect", "exam"), "finished") return self.on_lects()
def on_stats_target(target): select = Cache.get("info", "id") Cache.append("data", "type", target) Cache.append("data", "select", select) pages.append(StdStats(name="StdStats")) appReset.on_back(pages, screen)
def SubBullet2(self): op = Cache.get("users", "usedirect") entry = open(op + "/Bullets/BulletFormEntry." + date + ".docx", "a") entry.write(self.bullFor.text) entry.close() self.bullFor.text = "" BulletSubmition()
def __init__(self, filename, **kwargs): self.filename = filename self.svg_data = Cache.get("kivy.svg", filename) if not self.svg_data: new_svg = self.load(filename) Cache.append("kivy.svg", filename, new_svg) self.svg_data = new_svg
def _set_filename(self, value): if value is None or value == self._filename: return self._filename = value # construct uid as a key for Cache f = self.filename uid = type(f)(u'%s|%d|%d') % (f, self._mipmap, 0) # in case of Image have been asked with keep_data # check the kv.image cache instead of texture. image = Cache.get('kv.image', uid) if image: # we found an image, yeah ! but reset the texture now. self.image = image # if image.__class__ is core image then it's a texture # from atlas or other sources and has no data so skip if (image.__class__ != self.__class__ and not image.keep_data and self._keep_data): self.remove_from_cache() self._filename = '' self._set_filename(value) else: self._texture = None return else: # if we already got a texture, it will be automatically reloaded. _texture = Cache.get('kv.texture', uid) if _texture: self._texture = _texture return # if image not already in cache then load tmpfilename = self._filename image = ImageLoader.load( self._filename, keep_data=self._keep_data, mipmap=self._mipmap, nocache=self._nocache) self._filename = tmpfilename # put the image into the cache if needed if isinstance(image, Texture): self._texture = image self._size = image.size else: self.image = image if not self._nocache: Cache.append('kv.image', uid, self.image)
def __getitem__(self, item): if not self._loaded_textures[item]: # first, check if a texture with the same name already exist in the # cache # pylint: disable-msg=redefined-builtin chr = type(self._filename) uid = chr(u'%s|%d|%d') % (self._filename, self._mipmap, item) texture = Cache.get('kv.texture', uid) # if not create it and append to the cache if texture is None: zfilename = self._index_list[item] # read file and store it in mem with fileIO struct around it tmpfile = BytesIO(self._zip_file.read(zfilename)) ext = zfilename.split('.')[-1].lower() image = None for loader in ImageLoader.loaders: if (ext not in loader.extensions() or not loader.can_load_memory()): continue Logger.debug('Image%s: Load <%s> from <%s>', loader.__name__[11:], zfilename, self._filename) try: image = loader(zfilename, ext=ext, rawdata=tmpfile, inline=True) except: # pylint: disable-msg=bare-except # noqa # Loader failed, continue trying. continue break if image is None: raise AssertionError("Could not load image {} (index {}) " "from zip {}".format( zfilename, item, self._filename)) self.width = image.width self.height = image.height imagedata = image._data[ 0] # pylint: disable-msg=protected-access source = '{}{}|'.format( 'zip|' if self._filename.endswith('.zip') else '', self._no_cache) imagedata.source = chr(source) + uid texture = Texture.create_from_data(imagedata, mipmap=self._mipmap) if not self._no_cache: Cache.append('kv.texture', uid, texture) if imagedata.flip_vertical: texture.flip_vertical() self._loaded_textures[item] = texture return self._loaded_textures[item]
def on_config_change(self, config, section, key, value): main_screen = Cache.get('cache', 'MainScreen') if key == 'frames': main_screen.ids.video.fps = int(value) elif key == 'detection_certainty': main_screen.ids.video.detection_certainty = int(value) elif key == 'reading_certainty': main_screen.ids.video.reading_certainty = int(value)
def image(self, filename, load_callback=None, post_callback=None, **kwargs): '''Load a image using the Loader. A ProxyImage is returned with a loading image. You can use it as follows:: from kivy.app import App from kivy.uix.image import Image from kivy.loader import Loader class TestApp(App): def _image_loaded(self, proxyImage): if proxyImage.image.texture: self.image.texture = proxyImage.image.texture def build(self): proxyImage = Loader.image("myPic.jpg") proxyImage.bind(on_load=self._image_loaded) self.image = Image() return self.image TestApp().run() In order to cancel all background loading, call *Loader.stop()*. ''' data = Cache.get('kv.loader', filename) if data not in (None, False): # found image, if data is not here, need to reload. return ProxyImage(data, loading_image=self.loading_image, loaded=True, **kwargs) client = ProxyImage(self.loading_image, loading_image=self.loading_image, **kwargs) self._client.append((filename, client)) if data is None: # if data is None, this is really the first time self._q_load.appendleft({ 'filename': filename, 'load_callback': load_callback, 'post_callback': post_callback, 'kwargs': kwargs }) if not kwargs.get('nocache', False): Cache.append('kv.loader', filename, False) self._start_wanted = True self._trigger_update() else: # already queued for loading pass return client
def _img_iterate(self, *largs): # Purpose: check if image has sequences then animate self._iteration_done = True imgcount = count = 0 if self.image: imgcount = len(self.image._data) # get texture for first image from cache uid = '%s|%s|%s' % (self.filename, self._mipmap, count) _texture = Cache.get('kv.texture', uid) if not _texture: # if texture is not in cache while count < imgcount: # append the sequence of images to cache _texture= Texture.create_from_data( self.image._data[count], mipmap=self._mipmap) if not self.image.keep_data: # release excess memory self.image._data[count].release_data() # Cache texture Cache.append('kv.texture', uid, _texture) count += 1 uid = '%s|%s|%s' % (self.filename, self._mipmap, count) else: # texture already in cache for first image # assign texture for non sequenced cached images self._texture = _texture self._size = self.texture.size # check if image has sequence in cache uid = '%s|%s|%s' % (self.filename, self._mipmap, 1) # get texture for second image in sequence _texture_next = Cache.get('kv.texture', uid) if _texture_next: # enable animation (cached sequence img) imgcount = 2 _texture = _texture_next if imgcount > 1: self._anim_available = True # image sequence, animate self.anim_reset(True) self._texture = _texture # image loaded for the first time if self.image: self.image._texture = self._texture = _texture
def show_tx_details(self, item): ra_dialog = Cache.get('electrum_widgets', 'RecentActivityDialog') if not ra_dialog: Factory.register('RecentActivityDialog', module='electrum_gui.kivy.uix.dialogs.carousel_dialog') Factory.register('GridView', module='electrum_gui.kivy.uix.gridview') ra_dialog = ra_dialog = Factory.RecentActivityDialog() Cache.append('electrum_widgets', 'RecentActivityDialog', ra_dialog) ra_dialog.item = item ra_dialog.open()
def on_source(self, instance, value): if not value: self.texture = None else: filename = resource_find(value) texture = Cache.get('kv.texture', filename) if not texture: image = CoreImage(filename) texture = image.texture Cache.append('kv.texture', filename, texture) self.texture = texture
def _create_line_label(self, text): # Create a label from a text, using line options ntext = text.replace("\n", "").replace("\t", " " * self.tab_width) kw = self._get_line_options() cid = "%s\0%s" % (ntext, str(kw)) texture = Cache.get("textinput.label", cid) if not texture: label = Label(text=ntext, **kw) label.refresh() texture = label.texture Cache.append("textinput.label", cid, texture) return texture
def _create_line_label(self, text): # Create a label from a text, using line options ntext = text.replace('\n', '').replace('\t', ' ' * self.tab_width) kw = self._get_line_options() cid = '%s\0%s' % (ntext, str(kw)) texture = Cache.get('textinput.label', cid) if not texture: label = Label(text=ntext, **kw) label.refresh() texture = label.texture Cache.append('textinput.label', cid, texture) return texture
def texture_update(self, *largs): if not self.source: self.texture = None else: filename = resource_find(self.source) mipmap = self.mipmap uid = '%s|%s' % (filename, mipmap) texture = Cache.get('kv.texture', uid) if not texture: image = CoreImage(filename, mipmap=mipmap) texture = image.texture Cache.append('kv.texture', uid, texture) self.texture = texture
def image(self, filename, load_callback=None, post_callback=None, **kwargs): '''Load a image using the Loader. A ProxyImage is returned with a loading image. You can use it as follows:: from kivy.app import App from kivy.uix.image import Image from kivy.loader import Loader class TestApp(App): def _image_loaded(self, proxyImage): if proxyImage.image.texture: self.image.texture = proxyImage.image.texture def build(self): proxyImage = Loader.image("myPic.jpg") proxyImage.bind(on_load=self._image_loaded) self.image = Image() return self.image TestApp().run() In order to cancel all background loading, call *Loader.stop()*. ''' data = Cache.get('kv.loader', filename) if data not in (None, False): # found image, if data is not here, need to reload. return ProxyImage(data, loading_image=self.loading_image, loaded=True, **kwargs) client = ProxyImage(self.loading_image, loading_image=self.loading_image, **kwargs) self._client.append((filename, client)) if data is None: # if data is None, this is really the first time self._q_load.appendleft({ 'filename': filename, 'load_callback': load_callback, 'post_callback': post_callback, 'kwargs': kwargs}) if not kwargs.get('nocache', False): Cache.append('kv.loader', filename, False) self._start_wanted = True self._trigger_update() else: # already queued for loading pass return client
def _get_text_width(self, text): # fix cursor placement diff cause of markup kw = self._line_options ntext = text.replace('\t', ' ' * self.tab_width) cid = '%s\0%s' % (ntext, str(kw)) width = Cache.get('textinput.label.width', cid) if not width: texture = self._create_line_label(ntext) # use width of texture of '.' instead of ' ' in start of line, # which is of 0 width in markup width = texture.width if texture else\ self._label_cached.get_extents('.')[0] * len(ntext) Cache.append('codeinput.label.width', cid, width) return width
def texture_update(self, *largs): if not self.source: self.texture = None else: filename = resource_find(self.source) if filename is None: return mipmap = self.mipmap uid = "%s|%s" % (filename, mipmap) texture = Cache.get("kv.texture", uid) if not texture: image = CoreImage(filename, mipmap=mipmap) texture = image.texture Cache.append("kv.texture", uid, texture) self.texture = texture
def _anim(self, *largs): # called on every interval of clock as set by anim_reset uid = '%s|%s|%s' % (self._filename, self._mipmap, self._anim_index) _tex = Cache.get('kv.texture', uid) if _tex: # if not last frame self._texture = _tex self._anim_index += 1 # fire a texture update(to be handled by widget/s) self.dispatch('on_texture') else: # Prevent infinite looping in case we set manually an image if self._anim_index == 0: return False # Restart animation from first Frame self._anim_index = 0 self._anim()
def _create_line_label(self, text): #TODO: optimize this func, it's horribly inefficient ntext = text.replace('\n', '').replace('\t', ' ' * self.tab_width) # Create a label from a text, using line options kw = self._line_options cid = '%s\0%s' % (ntext, str(kw)) texture = Cache.get('codeinput.label', cid) if not texture: #if multiple lines render empty texture wait for refresh text' if text.find('\n') > 0: label = self._label_cached label.text = '' label.refresh() texture = label.texture Cache.append('codeinput.label', cid, texture) return texture #get bbcoded text for python try: ntext[0] # replace brackets with special chars that aren't highlighted # by pygment. can't use &bl; ... cause & is highlighted # if at some time support for braille is added then replace these # characters with something else ntext = ntext.replace('[', u'⣿;').replace(']', u'⣾;') ntext = highlight(ntext, self.lexer, self.formatter) ntext = ntext.replace(u'⣿;', '&bl;').replace(u'⣾;', '&br;') # replace special chars with &bl; and &br; ntext = ''.join(('[color=rgba', str(self.text_color), ']', ntext, '[/color]')) except IndexError: pass # FIXME right now, we can't render very long line... # if we move on "VBO" version as fallback, we won't need to do this. # try to found the maximum text we can handle label = self._markup_label_cached label.text = ntext label.texture_update() texture = label.texture label.text = '' Cache.append('codeinput.label', cid, texture) return texture
def remove_from_cache(self): '''Remove the Image from cache. This facilitates re-loading of image from disk in case of contents having been changed. .. versionadded:: 1.3.0 Usage:: im = CoreImage('1.jpg') # -- do something -- im.remove_from_cache() im = CoreImage('1.jpg') # this time image will be re-loaded from disk ''' count = 0 uid = '%s|%s|%s' % (self.filename, self._mipmap, count) Cache.remove("kv.image", uid) while Cache.get("kv.texture", uid): Cache.remove("kv.texture", uid) count += 1 uid = '%s|%s|%s' % (self.filename, self._mipmap, count)
def get(self, nx, ny, zoom, maptype, format='png'): '''Get a tile ''' filename = self.to_filename(nx, ny, zoom, maptype, format) img = Cache.get('tileserver.tiles', filename) # check if the tile is already being loaded if img is False: return None # check if the tile exist in the cache if img is not None: return img # no tile, ask to workers to download Cache.append('tileserver.tiles', filename, False) self.q_count += 1 self.q_in.append((nx, ny, zoom, maptype, format)) self.c_in.acquire() self.c_in.notify() self.c_in.release() return None
def remove_from_cache(self): '''Remove the Image from cache. This facilitates re-loading of images from disk in case the image content has changed. .. versionadded:: 1.3.0 Usage:: im = CoreImage('1.jpg') # -- do something -- im.remove_from_cache() im = CoreImage('1.jpg') # this time image will be re-loaded from disk ''' count = 0 f = self.filename pat = type(f)(u'%s|%d|%d') uid = pat % (f, self._mipmap, count) Cache.remove("kv.image", uid) while Cache.get("kv.texture", uid): Cache.remove("kv.texture", uid) count += 1 uid = pat % (f, self._mipmap, count)