def post(self, request, format=None):
        """
        Return auth token
        """
        try:
            serializer = LoginUserNamenSerializer(data=request.data)
            if serializer.is_valid():
                username = serializer.validated_data["username"]
                password = serializer.validated_data["password"]
                auth = authenticate(username=username, password=password)

                if auth is not None:
                    try:
                        refresh = RefreshToken.for_user(auth)
                        token = str(refresh.access_token)
                        data = {"token": token}
                        # logger
                        Log.info(f"success | Authentication success", request)
                        return Response(prepare_success_response(
                            message="Authentication successfull", data=data),
                                        status=HTTP_200_OK)
                    except Exception as ex:
                        # logger
                        Log.error(ex, request)
                        response_param = {
                            "message": "Token generation failed",
                            "data": {},
                            "type": "error"
                        }
                        return Response(response_param, status=HTTP_200_OK)

                else:
                    # logger
                    Log.error(f"error | Employee id or password mistmatch",
                              request)
                    return Response(prepare_error_response(
                        "'Employee id' or 'Password' Mismatch"),
                                    status=HTTP_400_BAD_REQUEST)

            else:
                # logger
                Log.error(f"error | Plz enter correct data.", request)
                return Response(
                    prepare_error_response("Plz, enter correct data."),
                    status=HTTP_400_BAD_REQUEST)

        except Exception as ex:
            Log.error(ex, request)
            return Response(
                {
                    "message": "Internal server error",
                    "data": None,
                    "type": "error"
                },
                status=HTTP_500_INTERNAL_SERVER_ERROR)
Exemple #2
0
    def find_element(self,element,name):
        ele = read_ini.get_value(str(element))
        with allure.step("检查:'{0}'".format(name)):
                try:
                    if ele.startswith('//'):
                        return WebDriverWait(self.driver, 10).until(lambda driver: driver.find_element_by_xpath(ele), '失败了')
                    else:
                        return WebDriverWait(self.driver, 10).until(lambda driver: driver.find_element_by_id(ele),'失败')

                except Exception as e:
                    print(e)
                    L.e("页面中未能找到 %s 元素" % name)
                    raise Exception("页面中未能找到 [%s]" % name)
Exemple #3
0
    def charger_dune_chaine(self, chaine):
        """Vide le damier actuel et le remplit avec les informations reçues dans une chaîne de caractères. Le format de
        la chaîne est expliqué dans la documentation de la méthode convertir_en_chaine.

        Args:
            chaine (str): La chaîne de caractères.
        """
        for vieux_pats in self.id_patrouilleurs:
            self.id_patrouilleurs[vieux_pats] = None
        numero_de_ligne = 0
        patrouilleur = False
        for information_quart in chaine.split("\n"):
            if information_quart in ["204", "205", "206", "207"]:
                numero_de_ligne = 1
                poste = information_quart
                patrouilleur = True
            if information_quart != "":
                if numero_de_ligne == 0:
                    nb_patrouilleurs, self.couleur_lieutenant, nom_lieutenant, titre_lieutenant, indicatif_lieutenant, \
                    self.dernier_pat_log = information_quart.split(";")
                    self.nb_patrouilleurs = int(nb_patrouilleurs)
                elif patrouilleur:
                    if numero_de_ligne == 2:
                        nom, titre, indicatif, couleur1, couleur2 = information_quart.split(
                            ";")
                        self.id_patrouilleurs[poste] = \
                            Patrouilleur(Agent(nom, titre, indicatif), poste, [couleur1, couleur2])
                    elif numero_de_ligne != 1:
                        nouveau_log = Log()
                        nouveau_log.charger_dune_chaine(information_quart)
                        self.id_patrouilleurs[poste].logs.insert(
                            0, nouveau_log)
            numero_de_ligne += 1

        self.id_lieutenant = Agent(nom_lieutenant, titre_lieutenant,
                                   indicatif_lieutenant)
        for pat in self.id_patrouilleurs:
            if self.id_patrouilleurs[pat] is not None:
                self.id_patrouilleurs[pat].position = self.id_patrouilleurs[
                    pat].logs[0]
                self.id_patrouilleurs[pat].logs.pop(0)

        self.dernier_pat_log = self.dernier_pat_log.split("-")
        new_list = []
        for item in self.dernier_pat_log:
            new_list.append(item.split(","))
        self.dernier_pat_log = new_list
