Beispiel #1
0
    def permute(self, order):
        """ returns a tensor permuted by the order specified. """
        
        if (order.__class__ == list):
            order = numpy.array(order);
            
        if(self.ndims() != len(order)):
            raise ValueError("Invalid permutation order");
           
        sortedorder = order.copy();
        sortedorder.sort();
        
        if not ((sortedorder == numpy.arange(self.data.ndim)).all()):
            raise ValueError("Invalid permutation order");
        
        neworder = numpy.arange(len(order)).tolist();
        newshape = list(self.shape);
        newdata = self.data.copy();

        for i in range(0,len(order)-1):
            index = tools.find(neworder, order[i]);
            newdata = newdata.swapaxes(i,index);
            
            temp = newshape[i];
            newshape[i] = newshape[index];
            newshape[index] = temp;
            temp = neworder[i];
            neworder[i] = neworder[index];
            neworder[index] = temp;
        
        newshape = tuple(newshape);
        return tensor(newdata,newshape);
Beispiel #2
0
 def ipermute(self, order):
     """ returns a tensor permuted by the inverse of the order specified. """
     #calculate the inverse of iorder
     iorder = [];
     for i in range(0, len(order)):
         iorder.extend([tools.find(order, i)]);
     
     #returns the permuted tensor by the inverse
     return self.permute(iorder);
Beispiel #3
0
 def tosptensor(self):
     # extract the shape of sptensor
     newshape = self.tsize;
     
     #extract the subscripts of sptensor
     rowsubs = [];
     if (len(self.rdims) != 0):
         rowshape = [];
         for i in range(0, len(self.rdims)):
             rowshape.extend([self.tsize[self.rdims[i]]]);
             
         for i in range(0, len(self.subs)):
             rowsubs.extend([tools.ind2sub(rowshape,self.subs[i][0])]);
     rowsubs = numpy.array(rowsubs);
     
     colsubs = [];
     if (len(self.cdims) != 0):
         colshape = [];
         for i in range(0, len(self.cdims)):
             colshape.extend([self.tsize[self.cdims[i]]]);
             
         for i in range(0, len(self.subs)):
             colsubs.extend([tools.ind2sub(colshape,self.subs[i][1])]);
     colsubs = numpy.array(colsubs);
     
     newsubs = [];
     for i in range(0, len(self.subs)):
         newsubs.extend([[]]);
     
     
     for k in range(0, len(newshape)):
         find = tools.find(self.rdims,k);
         if(find != -1):
             newsubs = numpy.concatenate((newsubs, rowsubs[:,find].reshape([len(self.subs),1])), axis = 1);
         else:
             find = tools.find(self.cdims,k);
             newsubs = numpy.concatenate((newsubs, colsubs[:,find].reshape([len(self.subs),1])), axis = 1);
     
     #extract the values of sptensor
     newvals = self.vals;
     
     return sptensor.sptensor(newsubs, newvals, newshape);
Beispiel #4
0
def fixDescriptions(descriptionsText):
	ret = descriptionsText.replace(' ', ' ')
	ret = ret.replace('—', '-')
	ret = ret.replace('…', '')

	startIndex = ret.rfind('<span class="q">')
	if startIndex >= 0:
		ret = ret[startIndex + len('<span class="q">') : ]

	ret = ret.replace(u'На эту способность не влияет общее время восстановления.', '')
	ret = ret.replace('<table width="100%">', ' ')
	ret = ret.replace('<table>', '')
	ret = ret.replace('</table>', ' ')
	ret = ret.replace('<tr>', '')
	ret = ret.replace('</tr>', ' ')
	ret = ret.replace('<td>', '')
	ret = ret.replace('</td>', ' ')
	ret = ret.replace('<th>', '')
	ret = ret.replace('</th>', ' ')
	ret = ret.replace('<span>', '')
	ret = ret.replace('</span>', ' ')
	ret = ret.replace('<b>', '')
	ret = ret.replace('</b>', '')
	ret = ret.replace('<br />', ' ')
	ret = ret.replace('</a>', '')

	match = tools.find(ret, '<span', '>', 0, False)
	while match:
		ret = ret.replace('<span'+match+'>', '')
		match = tools.find(ret, '<span', '>', 0, False)
	
	match = re.search('<a[^>]+>', ret)
	while match:
		ret = ret.replace(match.group(0), '')
		match = re.search('<a[^>]+>', ret)

	match = re.search('<!--[^>]+>', ret)
	while match:
		ret = ret.replace(match.group(0), '')
		match = re.search('<!--[^>]+>', ret)

	return ret
Beispiel #5
0
def main():
	fin = codecs.open('data_2-ids.txt', 'r', 'utf-8')
	rows = fin.read().split('\n')
	fin.close()
	items = []
	for row in rows:
		match = re.search('(\\d+) (.+)', row)
		if match:
			items.append((int(match.group(1)), match.group(2)))

	tools.makeFileBackup('data_3-rawText.txt')
	fout = codecs.open('data_3-rawText.txt', 'w', 'utf-8')

	startId = -1
	if len(sys.argv) > 1:
		startId = int(sys.argv[1])

	for i in range(0, len(items)):
		id = items[i][0]
		name = items[i][1]

		if startId != -1:
			if id == startId:
				startId = -1
			else:
				continue

		tools.reprint('Downloading %d %s - %d/%d - %d%%' % (id, name, i, len(items), (i * 100) / len(items)))
		try:
			url = urllib2.urlopen('http://ru.wowhead.com/item=%d' % (id))
		except:
			tools.endReprint()
			print('Error: Can not open %d item - %s' % (id, name))
			return False
		text = codecs.decode(url.read(), 'utf-8', 'ignore')
		url.close()
		text = text.replace('\r\n', '')
		text = text.replace('\n', ' ')

		description = tools.find(text, u'Использование:', '</span>', dumpFindError=False)
		if description == None:
			tools.endReprint()
			print('Error: Can not find item description')
		else:
			fout.write('%d %s | %s\n' % (id, name, description))
		
		time.sleep(0.3)

	fout.close()

	tools.clearReprint()
	print("\nAll items downloded successfuly!")
	return True
