def load_dictionary(self, source, language, dict_path): counter, start_at = 0, int(time.time()) print("\nLoading entity_dictionary from: {}".format(dict_path)) with open(dict_path, "r", encoding="utf-8") as rf: for line in rf: line_arr = line.strip().split("\t\t") if len(line_arr) != 4: continue title, sub_title, uris, entity_id = line_arr uris = uris.split("::;") counter += 1 entity = Entity(entity_id, title, sub_title, source, language) for uri in uris: self._uri_2_id[uri] = entity_id self._fulltitle_2_id[entity.get_full_title()] = entity_id title_mention = self.get_mention_from_title( entity.get_full_title()) if self._mention_2_ids.get(title_mention) is None: self._mention_2_ids[title_mention] = dict() self._mention_2_ids[title_mention][entity_id] = None self.entity_dict[entity_id] = entity print("Loaded, #{}, time: {}.".format( counter, str(datetime.timedelta(seconds=int(time.time()) - start_at))))
def set(): data = request.get_json() key = data['key'] value = data['value'] # check empty one of below if key and value: query = db.session.query(Entity).filter( Entity.key == key, Entity.user_id == session['owner']).first() if query is not None: # check the same value exist if query.value == value: flash('key/value already exist', 'warning') return json.dumps({'status': 'key/value already exist'}) # change only value query.value = value db.session.commit() else: # full query db.session.add( Entity(key=key, value=value, user_id=session['owner'])) db.session.commit() message = ('').join(("Set ", key, "/", value)) flash(message) else: flash('Not correct data!', 'error') return json.dumps({'status': 'Not correct data!'}) return json.dumps({'status': 'OK'})
def create_entities(name_to_info): """Create the entities from the list of names. Returns the dict to map names indices to the Mongo Entity ID Args: * name_to_info: dict {name: {'id': index, 'image_url': image_url, 'twitter': <twitter_account>, ...}, ...} Returns: * index_to_id: dict {name_index: entity.id} """ index_to_id = {} for name, attr in name_to_info.items(): kwargs = {} # We may not have the image if 'image_url' in attr: kwargs['image_url'] = attr['image_url'] # Social media accounts kwargs['accounts'] = { k: attr[k] for k in attr if k not in ['id', 'image_url'] } ent = Entity(name=name, **kwargs) ent.save() # Store the indices to link the index from the timecode and the Mongo index index = attr['id'] index_to_id[index] = ent.id return index_to_id
def analyse_sentiment(id, text, posted_at): document = types.Document(content=text, type=enums.Document.Type.PLAIN_TEXT) # Detect the entities in the text try: entities = nl_api_client.analyze_entity_sentiment( document=document, encoding_type='UTF8').entities # Build up our entities object to insert into the table entities_object = [] for e in entities: entity = Entity( name=e.name, \ type=e.type, \ wikipedia_url=e.metadata['wikipedia_url'], \ mid=e.metadata['mid'], \ salience=e.salience, \ sentiment_score=e.sentiment.score, \ sentiment_magnitude=e.sentiment.magnitude, \ posted_at=posted_at, \ remote_post_id=id ) entity.mentions = create_entity_mentions(e.mentions) entities_object.append(entity) except InvalidArgument as err: print(err) return False # Insert entities and mentions into the database session.add_all(entities_object)
def add_entities(session): added = False for entity_value in ENTITIES: entity = session.query(Entity).filter(Entity.label == entity_value) if not entity.count(): added = True session.add(Entity(label=entity_value)) else: entity_records[entity_value] = entity.first() if added: session.commit()
async def init_db(): from models import Department, Employee, Role, User, Entity Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine) # Create Fixture for Users user1 = User(name='user1') db_session.add(user1) user2 = User(name='user2') db_session.add(user2) # Create Fixture for Profiles entity1 = Entity(user=user1, provider="email", data={"email": "*****@*****.**"}) db_session.add(entity1) entity2 = Entity(user=user1, provider="facebook", data={"token": "blablabla"}) db_session.add(entity2) entity3 = Entity(user=user2, provider="email", data={"email": "*****@*****.**"}) db_session.add(entity3) # Insert seed data into database db_session.commit() print('committed!')
def post(self): template_values = get_template_values(self) user = users.get_current_user() try: entity_query = Entity.query(Entity.id == user.user_id()).fetch() entity = entity_query[0] except IndexError: # This user must not exist yet, so create one entity = Entity( user=user, id=user.user_id(), created=datetime.datetime.now(), test_groups=[], ) if not entity.display_name: posted_name = self.request.get('display_name') else: posted_name = entity.display_name # Show an error if the name isn't formatted properly. if re.match('^[a-z0-9]{3,16}$', posted_name) is None: template_values[ 'error'] = "Usernames must be 16 or fewer alphanumeric characters [a-z0-9]." path = os.path.join(os.path.dirname(__file__), os.path.join(template_dir, 'register.html')) self.response.out.write(template.render(path, template_values)) return users_with_name = Entity.query( Entity.display_name == posted_name).count() if users_with_name == 0 or entity.display_name == posted_name: # Update values entity.display_name = posted_name if posted_name else entity.display_name entity.bio = self.request.get('bio') if len( self.request.get('bio')) > 0 else "I am mysterious." # Save and visit entity.put() time.sleep( 0.1 ) # The user doesn't exist for a short period of time after put() self.redirect('/u/%s' % entity.display_name) else: template_values[ 'error'] = "That username is in use. Please choose again." path = os.path.join(os.path.dirname(__file__), os.path.join(template_dir, 'register.html')) self.response.out.write(template.render(path, template_values)) return
def _handle_entities(self, tweet, tweet_data): for category in tweet_data.entities: for entity_data in tweet_data.entities[category]: content = '' if category == 'urls': content = entity_data['expanded_url'] if category == 'hashtags': content = entity_data['text'] if category == 'user_mentions': content = entity_data['screen_name'] entity = Entity(category=category, tweet=tweet, content=content) self.session.add(entity)
def update_entity(): tree = Tree() all_nodes = tree.build('./post/entity.txt', False) for node in all_nodes: node = tree.get_or_create(node) entity = Entity.query(Entity.name == node.entity).get() print '-----------------------' print node.get_parent() print node.entity print node.get_children() print node.get_ref() if entity: entity.from_entity = node.get_parent() entity.to_entity = node.get_children() entity.ref_entity = node.get_ref() entity.put() else: Entity( name=node.entity, from_entity=node.get_parent(), to_entity=node.get_children(), ref_entity=node.get_ref(), ).put()
def main(): pygame.init() screen = pygame.display.set_mode((xRes, yRes)) pygame.display.set_caption('Roguelike') animationIndex, spriteIndex = 0, 0 clock = pygame.time.Clock() player = Entity(level) loadTextures() loadLevel(tileData, decorationData, level) while True: clock.tick(24) player.isMoving = False player.dx, player.dy = 0, 0 keys = pygame.key.get_pressed() if keys[K_ESCAPE]: return if keys[K_UP]: player.isMoving = True player.dy = -2 * gameScale if keys[K_DOWN]: player.isMoving = True player.dy = 2 * gameScale if keys[K_LEFT]: player.isFacingRight = False player.isMoving = True player.dx = -2 * gameScale if keys[K_RIGHT]: player.isFacingRight = True player.isMoving = True player.dx = 2 * gameScale if keys[K_z]: player.isCasting = True animationIndex = 0 for event in pygame.event.get(): if event.type == QUIT: return if animationIndex < 9: animationIndex += 1 else: animationIndex = 0 player.isCasting = False player.isMoving = False if player.isCasting: spriteIndex = 3 elif player.isMoving: spriteIndex = 2 else: spriteIndex = 0 player.image, player.rect = playerTextures[spriteIndex][animationIndex] if not player.isFacingRight: player.image = pygame.transform.flip(player.image, True, False) pX, pY = player.update() for y in range(0, 16): for x in range(0, 16): screen.blit( level.getTileAt(x, y).image, (x * 16 * gameScale, y * 16 * gameScale + level.getTileAt(x, y).offsetY)) if (level.getDecorationAt(x, y) is not None): screen.blit( level.getDecorationAt(x, y).image, (x * 16 * gameScale, y * 16 * gameScale + level.getDecorationAt(x, y).offsetY)) if ((x, y - 1) == (pX, pY)): screen.blit( player.image, (player.x + player.offsetX, player.y + player.offsetY)) playerPos = (player.x + player.offsetX, player.y + player.offsetY ) #позиция игрока на карте x,y for indx, _ in enumerate( gameObjectList): #в массиве всех созданным нами объектов curObj = gameObjectList[indx] screen.blit( curObj.img, curObj.pos ) #рисуем картинку каждого объекта на поверхность игрового экрана if (playerPos[1] + player.rect[3]) >= ( curObj.pos[1] + curObj.lowestY ): #если самая нижняя точка игрока объекта выше игрока screen.blit(player.image, playerPos) #рисуем игрока поверх объекта pygame.display.flip()
def main(): pygame.init() screen = pygame.display.set_mode((xRes, yRes)) pygame.display.set_caption('Roguelike') animationIndex, spriteIndex = 0, 0 clock = pygame.time.Clock() player = Entity(level) loadTextures() loadLevel(tileData, decorationData, level) while True: clock.tick(24) player.isMoving = False player.dx, player.dy = 0, 0 keys = pygame.key.get_pressed() if keys[K_ESCAPE]: return if keys[K_UP]: player.isMoving = True player.dy = -2 * gameScale if keys[K_DOWN]: player.isMoving = True player.dy = 2 * gameScale if keys[K_LEFT]: player.isFacingRight = False player.isMoving = True player.dx = -2 * gameScale if keys[K_RIGHT]: player.isFacingRight = True player.isMoving = True player.dx = 2 * gameScale if keys[K_z]: player.isCasting = True animationIndex = 0 mouse_pos = pygame.mouse.get_pos( ) # получение координат указателя мыши ## ОБРАБОТКА НАЖАТИЙ КЛАВИАТУРЫ И МЫШИ ## for event in pygame.event.get( ): # добавляем свой функционал в цикл получения сообщений от мыши и клавиатуры if event.type == MOUSEBUTTONDOWN: # если произошло событие - нажатие кнопки мыши #mouse_pos = event.pos # Получаем x,y координаты мыши на экране игры for cur_obj in gameObjectList: # Для всех объектов проверяем попадение курсора мыши в этот объект pos_in_mask = mouse_pos[0] - cur_obj.img_rect.x, mouse_pos[ 1] - cur_obj.img_rect.y # вычисление позиции курсора относительно координат маски прозрачности объекта if cur_obj.img_rect.collidepoint( mouse_pos ) and cur_obj.img_mask.get_at( pos_in_mask ) == 1: # проверяем, находится ли мышь на каком-то объекте, и прозрачен ли пиксель, на котором находится указатель мыши cur_obj_name = 'unnamed' ### имя объекта, по-умолчанию безымянный if 'ObjectName' in cur_obj.obj_props: ### если в словаре есть свойство ИмяОбъекта cur_obj_name = cur_obj.obj_props[ "ObjectName"] ### создаем надпись с этим именем new_text_obj = models.TextObject( [mouse_pos[0], mouse_pos[1]], cur_obj_name, white_color, 1500 ) # Создаем текстовый объект с координатами указателя мыши, текстом, равным имени объекта под мышкой, белым цветом шрифтаwhite_color и временем существования 1500 миллисеукнд new_text_obj.time1 = time.time( ) # в свойство текстового объекта time1 заносим время, когда этот текст создан if pygame.mouse.get_pressed( )[2]: ### если нажата ПРАВАЯ кнопка мыши textObjectList.append( new_text_obj ) # Добавляем новую надпись(текстовый объект) в список всех надписей else: ### если нажата ЛЕВАЯ кнопка мыши, захватываем объект cur_obj.follow_mouse = True # устанавливаем флаг следования за мышкой(захватываем объект мышкой) cur_obj.follow_mouse_offset = [ mouse_pos[0] - cur_obj.pos[0], mouse_pos[1] - cur_obj.pos[1] ] # смещение мышки относительно нулевых координат области объекта break # после первого найденного объекта под мышкой, выходим из цикла, чтобы не появлялось несколько надписей в одном месте elif event.type == pygame.KEYUP: if event.key == pygame.K_e: ### Если на клавитуре нажата клавиша 'e' if World.edit_mode == None: ### Включаеv режим EDIT(Редактирования объектов) mode_text_obj = models.TextObject( [10, 10], "EDIT", white_color, -1, 40) ### создаем надпись слева вверху textObjectList.append( mode_text_obj ) ### Добавляем надпись в список всех текстовых объектов World.edit_mode = textObjectList[len(textObjectList) - 1] else: ### Если режим Редактирования уже включен, textObjectList.remove( World.edit_mode) ### Удаляем надпись World.edit_mode = None ### Отменяем режим Редактирования(EDIT) ## При выключении режима редактирования, выводим в консоль все объекты all_objects_dict = [] ###список со всеми объектами for i in range(len(gameObjectList) - 1): ### Для всех оюъектов в игре cur_obj = gameObjectList[i] ###текущий объект new_obj_dict = { 'obj_props': cur_obj. obj_props, ### все свойства объекта заносим во вложенный словарь 'posX': cur_obj.pos[0], ### Позиция X 'posY': cur_obj.pos[1], ### Позиция Y 'width': cur_obj.img_rect.w, ### Ширина картинки 'height': cur_obj.img_rect.h ### Высота картинки } all_objects_dict.append( new_obj_dict ) ### добавляем новый объект с описанием в список всех объектов json_dump = json.dumps( all_objects_dict ) ### выгружаем описание всех объектов игры в json-формате print(json.dumps( json_dump)) ### выводим полученный json в консоль elif event.key == pygame.K_r: ### Постоянное отображение рамок все объектов if World.show_rects: ### Если включено World.show_rects = False ### выключаем режим else: ### включаем, если отключено World.show_rects = True elif event.type == QUIT: return if animationIndex < 9: animationIndex += 1 else: animationIndex = 0 player.isCasting = False player.isMoving = False if player.isCasting: spriteIndex = 3 elif player.isMoving: spriteIndex = 2 else: spriteIndex = 0 player.image, player.rect = playerTextures[spriteIndex][animationIndex] if not player.isFacingRight: player.image = pygame.transform.flip(player.image, True, False) pX, pY = player.update() for y in range(0, 16): for x in range(0, 16): screen.blit( level.getTileAt(x, y).image, (x * 16 * gameScale, y * 16 * gameScale + level.getTileAt(x, y).offsetY)) if (level.getDecorationAt(x, y) is not None): screen.blit( level.getDecorationAt(x, y).image, (x * 16 * gameScale, y * 16 * gameScale + level.getDecorationAt(x, y).offsetY)) if ((x, y - 1) == (pX, pY)): screen.blit( player.image, (player.x + player.offsetX, player.y + player.offsetY)) ## ОТРИСОВКА ОБЪЕКТОВ ## player_pos = (player.x + player.offsetX, player.y + player.offsetY ) #позиция игрока на карте x,y for indx, _ in enumerate( gameObjectList): #в массиве всех созданным нами объектов cur_obj = gameObjectList[indx] if cur_obj.follow_mouse: # Если установлен флаг следования за мышкой (объект взят) if World.edit_mode != None or ( 'CanMove' in cur_obj.obj_props and cur_obj.obj_props['CanMove'] == 'True' ): ### Если включен режим редактирования(EDIT) # получение состояния нажатия всех кнопок мыши if pygame.mouse.get_pressed( )[0]: # проверяем, нажата ли ЛЕВАЯ кнопка мыши newPosX = mouse_pos[0] - cur_obj.follow_mouse_offset[ 0] # высчитываем новую позицию с учетом смещения X-координату newPosY = mouse_pos[1] - cur_obj.follow_mouse_offset[ 1] # Y-координату cur_obj.set_position( [newPosX, newPosY] ) # при зажатой кнопке мыши, переносим объект на текущую позицию мыши else: # если левая кнопка отпущена, бросаем предмет cur_obj.follow_mouse = False # отключаем следование за мышью(бросаем объект) gameObjectList.sort( key=lambda x: x.pos[1] + x.lowestY ) # снова сортируем объекты в правильном порядке по самому нижнему пикселю screen.blit( cur_obj.img, cur_obj.pos ) #рисуем картинку каждого объекта на поверхность игрового экрана if World.show_rects or ( World.edit_mode != None and cur_obj.follow_mouse ): ### Если включен режим Редактирования(EDIT), рисуем прямоугольники, очерчивающие непрозрачную область объекта и прямоугольник для коллизий opq_rect = pygame.Rect( cur_obj.pos[0] + cur_obj.opaq_rect[0], cur_obj.pos[1] + cur_obj.opaq_rect[1], cur_obj.opaq_rect[2], cur_obj.opaq_rect[3] ) ### расчет прямоугольника для отображения на игровом экране pygame.draw.rect(screen, white_color, opq_rect, 1) ### рисуем рамку объекта col_rect = pygame.Rect(cur_obj.pos[0] + cur_obj.coll_rect[0], cur_obj.pos[1] + cur_obj.coll_rect[1], cur_obj.coll_rect[2], cur_obj.coll_rect[3]) pygame.draw.rect( screen, (100, 255, 0), col_rect, 2 ) ### зеленым цветом рисуем область коллизий данного объекта if (player_pos[1] + player.rect[3]) >= ( cur_obj.pos[1] + cur_obj.lowestY ): #если самая нижняя точка игрока объекта выше игрока screen.blit(player.image, player_pos) #рисуем игрока поверх объекта if World.edit_mode != None: ### Если режим EDIT player_rect = pygame.Rect( player_pos[0], player_pos[1], player.rect[2], player.rect[3]) ### Расчитываем прямоугольник вокруг игрока pygame.draw.rect(screen, (0, 0, 255), player_rect, 2) ### рисуем рамку игрока ## ОТРИСОВКА ТЕКСТОВЫХ ОБЪЕКТОВ ## for indx, _ in enumerate( textObjectList ): # перечисляем все надписи(текстовые объекты из их общего списка) text_obj = textObjectList[ indx] # работаем с самим объектом, а не копией, как в случае просто for цикла, чтобы не тратить лишнюю память if text_obj.text_visible == False: # Если в объекте указана невидимость continue # пропускаем этот объект text_surface = pygame.font.SysFont( text_obj.font_name, text_obj.font_size).render( text_obj.text_str, False, text_obj.text_color ) # рисуем текст(создаем поверхность Surface с текстом) screen.blit( text_surface, text_obj.pos ) # накладываем поверхность с нарисованным текстом на поверхность экрана, выводя текст на игровой экран if text_obj.exist_time != -1: # если у надписи указано время существования(exist_time) elapsed = ( time.time() - text_obj.time1 ) * 1000 #проверяем сколько миллисекунд прошло со времени создания надписи if elapsed > text_obj.exist_time: # если прошло больше времени, чем указано во времени существования (exist_time) textObjectList.pop( indx) # удаляем объект из списка надписей pygame.display.flip()
def run(train_file, label_file, flag): examples = [] ex = Example(None, None, []) cur_entity = Entity(0, 0, None, None) text = "" entities = [] with open(train_file, "r") as tr: with open(label_file, "r") as lb: for line in tr.readlines(): if line == "\n": if cur_entity.to_add: entities.append(cur_entity) cur_label = lb.readline() ex.text = text ex.intent = transform_intent(cur_label.split("\n")[0]) for ent in entities: ent.find_start_end(ex.text) ex.entities.append(ent) examples.append(ex) ex = Example(None, None, []) text = "" entities = [] cur_entity = Entity(0, 0, None, None) else: word, tag = line.split("\t") if text == "": text = word else: text = text + " " + word tag = tag.split("\n")[0] if tag == "O": if cur_entity.entity is not None: entities.append(cur_entity) cur_entity = Entity(0, 0, None, None) elif tag.startswith("B"): if cur_entity.entity is not None: entities.append(cur_entity) cur_entity = Entity(0, 0, word, tag[2:]) else: cur_entity.entity = tag[2:] cur_entity.value = word cur_entity.to_add = True elif tag.startswith("I"): if cur_entity is not None: if cur_entity.entity == tag[2:]: cur_entity.value = cur_entity.value + " " + word cur_entity.to_add = True final_json = { "rasa_nlu_data": { "common_examples": [example.get_json() for example in examples], "entity_examples": [], "intent_examples": [] } } file_names = ["exact.json", "test.json"] with open("basic_intents.json") as f: data = json.load(f) for el in data: final_json["rasa_nlu_data"]["common_examples"].append(el) with open(file_names[flag], "w") as j: json.dump(final_json, j)
def main(): pygame.init() screen = pygame.display.set_mode((xRes, yRes)) pygame.display.set_caption('Roguelike') animationIndex, spriteIndex = 0, 0 clock = pygame.time.Clock() player = Entity(level) loadTextures() loadLevel(tileData, decorationData, level) while True: clock.tick(24) player.isMoving = False player.dx, player.dy = 0, 0 mouse_pressed1, mouse_pressed2, mouse_pressed3 = pygame.mouse.get_pressed( ) ### получаем состояние нажатых на мышке кнопок keys = pygame.key.get_pressed() if keys[K_ESCAPE]: return if keys[K_UP]: player.isMoving = True player.dy = -2 * gameScale if keys[K_DOWN]: player.isMoving = True player.dy = 2 * gameScale if keys[K_LEFT]: player.isFacingRight = False player.isMoving = True player.dx = -2 * gameScale if keys[K_RIGHT]: player.isFacingRight = True player.isMoving = True player.dx = 2 * gameScale if keys[K_z]: player.isCasting = True animationIndex = 0 #### ОБРАБОТКА НАЖАТИЙ КЛАВИАТУРЫ И МЫШИ #### for event in pygame.event.get( ): ### добавляем свой функционал в цикл получения сообщений от мыши и клавиатуры if event.type == MOUSEBUTTONDOWN: ### если произошло событие - нажатие кнопки мыши mouse_pos = event.pos ### Получаем x,y координаты мыши на экране игры for curObj in gameObjectList: ### Для всех объектов проверяем попадение курсора мыши в этот объект pos_in_mask = mouse_pos[0] - curObj.img_rect.x, mouse_pos[ 1] - curObj.img_rect.y ### вычисление позиции курсора относительно координат маски прозрачности объекта if curObj.img_rect.collidepoint( mouse_pos ) and curObj.img_mask.get_at( pos_in_mask ) == 1: ### проверяем, находится ли мышь на каком-то объекте, и прозрачен ли пиксель, на котором находится указатель мыши new_time_obj = models.textObj( [mouse_pos[0], mouse_pos[1]], curObj.objName, (255, 255, 255), 1500 ) ### Создаем текстовый объект с координатами указателя мыши, текстом, равным имени объекта под мышкой, белым цветом шрифта(255,255,255) и временем существования 1500 миллисеукнд new_time_obj.time1 = time.time( ) ### в свойство текстового объекта time1 заносим время, когда этот текст создан textObjectList.append( new_time_obj ) ### Добавляем новую надпись(текстовый объект) в список всех надписей break ### после первого найденного объекта под мышью, выходим из цикла, чтобы не появлялось несколько надписей в одном месте elif event.type == QUIT: return if animationIndex < 9: animationIndex += 1 else: animationIndex = 0 player.isCasting = False player.isMoving = False if player.isCasting: spriteIndex = 3 elif player.isMoving: spriteIndex = 2 else: spriteIndex = 0 player.image, player.rect = playerTextures[spriteIndex][animationIndex] if not player.isFacingRight: player.image = pygame.transform.flip(player.image, True, False) pX, pY = player.update() for y in range(0, 16): for x in range(0, 16): screen.blit( level.getTileAt(x, y).image, (x * 16 * gameScale, y * 16 * gameScale + level.getTileAt(x, y).offsetY)) if (level.getDecorationAt(x, y) is not None): screen.blit( level.getDecorationAt(x, y).image, (x * 16 * gameScale, y * 16 * gameScale + level.getDecorationAt(x, y).offsetY)) if ((x, y - 1) == (pX, pY)): screen.blit( player.image, (player.x + player.offsetX, player.y + player.offsetY)) #### ОТРИСОВКА ОБЪЕКТОВ #### playerPos = (player.x + player.offsetX, player.y + player.offsetY ) #позиция игрока на карте x,y for indx, _ in enumerate( gameObjectList): #в массиве всех созданным нами объектов curObj = gameObjectList[indx] screen.blit( curObj.img, curObj.pos ) #рисуем картинку каждого объекта на поверхность игрового экрана if (playerPos[1] + player.rect[3]) >= ( curObj.pos[1] + curObj.lowestY ): #если самая нижняя точка игрока объекта выше игрока screen.blit(player.image, playerPos) #рисуем игрока поверх объекта #### ОТРИСОВКА ТЕКСТА #### for indx, _ in enumerate( textObjectList ): ### перечисляем все надписи(текстовые объекты из их общего списка) textObj = textObjectList[ indx] ### работаем с самим объектом, а не копией, как в случае просто for цикла, чтобы не тратить лишнюю память if textObj.textVisible == False: ### Если в объекте указана невидимость continue ### пропускаем этот объект textSurf = pygame.font.SysFont( textObj.fontName, textObj.fontSize).render( textObj.text_str, False, textObj.text_color ) ### рисуем текст(создаем поверхность Surface с текстом) screen.blit( textSurf, textObj.pos ) ### накладываем поверхность с нарисованным текстом на поверхность экрана, выводя текст на игровой экран if textObj.exist_time != -1: ### если у надписи указано время существования(exist_time) elapsed = ( time.time() - textObj.time1 ) * 1000 ###проверяем сколько миллисекунд прошло со времени создания надписи if elapsed > textObj.exist_time: ### если прошло больше времени, чем указано во времени существования (exist_time) textObjectList.pop( indx) ### удаляем объект из списка надписей pygame.display.flip()
def main(): pygame.init() screen = pygame.display.set_mode((xRes, yRes)) pygame.display.set_caption('Roguelike') animationIndex, spriteIndex = 0, 0 clock = pygame.time.Clock() player = Entity(level) loadTextures() loadLevel(tileData, decorationData, level) while True: clock.tick(24) player.isMoving = False player.dx, player.dy = 0, 0 keys = pygame.key.get_pressed() if keys[K_ESCAPE]: return if keys[K_UP]: player.isMoving = True player.dy = -2 * gameScale if keys[K_DOWN]: player.isMoving = True player.dy = 2 * gameScale if keys[K_LEFT]: player.isFacingRight = False player.isMoving = True player.dx = -2 * gameScale if keys[K_RIGHT]: player.isFacingRight = True player.isMoving = True player.dx = 2 * gameScale if keys[K_z]: player.isCasting = True animationIndex = 0 for event in pygame.event.get(): if event.type == QUIT: return if animationIndex < 9: animationIndex += 1 else: animationIndex = 0 player.isCasting = False player.isMoving = False if player.isCasting: spriteIndex = 3 elif player.isMoving: spriteIndex = 2 else: spriteIndex = 0 player.image, player.rect = playerTextures[spriteIndex][animationIndex] if not player.isFacingRight: player.image = pygame.transform.flip(player.image, True, False) pX, pY = player.update() for y in range(0, 16): for x in range(0, 16): screen.blit( level.getTileAt(x, y).image, (x * 16 * gameScale, y * 16 * gameScale + level.getTileAt(x, y).offsetY)) if (level.getDecorationAt(x, y) is not None): screen.blit( level.getDecorationAt(x, y).image, (x * 16 * gameScale, y * 16 * gameScale + level.getDecorationAt(x, y).offsetY)) if ((x, y - 1) == (pX, pY)): screen.blit( player.image, (player.x + player.offsetX, player.y + player.offsetY)) pygame.display.flip()
import nltk import spacy en = spacy.load('en_core_web_lg') #nltk.download('reuters') from nltk.corpus import reuters import json from models import Entity from models import Document docDict = {} from tqdm import tqdm for fid in tqdm(reuters.fileids()): # set each key in the dictionary to be the fileid... # then the value will be an empty instance of the Document class docDict[fid] = {'Doc': Document(), 'ents': []} docDict[fid]['Doc'].text = reuters.raw(fid) nlpTemp = en(docDict[fid]['Doc'].text) raw_ents = [[m.start_char, m.end_char, m.label_, m.text] for m in nlpTemp.ents] if len(nlpTemp.ents) > 0: [ docDict[fid]['ents'].append(Entity()) for x in range(len(nlpTemp.ents)) ] for x in range(len(nlpTemp.ents)): docDict[fid]['ents'][x].setOffsets(raw_ents[x][0], raw_ents[x][1]) docDict[fid]['ents'][x].setLabel(raw_ents[x][2]) docDict[fid]['ents'][x].setText(raw_ents[x][3]) docDict[fid]['Doc'].addEntity(docDict[fid]['ents'][x])
def format_db_files(part_i_files, part_ii_files): # print(part_ii_files) concept_out, sentence_out = [open_out_csv(out_path(filename)) for filename in config.entity_files] concept_out.writerow(config.output_headers['concept']) sentence_out.writerow(config.output_headers['sentence']) in_sentence_out, has_predicate_out = [open_out_csv(out_path(filename)) for filename in config.relation_files] in_sentence_out.writerow(config.output_headers['in_sentence']) has_predicate_out.writerow(config.output_headers['has_predicate']) i = 0 for part_i_file, part_ii_file in zip( sorted(part_i_files, reverse=True), sorted(part_ii_files, reverse=True) ): print(part_i_file, part_ii_file) start_time = time.time() predicate_out = open_out_csv( out_path(config.predicates_file.replace('.csv','%i.csv'%i)) ) statement_out = open_out_csv( out_path(config.statements_file.replace('.csv','%i.csv'%i)) ) i = i + 1 in_csv = open_in_csv( in_path(part_i_file) ) part_i_header = next(in_csv)[1:] statements_header = config.output_headers['statement'] + part_i_header predicates_header = config.output_headers['predicate'] + part_i_header statement_out.writerow( statements_header ) predicate_out.writerow( predicates_header ) predicates = dict() for line in in_csv: predicates[line[0]] = np.array(list(map(float,line[1:]))) print("finished processing ", part_i_file, time.time() - start_time) # Generate the output final output file as we iterate of the part-ii file in_csv = open_in_csv(in_path(part_ii_file)) header = next(in_csv) + part_i_header # Instantiate entity parser objects for each entity type subj = Entity( ids=config.subj_id, labels=config.subj_label, props=config.subj_props, header=header ) obj = Entity( ids=config.obj_id, labels=config.obj_label, props=config.obj_props, header=header) sentence = Entity( ids=config.sentence_id, labels=config.sentence_label, props=config.sentence_props, header=header ) predicate = Entity( ids=config.predicate_id, labels=config.predicate_label, props=part_i_header, header=header ) # Instantiate relationship(s) parser objects for each relationship type subj_in_sentence = Relation( enty1=subj, enty2=sentence, props=config.subj_in_sentence_props, header=header ) obj_in_sentence = Relation( enty1=obj, enty2=sentence, props=config.obj_in_sentence_props, header=header ) sentence_has_predicate = Relation( enty1=sentence, enty2=predicate, props=config.has_predicate_props, header=header ) statement = Statement( enty1=subj, enty2=obj, props=part_i_header, header=header ) print("started processing ", part_ii_file, time.time() - start_time) q = 0 for line in in_csv: key = line[13] info = line + list(predicates[key]) # statement.update(info) write_entity(subj, info, concept_out) write_entity(obj, info, concept_out) # write_entity(sentence, info, sentence_out) # write_entity(predicate, info, predicate_out) # write_relation(subj_in_sentence, info, in_sentence_out) # write_relation(obj_in_sentence, info, in_sentence_out) # write_relation(sentence_has_predicate, info, has_predicate_out) q = q + 1 if q%100000 == 0: print("%i loops "%q, time.time() - start_time) print("finished processing ", part_ii_file, time.time() - start_time) # for line in statement.fetch_statements(): # statement_out.writerow(line) # print("finished loop ", time.time() - start_time) exit()
def message(bot, update): chat_id = update.message.chat_id user_id = update.message.from_user.id msg = update.message.text username = update.message.from_user.username fullname = " ".join([ update.message.from_user.first_name, update.message.from_user.last_name ]) chat_type = update.message.chat.type chat_title = update.message.chat.title # If message from group if chat_type == 'group' or chat_type == 'supergroup': # Add chat and user to DB User().add(user_id, username, fullname) Chat().add(chat_id, chat_title, bot.getChat(chat_id).username) if update.message.photo: Entity().add(chat_id, 'photo', None) if update.message.video: Entity().add(chat_id, 'video', None) if update.message.audio: Entity().add(chat_id, 'audio', None) if update.message.voice: Entity().add(chat_id, 'voice', None) if update.message.document: Entity().add(chat_id, 'document', None) for entity in update.message.entities: # http://link.com if entity['type'] == 'url': link = msg[entity['offset']:entity['offset'] + entity['length']] link = re.sub('(.*)://', '', link) link = link.split('/')[0] Entity().add(cid=chat_id, type='url', title=link) # /command if entity['type'] == 'bot_command': title = msg[entity['offset']:entity['offset'] + entity['length']] Entity().add(cid=chat_id, type='bot_command', title=title) # #hashtag if entity['type'] == 'hashtag': title = msg[entity['offset']:entity['offset'] + entity['length']] Entity().add(cid=chat_id, type='hashtag', title=title) # @username if entity['type'] == 'mention': title = msg[entity['offset']:entity['offset'] + entity['length']] Entity().add(cid=chat_id, type='mention', title=title) user_stat = UserStat.get(user_id, chat_id) # If user already in group if user_stat: today = datetime.today().day last_activity = datetime.fromtimestamp( timestamp=user_stat.last_activity).day # If last activity was not today if (timedelta(today).days - timedelta(last_activity).days) != 0: Stack().add({'cid': chat_id, 'msg_count': 1, 'users_count': 1}) else: Stack().add({'cid': chat_id, 'msg_count': 1, 'users_count': 0}) else: Stack().add({'cid': chat_id, 'msg_count': 1, 'users_count': 1}) # Update user messages count UserStat().add(user_id, chat_id) else: # If message from user pass
'object_id': new_lex.object_id } link_ids.append((old_parent_ids, { 'client_id': new_lex.client_id, 'object_id': new_lex.object_id })) parent_ids = { 'client_id': new_lex.client_id, 'object_id': new_lex.object_id } new_entity = Entity( client_id=entity.client_id, content=entity.content, locale_id=entity.locale_id, marked_for_deletion=entity.marked_for_deletion, field_client_id=fields[entity.entity_type]['client_id'], field_object_id=fields[entity.entity_type]['object_id'], parent_client_id=parent_ids['client_id'], parent_object_id=parent_ids['object_id'], created_at=entity.created_at) if entity.additional_metadata: new_entity.additional_metadata = json.loads(entity.additional_metadata) DBSession.add(new_entity) l1entity_ids[str(entity.client_id) + '_' + str(entity.object_id)] = { 'client_id': new_entity.client_id, 'object_id': new_entity.object_id } pub_ent = old_DBSession.query(old_publ1entity).filter_by( entity=entity).first() if pub_ent and not pub_ent.marked_for_deletion:
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from models import User, Entity from faker import Faker fake = Faker() engine = create_engine('sqlite:///main.db', echo=True) # create a Session Session = sessionmaker(bind=engine) session = Session() user = User("admin", "password") session.add(user) user = User("Alex", "Dubovyk") session.add(user) # commit the record the database session.commit() for i in range(1,3): for key, value in fake.pydict(10, True).items(): session.add(Entity(key, str(value), i)) session.commit()