Exemple #4
0
    def __init__(self, agent, poste, theme):
        """Constructeur de la classe Patrouilleur. Initialise les deux quatre de la classe.

        Args:
            agent (agent) : Identité du patrouilleur
            poste (int) : Numéro du poste occupé (200, 204, 205, 206 ou 207)
            position (log) : Position actuelle du patrouilleur
            logs (list) : Liste des logs précédents du patrouilleur

        """
        if poste not in {"204", "205", "206", "207"}:
            raise ValueError("Poste invalide. Doit être entre 200 et 207")

        self.agent = agent
        self.poste = poste
        self.theme = theme
        self.position = Log("00:00", None, "Terminal", None, "Début du quart")
        self.logs = []
Exemple #5
0
class Patrouilleur:
    """Agent de la sûreté en poste.

    Attributes:
        agent (agent) : Nom de l'agent
        poste (int) : Numéro du poste occupé (200, 204, 205, 206 ou 207)
        position (log) : Position actuelle du patrouille
        logs (list) : Liste des logs précédents du patrouilleur

    """
    def __init__(self, agent, poste, theme):
        """Constructeur de la classe Patrouilleur. Initialise les deux quatre de la classe.

        Args:
            agent (agent) : Identité du patrouilleur
            poste (int) : Numéro du poste occupé (200, 204, 205, 206 ou 207)
            position (log) : Position actuelle du patrouilleur
            logs (list) : Liste des logs précédents du patrouilleur

        """
        if poste not in {"204", "205", "206", "207"}:
            raise ValueError("Poste invalide. Doit être entre 200 et 207")

        self.agent = agent
        self.poste = poste
        self.theme = theme
        self.position = Log("00:00", None, "Terminal", None, "Début du quart")
        self.logs = []

    def nouveau_log(self, log, nouvelle_heure):
        """Ajoute un log dans la position actuelle et envoie le log précédent dans la liste de logs

        Args:
            position (Position): La position où vérifier.

        """
        if nouvelle_heure:
            self.position.heure_fin = log.heure_debut
        self.logs.insert(0, self.position)
        self.position = log

    def effacer_dernier_log(self):
        if len(self.logs) != 0:
            self.position = self.logs[0]
            self.position.heure_fin = None
            self.logs.pop(0)

    def convertir_en_chaine(self):
        chaine = "{}\n{};{};{}\n{}\n".format(
            self.poste, self.agent.convertir_en_chaine(), self.theme[0],
            self.theme[1], self.position.convertir_en_chaine())
        for log in self.logs:
            chaine += "{}\n".format(log.convertir_en_chaine())

        return chaine
    def get(self, request, *args, **kwargs):
        """
        :param request:
        :param args: language, country
        :param kwargs:
        :return: searched country
        """
        try:
            query_object = country_filtering(request)
            if len(query_object) < 1:
                # logger
                Log.error("Query params didn't provide.", request)
                return Response(prepare_error_response(
                    message="Query params didn't provide."),
                                status=HTTP_400_BAD_REQUEST)

            obj = CountryInfo.objects.filter(query_object)
            serializer = CountryModelSerializer(obj,
                                                context={'request': request},
                                                many=True)

            # logger
            Log.info("Successfully returned", request)
            return Response(prepare_success_response(
                message="Successfully returned", data=serializer.data),
                            status=HTTP_200_OK)
        except Exception as ex:
            # logger
            Log.error(str(ex), request)
            return Response(prepare_error_response(message=str(ex)),
                            status=HTTP_500_INTERNAL_SERVER_ERROR)