Beispiel #6
0
def notification():
    while True:
        time.sleep(60)
        date_day = date.today()
        for client in users:
            #               UTC 0                         пользовательский UTC
            localtime = datetime.now() + timedelta(
                minutes=client.settings['UTC'] * 60)
            if client.settings['notification'] \
                    and client.time == localtime.strftime('%H:%M') \
                    and client.working_day[date_day.weekday()]:  # отправка уведомлений
                bot.send_message(
                    client.id,
                    information_line_daily(client, int(tools.get_even()),
                                           datetime.today().isoweekday()) +
                    '\n' + daily_schedule(client, int(tools.get_even()),
                                          datetime.today().isoweekday()))
                if client.time == '4:20':
                    bot.send_message(client.id, os.environ.get("message"))

            try:
                if client.position[
                        'last message type'] == 'today':  # обновление сообщения today
                    bot.edit_message_text(
                        chat_id=client.id,
                        message_id=client.position['last message id'],
                        text=information_line(client, int(tools.get_even()),
                                              datetime.today().isoweekday()) +
                        '\n' + daily_schedule(client,
                                              int(tools.get_even()),
                                              datetime.today().isoweekday(),
                                              arrow=True))
            except Exception as e:
                print(
                    f' *(today upd) {client.id}, \n{client.name}, \n{client.position}\n has a problem - {e}\n'
                )
                num = tools.find(users, client.id)
                users[num].position['last message type'] = 'null'
Beispiel #7
0
    def permute(self, order):
        """returns a new sptensor permuted by the given order"""
        if (order.__class__ == list):
            order = numpy.array(order);
            
        if(self.ndims() != len(order)):
            raise ValueError("invalid permutation order")
        
        sortedorder = order.copy();
        sortedorder.sort();
        
        if not ((sortedorder == numpy.arange(len(self.shape))).all()):
            raise ValueError("invalid permutation order");
        
        neworder = numpy.arange(len(order)).tolist();
        newsiz = list(self.shape);
        newval = self.vals.copy();
        newsub = self.subs.copy();

        for i in range(0,len(order)-1):
            index = tools.find(neworder, order[i]);            
            
            for s in newsub:
                temp = s[i];
                s[i] = s[index];
                s[index] = temp;
            
            temp = newsiz[i];
            newsiz[i] = newsiz[index];
            newsiz[index] = temp;
            
            temp = neworder[i];
            neworder[i] = neworder[index];
            neworder[index] = temp;
            
        return sptensor(newsub, newval, newsiz, self.func);
Beispiel #8
0
    def permute(self, order):
        """returns a new sptensor permuted by the given order"""
        if (order.__class__ == list):
            order = numpy.array(order);
            
        if(self.ndims() != len(order)):
            raise ValueError("invalid permutation order")
        
        sortedorder = order.copy();
        sortedorder.sort();
        
        if not ((sortedorder == numpy.arange(len(self.shape))).all()):
            raise ValueError("invalid permutation order");
        
        neworder = numpy.arange(len(order)).tolist();
        newsiz = list(self.shape);
        newval = self.vals.copy();
        newsub = self.subs.copy();

        for i in range(0,len(order)-1):
            index = tools.find(neworder, order[i]);            
            
            for s in newsub:
                temp = s[i];
                s[i] = s[index];
                s[index] = temp;
            
            temp = newsiz[i];
            newsiz[i] = newsiz[index];
            newsiz[index] = temp;
            
            temp = neworder[i];
            neworder[i] = neworder[index];
            neworder[index] = temp;
            
        return sptensor(newsub, newval, newsiz, self.func);
Beispiel #9
0
def group_user_is_ready(payload):
    find(lambda member: member["id"] == payload["user"]["userid"],
         model.container.group.members)["ready"] = True
    render_group()
    logger.info("%s is ready.", payload["user"]["username"])
Beispiel #10
0
async def on_ready_clicked():
    if find(lambda member: member["id"] == model.container.user.userid,
            model.container.group.members)["ready"]:
        await model.mark_as_not_ready()
    else:
        await model.mark_as_ready()
def main(B, D, N, max_energy=[0], energy_plot=False, small_plot=False):
    figsize = (5.8, 4) if not small_plot else (5.8, 3.5)
    fig, ax = plt.subplots(figsize=figsize, nrows=1, ncols=2)
    symblols = ['o', '^', 'v', 's', 'p', '*']
    if energy_plot:
        marks = itertools.cycle(symblols[:len(B)])
    else:
        marks = itertools.cycle(symblols[:len(max_energy)])

    # alpha
    files = find('alpha*.txt', '../output')
    msize = 8
    for n_i in N:
        if energy_plot:
            for b_i in B:
                marker = next(marks)
                alpha.e_plot(files, ax[0], n_i, b_i, msize, marker)
        else:
            for max_e in max_energy:
                marker = next(marks)
                alpha.b_plot(files, ax[0], n_i, max_e, msize, marker)
        msize -= 2

    # eta
    msize = 4
    for n_i in N:
        if energy_plot:
            for b_i in B:
                marker = next(marks)
                eta.e_plot(b_i, D[0], n_i, max_energy, ax[1], msize, marker)
        else:
            for max_e in max_energy:
                marker = next(marks)
                eta.b_plot(B, D[0], n_i, max_e, ax[1], msize, marker)
        msize -= 2

    ax[0].set_ylabel('$\\alpha$')
    ax[1].set_ylabel('$\\eta$')
    for col in ax:
        if energy_plot:
            col.set_xlabel('$\\Delta E$')
        else:
            col.set_xlabel('$B$')
        col.set_ylim([0, 1.2])
        if not energy_plot:
            col.set_xlim([0, 1])
        col.legend()
    plt.tight_layout(pad=0.3)
    # fig.show()
    if energy_plot:
        fig.savefig('../Statistics/alpha-eta_e_B[' +
                    ', '.join('{:.2}'
                              for i in B).format(*B) + ']_N' + str(N) + '.pdf',
                    dpi=400)
    else:
        fig.savefig(
            '../Statistics/alpha-eta_N' + str(N) +
            ('_max_e_' + str(max_energy) +
             '.pdf' if len(max_energy) > 1 or max_energy[0] else '.pdf'),
            dpi=400)
    plt.close()
