def __str__(self): result = "" remarks = filter(lambda x: x.iss("rem"), self.__tags__) for tag in remarks: result += str(tag) + "\n" result += str( self.performer) + "\n" if self.performer is not None else "" result += str(self.title) + "\n" if self.title is not None else "" result += str( self.filename) + "\n" if self.filename is not None else "" timestamp = datetime.timedelta() spaces = "".join([' ' for i in range(indent_space_count)]) for number, song in enumerate(self.songs, 1): # TODO сохранять нумерацию из формы track_tag = Tag("track", ["{0:02d}".format(number), "AUDIO"]) result += spaces + str(track_tag) + "\n" result += spaces * 2 + str(song.title) + "\n" result += spaces * 2 + str(song.performer) + "\n" if not song.is_same_file: result += spaces * 2 + str(song.filename) + "\n" index_tag = Tag("index", ["01", Song.timespamp_str(timestamp)]) result += spaces * 2 + str(index_tag) + "\n" timestamp += song.duration return result
def add_tag_by_name(self, tag_name, vocab=None, autoflush=True): """Add a tag with the given name to this package's tags. By default the given tag_name will be searched for among the free tags (tags which do not belong to any vocabulary) only. If the optional argument `vocab` is given then the named vocab will be searched for the tag name instead. If no tag with the given name is found, one will be created. If the optional argument vocab is given and there is no tag with the given name in the given vocabulary, then a new tag will be created and added to the vocabulary. """ from tag import Tag if not tag_name: return # Get the named tag. tag = Tag.by_name(tag_name, vocab=vocab, autoflush=autoflush) if not tag: # Tag doesn't exist yet, make a new one. if vocab: tag = Tag(name=tag_name, vocabulary_id=vocab.id) else: tag = Tag(name=tag_name) assert tag is not None self.add_tag(tag)
def test_readAllTags(): with open("test/read_all_tags.json", encoding='utf-8') as f: # Init data = json.load(f) # Run allTags = CampaignLogReader(data).readAllTags() # Test expected = [ Tag("§S01E01 Schicksalsfäden").increaseCount().increaseCount(), Tag("#Villerville").increaseCount(), Tag("@Jean Luchs"), ] assert len(allTags) == len(expected) index = 0 for tag in allTags: assert allTags[0].id == expected[ 0].id, "id was " + allTags[0].id + " not " + expected[0].id assert allTags[0].count == expected[ 0].count, "count was " + allTags[0].count + " not " + expected[ 0].count index += 1
def parse_html(self): dom = Dom() index = 0 while index <= len(self.html) - 1: char = self.html[index] if char == "<": if self.html[index + 1] == "/": # Ending a tag self.current_tag.set_closed(True) index = self.html.find(">", index) # Skip over to the end self.current_tag = self.current_tag.parent else: # It's just a normal tag guys, calm down index += 1 char = self.html[index] tag_name = "" while char != ">": # Fill up the name of the tag tag_name += char index += 1 char = self.html[index] if self.current_tag is None: # It's our first tag self.current_tag = Tag(tag_name) dom.set_root(self.current_tag) else: # It's not our first tag self.current_tag = Tag(tag_name, self.current_tag) index += 1 return dom
def interest(): # get the user's tags userTags = Tag().user_tags(graph_db, request.get_cookie(graphstoryUserAuthKey)) # get the tags of user's friends tagsInNetwork = Tag().tags_in_network( graph_db, request.get_cookie(graphstoryUserAuthKey)) # if the user's content was requested if request.query.get('userscontent') == "true": contents = Content().get_user_content_with_tag( graph_db, request.get_cookie(graphstoryUserAuthKey), request.query.get('tag')) # if the user's friends' content was requested else: contents = Content().get_following_content_with_tag( graph_db, request.get_cookie(graphstoryUserAuthKey), request.query.get('tag')) return template('public/templates/graphs/interest/index.html', layout=applayout, userTags=userTags, tagsInNetwork=tagsInNetwork, contents=contents, title="Interest")
def filename(self, name: str): if not (isinstance(name, str) and name != ""): raise ValueError("Недопустимое значение имени файла") filename_tag_r = [(index, tag) for index, tag in enumerate(self.__tags__) if tag.tag_name == "file"] tag_index = filename_tag_r[0][0] if filename_tag_r else None if tag_index is None: self.__tags__.append(Tag("file", [name, "WAVE"])) else: self.__tags__[tag_index] = Tag("file", [name, "WAVE"])
def title(self, name: str): if not(isinstance(name, str)): raise ValueError("Недопустимое значение названия песни") title_tag_r = [(index, tag) for index, tag in enumerate(self.__tags__) if tag.tag_name == "title"] tag_index = title_tag_r[0][0] if title_tag_r else None if tag_index is None: self.__tags__.append(Tag("title", [name])) else: self.__tags__[tag_index] = Tag("title", [name])
def scramble_tags(self, tags): result = [] if len(tags) is not 1: for tag in tags: '''print('avant: '+tag.id)''' result.append(Tag(''.join(random.sample(tag.id, len(tag.id))), tag.hash)) '''print('après: '+tag.id)''' else: result.append(Tag(tags[0].id, tags[0].hash)) return result
def performer(self, name: str): if not (isinstance(name, str)): raise ValueError("Недопустимое значение исполнителя") if name == "": return performer_tag_r = [(index, tag) for index, tag in enumerate(self.__tags__) if tag.tag_name == "performer"] tag_index = performer_tag_r[0][0] if performer_tag_r else None if tag_index is None: self.__tags__.append(Tag("performer", [name])) else: self.__tags__[tag_index] = Tag("performer", [name])
def comment(self, value: str): if not (isinstance(value, str)): raise ValueError("Недопустимое значение комментария") comment_tag_r = [ tag for tag in self.__tags__ if tag.tag_name == "rem" and tag.value[0].lower() == "comment" ] tag_index = comment_tag_r[0][0] if comment_tag_r else None if tag_index is None: self.__tags__.append(Tag("rem", ["comment", value])) else: self.__tags__[tag_index] = Tag("rem", ["comment", value])
def discnumber(self, value: int): if not (isinstance(value, int)): raise ValueError("Недопустимое значение номера диска") comment_tag_r = [ tag for tag in self.__tags__ if tag.tag_name == "rem" and tag.value[0].lower() == "discnumber" ] tag_index = comment_tag_r[0][0] if comment_tag_r else None if tag_index is None: self.__tags__.append(Tag("rem", ["discnumber", value])) else: self.__tags__[tag_index] = Tag("rem", ["discnumber", value])
def _get_tag(value): """ Create a tag from either a string or a numerical value """ if isinstance(value, basestring): tag = name_dictionary.get(value, None) if tag is not None: tag = Tag(tag) else: tag = Tag(value) return tag
def genre(self, name: str): if not (isinstance(name, str)): raise ValueError("Недопустимое значение названия жанра") if name == "": return genre_tag_r = [ tag for tag in self.__tags__ if tag.tag_name == "rem" and tag.value[0].lower() == "genre" ] tag_index = genre_tag_r[0][0] if genre_tag_r else None if tag_index is None: self.__tags__.append(Tag("rem", ["genre", name])) else: self.__tags__[tag_index] = Tag("rem", ["genre", name])
def date(self, value: int): if not (isinstance(value, int)): raise ValueError("Недопустимое значение даты") if value == 0: return date_tag_r = [ tag for tag in self.__tags__ if tag.tag_name == "rem" and tag.value[0].lower() == "date" ] tag_index = date_tag_r[0][0] if date_tag_r else None if tag_index is None: self.__tags__.append(Tag("rem", ["date", value])) else: self.__tags__[tag_index] = Tag("rem", ["date", value])
def handle_starttag(self, tag, attrs): if self.is_result_title(tag, attrs): self.isResult = True self.info = Info() if self.isResult: self.tags.append(Tag(tag, attrs)) else: return if self.is_c_title(tag, attrs): self.isCTitle = True return if self.isCTitle and tag == 'a': for key, value in attrs: if key == 'href': self.info.link = "https://www.google.com" + value return if self.is_c_title_author(tag, attrs): self.isAuthor = True return if self.is_date(tag, attrs): self.isDate = True return
def apply_object_actions(cls, is_build_eco_effects_enabled): if not is_build_eco_effects_enabled: return if not cls.object_tag_to_actions: return object_tags = list(cls.object_tag_to_actions.keys()) curr_obj_tag_id_to_count = services.active_lot( ).get_object_count_by_tags(object_tags) if cls._obj_tag_id_to_count is None: delta_obj_tag_id_to_count = curr_obj_tag_id_to_count else: delta_obj_tag_id_to_count = { key: curr_obj_tag_id_to_count[key] - cls._obj_tag_id_to_count[key] for key in curr_obj_tag_id_to_count } zone = services.current_zone() for (obj_tag_id, obj_count) in delta_obj_tag_id_to_count.items(): if obj_count != 0: for action in cls.object_tag_to_actions[Tag(obj_tag_id)]: success = action.apply(obj_count) if not success: continue if action.action_type == ZoneModifierFromObjectsActionType.STATISTIC_CHANGE: zone.zone_architectural_stat_effects[ action.stat.guid64] += action.get_value(obj_count) cls._on_build_objects_environment_score_update() cls._obj_tag_id_to_count = curr_obj_tag_id_to_count
def __init__(self, *args, **kwargs): self.id = next(id_generator) self.hasfocus = False #set available tags for this control self.availabletags = () if self.COMMON: self.availabletags += self.common_tag if self.FOCUSABLE: self.availabletags += self.focusable_tag if self.ACTION: self.availabletags += self.action_tag self.availabletags += self.additional_tag self.tags = {} #set default tag if necessary if not kwargs.has_key('defaultSKin') or kwargs['defaultSKin'] == True: for default in defaultSkinSetting: if default in self.availabletags: xbmcxml.setTag(self, Tag(default, defaultSkinSetting[default])) #set tag from args for tag in args: if tag.getKey() in self.availabletags: xbmcxml.setTag(self, tag) self.onInit()
def save_photo_description(self, user, title, caption, tag_list): self.title = title self.caption = caption i = 0 tag_list = set([t.strip() for t in tag_list if t.strip() != '']) for t in tag_list: i += 1 # 序号计数 # 统计标签 try: tt = Tag.objects.get(name=t) except Tag.DoesNotExist: tt = Tag(name=t) # 该标签首次出现,创建 else: tt.used_count += 1 # 该标签已存在,增加使用计数 tt.save() self.tags.add(tt) # 为照片添加标签,tags为多对多关系 # 为该用户添加使用的标签 try: usertag = UserTag.objects.get(user=self.owner, tag=tt) except UserTag.DoesNotExist: usertag = UserTag(user=self.owner, tag=tt) # 该用户从未使用过该标签,创建 else: usertag.used_count += 1 # 该用户已有该标签,增加使用计数 usertag.save() self.save() # 保存照片信息
def do(): f = open(CHATS_COLLECTION_NAME) tags = json.loads(f.read()) f.close() chats_by_id = {} for id, tags_json in tags.items(): tags = [] for j in tags_json: user_json = j["from"] first_name = user_json.get("first_name", "") last_name = user_json.get("last_name", "") username = user_json.get("username", "") user = User(user_json["id"], first_name, last_name, username) tag = Tag(j["text"], user, j["date"]) tags.append(tag) admin = 58699815 chats_by_id[id] = Chat(id, tags=tags, admin=admin) encoded = jsonpickle.encode(chats_by_id) f = open(CHATS_COLLECTION_NAME, "w") f.write(encoded) f.close()
def __iter__(s): center(s.__class__.__name__) s.__fetch_if_needed() for item in s.__tags: n = Tag(client=s.__maas).load_dict(item) yield n cleave(s.__class__.__name__)
def load(self, blacklist_data_proto): for blacklist_data in blacklist_data_proto.tag_data: try: tag = Tag(blacklist_data.tag) except KeyError: continue self._blacklist_times[tag] = DateAndTime(blacklist_data.time)
def get_encrypt_datas(self, start_date, end_date): """ 获取加密的数据 :param start_date: 格式化后的开始日期 :param end_date: 格式化后的结束日期 :param tag_url: 需要访问的目标url :return: 加密的结果数据 """ request_args = { 'word': self._keywords, 'startDate': start_date, 'endDate': end_date, 'area': self._area, } # 通过指定目标构造url tag = Tag(self._target) url = tag.structure_urls(request_args) # 获取页面数据 html = self.http_get(url, self._cookie) datas = json.loads(html) if datas['status'] != 0: raise StatusException(datas['status']) uniqid = datas['data']['uniqid'] encrypt_datas = [] if 'userIndexes' in datas['data']: for single_data in datas['data']['userIndexes']: encrypt_datas.append(single_data) else: for single_data in datas['data']['index']: encrypt_datas.append(single_data) return (encrypt_datas, uniqid)
def _parse_tag(self) -> Tag: """ Parse a tag and its subdocument or value """ tag = Tag() # If tag is a processing tag if self.doc[self.i] == '?': tag.type = Tag.TYPES.PROCESSOR self.i += 1 else: tag.type = Tag.TYPES.NORMAL if not is_name_start(self.doc[self.i]): raise InvalidTagName() tag.name = self._parse_name() tag.attributes = self._parse_attributes() if tag.type == Tag.TYPES.NORMAL: # parse subdocument tag.children, tag.value = self._parse_document(tag.name) return tag
def open(self): self.hcontext = HResult(smartcard.scard.SCardEstablishContext(smartcard.scard.SCARD_SCOPE_USER)) self.hcard, dwActiveProtocol = HResult(smartcard.scard.SCardConnect( self.hcontext, self.name, smartcard.scard.SCARD_SHARE_EXCLUSIVE, smartcard.scard.SCARD_PROTOCOL_T0)) self.tag = Tag(self, None, None, None) self.tag.uid = None self.tag.ats = []
def toXml(self): xml = '' xml += '<item id="%d">\n' % self.id if not self.hasTag('onclick'): self.setTag(Tag('onclick', '-')) xml += xbmcxml.toXml(self) xml += '</item>\n' return xml
def setUp(self): self.tag_time_series = (np.array(list(range(20))) + 1) * 100 self.alignment_offset_video_to_tag_ms = -60 self.tag = Tag( latitude_series=None, longitude_series=None, time_series=self.tag_time_series, alignment_offset_video_to_tag_ms=self.alignment_offset_video_to_tag_ms )
def add_tag_by_name(self, tagname, autoflush=True): from tag import Tag if not tagname: return tag = Tag.by_name(tagname, autoflush=autoflush) if not tag: tag = Tag(name=tagname) if not tag in self.tags: self.tags.append(tag)
def index(q): response.content_type = 'application/json' tags = Tag().search_tags(graph_db, q) tagArray = [] # build array for t in tags: tagArray.append({"name": t.name, "id": t.id, "label": t.label}) return dumps(tagArray)
def get_tag(self, name): """ Returns a Tag for the passed name, associated with this API object. If you know the count value for this tag, pass it to update the object. There is no way to query the count directly from the API, but it can be retrieved from other calls such as 'artist', however. """ if name in self.cached_tags.keys(): return self.cached_tags[name] else: return Tag(name, self)
def parse(self, doc: str): """ Parse an XML String """ self.i = 0 self.doc = doc tags, _ = self._parse_document() root = Tag() root.children = tags return root