Exemple #7
0
    def loadDataSet(self):

        l = Log("logs/logfiles/")

        for fic in range(l.getLatestLogNr()):
            line = l.readLogNP(fic)
            for x in range (len(line)):
                belief = line[x][0]
                cards = line[x][1]
                reward = (line[x][2]+22)/44

                inpt = tuple(np.append(belief, cards))

                try:
                    belief2 = line[x + 1][0]
                    cards2 = line[x + 1][1]
                    output2 = self.test(tuple(np.append(belief2,cards2)))
                    target = tuple(reward + self.df*output2)
                except:
                    target = tuple(reward)

                self.ds.addSample(inpt,target)
Exemple #8
0
    def creer_log(self, patrouilleurs, terminal_exterieur, cote, log, note):
        heure = datetime.datetime.now().strftime("%H:%M")
        nouveau_log = Log(heure, None, terminal_exterieur, cote, log, note)
        for pats in self.quart.id_patrouilleurs:
            if self.quart.id_patrouilleurs[pats] is not None:
                self.quart.id_patrouilleurs[
                    pats].position.heure_debut = self.cadres_patrouilleurs[
                        pats].heure_position.get()
        for pat in patrouilleurs:
            self.quart.id_patrouilleurs[pat].nouveau_log(nouveau_log, True)
            self.afficher_logs(pat)
        self.quart.dernier_pat_log.insert(0, patrouilleurs)

        self.sauvegarder_quart(False)
Exemple #9
0
def login(request: HttpRequest):
    data = request.POST.dict()
    print(data)
    account = data["account"]
    password = data["password"]
    user_type = data["type"]
    Log.i(__name__, account + "尝试登录...")
    try:
        if user_type == "student":  # 学生登录
            stu = Student.objects.filter(stu_id=account).first()
            _account = StuAccount.objects.filter(
                account_name_id=stu.id).first()
            _pwd = _account.pwd
            if _pwd == password:  # 密码正确
                obj = redirect("/stu_index")
                obj.set_cookie("account", account)
                obj.set_cookie("is_login", True)
                return obj

        else:  # 教师登录
            tea = Teacher.objects.filter(tea_id=account).first()
            _account = ManagerAccount.objects.filter(
                account_name_id=tea.id).first()
            _pwd = _account.pwd
            if _pwd == password:
                obj = redirect("/teacher/index")
                obj.set_cookie("account", account)
                obj.set_cookie("is_login", True)
                obj.set_cookie("level", _account.level)
                return obj
    except Exception:
        traceback.print_exc()
        Log.i(__name__, account + "账号错误, 登录失败...")
        return render(request, "index.html", {"status": "account_error"})
    finally:
        Log.i(__name__, account + "密码错误, 登录失败...")
    return render(request, "index.html", {"status": "password_error"})
Exemple #10
0
 def test_init_console(self):
     log = Log(target='console').get_logger(__name__)
     log.debug('hello,world')
Exemple #11
0
 def test_get_logger(self):
     log = Log(target='console').get_logger('TEST')
     log.debug('hello,world')
Exemple #12
0
 def test_level(self):
     log = Log(target='console', level=logging.ERROR).get_logger(__name__)
     log.debug('hello,world~')
     log.info('python logs package.')
     log.warning('do not touch it!')
     log.error('runtime error!!')
     log.critical('out of memory!!!')
Exemple #13
0
 def test_multiple_output(self):
     ins = Log(target='console')
     ins.add_handler_file()
     log = ins.get_logger(__name__)
     log.debug('hello,world')
Exemple #14
0
 def test_init_rotating_file(self):
     log = Log(target='rotating_file').get_logger(__name__)
     log.debug('hello,world')