Beispiel #12
0
def main():
	tools.makeFileBackup('result_1-spells.txt')
	fout = codecs.open('result_1-spells.txt', 'w', 'utf-8')

	languages = ['ru', 'en', 'de', 'es', 'fr', 'it', 'pt', 'cn', 'ko']
	classNames = ['Warrior', 'Paladin', 'Hunter', 'Rogue', 'Priest', 'Death knight', 'Shaman', 'Mage', 'Warlock', 'Monk', 'Druid', 'Demon hunter', 'Custom']

	spellIds = []
	for i in range(0, len(classNames)):
		spellIds.append([])
		
	spellIds[0] = [	# Warrior:
		202751,	#Безудержная энергия
		46924,	#Вихрь клинков
		152277,	#Опустошитель
		228920,	#Опустошитель
		118000,	#Рев дракона
		202743,	#Луженая глотка
		215550,	#Добивание
		772,	#Кровопускание
		202168,	#Верная победа
		7384,	#Превосходство

		107570,	#Удар громовержца
		46968,	#Ударная волна
		184367,	#Буйство

		1680,	#Вихрь
		190411,	#Вихрь
		227847,	#Вихрь клинков
		200847,	#Жажда битвы
		5308,	#Казнь
		163201,	#Казнь
		200859,	#Кровавое безумие
		23881,	#Кровожадность
		100130,	#Неистовый удар сплеча
		200856,	#Неуправляемая ярость

		198304,	#Перехват
		34428,	#Победный раж
		1715,	#Подрезать сухожилия
		845,	#Рассекающий удар
		6572,	#Реванш
		206572,	#Рывок дракона
		12294,	#Смертельный удар
		20243,	#Сокрушение
		190456,	#Стойкость к боли
		167105,	#Удар колосса
		85288,	#Яростный выпад
		57755,	#Героический бросок
		6544,	#Героический прыжок
		115767,	#Глубокие раны
		209577,	#Миротворец

		100,	#Рывок
		215537,	#Травма
		203524,	#Ярость Нелтариона
		203526,	#Ярость Нелтариона
		205545,	#Ярость Одина
		205546,	#Ярость Одина
		205547	#Ярость Одина
	]

	spellIds[1] = [	# Paladin:
		210220,	#Гнев небес
		204054,	#Освященная земля
		114165,	#Божественная призма
		213652,	#Длань защитника
		215661,	#Отмщение вершителя правосудия
		210191,	#Торжество
		183415,	#Аура сострадания
		198034,	#Божественный молот
		202270,	#Клинок гнева
		115750,	#Слепящий свет
		204019,	#Благословенный молот
		217020,	#Фанатизм
		223306,	#Дарование веры
		114158,	#Молот Света

		205228,	#Освящение
		213757,	#Смертный приговор
		85222,	#Свет зари
		53385,	#Божественная буря

		203538,	#Великое благословение королей
		85256,	#Вердикт храмовника
		19750,	#Вспышка Света
		193058,	#Исцеляющая буря
		184575,	#Клинок Справедливости
		53595,	#Молот праведника
		26573,	#Освящение

		184092,	#Свет защитника
		183998,	#Свет мученика
		82326,	#Свет небес
		209539,	#Свет титанов
		20473,	#Шок небес
		31935,	#Щит мстителя
		184662,	#Щит мстителя
		53600,	#Щит праведника

		200652,	#Избавление Тира
		200654,	#Избавление Тира
		205273,	#Испепеляющий след
		209202,	#Око Тира
		20271,	#Правосудие
		35395	#Удар воина Света
	]

	spellIds[2] = [	# Hunter:
		198670,	#Пронзающий выстрел
		214579,	#Рогатые гремучие змеи
		194855,	#Граната пламени дракона
		194386,	#Залп
		212436,	#Свежевание туш
		131894,	#Стая воронов
		87935,	#Укус змеи
		120360,	#Шквал
		199483,	#Камуфляж
		162488,	#Капкан
		212431,	#Разрывной выстрел
		194277,	#Шипы
		53209,	#Выстрел химеры
		199530,	#Топот
		194599,	#Черная стрела
		200163,	#Метательные топоры

		193265,	#Бросок топорика
		191433,	#Взрывная ловушка
		186387,	#Взрывной выстрел
		193455,	#Выстрел кобры

		109304,	#Живость
		194291,	#Живость
		2643,	#Залп
		34026,	#Команда "Взять!"
		202800,	#Обходной удар
		19434,	#Прицельный выстрел
		185901,	#Прицельный залп
		187708,	#Разделка туши
		185855,	#Режущий удар

		186270,	#Удар ящера
		190928,	#Укус мангуста
		185358,	#Чародейский выстрел
		207068,	#Гром титанов
		207097,	#Гром титанов
		212621,	#Прицельный залп

		204147,	#Шквальный ветер
		203413,	#Ярость орла
		203415	#Ярость орла
	]

	spellIds[3] = [	# Rogue:
		152150,	#Смерть с небес
		200802,	#Мучительный яд
		185767,	#Обстрел ядрами
		51690,	#Череда убийств
		154904,	#Внутреннее кровотечение
		200758,	#Клинок мрака
		16511,	#Кровоизлияние
		196937,	#Призрачный удар

		703,	#Гаррота
		32645,	#Отравление
		1943,	#Рваная рана
		202820,	#Алчность
		114014,	#Бросок сюрикэна
		51723,	#Веер клинков
		8676,	#Внезапный удар
		185763,	#Выстрел из пистоли
		192428,	#Из тени

		2098,	#Круговая атака
		195452,	#Ночной клинок
		185565,	#Отравленный нож
		1776,	#Парализующий удар
		196819,	#Потрошение
		199804,	#Промеж глаз
		1329,	#Расправа
		2823,	#Смертоносный яд

		53,	#Удар в спину
		193315,	#Удар саблей
		185438,	#Удар Тьмы
		197835,	#Шквал сюрикэнов
		192759,	#Погибель королей
		192760,	#Погибель королей
		222062,	#Погибель королей
		209782,	#Укус Кровавой Пасти
		209783,	#Укус Кровавой Пасти
		209784,	#Укус Кровавой Пасти
		212205	#Создать предмет: алый фиал
	]

	spellIds[4] = [	# Priest:
		204883,	#Круг исцеления
		204197,	#Очищение зла
		73510,	#Пронзание разума
		204065,	#Темный завет
		110744,	#Божественная звезда
		120517,	#Сияние
		205385,	#Темное сокрушение
		152118,	#Ясность воли
		32546,	#Связующее исцеление
		162452,	#Темное прозрение
		123040,	#Подчиняющий разум
		129250,	#Слово силы: Утешение
		214121,	#Тело и разум
		200347,	#Исповедник

		228260,	#Извержение Бездны
		48045,	#Иссушение разума
		132157,	#Кольцо света
		596,	#Молитва исцеления
		34914,	#Прикосновение вампира
		14914,	#Священный огонь
		194018,	#Сила разума

		88625,	#Слово Света: Наказание
		194509,	#Слово силы: Сияние
		32379,	#Слово Тьмы: Смерть
		228266,	#Стрела Бездны
		186263,	#Темное восстановление
		585,	#Кара
		205065,	#Поток Бездны
		208065,	#Свет Т'ууре
		207946,	#Ярость Света
		207948	#Ярость Света
	]

	spellIds[5] = [	# Death knight:
		194844,	#Буря костей
		152279,	#Дыхание Синдрагосы
		130736,	#Жнец душ
		194913,	#Ледяной натиск
		152280,	#Осквернение
		207230,	#Ледяная коса
		207142,	#Лавина
		207311,	#Стискивающие тени

		212744,	#Пожирание душ
		207317,	#Эпидемия
		206931,	#Кровопийца
		43265,	#Смерть и разложение

		196770,	#Беспощадность зимы
		49184,	#Воющий ветер
		50842,	#Вскипание крови
		77575,	#Вспышка болезни
		195182,	#Дробление хребта
		49143,	#Ледяной удар
		47541,	#Лик смерти

		191637,	#Портал в Нижний мир
		195292,	#Прикосновение смерти
		206930,	#Удар в сердце
		55090,	#Удар Плети
		85948,	#Удар разложения
		49020,	#Уничтожение
		48707,	#Антимагический панцирь
		220143,	#Апокалипсис

		190780,	#Ледяное дыхание
		55095,	#Озноб
		205223,	#Увядание
		205224,	#Увядание
		49998,	#Удар смерти
		190778	#Ярость Синдрагосы
	]

	spellIds[6] = [	# Shaman:
		210689,	#Грозовой разрядник
		188089,	#Земляной шип
		197995,	#Родник
		192222,	#Тотем жидкой магмы
		197467,	#Бездонная пропасть
		197211,	#Гнев Воздуха
		197214,	#Раскол
		192246,	#Сокрушающая буря
		210714,	#Ледяная ярость
		210727,	#Перезарядка
		198838,	#Тотем земного щита
		210731,	#Усиленный бурехлест
		117014,	#Удар духов стихии
		192106,	#Щит молний
		215864,	#Ливень
		196884,	#Свирепый выпад
		201898,	#Песнь ветра
		201897,	#Тяжелый кулак

		61295,	#Быстрина
		51505,	#Выброс лавы
		8004,	#Исцеляющий всплеск
		403,	#Молния
		5394,	#Тотем исцеляющего потока
		17364,	#Удар бури
		421,	#Цепная молния
		77472,	#Волна исцеления
		60103,	#Вскипание лавы

		51490,	#Гром и молния
		8042,	#Земной шок
		188070,	#Исцеляющий всплеск
		193786,	#Камнедробитель
		196834,	#Ледяное клеймо
		196840,	#Ледяной шок
		187837,	#Молния
		188196,	#Молния
		188389,	#Огненный шок
		188838,	#Огненный шок

		187874,	#Сокрушающая молния
		16164,	#Средоточие стихий
		61882,	#Тотем землетрясения
		108280,	#Тотем целительного прилива
		188443,	#Цепная молния
		1064,	#Цепное исцеление
		193796,	#Язык пламени
		207778	#Дар королевы
	]

	spellIds[7] = [	# Mage:
		153595,	#Буря комет
		198929,	#Вихрь углей
		199786,	#Ледовый шип
		153561,	#Метеор
		153626,	#Чародейский шар
		114923,	#Буря Пустоты
		44457,	#Живая бомба
		112948,	#Ледяная бомба
		205037,	#Огненный след
		157981,	#Взрывная волна
		157997,	#Кольцо обледенения
		157980,	#Сверхновая
		205023,	#Воспламенение
		205021,	#Морозный луч

		116,	#Ледяная стрела
		11366,	#Огненная глыба
		133,	#Огненный шар
		2948,	#Ожог
		12051,	#Прилив сил
		30451,	#Чародейская вспышка
		44614,	#Шквал
		194487,	#Горнило
		31661,	#Дыхание дракона
		224968,	#Знак Алунета
		210725,	#Касание мага
		120,	#Конус холода
		30455,	#Ледяное копье
		84714,	#Ледяной шар
		112965,	#Ледяные пальцы

		108853,	#Огненный взрыв
		190356,	#Снежная буря
		5143,	#Чародейские стрелы
		1449,	#Чародейский взрыв
		44425,	#Чародейский обстрел
		210726,	#Знак Алунета
		211076,	#Знак Алунета

		211088,	#Знак Алунета
		122,	#Кольцо льда
		11426,	#Ледяная преграда
		194466,	#Пламя феникса
		214634,	#Полярная стрела
		135029	#Сильная струя воды
	]

	spellIds[8] = [	# Warlock:
		157695,	#Демонический заряд
		196447,	#Направленный демонический огонь
		205179,	#Призрачная сингулярность
		205180,	#Призыв созерцателя Тьмы
		108503,	#Гримуар жертвоприношения
		196277,	#Имплозия
		152108,	#Катаклизм
		48181,	#Блуждающий дух
		17877,	#Ожог Тьмы
		205181,	#Пламя Тьмы
		198590,	#Похищение души

		980,	#Агония
		348,	#Жертвенный огонь
		29722,	#Испепеление
		30108,	#Нестабильное колдовство
		172,	#Порча
		686,	#Стрела Тьмы
		116858,	#Стрела Хаоса
		193440,	#Демонический гнев
		193541,	#Жертвенный огонь
		1454,	#Жизнеотвод
		5740,	#Огненный ливень

		17962,	#Поджигание
		27243,	#Семя порчи
		216698,	#Жатва душ
		187394,	#Залп Хаоса
		689,	#Похищение жизни

		1122,	#Призыв инфернала
		196657,	#Стрела Тьмы
		215279	#Стрела Хаоса
	]

	spellIds[9] = [	# Monk:
		196743,	#Сгусток ци
		152175,	#Удар крутящегося дракона
		196725,	#Освежающий нефритовый ветер
		196730,	#Особая доставка
		116847,	#Порыв нефритового ветра
		123904,	#Призыв Сюэня, Белого Тигра
		198664,	#Призыв Чи-Цзи, Красного Журавля
		115098,	#Волна ци
		123986,	#Выброс ци
		196607,	#Глаз тигра
		124081,	#Дзен-импульс
		197945,	#Странник туманов

		101546,	#Танцующий журавль
		115151,	#Заживляющий туман
		116849,	#Исцеляющий кокон

		191837,	#Купель сущности
		205523,	#Нокаутирующая атака
		116670,	#Оживить
		124682,	#Окутывающий туман
		213183,	#Отвар драконьего пламени
		115181,	#Пламенное дыхание
		220357,	#Порывы вихря

		107428,	#Удар восходящего солнца
		101545,	#Удар летящего змея
		214326,	#Взрывной бочонок
		205406,	#Дар Шей-луна
		100780,	#Лапа тигра
		100784,	#Нокаутирующий удар
		117952,	#Сверкающая нефритовая молния
		205320,	#Удар Владыки Ветра
		205414,	#Удар Владыки Ветра
		222029,	#Удар Владыки Ветра
		209525	#Успокаивающий туман
	]

	spellIds[10] = [	# Druid:
		202028,	#Жестокий удар когтями
		204066,	#Лунный луч
		80313,	#Раздавить
		202770,	#Ярость Элуны
		202359,	#Астральное единение
		202347,	#Звездная вспышка
		200390,	#Проращивание
		108238,	#Обновление

		203953,	#Острые колючки
		102351,	#Щит Кенария
		48438,	#Буйный рост
		8936,	#Восстановление
		1822,	#Глубокая рана
		33763,	#Жизнецвет
		78674,	#Звездный поток
		774,	#Омоложение
		5176,	#Солнечный гнев

		18562,	#Быстрое восстановление
		191034,	#Звездопад
		22570,	#Калечение
		194153,	#Лунный удар

		5221,	#Полоснуть
		1079,	#Разорвать
		22568,	#Свирепый укус
		190984,	#Солнечный гнев
		93402,	#Солнечный огонь
		740,	#Спокойствие

		6807,	#Трепка
		33917,	#Увечье
		5185,	#Целительное прикосновение
		210722,	#Бешенство Пеплошкурой
		210723,	#Бешенство Пеплошкурой
		77758,	#Взбучка
		106830,	#Взбучка
		8921,	#Лунный огонь
		202767,	#Новолуние
		202771,	#Полная луна
		202768,	#Полумесяц
		164815,	#Солнечный огонь
		200851,	#Ярость Спящего
		219432	#Ярость Спящего
	]

	spellIds[11] = [	# Demon hunter:
		211053,	#Обстрел Скверны
		227225,	#Призрачный барьер
		218679,	#Взрывная душа
		212084,	#Опустошение Скверны
		211881,	#Извержение Скверны
		209795,	#Трещина
		213241,	#Клинок Скверны
		206473,	#Кровопускание
		207697,	#Пиршество душ
		207739,	#Сожжение заживо

		204157,	#Бросок боевого клинка
		178740,	#Жар преисподней
		189110,	#Инфернальный удар
		203782,	#Иссечение

		204021,	#Огненное клеймо
		228477,	#Раскалывание душ
		185123,	#Бросок боевого клинка
		179057,	#Кольцо Хаоса
		191427,	#Метаморфоза
		198013,	#Пронзающий взгляд
		207407,	#Разрубатель душ
		214743,	#Разрубатель душ
		195072,	#Рывок Скверны
		188499,	#Танец клинков

		162794,	#Удар Хаоса
		197125,	#Удар Хаоса
		162243,	#Укус демона
		201467,	#Ярость иллидари
		201628,	#Ярость иллидари
		201789	#Ярость иллидари
	]

	spellIds[12] = [	# Custom:
		
	]


	firstClass = 0
	if len(sys.argv) > 1:
		firstClass = int(sys.argv[1])

	firstSpell = 0
	if len(sys.argv) > 2:
		spellsLen = len(spellIds[firstClass])
		for i in range(0, spellsLen):
			if spellIds[firstClass][i] == int(sys.argv[2]):
				firstSpell = i
				break

	for i in range(firstClass, len(classNames)):
		tools.clearReprint()
		print('Downloading %s class' % classNames[i])

		fout.write('\n\n======= %s\n' % classNames[i])
		
		if i != firstClass:
			firstSpell = 0

		spellIdsLen = len(spellIds[i])
		for j in range(firstSpell, spellIdsLen):
			spellId = spellIds[i][j]
			
			spellRuName = None
			spellEnName = None
			descriptions = []

			for k in range(0, len(languages)):
				tools.reprint('Downloading %s %d - %d/%d - %d%%' % (languages[k], spellId, j*len(languages) + k, spellIdsLen*len(languages), (j * 100 * len(languages) + k) / spellIdsLen / len(languages)))

				try:
					url = urllib2.urlopen('http://%s.wowhead.com/spell=%d' % (languages[k], spellId))
				except:
					tools.endReprint()
					print('Error: Can not open %s %d spell - %d' % (languages[k], i, spellId))
					return False
				text = codecs.decode(url.read(), 'utf-8', 'ignore')
				url.close()
				text = text.replace('\r\n', '')

				spellName = tools.find(text, '<h1 class="heading-size-1">', '</h1>')
				if spellName == None:
					tools.endReprint()
					print('Error: Can not find spell name')
					return False

				if k == 0:
					spellRuName = spellName
				elif k == 1:
					spellEnName = spellName

				descr = tools.find(text, '<noscript><table><tr><td>', '</noscript>')
				if descr == None:
					tools.endReprint()
					print('Error: Can not find spell description')
					return False

				descriptions.append(descr)

			fout.write('\n+++ %d | %s | %s' % (spellId, spellRuName, spellEnName))
			for descr in descriptions:
				fout.write('\n   %s' % (descr))
			time.sleep(0.2)

	fout.close()

	tools.clearReprint()
	print("\nAll spells downloded successfuly!")
	return True