Exemple #15
0
class System:
    def __init__(self, controller, color_street):
        self._controller = self.__define_controller(controller)
        self._color = color_street
        self._log = Log()
        self._initial_time = time.time()

    def output(self, video, img_to_show):
        video_processed, dist_center, curv = self.__video_processing(video)
        curv_max = self.__set_max(curv, -200.0, 200.0)
        dist_center_max = self.__set_max(dist_center, -0.5, 0.5)
        run_time = self.__get_run_time()
        speed, angle = self._controller.output(dist_center_max, curv_max, run_time)
        # self.__store_object_log(speed, angle, dist_center, curv)
        self.__store_object_log(speed, angle, dist_center_max, curv_max, run_time)

        if img_to_show == STREET_ORIGINAL_IMAGE:
            return video, speed, angle
        # elif img_to_show == STREET_DETECTING:
        #     return self.__detect_street_by_color(video), speed, angle
        elif img_to_show == STREET_LINES_DRAWN:
            return video_processed, speed, angle
        else:
            print "img_to_show: ", img_to_show, " not found!"
            return video, 0, 0

    # define range of color in HSV
    def __detect_street_by_color(self, video):
        if self._color == DETECT_YELLOW:
            lower_color, upper_color = np.array([20, 0, 100]), np.array([30, 255, 255])
            # lower_color, upper_color = np.array([20, 100, 100]), np.array([30, 255, 255])
        elif self._color == DETECT_BLACK:
            lower_color, upper_color = np.array([0, 0, 0]), np.array([180, 255, 100])
        else:
            raise ValueError('Color to found the street not found!')
        return detect_street(video, lower_color, upper_color)

    # Video processing
    # Return the processing video
    # Color image loaded by OpenCV is in BGR mode.
    def __video_processing(self, video):
        video_street = self.__detect_street_by_color(video)
        try:
            left_fit, right_fit, video_shape = fit_lines(video_street)
            # show_image(video_processed)
            left_cur, right_cur, left_x, right_x, distance_center = curvature(left_fit, right_fit, video_shape)

            video_road = draw_lines(video, left_x, right_x)
            curv = (left_cur + right_cur) / 2.0
            add_text_to_image(video_road, curv, distance_center)

            return video_road, distance_center, curv

        except Exception as e:
            print str(e)
            return video, 0, 0

    def reset_log(self):
        self._log.clean_log()
        self._initial_time = time.time()
        self._controller.reset(self._initial_time)

    def get_log_system(self):
        return self._log.get_log()

    def __store_object_log(self, speed, angle, dist_center, curv, run_time):
        try:
            log_object = LogDto(run_time, speed, angle, dist_center, curv)
            log_obj_str = repr(log_object)
            self._log.store_object(log_obj_str)
        except Exception as e:
            print "Error while storing log: ", str(e)

    def __get_run_time(self):
        return time.time() - self._initial_time

    # Define which controller to use
    @staticmethod
    def __define_controller(controller):
        if controller == FUZZY_CONTROLLER:
            return FuzzyController()
        elif controller == PID_CONTROLLER:
            return PIDController()
        else:
            print "Controller not found"

    @staticmethod
    def __set_max(value, min_value, max_value):
        if value > 0 and value > max_value:
            return max_value
        if value < 0 and value < min_value:
            return min_value
        return value
Exemple #16
0
import os
import sys
from tempfile import TemporaryDirectory

from logs.log import Log

with TemporaryDirectory() as dirname:

    file1 = os.path.join(dirname, "file1")
    file2 = os.path.join(dirname, "file2")
    file3 = os.path.join(dirname, "file3")
    file4 = os.path.join(dirname, "file4")
    file5 = os.path.join(dirname, "file5")    
    
    log = Log()

    log.set_file_levels([file1, file2], ['info', 'verbose', 'critical'])
    log.set_file_levels([file3], ['debug', 'critical'])
    log.set_file_levels([file4], ['debug', 'info'])
    log.set_file_levels([file5], ['verbose'])    

    assert(file1 in log.get_files())
    assert(file2 in log.get_files())
    assert(file3 in log.get_files())
    assert(file4 in log.get_files())
    assert(file5 in log.get_files())    
    assert(len([x for x in log.get_files()]) == 5)

    log.set_default_levels('critical')
Exemple #17
0
 def __init__(self, controller, color_street):
     self._controller = self.__define_controller(controller)
     self._color = color_street
     self._log = Log()
     self._initial_time = time.time()
Exemple #18
0
    def gameLoop(self):
        log = Log("logs/logfiles/")
        #incializacoes de jogo e alteracoes no objecto game
        loops = 20
        self.init()
        ##print("Trump:", self.trumpCard.getNaipe(), "\n")
        firstPlayer = NFQAgent("NFQAgent", self.baralho[:3],40)
        secondPlayer = MinimaxPlayer("MinimaxPlayer", self.baralho[3:6])
        ##firstPlayer.printCards()
        ##secondPlayer.printCards()
        del self.baralho[:6]
        i = 0
        for i in range (loops):
            ##print("Loop: ", i)
            self.players = {firstPlayer.getPlayerId(): firstPlayer, secondPlayer.getPlayerId(): secondPlayer}
            firstPlayer.playerLoop(self.cardsPlayedInTurn, self)
            secondPlayer.playerLoop(self.cardsPlayedInTurn, self)
            winner = self.winner(firstPlayer.getPlayerId(),self.cardsPlayedInTurn[0],secondPlayer.getPlayerId() ,self.cardsPlayedInTurn[1])
            if(firstPlayer.getPlayerId() == "NFQAgent"):
                firstPlayer.reviewTurn(self.cardsPlayedInTurn[1])
                ##firstPlayer.printState()
            ##else:
                ##secondPlayer.printState()
            ##print("")
            ##print("Winner:", winner)
            points = self.pointsPerTurn()
            ##print("Points:",points, "\n")

            beliefsLOG = []
            cardsLOG = []
            pointsLOG = 0
            if(self.logging == 1):

                if(firstPlayer.getPlayerId()=="NFQAgent"):
                    if(winner == firstPlayer.getPlayerId()):
                        pointsLOG = self.pointsPerTurn()
                    else:
                        pointsLOG = -self.pointsPerTurn()
                    beliefsLOG = firstPlayer.beliefs
                    cardsLOG = firstPlayer.currentCards
                else:
                    if(winner == secondPlayer.getPlayerId()):
                        pointsLOG = self.pointsPerTurn()
                    else:
                        pointsLOG = -self.pointsPerTurn()
                    beliefsLOG = secondPlayer.beliefs
                    cardsLOG = secondPlayer.currentCards


                #log
                log.writeLogNP(beliefsLOG, cardsLOG,pointsLOG)


            self.closeTurn(self.cardsPlayedInTurn)
            firstPlayer = self.players.pop(winner)
            firstPlayer.updatePoints(points)
            secondPlayer = list(self.players.values())[0]

        log.closeLog()
        ##print(firstPlayer.getPlayerId(), firstPlayer.points, secondPlayer.getPlayerId(), secondPlayer.points)

        if(firstPlayer.points > secondPlayer.points):
            return firstPlayer
        else:
            return secondPlayer
Exemple #19
0
import os
import sys
from tempfile import TemporaryDirectory

from logs.log import Log

with TemporaryDirectory() as dirname:

    file1 = os.path.join(dirname, "file1")
    file2 = os.path.join(dirname, "file2")
    file3 = os.path.join(dirname, "file3")
    file4 = os.path.join(dirname, "file4")
    file5 = os.path.join(dirname, "file5")

    log = Log()

    log.set_file_levels([file1, file2], ['info', 'verbose', 'critical'])
    log.set_file_levels([file3], ['debug', 'critical'])
    log.set_file_levels([file4], ['debug', 'info'])
    log.set_file_levels([file5], ['verbose'])

    assert (file1 in log.get_files())
    assert (file2 in log.get_files())
    assert (file3 in log.get_files())
    assert (file4 in log.get_files())
    assert (file5 in log.get_files())
    assert (len([x for x in log.get_files()]) == 5)

    log.set_default_levels('critical')
Exemple #20
0
import numpy as np
from logs.log import Log

l = Log()

def testWrite():
    i=0
    for i in range(10):
       j=0
       for j in range(3):
           l.writeLogNP(np.array([i,j]),np.array([i,j]),np.array([j]))
       j=0
       l.closeLog() #ao chamar este metodo é escrito um novo ficheiro de log  na proxima iteracao