Beispiel #13
0
def callback_worker(call):
    # поиск пользователя:
    global users
    number = tools.find(users, call.message.chat.id)

    if number is None:
        bot.answer_callback_query(callback_query_id=call.id,
                                  text='Take it easy!')

    else:
        # смена языка:
        if call.data == 'us' or call.data == 'ua' or call.data == 'ru':
            past = users[number].settings['language']
            if call.data == 'us':
                users[number].settings['language'] = 'us'

            elif call.data == 'ua':
                users[number].settings['language'] = 'ua'

            elif call.data == 'ru':
                users[number].settings['language'] = 'ru'

            if call.data != past:
                bot.edit_message_text(
                    chat_id=call.message.chat.id,
                    message_id=call.message.message_id,
                    text=languages.assembly['choose a language'][
                        users[number].settings['language']],
                    reply_markup=language_selection)
            else:
                bot.answer_callback_query(
                    callback_query_id=call.id,
                    text=languages.assembly['been selected'][
                        users[number].settings['language']])
            return

        # слияние недель
        if call.data[:16] == 'connection weeks':
            past = users[number].settings['combination of weeks']

            if call.data == 'connection weeks yes':
                users[number].settings['combination of weeks'] = True

            elif call.data == 'connection weeks no':
                users[number].settings['combination of weeks'] = False

            if call.data != past:
                if call.data == 'connection weeks yes':
                    bot.answer_callback_query(callback_query_id=call.id,
                                              text='Weeks are the same: True')

                if call.data == 'connection weeks no':
                    bot.answer_callback_query(callback_query_id=call.id,
                                              text='Weeks are the same: False')

            else:
                bot.answer_callback_query(
                    callback_query_id=call.id,
                    text=languages.assembly['been selected'][
                        users[number].settings['language']])
            return

        # поменять местами расписание
        if call.data[:13] == 'swap schedule':
            past = users[number].position['week even']
            if call.data == 'swap schedule yes':
                users[number].position['week even'] = True

            elif call.data == 'swap schedule no':
                users[number].position['week even'] = False

            if call.data != past:
                if call.data == 'swap schedule yes':
                    bot.answer_callback_query(
                        callback_query_id=call.id,
                        text='Parity and non-parity have changed: True')
                if call.data == 'swap schedule no':
                    bot.answer_callback_query(
                        callback_query_id=call.id,
                        text='Parity and non-parity have changed: False')

            else:
                bot.answer_callback_query(
                    callback_query_id=call.id,
                    text=languages.assembly['been selected'][
                        users[number].settings['language']])
            return

        # включить уведомления
        if call.data[:15] == 'notification on':
            past = users[number].settings['notification']
            if call.data == 'notification on yes':
                users[number].settings['notification'] = True

            elif call.data == 'notification on no':
                users[number].settings['notification'] = False

            if call.data != past:
                if call.data == 'notification on yes':
                    bot.answer_callback_query(
                        callback_query_id=call.id,
                        text='Notifications are included: True')
                if call.data == 'notification on no':
                    bot.answer_callback_query(
                        callback_query_id=call.id,
                        text='Notifications are included: False')

            else:
                bot.answer_callback_query(
                    callback_query_id=call.id,
                    text=languages.assembly['been selected'][
                        users[number].settings['language']])
            return

        # расписание на неделю
        if call.data[:4] == 'week':
            if call.data == 'week another':
                if users[number].position['week'] == 0:
                    users[number].position['week'] = 1

                else:
                    users[number].position['week'] = 0

            if call.data == 'week back':
                if users[number].position['day'] == 1:
                    users[number].position['day'] = 7

                else:
                    users[number].position[
                        'day'] = users[number].position['day'] - 1

            if call.data == 'week forward':
                if users[number].position['day'] == 7:
                    users[number].position['day'] = 1

                else:
                    users[number].position[
                        'day'] = users[number].position['day'] + 1

            navigation = types.InlineKeyboardMarkup()  # пересобираем навигацию
            week_back = types.InlineKeyboardButton(text='<',
                                                   callback_data='week back')
            week_forward = types.InlineKeyboardButton(
                text='>', callback_data='week forward')
            navigation.add(week_back, week_forward)

            if not users[number].settings['combination of weeks']:
                week_another = types.InlineKeyboardButton(
                    text=languages.assembly['another'][
                        users[number].settings['language']],
                    callback_data='week another')
                navigation.add(week_another)

            bot.edit_message_text(
                chat_id=call.message.chat.id,
                message_id=call.message.message_id,
                text=information_line(users[number],
                                      users[number].position['week'],
                                      users[number].position['day']) + '\n' +
                daily_schedule(users[number], users[number].position['week'],
                               users[number].position['day']),
                reply_markup=navigation)
            return

        # управление edit week
        if call.data[:4] == 'edit':

            if call.data == 'edit another':
                if users[number].position['week'] == 0:
                    users[number].position['week'] = 1

                else:
                    users[number].position['week'] = 0

                users[number].position['last message type'] = 'edit false'

            if call.data == 'edit back':
                if users[number].position['day'] == 1:
                    users[number].position['day'] = 7

                else:
                    users[number].position[
                        'day'] = users[number].position['day'] - 1

                users[number].position['last message type'] = 'edit false'

            if call.data == 'edit forward':
                if users[number].position['day'] == 7:
                    users[number].position['day'] = 1

                else:
                    users[number].position[
                        'day'] = users[number].position['day'] + 1

                users[number].position['last message type'] = 'edit false'

            if call.data == 'edit day':
                if users[number].position['last message type'] == 'edit true':
                    users[number].position['lesson'] = 0
                    users[number].position['last message type'] = 'edit false'

                else:
                    users[number].position['lesson'] = 1
                    users[number].position['last message type'] = 'edit true'

            if call.data == 'edit up':  # но ниже по списку
                if users[number].position['lesson'] > 1:
                    users[number].position[
                        'lesson'] = users[number].position['lesson'] - 1
                    users[number].position['last message type'] = 'edit true'
                else:
                    bot.answer_callback_query(
                        callback_query_id=call.id,
                        text=languages.assembly['ed down'][
                            users[number].settings['language']])
                    return

            if call.data == 'edit down':  # но выше по списку
                if users[number].position['lesson'] < len(
                        users[number].schedule[users[number].position['week']][
                            users[number].position['day'] - 1]):
                    users[number].position[
                        'lesson'] = users[number].position['lesson'] + 1
                    users[number].position['last message type'] = 'edit true'
                else:
                    bot.answer_callback_query(
                        callback_query_id=call.id,
                        text=languages.assembly['ed up'][
                            users[number].settings['language']])
                    return

            if call.data == 'edit add before':
                users[number].position['last message type'] = 'edit true'
                temp = users[number].schedule
                temp_b = users[number].schedule[users[number].position[
                    'week']][users[number].position['day'] - 1]
                temp_b.reverse()
                temp_a = temp_b[:(len(temp_b) -
                                  (users[number].position['lesson'] - 1))]
                temp_b.reverse()
                temp_a.reverse()
                temp_b = temp_b[:users[number].position['lesson'] - 1]
                temp_b.append(' ')

                temp[users[number].position['week']][
                    users[number].position['day'] - 1] = temp_b + temp_a
                users[number].schedule = temp
                users[number].position[
                    'lesson'] = users[number].position['lesson'] + 1

            if call.data == 'edit add after':
                users[number].position['last message type'] = 'edit true'
                temp = users[number].schedule
                temp_b = users[number].schedule[users[number].position[
                    'week']][users[number].position['day'] - 1]
                temp_b.reverse()
                temp_a = temp_b[:(len(temp_b) -
                                  (users[number].position['lesson']))]
                temp_b.reverse()
                temp_a.reverse()
                temp_b = temp_b[:users[number].position['lesson']]
                temp_b.append(' ')

                temp[users[number].position['week']][
                    users[number].position['day'] - 1] = temp_b + temp_a
                users[number].schedule = temp

            if call.data == 'edit delete':
                try:
                    users[number].position['last message type'] = 'edit true'
                    temp = users[number].schedule
                    del temp[users[number].position['week']][
                        users[number].position['day'] -
                        1][users[number].position['lesson'] - 1]
                    lesson = users[number].position['lesson']
                    if len(users[number].schedule[users[number].position[
                            'week']][users[number].position['day'] -
                                     1]) < users[number].position['lesson']:
                        lesson += -1
                    users[number].schedule = temp
                    users[number].position['lesson'] = (lesson
                                                        if lesson >= 1 else 1)
                except Exception as e:
                    bot.answer_callback_query(
                        callback_query_id=call.id,
                        text=f'Unexpected error during deletion code: {e}')
                    return

            users[number].position['last message id'] = call.message.message_id

            edit_day_week(
                user_id=call.message.chat.id,
                message_id=call.message.message_id)  # сборка расписания
            return

        # Время вместо цифр в расписании
        if call.data == 'torn on no' or call.data == 'torn on yes':
            past = users[number].settings['Time instead of number']
            if call.data == 'torn on yes':
                users[number].settings['Time instead of number'] = True

            elif call.data == 'torn on no':
                users[number].settings['Time instead of number'] = False

            if call.data != past:
                if users[number].settings['Time instead of number']:
                    decision = languages.assembly['enable']['on'][
                        users[number].settings['language']]
                else:
                    decision = languages.assembly['enable']['off'][
                        users[number].settings['language']]

                bot.answer_callback_query(
                    callback_query_id=call.id,
                    text=languages.assembly['Time instead of number'][
                        users[number].settings['language']] + decision)

            else:
                bot.answer_callback_query(
                    callback_query_id=call.id,
                    text=languages.assembly['been selected'][
                        users[number].settings['language']])
            return

        if call.data[:2] == 'wd':
            users[number].working_day[int(
                call.data[-1])] = not users[number].working_day[int(
                    call.data[-1])]

            working_day(call.message.chat.id, call.message.message_id)
            return