def testRead():
    for i in range(l.getLatestLogNr()):
        print("Log " + str(i) + " : " + str(l.readLogNP(i))) # le cada row do ficheiro para uma entrada na lista

testWrite()
testRead()
Exemple #21
0
    def gameLoop(self):
        log = Log("logs/logfiles/")
        #incializacoes de jogo e alteracoes no objecto game
        loops = 20
        self.init()
        ##print("Trump:", self.trumpCard.getNaipe(), "\n")
        firstPlayer = NFQAgent("NFQAgent", self.baralho[:3], 40)
        secondPlayer = MinimaxPlayer("MinimaxPlayer", self.baralho[3:6])
        ##firstPlayer.printCards()
        ##secondPlayer.printCards()
        del self.baralho[:6]
        i = 0
        for i in range(loops):
            ##print("Loop: ", i)
            self.players = {
                firstPlayer.getPlayerId(): firstPlayer,
                secondPlayer.getPlayerId(): secondPlayer
            }
            firstPlayer.playerLoop(self.cardsPlayedInTurn, self)
            secondPlayer.playerLoop(self.cardsPlayedInTurn, self)
            winner = self.winner(firstPlayer.getPlayerId(),
                                 self.cardsPlayedInTurn[0],
                                 secondPlayer.getPlayerId(),
                                 self.cardsPlayedInTurn[1])
            if (firstPlayer.getPlayerId() == "NFQAgent"):
                firstPlayer.reviewTurn(self.cardsPlayedInTurn[1])
                ##firstPlayer.printState()
            ##else:
            ##secondPlayer.printState()
            ##print("")
            ##print("Winner:", winner)
            points = self.pointsPerTurn()
            ##print("Points:",points, "\n")

            beliefsLOG = []
            cardsLOG = []
            pointsLOG = 0
            if (self.logging == 1):

                if (firstPlayer.getPlayerId() == "NFQAgent"):
                    if (winner == firstPlayer.getPlayerId()):
                        pointsLOG = self.pointsPerTurn()
                    else:
                        pointsLOG = -self.pointsPerTurn()
                    beliefsLOG = firstPlayer.beliefs
                    cardsLOG = firstPlayer.currentCards
                else:
                    if (winner == secondPlayer.getPlayerId()):
                        pointsLOG = self.pointsPerTurn()
                    else:
                        pointsLOG = -self.pointsPerTurn()
                    beliefsLOG = secondPlayer.beliefs
                    cardsLOG = secondPlayer.currentCards

                #log
                log.writeLogNP(beliefsLOG, cardsLOG, pointsLOG)

            self.closeTurn(self.cardsPlayedInTurn)
            firstPlayer = self.players.pop(winner)
            firstPlayer.updatePoints(points)
            secondPlayer = list(self.players.values())[0]

        log.closeLog()
        ##print(firstPlayer.getPlayerId(), firstPlayer.points, secondPlayer.getPlayerId(), secondPlayer.points)

        if (firstPlayer.points > secondPlayer.points):
            return firstPlayer
        else:
            return secondPlayer
Exemple #22
0
    elif sys_name.startswith("POSIX"):  # unix linux 系列
        # os.system("python3 manage.py makemigrations")
        # os.system("python3 manage.py migrate")
        os.system("python3 manage.py runserver 8000")


def start_eel():
    # 启动的函数调用放在最后,port=0表示使用随机端口,size=(宽,高)
    eel.start('db.html', port=8001, size=(1024, 800))


if __name__ == "__main__":
    # html文件所在文件夹
    eel.init('DormFrontend')
    # 检测数据库配置
    Log.i(__name__, "开始检查数据库配置")

    # 调用线程
    try:
        Log.i(__name__, "开始启动django")
        django = threading.Thread(target=start_django)
        django.setDaemon(True)
        django.start()
    except pymysql.err.InternalError:
        print_exc()
        Log.e(__name__, "数据库配置错误, django启动失败")
        sys.exit(0)

    sleep(2)
    Log.i(__name__, "开始尝试启动EEL")
    eel_t = threading.Thread(target=start_eel)