Beispiel #14
0
def text(message):
    global users
    number = tools.find(users, message.chat.id)

    if number is None:
        bot.send_message(message.chat.id,
                         languages.assembly['not in the database']['ru'])

    else:
        # установить utc
        if users[number].position['last message type'] == 'utc':
            try:
                users[number].settings['UTC'] = float(message.text)

                bot.send_message(
                    message.chat.id, languages.assembly['done utc'][
                        users[number].settings['language']] + ' ' +
                    str(users[number].settings['UTC']) + '.')
                users[number].position['last message type'] = 'null'

            except Exception as e:
                bot.send_message(message.chat.id, str(e))

        # установить время
        if users[number].position['last message type'] == 'time':
            try:
                time_clock = datetime.strptime(str(message.text),
                                               '%H:%M').time()
                # если что-то пойдет не так то выкенет Exception

                users[number].time = time_clock.strftime('%H:%M')
                bot.send_message(
                    message.chat.id, languages.assembly['done time'][
                        users[number].settings['language']] + ' ' +
                    str(users[number].time))

                users[number].position['last message type'] = 'null'

            except Exception as e:
                bot.send_message(message.chat.id, str(e))

        # меняем занятие
        if users[number].position['last message type'] == 'edit true':
            try:
                temp = users[number].schedule
                temp[users[number].position['week']][
                    users[number].position['day'] -
                    1][users[number].position['lesson'] - 1] = message.text
                users[number].schedule = temp
                del temp

                edit_day_week(
                    user_id=message.chat.id,
                    message_id=users[number].position['last message id'])
                bot.delete_message(message.chat.id, message.message_id)

            except Exception as e:
                bot.send_message(message.chat.id, str(e))

        if users[number].position['last message type'] == 'letime':
            users[
                number].couples_schedule = tools.from_text_to_array_couples_schedule(
                    message.text + '\n', separator='\n')
            edit = tools.from_array_to_text(
                users[number].couples_schedule.values(), separator='\n')
            if edit != users[number].position['last message'] + '\n':
                users[number].position['last message'] = edit
                bot.edit_message_text(
                    edit, message.chat.id,
                    users[number].position['last message id'])
                bot.delete_message(message.chat.id, message.message_id)
                return
            bot.send_message(
                message.chat.id, languages.assembly['been selected'][
                    users[number].settings['language']])
            return
Beispiel #15
0
def edit_day_week(user_id=0, message_id=0):
    global users
    number = tools.find(users, user_id)

    navigation = types.InlineKeyboardMarkup()
    if users[number].position[
            'last message type'] == 'edit true':  # вносим изменения
        week_up = types.InlineKeyboardButton(text='↑', callback_data='edit up')
        week_down = types.InlineKeyboardButton(text='↓',
                                               callback_data='edit down')
        week_add_b = types.InlineKeyboardButton(
            text=languages.assembly['e add']['add b'][
                users[number].settings['language']],
            callback_data='edit add before')
        week_add_a = types.InlineKeyboardButton(
            text=languages.assembly['e add']['add a'][
                users[number].settings['language']],
            callback_data='edit add after')
        week_del = types.InlineKeyboardButton(
            text=languages.assembly['del'][users[number].settings['language']],
            callback_data='edit delete')
        edit_day = types.InlineKeyboardButton(
            text=languages.assembly['back to day selection'][
                users[number].settings['language']],
            callback_data='edit day')

        navigation.add(week_up, week_add_b)
        navigation.add(week_down, week_add_a)
        navigation.add(week_del)
        navigation.add(edit_day)

        # весь текст сообщения
        information = information_line(
            users[number],
            users[number].position['week'],
            users[number].position['day'],
            message=languages.assembly['editing'][
                users[number].settings['language']],
            week_even_ignore=True) + "\n" + daily_schedule(
                users[number],
                users[number].position['week'],
                users[number].position['day'],
                choice=True,
                week_even_ignore=True)
        if message_id == 0:  # отправка сообщения
            bot.send_message(users[number].id,
                             text=information,
                             reply_markup=navigation)

        else:  # изменение уже существующего сообщения
            bot.edit_message_text(chat_id=users[number].id,
                                  message_id=message_id,
                                  text=information,
                                  reply_markup=navigation)

    else:  # выбор дня для редактирования
        users[number].position['last message type'] = 'edit false'
        week_back = types.InlineKeyboardButton(text='<',
                                               callback_data='edit back')
        week_forward = types.InlineKeyboardButton(text='>',
                                                  callback_data='edit forward')
        edit_day = types.InlineKeyboardButton(
            text=languages.assembly['edit this day'][
                users[number].settings['language']],
            callback_data='edit day')
        navigation.add(week_back, week_forward)
        message_id_s = 0
        message_text = ''
        if not users[number].settings['combination of weeks']:
            week_another = types.InlineKeyboardButton(
                text=languages.assembly['another'][
                    users[number].settings['language']],
                callback_data='edit another')
            navigation.add(week_another)

        navigation.add(edit_day)

        if message_id == 0:
            mes = bot.send_message(
                users[number].id,
                information_line(users[number], users[number].position['week'],
                                 users[number].position['day']) + '\n' +
                daily_schedule(users[number],
                               users[number].position['week'],
                               users[number].position['day'],
                               week_even_ignore=True),
                reply_markup=navigation)
            message_id_s = mes.message_id
            message_text = mes.text
        else:
            answer = information_line(users[number],
                                      users[number].position['week'],
                                      users[number].position['day']) + '\n' \
                     + daily_schedule(users[number],
                                      users[number].position['week'],
                                      users[number].position['day'],
                                      choice=True,
                                      week_even_ignore=True)

            if users[number].position['last message id'] != answer:
                bot.edit_message_text(chat_id=users[number].id,
                                      message_id=message_id,
                                      text=answer,
                                      reply_markup=navigation)
            else:
                bot.answer_callback_query(
                    callback_query_id=users[number].id,
                    text='Nothing has changed here \(゚ー゚\)')

        if message_id_s != 0:
            users[number].position['last message id'] = message_id_s
            users[number].position['last message'] = message_text