import requests
from datetime import datetime
import api_keys

now = datetime.now()
formatted_now_date = now.strftime("%d/%m/%Y")
formatted_now_time = now.time().strftime("%H:%M:%S")
exercise_ep = "https://trackapi.nutritionix.com/v2/natural/exercise"
sheety_url = "https://api.sheety.co/dd81a891f83891fcffdab1dcc7c5a53e/casualWorkoutTracking/workouts"

exercise_params = {
    "query": input("Tell me which exercises you did today: \n"),
    "gender": api_keys.GENDER,
    "weight_kg": api_keys.WEIGHT_KG,
    "height_cm": api_keys.HEIGHT_CM,
    "age": api_keys.AGE

}

exercise_response = requests.post(url=exercise_ep, headers=api_keys.header, json=exercise_params)
exercise_data = exercise_response.json()

headers = {
    "Authorization": f"Bearer {api_keys.BEARER_TOKEN}"
}

for exercise in exercise_data["exercises"]:
    print(exercise)
    print("==========================================")

    body = {
        "workout": {
            "date": formatted_now_date,
            "time": formatted_now_time,
            "exercise": exercise["name"],
            "calories": exercise["nf_calories"],
            "duration": exercise["duration_min"]
        }
    }
    sheety_response = requests.post(url=sheety_url, json=body, headers=headers)
    sheety_data = sheety_response.json()
    print(sheety_data)


# the simplest solution - simply run this script at startup
# - output will go to console and alert if there is a diff
# For first run will compare with specified html file
# 	or create new one if nonexistant
import time
import urllib.request as ur
import sys, getopt
import os.path
from datetime import datetime
import difflib
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import logging

##   If you are going to recommit this file with your own information, look for no-comit hooks
   # These hooks will filter sensitive information on my machine, but will not do so on your machine

# logging setup
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename='tmp.log',
                    filemode='w')

### default params, can be passed as flags to change
secondsToSleep = 3600 # 3600s = 1hr
numberOfRuns = -1 #-1 is infinite
urlToCheck = "www.Google.com" #no-commit
fileToWrite = "sourceOfLastRun.html" # file with last source of site
verbose = True # if True, print
log = True # if True, write to log

# email parameters
sendEmailFlag = True
emailDest = ["www.Google.com"]  #no-commit, make a list if multiple recipients
emailType = 'html' # can also be html.  Other values will break!
#############

### Values to be set by modifying this file only, not thru command line
emailSrc = emailDest[0] # change here if dest is different than from
emailSrcPass = "www.Google.com"  #no-commit this password generated from https://support.google.com/accounts/answer/185833
									# refer to README.md for more details
#############

def checkUrl():
	with ur.urlopen(urlToCheck) as openedUrl:
		fetchedHtml = str(openedUrl.read().decode('utf-8'))

	if (os.path.isfile(fileToWrite)):
		currentFileHtml = open(fileToWrite).read()
		if (currentFileHtml == fetchedHtml):
			writeLine("same at " + createTimeStamp())
		else:
			writeFileBack(fetchedHtml)
			writeLine("diff at " + createTimeStamp())
			diff = getDiffString(currentFileHtml, fetchedHtml)
			emailDiff(diff)

	else:
		writeFileBack(fetchedHtml, True)
		checkUrl()

# feel free to modify this function as needed to 'prettify' your email bodies
def emailDiff(diff):
	if (sendEmailFlag):
		server = smtplib.SMTP('smtp.gmail.com', 587)
		server.starttls()
		server.login(emailSrc, emailSrcPass)

		msg = createMIMEMsg(diff)

		server.sendmail(emailSrc, emailDest, msg.as_string())
		server.quit()

def createMIMEMsg(txt):
	msg = MIMEMultipart('alternative')
	msg['Subject'] = 'Latest diff of webpage "www.Google.com"' #no-commit
	msg['To'] = emailDest[0]

	txt += "\n\n\n\n\n\nURL of webpage: " + urlToCheck
	html =  MIMEText(txt, emailType)

	msg.attach(html)
	return msg

def writeFileBack(src, created = False,):
	with open(fileToWrite, 'w') as f:
		f.write(src)
	if (created):
		action = 'created'
	else:
		action = 'overwritten'

	writeLine("		File " + action + " at " + createTimeStamp())

def getDiffString(orig, new):
	diff = list(difflib.context_diff(orig.splitlines(), new.splitlines()))
	diff = [line[1:] for line in diff if line[0] == '!'] # the '!' corresponds with difflib for diff presentation
	return '\n'.join(list(diff))

# prints a simple time stamp for readibility
def createTimeStamp():
	now = datetime.now()
	return now.strftime("%b %d, %Y at %I:%M.%S %p")

def writeLine(s):
	if verbose:
		print(s)
	if log:
		logging.info(s)

if __name__ == "__main__":
	opts, args = getopt.getopt(sys.argv[1:],"hs:r:",["seconds=", "runs="])

	for opt, arg in opts:
		if opt == '-h':
			print('python checkURLNoTask.py -s <seconds>')
			sys.exit()
		elif opt in ("-s", "--seconds"):
			secondsToSleep = int(arg)
		elif opt in ("-r", "--runs"):
			numberOfRuns = int(arg)

	line = "checking url: " + urlToCheck + " every " + str(secondsToSleep) + " seconds " + str(numberOfRuns) + " times with email sending: " + str(sendEmailFlag)
	writeLine(line)

	runCount = 0
	while runCount != numberOfRuns:
		checkUrl()
		runCount+=1
		time.sleep(secondsToSleep)

	writeLine("Checked URL " + str(numberOfRuns) + ", ending script")


#!/usr/bin/env python3

import numpy
import opt_analy
import matplotlib
import matplotlib.pyplot as plt

def plot(az_list, el_list, dx_list, dy_list, file_list, raw=True):

    if raw == True:
        dx_avg, dy_avg, dx_std, dy_std, *_ = opt_analy.process_static(file_list, clip_sigma=(3.,3.))
    else:
        az = [e for inner_list in az_list for e in inner_list]
        el = [e for inner_list in el_list for e in inner_list]
        dx = [e for inner_list in dx_list for e in inner_list]
        dy = [e for inner_list in dy_list for e in inner_list]
        dx_avg, dy_avg, dx_std, dy_std = numpy.average(dx), numpy.average(dy), numpy.std(dx), numpy.std(dy)

    nrow = 3
    ncol = 2
    nax = ncol * nrow
    figsize = (ncol * 4, nrow * 4)

    fig = plt.figure(figsize=figsize)
    fig.subplots_adjust(wspace=0.4, hspace=0.4)
    ax = [fig.add_subplot(nrow, ncol, i+1) for i in range(nax-1)]

    matplotlib.rcParams['savefig.dpi'] = 200
    matplotlib.rcParams['font.size'] = 14

    for az, el, dx, dy in zip(az_list, el_list, dx_list, dy_list):
        ax[0].plot(az, dx, '.', label='diff')
        ax[1].plot(el, dx, '.', label='diff')
        ax[2].plot(az, dy, '.', label='diff')
        ax[3].plot(el, dy, '.', label='diff')
        ax[4].plot(dx, dy, '.', label='diff')

    ax[0].set_xlabel('Az [deg.]')
    ax[0].set_ylabel('dx [arcsec.]')
    ax[0].set_title('Az vs dx')

    ax[1].set_xlabel('El [deg.]')
    ax[1].set_ylabel('dx [arcsec.]')
    ax[1].set_title('El vs dx')

    ax[2].set_xlabel('Az [deg.]')
    ax[2].set_ylabel('dy [arcsec.]')
    ax[2].set_title('Az vs dy')

    ax[3].set_xlabel('El [deg.]')
    ax[3].set_ylabel('dy [arcsec.]')
    ax[3].set_title('El vs dy')

    ax[4].set_xlabel('dx [arcsec.]')
    ax[4].set_ylabel('dy [arcsec.]')
    ax[4].set_title('dx vs dy')

    [_ax.grid() for _ax in ax]

    if len(file_list) < 8:
        tbl_loc = 'lower center'
        legend_loc = (1.1, 0.35)
    else:
        tbl_loc = 'bottom'
        legend_loc = (1.1, 0.02)

    tbl = fig.add_subplot(3,2,6)
    col_labels=['average','std dev',]
    row_labels=[' dx ',' dy ', ' unite ']
    tbl_vals=[["{:.2e}".format(dx_avg), "{:.2f}".format(dx_std)],
              ["{:.2e}".format(dy_avg), "{:.2f}".format(dy_std)],
              ["{:.2e}".format(numpy.sqrt(dx_avg**2+dy_avg**2)), "{:.2e}".format(numpy.sqrt(dx_std**2+dy_std**2))]
    ]

    tbl.table(cellText=tbl_vals, rowLabels=row_labels, colLabels=col_labels, loc=tbl_loc)

    tbl.set_axis_off()
    fig.tight_layout()
    ax[4].legend(labels=file_list, loc=legend_loc)

    plt.show()


from io import BytesIO
from .models import Book
from librarian import DocProvider
from django.http import HttpResponse

class RedakcjaDocProvider(DocProvider):
    """Used for getting books' children."""

    def __init__(self, publishable):
        self.publishable = publishable

    def by_slug(self, slug):
        print(slug)
        return BytesIO(Book.objects.get(catalogue_book_id=slug
                    ).materialize(publishable=self.publishable
                    ).encode('utf-8'))

def serve_file(file_path, name, mime_type):
    def read_chunks(f, size=8192):
        chunk = f.read(size)
        while chunk:
            yield chunk
            chunk = f.read(size)

    response = HttpResponse(content_type=mime_type)
    response['Content-Disposition'] = 'attachment; filename=%s' % name
    with open(file_path, 'rb') as f:
        for chunk in read_chunks(f):
            response.write(chunk)
    return response


from aiogram import types, Dispatcher
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Text

async def cmd_start(message: types.Message, state: FSMContext):
    await state.finish()
    await message.answer(
        "Начните ваш заказ (/food)!",
        reply_markup=types.ReplyKeyboardRemove()
    )

async def cmd_cancel(message: types.Message, state: FSMContext):
    await state.finish()
    await message.answer("Действие отменено", reply_markup=types.ReplyKeyboardRemove())

def register_handlers_common(dp: Dispatcher):
    dp.register_message_handler(cmd_start, commands="start", state="*")
    dp.register_message_handler(cmd_cancel, commands="cancel", state="*")
    dp.register_message_handler(cmd_cancel, Text(equals="отмена", ignore_case=True), state="*")


import torch
import numpy as np

class CategoriesSampler():

    def __init__(self, label, n_batch, n_cls, n_per):
        self.n_batch = n_batch
        self.n_cls = n_cls
        self.n_per = n_per

        label = np.array(label)
        self.m_ind = []
        for i in range(max(label) + 1):
            ind = np.argwhere(label == i).reshape(-1)
            ind = torch.from_numpy(ind)
            self.m_ind.append(ind)

    def __len__(self):
        return self.n_batch

    def __iter__(self):
        for i_batch in range(self.n_batch):
            batch = []
            classes = torch.randperm(len(self.m_ind))[:self.n_cls]
            for c in classes:
                l = self.m_ind[c]
                pos = torch.randperm(len(l))[:self.n_per]
                batch.append(l[pos])
            batch = torch.stack(batch).t().reshape(-1)
            yield batch


import re
from dataclasses import dataclass
from pprint import pprint

import pygame
import pyscroll
import pytmx
from random import randint, seed

from src import player
from src.player import NPC, Player
from lib_dijkstra import Point

verbose = False
# seed(1)

def groups_in_list(lst, code='X', blank=' '):
    """Find a list of continuous signs. This is used to try to reduce memory usage.
    >>> groups_in_list ((' ', ' ', 'X', 'X', 'X', 'X', 'X', ' ', 'X', 'X', ' '))
    [(2, 6), (8, 9)]
    >>> groups_in_list ((' ', ' ', 'X', 'X', 'X', 'X', 'X', ' ', 'X', 'X'))
    [(2, 6), (8, 9)]
    """
    walls = []
    again = True
    current = 0
    while again:
        try:
            first = lst.index(code, current)
        except ValueError:
            break

        try:
            last = lst.index(blank, first + 1)
        except ValueError:
            last = len(lst)

        if last:
            walls.append((first, last - 1))
            current = last
        else:
            again = False
    return walls

@dataclass
class Portal:
    from_world: str
    origin_point: str
    target_world: str
    teleport_point: str

# Vient de https://coderslegacy.com/pygame-platformer-coins-and-images/
class Coin(pygame.sprite.Sprite):
    # Intentionally, there are more 1 point coins than 50 points coins.
    values = (1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 5, 5, 5, 10, 10, 20, 50)

    def __init__(self, pos):
        super().__init__()
        self.name = 'coin'
        self.image = pygame.image.load("../map/coin.png")
        self.rect = self.image.get_rect()
        self.rect.topleft = pos
        self.feet = pygame.Rect(0, 0, self.rect.width * 0.5, 16)
        self.value = Coin.values[randint(0, len(Coin.values) - 1)]

    def move_back(self):
        pass

@dataclass
class Map:
    name: str
    walls: list[pygame.Rect]
    group: pyscroll.PyscrollGroup
    simple_map: list
    tmx_data: pytmx.TiledMap
    portals: list[Portal]
    npcs: list[NPC]

class MapManager:
    """General manager of all maps"""

    def __init__(self, master_game, screen, player):
        """Charge les cartes, puis téléporte le joueur et enfin les NPC"""
        self.master_game = master_game
        self.maps = dict()  # "house" -> Map ("house", walls, group)
        self.screen = screen
        self.player = player
        self.current_map = 'world'

        # Dans Portal on indique comment entrer dans un autre monde.
        # Attention le from_world doit absolument avoir tous les origin_points.
        self.register_map('world',
                          portals=[Portal(from_world="world", origin_point='enter_house', target_world="house",
                                          teleport_point="spawn_from_world")],
                          npcs=[# NPC('paul', nb_areas=4),
                              NPC('robin', self, 'world')])

        self.register_map('house',
                          portals=[
                              Portal(from_world='house', origin_point='enter_world', target_world='world',
                                     teleport_point="spawn_from_house"),
                              Portal(from_world='house', origin_point='enter_dungeon', target_world='dungeon',
                                     teleport_point="spawn_from_house")
                          ])

        self.register_map('dungeon',
                          portals=[
                              Portal(from_world='dungeon', origin_point='enter_house', target_world='house',
                                     teleport_point="spawn_from_dungeon"),
                              Portal(from_world='dungeon', origin_point='enter_world', target_world='world',
                                     teleport_point="spawn_from_dungeon")
                          ])

        self.teleport_player('player')
        self.teleport_npcs()

    def register_map(self, map_name, portals=None, npcs=None):
        if npcs is None:
            npcs = []
        if portals is None:
            portals = []
        if verbose:
            print("Registering map", map_name)

        # Charger les cartes
        tmx_data = pytmx.util_pygame.load_pygame(f"../map/{map_name}.tmx")
        map_data = pyscroll.data.TiledMapData(tmx_data)
        map_layer = pyscroll.orthographic.BufferedRenderer(map_data, self.screen.get_size())
        map_layer.zoom = 1

        # Définir une liste de collisions
        walls = []
        # Je vais ajouter des pièces/coins en tant que sprites (méthode venant de
        # https://coderslegacy.com/pygame-platformer-coins-and-images/ )
        coins = pygame.sprite.Group()

        for obj in tmx_data.objects:
            if obj.type == "collision":
                walls.append(pygame.Rect(obj.x, obj.y, obj.width, obj.height))
            elif obj.type == "coin_place":
                coins.add(Coin((obj.x - 24, obj.y - 24)))  # Valeur mal ajustée

        # Ajouter en wall toute la zone d'eau, sauf s'il y a un path par-dessus
        water_blocks = []
        if 'water' in tmx_data.layernames:
            for y, line in enumerate(tmx_data.layernames['water'].data):
                line_wall = []
                for x, cell in enumerate(line):
                    if cell != 0 and tmx_data.layernames['path'].data[y][x] == 0:
                        line_wall.append('X')
                    else:
                        line_wall.append(' ')
                water_blocks.append(line_wall)

            for y, line in enumerate(water_blocks):
                for group in groups_in_list(line, code='X', blank=' '):
                    walls.append(pygame.Rect(group[0] * 16, y * 16, (group[1] - group[0] + 1) * 16, 16))

        # Dessiner le groupe de calques
        # default_layer à 0 : bonhomme sur herbe, sous chemin
        group = pyscroll.PyscrollGroup(map_layer=map_layer, default_layer=5)  # Pourquoi 5 :
        group.add(self.player)
        # group.add(npcs)
        group.add(coins)
        for npc in npcs:
            group.add(npc)

        # fabriquer une carte simplifiée de 0 et de 1 pour les walls
        simple_map = build_simple_map_from_tmx(tmx_data, walls, reduction_factor=2)

        # Créer un objet Map
        self.maps[map_name] = Map(map_name, walls, group, simple_map, tmx_data, portals, npcs)

    def teleport_player(self, player_name):
        point = self.get_object(player_name)
        self.player.position[0] = point.x - 16
        self.player.position[1] = point.y - 32  # pour régler le niveau des pieds.
        self.player.save_location()

    def teleport_npcs(self):
        for map_name in self.maps:
            map_data = self.maps[map_name]
            for npc in map_data.npcs:
                npc.areas = self.get_object_by_regex(map_data, r"robin_path\d")
                npc.areas_nb = len(npc.areas)  # BOUH
                npc.define_first_target()
                npc.calculate_move_direction()
                npc.calculate_dijkstra()
                npc.teleport_npc()
                pass

    def check_collision(self):
        # portals
        for portal in self.get_map().portals:
            if portal.from_world == self.current_map:
                point = self.get_object(portal.origin_point)
                rect = pygame.Rect(point.x, point.y, point.width, point.height)

                if self.player.feet.colliderect(rect):
                    copy_portal = portal
                    self.current_map = portal.target_world
                    self.teleport_player(copy_portal.teleport_point)
                    self.master_game.point_counter.points += 100

        # collisions, coins
        for my_sprite in self.get_group().sprites():
            # fix BUG_SAUT : Ne reculer que si le sprite est un Player, pas un NPC
            # if isinstance(my_sprite, Player):
            if my_sprite.name == "player":
                if my_sprite.feet.collidelist(self.get_walls()) > -1:
                    my_sprite.move_back()
            if isinstance(my_sprite, Coin):
                if self.player.feet.colliderect(my_sprite):
                    if verbose:
                        print(f"Miam ! {my_sprite.value} points !!")
                    self.master_game.point_counter.points += my_sprite.value
                    my_sprite.kill()

    def get_map(self):
        return self.maps[self.current_map]

    def get_group(self):
        return self.get_map().group

    def get_walls(self):
        return self.get_map().walls

    def get_object(self, name):
        return self.get_map().tmx_data.get_object_by_name(name)

    # trouver automatiquement le nombre d'objets correspondant à une regex
    # par exemple "paul_path\d"
    def get_object_by_regex(self, map, regex):
        """Return objects witch name match with a regex"""
        carte = map.tmx_data
        all_objects = carte.objects

        matching_lst = []
        for tiled_object in all_objects:
            if re.match(regex, str(tiled_object.name)):
                obj = self.get_object(tiled_object.name)
                matching_lst.append(pygame.Rect(obj.x, obj.y, obj.width, obj.height))
        return matching_lst

    def update(self):
        """Fonction pour toutes les maps, appelée à chaque image"""
        self.get_group().update()
        self.check_collision()
        # Bouger les NPC
        for npc in self.get_map().npcs:
            npc.move()

    def draw(self):
        self.get_group().draw(self.screen)
        self.get_group().center(self.player.rect.center)

def build_simple_map_from_tmx(tmx_data, walls_block_list, reduction_factor):
    """Deduce a 2 dimensional array from a tmx map"""
    bin_map = []
    size = tmx_data.tilewidth
    map_w = tmx_data.width * size
    map_h = tmx_data.height * size
    steps = size * reduction_factor
    dec = int(steps / reduction_factor)
    for i, y in enumerate(range(0 + dec, map_h + dec, steps)):
        line_map = []
        for j, x in enumerate(range(0, map_w, steps)):
            PP = pygame.Rect(x, y, 1, 1)
            if PP.collidelist(walls_block_list) != -1:  # See documentation of colidelist()
                line_map.append(1)
            else:
                line_map.append(0)
        bin_map.append(line_map)
    if verbose:
        print("Même pas planté !")
        pprint(bin_map)
        print("La carte est ci-dessus : ! ")
    return (bin_map)


import matplotlib.pyplot as plt
import geopandas

# 3D Plot
def plot3Dtrajectory(name, desc, x, y, z):
    fig = plt.figure(figsize=(6,6))
    ax = fig.add_subplot(111, projection = '3d')

    ax.plot(x, y, z, color = 'purple', label = 'GPS', marker = '')

    plt.title(name + " " + desc)

    ax.set_xlabel('|X] = km')
    ax.set_ylabel('[Y] = km')
    ax.set_zlabel('[Z] = km')
    ax.set_xlim3d(-33000,33000)
    ax.set_ylim3d(-33000,33000)
    ax.set_zlim3d(-33000,33000)

    plt.savefig("Export/" + name + "_" + desc + '.png')

def plotGroundTrack(name, desc, lat, long, min, max):
    countries = geopandas.read_file(geopandas.datasets.get_path("naturalearth_lowres"))

    countries.plot(color = "grey")
    plt.scatter(long, lat, color = "purple")

    plt.grid()
    plt.ylim(-90,90)
    plt.xlim(-180,180)
    plt.title(name + " " + desc)
    plt.figtext(0.5, 0.15, "Minimale Breite: " + str(min) + "° / maximale Breite: " + str(max) + "°", ha = "center", fontsize = 9, style = "italic")

    plt.savefig("Export/" + name + "_" + desc + '.png')

def polarPlot(name, desc, az, el):

    fig, ax = plt.subplots(1,1, figsize=(8,8), subplot_kw=dict(projection='polar'))

    plt.scatter(az, el, color='purple', label=name)

    ax.set_theta_zero_location("N")
    ax.set_theta_direction(-1)
    plt.figtext(0.54, 0.5, "Elevation", rotation=62.5)
    plt.ylim(90,0)
    plt.title(name + " " + desc)

    plt.savefig("Export/" + name + "_" + desc + '.png')

def elevationPlot(name, desc, el, timeoverHorizon):
    time = []

    if name == "Lageos1":
        for i in range(0, 86401, 120):
            time.append(i)
    else:
        for i in range(0, 86401, 300):
            time.append(i)

    fig = plt.figure(figsize=(8, 6))

    ax = fig.add_subplot(111)
    plt.scatter(time, el, color= "purple")
    plt.ylim(0,90)
    plt.xlim(0, 86400)
    plt.grid()

    plt.title(name + " " + desc)
    plt.figtext(0.5, 0.03, "Sichtbare Zeit: " + str(timeoverHorizon) + "s (" + str(timeoverHorizon / 3600) + "h)", ha = "center", fontsize = 9)

    plt.savefig("Export/" + name + "_" + desc + '.png')


from flask import Flask, render_template, request, Response
import random
test_app = Flask(__name__)

@test_app.route('/')
def getRandomData():
   context = {"title": "Data table test"}
   data = [{ 'id': i,
             'name': "test_name_{0}".format(random.randint(0,1000)),
             'phone': random.randint(2308,903234),
             'status': random.choice([True, False])
           } for i in range(0,10000)]

   context['data'] = data
   return render_template('table_example.html', **context)

if __name__ == "__main__":
    test_app.run(host ="localhost")


import os
from multiprocessing import Process
from pathlib import Path
from shutil import rmtree
from time import sleep

import lmdb
import pytest
import rocksdb
from rocksdb.errors import RocksIOError

class TestDBPath:
    rocksdb = "test_rocksdb"
    lmdb = "test_lmdb"

def print_process_info(title):
    print("\n--------------------------")
    print(title)
    print("module name:", __name__)
    print("parent process:", os.getppid())
    print("process id:", os.getpid())

def f_rocksdb(name: str):
    print_process_info(f"function f_rocksdb({name})")
    data = b"test_test_test_rocksdb"

    try:
        db = rocksdb.DB(TestDBPath.rocksdb, rocksdb.Options(create_if_missing=True))
        db.put(b"name", data)
        print("f_rocksdb as a Writer")
    except RocksIOError:
        sleep(0.1)
        db = rocksdb.DB(TestDBPath.rocksdb, rocksdb.Options(create_if_missing=True), read_only=True)
        if data != db.get(b"name"):
            exit(-1)
        print("f_rocksdb as a Reader")
    sleep(1)

def f_lmdb(name: str):
    print_process_info(f"function f_lmdb({name})")
    data = b"test_test_test_lmdb"

    if name == "prop1":
        env = lmdb.open(TestDBPath.lmdb)
        with env.begin(write=True) as txn:
            txn.put(b"name", data)
        print("f_lmdb as a Writer")
    else:
        sleep(0.1)
        env = lmdb.open(TestDBPath.lmdb)
        with env.begin() as txn:
            if data != txn.get(b"name"):
                exit(-1)
        print("f_lmdb as a Reader")
    sleep(1)

def delete_test_db_dirs():
    db_paths = [Path(f"./{TestDBPath.lmdb}"), Path(f"./{TestDBPath.rocksdb}")]

    for db_path in db_paths:
        if db_path.exists():
            print(f"delete DB({db_path.resolve()})")
            rmtree(db_path)

@pytest.fixture(autouse=True)
def run_around_tests():
    delete_test_db_dirs()
    yield
    delete_test_db_dirs()

class TestMultiProcessLevelDB:
    store_process_functions = [f_rocksdb, f_lmdb]

    @pytest.mark.parametrize("store_process_function", store_process_functions)
    def test_multiprocessing_db(self, store_process_function):
        p1 = Process(target=store_process_function, args=("prop1",))
        p1.start()

        p2 = Process(target=store_process_function, args=("prop2",))
        p2.start()

        p1.join()
        p2.join()

        # RocksDB supports multiprocessing.
        assert p1.exitcode == 0
        assert p2.exitcode == 0


from parlai.core.teachers import FbDeprecatedDialogTeacher, MultiTaskTeacher
from .build import build

import copy
import os

def _path(task, opt):
    # Build the data if it doesn't exist.
    build(opt)
    suffix = ''
    dt = opt['datatype'].split(':')[0]
    if dt == 'train':
        suffix = 'train'
    elif dt == 'test':
        suffix = 'test_2500ex'
    elif dt == 'valid':
        suffix = 'valid_2000ex'

    return os.path.join(
        opt['datapath'], 'CBT', 'CBTest', 'data', task + '_' + suffix + '.txt'
    )

class NETeacher(FbDeprecatedDialogTeacher):
    def __init__(self, opt, shared=None):
        opt['datafile'] = _path('cbtest_NE', opt)
        opt['cloze'] = True
        super().__init__(opt, shared)

class CNTeacher(FbDeprecatedDialogTeacher):
    def __init__(self, opt, shared=None):
        opt['datafile'] = _path('cbtest_CN', opt)
        opt['cloze'] = True
        super().__init__(opt, shared)

class VTeacher(FbDeprecatedDialogTeacher):
    def __init__(self, opt, shared=None):
        opt['datafile'] = _path('cbtest_V', opt)
        opt['cloze'] = True
        super().__init__(opt, shared)

class PTeacher(FbDeprecatedDialogTeacher):
    def __init__(self, opt, shared=None):
        opt['datafile'] = _path('cbtest_P', opt)
        opt['cloze'] = True
        super().__init__(opt, shared)

# By default train on all tasks at once.
class DefaultTeacher(MultiTaskTeacher):
    def __init__(self, opt, shared=None):
        opt = copy.deepcopy(opt)
        opt['task'] = 'cbt:NE,cbt:CN,cbt:V,cbt:P'
        super().__init__(opt, shared)


from torch import nn
import torch
from torch.nn import CrossEntropyLoss
from transformers import BertPreTrainedModel, BertConfig, BertModel
from transformers.models.bert.modeling_bert import BertOnlyMLMHead

class BertForPTuning(BertPreTrainedModel):
    def __init__(self, config: BertConfig, prompt_index):
        super().__init__(config)
        self.num_labels = config.num_labels
        self.prompt_index = prompt_index

        self.bert = BertModel(config, add_pooling_layer=False)
        self.cls = BertOnlyMLMHead(config)

        self.prompt_embedding = torch.nn.Embedding(len(prompt_index), config.hidden_size)
        self.lstm_head = torch.nn.LSTM(input_size=config.hidden_size,
                                       hidden_size=config.hidden_size,
                                       num_layers=2,
                                       bidirectional=True,
                                       batch_first=True)
        self.mlp_head = nn.Sequential(nn.Linear(2 * config.hidden_size, config.hidden_size),
                                      nn.ReLU(),
                                      nn.Linear(config.hidden_size, config.hidden_size))
        self.init_weights()

    def set_output_embeddings(self, new_embeddings):
        self.cls.predictions.decoder.weight = new_embeddings.weight

    def forward(
            self,
            input_ids=None,
            attention_mask=None,
            token_type_ids=None,
            position_ids=None,
            head_mask=None,
            inputs_embeds=None,
            labels=None,
            output_attentions=None,
            output_hidden_states=None,
            return_dict=None):
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        self.set_output_embeddings(self.bert.embeddings.word_embeddings)

        # 替换embedding
        replace_embedding = self.prompt_embedding(torch.arange(len(self.prompt_index)).to(input_ids.device))[None, :]
        replace_embedding = self.lstm_head(replace_embedding)[0]
        replace_embedding = self.mlp_head(replace_embedding)
        raw_embedding = self.bert.embeddings.word_embeddings(input_ids)
        raw_embedding[:, self.prompt_index, :] = replace_embedding
        inputs_embeds = raw_embedding

        outputs = self.bert(
            input_ids=None,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        logits = self.cls(outputs[0])

        loss = None
        if labels is not None:
            loss_fct = CrossEntropyLoss()
            s = attention_mask.shape[0] * attention_mask.shape[1]
            loss = loss_fct(logits.view(s, -1), labels.view(-1))

        # token out / pool out / cls
        output = (logits,) + outputs[1:] + (outputs[0][:, 0],)
        return ((loss,) + output) if loss is not None else output


import re
import json
import logging

class Object:  # pylint: disable=too-many-instance-attributes
    def __str__(self):
        return json.dumps(self, default=lambda o: o.__dict__, indent=5)

class Device(Object):

    def __init__(self, uid, version, firmware):
        self.namespace = 'http://www.w3.org/2001/XMLSchema-instance'
        self.location = '../../db/resources/db.xsd'
        self.id = uid
        self.version = version
        self.firmware = firmware

def delete_attrs(obj, paths):
    """
    Delete attributes

    :param cterasdk.common.object.Object object: The object
    :param list[str] paths: List of attributes to remove

    :returns: The modified object
    :rtype: cterasdk.common.object.Object
    """
    for path in paths:
        delete_attr(obj, path)

def delete_attr(obj, path):
    """
    Delete attribute

    :param cterasdk.common.object.Object object: The object
    :param str path: Attribute path

    :returns: The modified object
    :rtype: cterasdk.common.object.Object
    """
    parts = re.findall('[^/]+', path)
    parent = find_attr(obj, parts[:-1])
    remove_attr(parent, parts[-1])

    if len(parts) > 1 and isinstance(parent, Object) and not parent.__dict__:
        grandparent = find_attr(obj, parts[:-2])
        setattr(grandparent, parts[-2], None)

def find_attr(obj, path):
    """
    Find attribute

    :param cterasdk.common.object.Object object: The object
    :param str path: A string or an array of the attribute path

    :returns: The attribute, or ``None`` if not found
    """
    parts = re.findall('[^/]+', path) if isinstance(path, str) else path

    attr = obj
    for part in parts:
        attr = get_attr(attr, part)
        if attr is None:
            logging.getLogger().warning('Could not find attribute. %s', {'path': f'/{"/".join(parts)}'})
            return attr
    return attr

def get_attr(obj, attr):
    """
    Get attribute

    :param cterasdk.common.object.Object object: The object
    :param str attr: The name of the attribute to retrieve

    :returns: The attribute, or ``None`` if not found
    """
    if isinstance(obj, list):
        try:
            attr = int(attr)
            return obj[attr]
        except ValueError:
            logging.getLogger().warning('Could not find attribute.')
            return None

    return getattr(obj, attr, None)

def remove_attr(obj, attr):
    """
    Remove attribute

    :param cterasdk.common.object.Object object: The object
    :param str attr: The name of the attribute to remove
    """
    if isinstance(obj, list):
        remove_array_element(obj, attr)
    else:
        try:
            delattr(obj, attr)
        except AttributeError:
            logging.getLogger().warning('Failed to remove attribute. Attribute not found. %s', {'attr': attr})

def remove_array_element(array, attr):

    try:
        attr = int(attr)
        if attr <= len(array) - 1:
            array.pop(attr)
        else:
            logging.getLogger().warning('Could not remove array item. Index out of range. %s', {'index': attr})
    except ValueError:
        pass

    if remove_array_element_by_key(array, '_uuid', attr):
        return

    remove_array_element_by_key(array, 'name', attr)

def remove_array_element_by_key(array, key, value):
    for index, element in enumerate(array):
        element_value = getattr(element, key, None)
        if element_value == value:
            return array.pop(index)
    return None


import sys
import io
import os
import shutil
import base64
import hashlib
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PublicKey
from Crypto.Cipher import AES
from Crypto.Util import Counter

RANSOM_EXT = '.INC'

ENC_MARKER = b'INC'

# x25519
X25519_KEY_SIZE = 32

# AES
AES_KEY_SIZE = 16
AES_IV_SIZE = 16

METADATA_SIZE = X25519_KEY_SIZE + len(ENC_MARKER)

ENC_BLOCK_SIZE = 1000000
ENC_BLOCK_STEP = 3 * ENC_BLOCK_SIZE

def derive_encryption_key_data(priv_key_data: bytes,
                               pub_key_data: bytes) -> bytes:
    """Derive encryption key data"""

    # Derive x25519 shared secret
    priv_key = X25519PrivateKey.from_private_bytes(priv_key_data)
    pub_key = X25519PublicKey.from_public_bytes(pub_key_data)
    shared_secret = priv_key.exchange(pub_key)

    # Derive encryption key data
    return hashlib.sha512(shared_secret).digest()

def decrypt_file(filename: str, priv_key_data: bytes) -> bool:
    """Decrypt file"""

    with io.open(filename, 'rb+') as f:

        # Read metadata
        try:
            f.seek(-METADATA_SIZE, 2)
        except OSError:
            return False

        metadata = f.read(METADATA_SIZE)

        if metadata[-len(ENC_MARKER):] != ENC_MARKER:
            return False

        pub_key_data = metadata[:X25519_KEY_SIZE]

        # Derive encryption key data
        key_data = derive_encryption_key_data(priv_key_data, pub_key_data)

        # AES-128 CTR
        key = key_data[:AES_KEY_SIZE]
        iv = key_data[AES_KEY_SIZE : AES_KEY_SIZE + AES_IV_SIZE]
        init_val = int.from_bytes(iv, byteorder='big')
        counter = Counter.new(128, initial_value=init_val,
                              little_endian=False)
        cipher = AES.new(key, AES.MODE_CTR, counter=counter)

        # Remove metadata
        f.seek(-METADATA_SIZE, 2)
        f.truncate()

        # Decrypt file data
        pos = 0

        while True:

            # Decrypt block
            f.seek(pos)
            enc_data = f.read(ENC_BLOCK_SIZE)
            if enc_data == b'':
                break

            data = cipher.decrypt(enc_data)

            f.seek(pos)
            f.write(data)

            pos += ENC_BLOCK_STEP

    return True

#
# Main
#
if len(sys.argv) != 2:
    print('Usage:', os.path.basename(sys.argv[0]), 'filename')
    sys.exit(0)

filename = sys.argv[1]

with io.open('privkey.txt', 'rb') as f:
    priv_key_data = base64.b64decode(f.read())

# Copy file
new_filename = filename
if new_filename.endswith(RANSOM_EXT):
    new_filename = new_filename[:-len(RANSOM_EXT)]
else:
    new_filename += '.dec'
shutil.copy(filename, new_filename)

# Decrypt file
if not decrypt_file(new_filename, priv_key_data):
    print('Error: Failed to decrypt file')
    sys.exit(1)


from rich.table import Table
from rich.console import Console
import os
import sqlite3
from sqlite3 import Error
from colorama import Fore
from colored import fg, attr
from datetime import date, datetime
# =============================================
con = sqlite3.connect("data.db")
os.system("cls")
# =============================================
def sql_connection(con):
    cur = con.cursor()
    cur.execute(
        "CREATE TABLE IF NOT EXISTS ManagerBuy(Id INTEGER PRIMARY KEY AUTOINCREMENT,Price INTEGER, Product_Name TEXT, Date TEXT, Time TEXT)")
    con.commit()
# =============================================
def help_list():
    print(f"""{fg(50)}
███    ███  █████  ███    ██  █████   ██████  ███████ ██████      ██████  ██    ██ ██    ██
████  ████ ██   ██ ████   ██ ██   ██ ██       ██      ██   ██     ██   ██ ██    ██  ██  ██
██ ████ ██ ███████ ██ ██  ██ ███████ ██   ███ █████   ██████      ██████  ██    ██   ████
██  ██  ██ ██   ██ ██  ██ ██ ██   ██ ██    ██ ██      ██   ██     ██   ██ ██    ██    ██
██      ██ ██   ██ ██   ████ ██   ██  ██████  ███████ ██   ██     ██████   ██████     ██   {fg(50)}
{fg(115)}===========================================================================================
**                                 Github : erfanbanaei                                  **
**                                 Twitter: @erfan_banaei                                **
**                                 YouTube: @Hero_Code                                   **
==========================================================================================={fg(115)}{attr(0)}

[{fg(50)}1{fg(50)}{attr(0)}] Init
[{fg(50)}2{fg(50)}{attr(0)}] Add
[{fg(50)}3{fg(50)}{attr(0)}] Show
[{fg(50)}4{fg(50)}{attr(0)}] Edit
[{fg(50)}5{fg(50)}{attr(0)}] Delete
[{fg(50)}6{fg(50)}{attr(0)}] Help
[{fg(50)}7{fg(50)}{attr(0)}] Exit
""")
# =============================================

def add(con):
    Price = int(
        input(f"[{fg(9)}?{fg(9)}{attr(0)}]Enter your purchase price : "))
    Product_Name = input(
        f"[{fg(9)}?{fg(9)}{attr(0)}] Enter your purchase name : ")
    t = datetime.now().time()
    time = f"{t.hour}:{t.minute}"
    date2 = date.today()
    full = (Price, Product_Name, date2, time)
    cur = con.cursor()
    cur.execute(
        "INSERT INTO ManagerBuy(Price, Product_Name, Date, Time) VALUES(?,?,?,?)", full)
    con.commit()
    os.system("cls")
# =============================================
def show(con):
    cur = con.cursor()
    cur.execute('SELECT * FROM ManagerBuy')
    rows = cur.fetchall()
    console = Console()
    table = Table(title="ManagerBuy")

    table.add_column("Id", justify="center", style="cyan")
    table.add_column("Price", justify="center", style="magenta")
    table.add_column("Product Name", justify="center", style="green")
    table.add_column("Date", justify="center", style="yellow")
    table.add_column("Time", justify="center", style="blue")

    for row in rows:
        table.add_row(str(row[0]),str(row[1]),str(row[2]),str(row[3]),str(row[4]))
    console.print(table)
# =============================================
def edit(con):
    try:
        data_id = int(input(f"[{fg(9)}?{fg(9)}{attr(0)}]Enter the ID of the product you want : "))
        new_name  = input(f"[{fg(9)}?{fg(9)}{attr(0)}]Enter the new name of the desired product : ")
        new_price = input(f"[{fg(9)}?{fg(9)}{attr(0)}]Enter the new price of the product you want :")
        full = (new_price,new_name,data_id)
        cur = con.cursor()
        cur.execute(f"UPDATE ManagerBuy SET Price = ?, Product_Name = ? WHERE Id = ?",full)
        con.commit()
    except Error as e:
        print(Fore.RED+ "Error" , e)
# =============================================
def delete_record(con):
    data_id = input(f"[{fg(9)}?{fg(9)}{attr(0)}]Enter the ID of the product you want (9999 => Remove all products) : ")
    cur = con.cursor()
    full = (int(data_id))
    if full == 9999:
        cur.execute(f"DELETE FROM ManagerBuy")
        con.commit()
        print(Fore.GREEN + "Removed all\n\n")
    else:
        cur.execute(f"DELETE FROM ManagerBuy WHERE Id = {full}")
        con.commit()
        print(Fore.GREEN + "Deleted Product\n\n")
# =============================================
def Help():
    print(f"""
Init {fg(50)}=>{fg(50)} {fg(115)}Create Database{fg(115)}{attr(0)}
Add {fg(50)}=>{fg(50)} {fg(115)}Add to Database(Price , Product Name){fg(115)}{attr(0)}
Show {fg(50)}=>{fg(50)} {fg(115)}Show all products{fg(115)}{attr(0)}
Edit {fg(50)}=>{fg(50)} {fg(115)}Product edit{fg(115)}{attr(0)}
Delete {fg(50)}=>{fg(50)} {fg(115)}Remove the product from the list{fg(115)}{attr(0)}
\n\n""")
# =============================================
while True:
    help_list()
    number = input(Fore.CYAN+"┌─["+Fore.LIGHTGREEN_EX+"ManagerBuy"+Fore.BLUE+"~"+Fore.WHITE+"@HOME"+Fore.CYAN+"""]
└──╼ """+Fore.WHITE+"$ ")
# =============================================
    if number == "1":
        os.system("cls")
        sql_connection(con)
        print(Fore.GREEN + "Created Database\n\n")
# =============================================
    elif number == "2":
        os.system("cls")
        add(con)
# =============================================
    elif number == "3":
        os.system("cls")
        show(con)
# =============================================
    elif number == "4":
        os.system("cls")
        edit(con)
# =============================================
    elif number == "5":
        os.system("cls")
        delete_record(con)
# =============================================
    elif number == "6":
        os.system("cls")
        Help()
# =============================================
    elif number == "7":
        quit()


from flask import Blueprint, render_template, request, redirect, url_for
import pendulum
import requests
from .static.sc.schedule import date_schedule, get_date
from . import db
from .models import User, List, ListFields

views = Blueprint('views', __name__)

@views.route('/')
def main():
    return render_template('index.html')

@views.route('/capacity')
def capacity():
    return render_template('capacity.html', page_class = 'capacity-page', page_title = 'capacity')

@views.route('/todo')
def todo():

    response = List.query.all()
    return render_template('todo.html', page_class = 'todo-page', page_title = 'todo', res=response, len=len(response))

@views.route('/post_task', methods=['POST'])
def post_task():
    text_task = request.form.get('text')
    deadline = request.form.get('deadline')
    task = List(text=text_task, deadline=deadline)
    db.session.add(task)
    db.session.commit()
    return redirect(url_for('views.todo'))

@views.route('/del_task', methods=['POST'])
def del_task():
    k = int(request.form.get('id'))
    task = List.query.filter_by(id=k).first()
    db.session.delete(task)
    db.session.commit()
    return redirect(url_for('views.todo'))

@views.route('/compl_task', methods=['POST'])
def compl_task():
    k = int(request.form.get('id'))
    task = List.query.filter_by(id=k).first()
    task.complete = True
    db.session.commit()
    return redirect(url_for('views.todo'))

@views.route('/encompl_task', methods=['POST'])
def encompl_task():
    k = int(request.form.get('id'))
    task = List.query.filter_by(id=k).first()
    task.complete = False
    db.session.commit()
    return redirect(url_for('views.todo'))

@views.route('/schedule/today')
def schedule():

    today = pendulum.now()
    d = today.strftime("%d/%m/%Y")
    today_sc = date_schedule(1307, today)
    return render_template('schedule.html',
        page_class = 'schedule-page', page_title = 'schedule',
         sc_date = d, sc = today_sc, current_date = today, pendulum = pendulum)

@views.route('/schedule/date/<n>/<m>/<y>')
def scdate(n, m, y):

    date = get_date([int(n), int(m), int(y)])
    d = date.strftime("%d/%m/%Y")
    today_sc = date_schedule(1307, date)
    return render_template('schedule.html',
        page_class = 'schedule-page', page_title = 'schedule',
        sc_date = d, sc = today_sc, current_date = date, pendulum = pendulum)


import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn import tree
from sklearn import svm
import warnings
warnings.filterwarnings('ignore')

def getData(category):
    crime_rate_df = pd.read_csv('dataset/boston_crime_2021-2022.csv', dtype=str)
    crime_dictionary = ['LARCENY', 'M/V ACCIDENT', 'LIQUOR', 'INCEST', 'MANSLAUGHTER', 'MISSING PERSON',
                        'PROPERTY - LOST', 'MURDER', 'FRAUD', 'PROSTITUTION', 'RAPE', 'ROBBERY', 'ASSAULT',
                        'SICK/INJURED/MEDICAL', 'TOWED MOTOR VEHICLE', 'TRESPASSING', 'VIOLATION', 'ANIMAL',
                        'AUTO THEFT', 'FIREARM/WEAPON', 'HUMAN TRAFFICKING', 'DRUGS', 'SEX OFFENSE', 'ARSON',
                        'VANDALISM', 'SEARCH WARRANT', 'KIDNAPPING', 'DEATH INVESTIGATION', 'CHILD ABUSE', 'HARASSMENT']

    crime_list = [0, 1, 2, 3, 4, 5,
                  6, 7, 8, 9, 10, 11, 12,
                  13, 14, 15, 16, 17,
                  18, 19, 20, 21, 22, 23,
                  24, 25, 26, 27, 28, 29]
    for j in range(len(crime_list)):
        crime_rate_df.loc[crime_rate_df['OFFENSE_DESCRIPTION'].str.contains(crime_dictionary[j]), 'GROUP'] = crime_list[j]

    crime_rate_df = crime_rate_df.dropna()

    Weekday = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    for i in range(len(Weekday)):
        crime_rate_df['DAY_OF_WEEK'] = np.where((crime_rate_df.DAY_OF_WEEK == Weekday[i]), i, crime_rate_df.DAY_OF_WEEK)
    X = crime_rate_df.drop([category, 'OFFENSE_DESCRIPTION', 'Location', 'DISTRICT', 'Dates', 'STREET', 'YEAR'], axis=1).values
    Y = crime_rate_df[[category]].values

    x_train, x_test, y_train, y_test = train_test_split(X, Y, train_size=0.8)
    return x_train, y_train, x_test, y_test

def getTable(cm, i, all=False):
    TP = cm[i][0][0]
    FP = cm[i][0][1]
    FN = cm[i][1][0]
    TN = cm[i][1][1]
    TPR = TP / (TP + FN)
    TNR = TN / (TN + FP)
    ACC = (TP + TN) / (TP + TN + FP + FN)
    d = {'Accuracy': [ACC], 'True positive rate': [TPR], 'True negative rate': [TNR]}
    dfx = pd.DataFrame(data=d)
    if all:
        return TP, FP, FN, TN, TPR, TNR, ACC
    return dfx

def predictCrime():
    cm = []
    x_train, y_train, x_test, y_test = getData('GROUP')

    NB_classifier = GaussianNB().fit(x_train, y_train)
    accuracy = accuracy_score(y_test, NB_classifier.predict(x_test))

    print("\n1:")
    print('Implement a Naive Bayesian classifier:')
    print('The accuracy is', accuracy)

    log_reg_classifier = LogisticRegression()
    log_reg_classifier.fit(x_train, y_train)
    accuracy = log_reg_classifier.score(x_train, y_train)

    print("\n2:")
    print('Implement a Logistic regression classifier:')
    print('The accuracy is', accuracy)

    clf = tree.DecisionTreeClassifier(criterion='entropy')
    clf = clf.fit(x_train, y_train)
    prediction = clf.predict(x_test)
    accuracy = accuracy_score(y_test, prediction)

    print("\n3:")
    print('Implement a Decision Tree:')
    print('The accuracy is', accuracy)

    # 5. Use Random Forest classifier
    error_rate = []
    random_forest_table = pd.DataFrame(columns=['n_estimators', 'max_depth', 'accuracy'])
    for i in range(1, 11):
        for j in range(1, 6):
            rf = RandomForestClassifier(n_estimators=i, max_depth=j)
            rf.fit(x_train, y_train)
            error_rate.append(1 - accuracy_score(y_test, rf.predict(x_test)))
            ACC = accuracy_score(y_test, rf.predict(x_test))
            random_forest_table.loc[len(random_forest_table.index)] = [i, j, ACC]

    best_n = error_rate.index(min(error_rate)) % 10 + 1
    best_max = error_rate.index(min(error_rate)) % 5 + 1

    print("\n4:")
    print('Implement a Random Forest classifier :')
    print("The best n_estimators and max_depth are", best_n, "and", best_max)

    rf = RandomForestClassifier(n_estimators=best_n, max_depth=best_max)
    rf.fit(x_train, y_train)
    accuracy = accuracy_score(y_test, rf.predict(x_test))

    print('The accuracy is', accuracy)

predictCrime()


"""Mel - a command-line utility to help with mole management."""

import argparse
import sys

import mel.cmd.addcluster
import mel.cmd.addsingle
import mel.cmd.error
import mel.cmd.list
import mel.cmd.microadd
import mel.cmd.microcompare
import mel.cmd.microview
import mel.cmd.rotomapautomark
import mel.cmd.rotomapautomark2
import mel.cmd.rotomapautomark2train
import mel.cmd.rotomapautomask
import mel.cmd.rotomapcalcspace
import mel.cmd.rotomapcompare
import mel.cmd.rotomapcompareextrastem
import mel.cmd.rotomapconfirm
import mel.cmd.rotomapedit
import mel.cmd.rotomapfiltermarks
import mel.cmd.rotomapfiltermarkspretrain
import mel.cmd.rotomapfiltermarkstrain
import mel.cmd.rotomapidentify
import mel.cmd.rotomapidentifytrain
import mel.cmd.rotomaplist
import mel.cmd.rotomaploadsave
import mel.cmd.rotomapmarkunchanged
import mel.cmd.rotomapmergeextrastem
import mel.cmd.rotomapmontagesingle
import mel.cmd.rotomaporganise
import mel.cmd.rotomaprm
import mel.cmd.rotomapuuid
import mel.cmd.status
import mel.cmd.timelog

COMMANDS = {
    "root": {
        "status": mel.cmd.status,
        "timelog": mel.cmd.timelog,
    },
    "micro": {
        "add-cluster": mel.cmd.addcluster,
        "add-single": mel.cmd.addsingle,
        "list": mel.cmd.list,
        "add": mel.cmd.microadd,
        "compare": mel.cmd.microcompare,
        "view": mel.cmd.microview,
    },
    "rotomap": {
        "automark": mel.cmd.rotomapautomark,
        "automark2": mel.cmd.rotomapautomark2,
        "automark2-train": mel.cmd.rotomapautomark2train,
        "automask": mel.cmd.rotomapautomask,
        "calc-space": mel.cmd.rotomapcalcspace,
        "compare": mel.cmd.rotomapcompare,
        "compare-extra-stem": mel.cmd.rotomapcompareextrastem,
        "confirm": mel.cmd.rotomapconfirm,
        "edit": mel.cmd.rotomapedit,
        "filter-marks": mel.cmd.rotomapfiltermarks,
        "filter-marks-pretrain": mel.cmd.rotomapfiltermarkspretrain,
        "filter-marks-train": mel.cmd.rotomapfiltermarkstrain,
        "identify": mel.cmd.rotomapidentify,
        "identify-train": mel.cmd.rotomapidentifytrain,
        "list": mel.cmd.rotomaplist,
        "loadsave": mel.cmd.rotomaploadsave,
        "mark-unchanged": mel.cmd.rotomapmarkunchanged,
        "merge-extra-stem": mel.cmd.rotomapmergeextrastem,
        "montage-single": mel.cmd.rotomapmontagesingle,
        "organise": mel.cmd.rotomaporganise,
        "rm": mel.cmd.rotomaprm,
        "uuid": mel.cmd.rotomapuuid,
    },
}

def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description=__doc__,
    )

    top_subparsers = parser.add_subparsers()

    micro_parser = top_subparsers.add_parser(
        "micro", help="Work with microscope images.", aliases=["m"]
    )

    rotomap_parser = top_subparsers.add_parser(
        "rotomap", help="Work with rotomap images.", aliases=["r", "roto"]
    )

    micro_subparsers = micro_parser.add_subparsers()
    rotomap_subparsers = rotomap_parser.add_subparsers()

    subparsers = top_subparsers

    # Work around a bug in argparse with subparsers no longer being required:
    # http://bugs.python.org/issue9253#msg186387
    subparsers.required = True
    subparsers.dest = "command"

    # vulture will report these as unused unless we do this
    #
    # pylint: disable=pointless-statement
    subparsers.required
    subparsers.dest
    # pylint: enable=pointless-statement

    parser_map = {
        "root": subparsers,
        "micro": micro_subparsers,
        "rotomap": rotomap_subparsers,
    }

    for pname, parser2 in parser_map.items():
        for name, module in COMMANDS[pname].items():
            _setup_parser_for_module(parser2, module, name)

    args = parser.parse_args()
    try:
        return args.func(args)
    except mel.cmd.error.UsageError as e:
        print("Usage error:", e, file=sys.stderr)
        return 2
    except BrokenPipeError:
        # Silently exit on broken pipes, e.g. when our output is piped to head.

        # Explicitly close stderr before exiting, to avoid an additional
        # message from Python on stderr about the pipe break being ignored.
        # http://bugs.python.org/issue11380,#msg153320
        sys.stderr.close()
    except mel.lib.ui.AbortKeyInterruptError:
        # Using this return code may also break us out of an outer loop, e.g.
        # 'xargs' will stop processing if the program it calls exists with 255.
        return 255

def _setup_parser_for_module(subparsers, module, name):
    doc = module.__doc__
    doc_subject = doc.splitlines()[0]
    doc_epilog = "\n".join(doc.splitlines()[1:])
    parser = subparsers.add_parser(
        name,
        formatter_class=argparse.RawDescriptionHelpFormatter,
        help=doc_subject,
        description=doc_subject,
        epilog=doc_epilog,
    )
    module.setup_parser(parser)
    parser.set_defaults(func=module.process_args)

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

# -----------------------------------------------------------------------------
# Copyright (C) 2015-2019 Angelos Evripiotis.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ------------------------------ END-OF-FILE ----------------------------------


from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('headless')
driver = webdriver.Chrome(options=options)

#driver.get("http://www.zhgc.com/dllt_wq1/arena.asp")
driver.get("http://www.zhgc.com/dllt_wq2/arena.asp")
file_name = 'write7.txt'

#for i in range(75,217):
for i in range(13,70):
    print("Page No.", i)
    btn = driver.find_element_by_partial_link_text(str(i))
    btn.click()
    data = driver.find_elements_by_xpath('/html/body/table/tbody/tr/td[2]/table[@id="AutoNumber1"]/tbody/tr/td[2]')
    for d in data:
        print(d.text)
        with open(file_name, 'a' , encoding='utf-8') as file_obj:
            file_obj.write(d.text+'\n')


import os

import openai
from flask import Flask, render_template, request, jsonify
from openai.error import ServiceUnavailableError, InvalidRequestError, RateLimitError

openai.api_key = os.environ.get('OPENAI_API_KEY')
app = Flask(__name__, template_folder='templates', static_folder='static')

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

@app.route('/api/speech-to-text', methods=['POST'])
def speech_to_text():
    transcript = request.json['transcript']
    messages = [{"role": "system", "content": "Ты дружелюбный, но саркастичный бот."},
                {"role": "user", "content": transcript}]
    print('Вопрос:', transcript)
    try:
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=messages,
            temperature=0.5,
            max_tokens=1000,
            top_p=1.0,
            frequency_penalty=0.5,
            presence_penalty=0.0,
        )
    except ServiceUnavailableError:
        return jsonify({'response': 'Извините, сервер openAI перегружен и не отвечает.'})
    except InvalidRequestError as e:
        return jsonify({'response': f'Проблема с запросом, {e}'})
    except RateLimitError:
        return jsonify({'response': 'Превышен лимит запросов в минуту.'})
    except BaseException as e:
        return jsonify({'response': f'Неизвестная ошибка: {e}'})

    print('GPT:', response.choices[0].message.content)
    return jsonify({'response': response.choices[0].message.content})

if __name__ == '__main__':
    app.run(debug=True)


import itertools
digits = [ x for x in range(10) ]

i = 0
for x in itertools.permutations(digits):
    i += 1
    if i == 1000000:
        print(x)
        break

for c in x:
    print(c,end="")


from django.utils.translation import gettext_lazy as _
from django.db import models
import uuid
from internal_users.models import InternalUser
from customer_users.models import CustomerUser
from homepageapp.models import RepairOrdersNewSQL02Model as RepairOrder
from django.utils import timezone
from core_operations.models import FormattedPhoneNumberField

APPT_STATUS_NOT_SUBMITTED = 0
APPT_STATUS_PENDING = 1
APPT_STATUS_CONFIRMED = 2
APPT_STATUS_REJECTED = 3
APPT_STATUS_RESCHEDULED = 4
APPT_STATUS_PORGRESSING = 5
APPT_STATUS_COMPLETED = 10
APPT_STATUS_CANCELLED = -20

class AppointmentRequest(models.Model):
    STATUS_CHOICES = (
        (APPT_STATUS_NOT_SUBMITTED, _('00_Not_Submitted')),
        (APPT_STATUS_PENDING, _('01_Pending')),
        (APPT_STATUS_CONFIRMED, _('02_Confirmed')),
        (APPT_STATUS_REJECTED, _('03_Rejected')),
        (APPT_STATUS_RESCHEDULED, _('04_Rescheduled')),
        (APPT_STATUS_PORGRESSING, _('05_Progressing (tracking status via repair order)')),
        (APPT_STATUS_COMPLETED, _('10_Completed')),
        (APPT_STATUS_CANCELLED, _('-20_Cancelled')),
    )
    REASON_CHOICES = (
        (0, '00-not selected.'),
        (1, '01-oil change and maintenance.'),
        (2, '02-a/c diagnosis, compressors etc.'),
        (3, '03-brakes, transmission'),
        (4, '04-service lights, engine related'),
        (5, '05-just inqurires, others'),
    )
    appointment_id = models.BigAutoField(primary_key=True)
    # appointment_date = models.DateField()
    appointment_requested_datetime = models.DateTimeField(
        null=True, blank=True, verbose_name='Requested Apptmnt Time')
    appointment_confirmed_datetime = models.DateTimeField(
        null=True, blank=True, verbose_name='Confirmed Apptmnt Time')
    appointment_reason_for_visit = models.PositiveSmallIntegerField(
        choices=REASON_CHOICES, default=0, verbose_name='Reason for visit?')
    appointment_customer_user = models.ForeignKey(
        CustomerUser, on_delete=models.SET_NULL, null=True, verbose_name='your linked user account')
    appointment_first_name = models.CharField(
        max_length=50, null=True, blank=True)
    appointment_last_name = models.CharField(
        max_length=50, null=True, blank=True)
    appointment_phone_number = FormattedPhoneNumberField(
        help_text='we will send appointment reminders to this number.')
    appointment_phone_number_digits_only = models.CharField(
        max_length=20, null=True)
    # recording either customer_user or internal_user
    appointment_user_type = models.CharField(
        max_length=50, blank=True, null=True)
    appointment_email = models.EmailField(null=True)
    appointment_vehicle_year = models.CharField(
        max_length=4, null=True, blank=True)
    appointment_vehicle_make = models.CharField(
        max_length=100, null=True, blank=True)
    appointment_vehicle_model = models.CharField(
        max_length=100, null=True, blank=True)
    appointment_vehicle_license_plate = models.CharField(
        max_length=20, null=True, blank=True)
    appointment_vehicle_license_state = models.CharField(
        max_length=2, null=True, blank=True)
    appointment_vehilce_vin_number = models.CharField(
        max_length=30, null=True, blank=True)
    appointment_vehicle_detail = models.TextField()
    appointment_vehicle_detail_in_json = models.CharField(
        max_length=4000, null=True)  # {'year': 2003, 'model': VW, ...}
    appointment_concern_description = models.TextField(blank=True)

    # check the status of the appointment
    appointment_status = models.CharField(
        max_length=50, choices=STATUS_CHOICES, default=APPT_STATUS_NOT_SUBMITTED, verbose_name='Appointment Status')
    appointment_status_comments = models.CharField(
        max_length=4000, null=True, blank=True)
    appointment_is_active = models.BooleanField(default=True)
    appointment_preferred_contact_method = models.CharField(
        max_length=100, blank=True, null=True)
    appointment_repair_order = models.ForeignKey(
        RepairOrder, on_delete=models.SET_NULL, null=True, related_name='appointment_repair_order')
    appointment_is_converted_to_ro = models.BooleanField(default=False)
    appointment_confirmation_id = models.UUIDField(
        default=uuid.uuid4, editable=False,  verbose_name='your appointment confirmation id')  # unique=True,
    # appointment can either be created by anoymous user, a signed-in customer_user or created by an internal_user when a customer shows up on the physical store.
    appointment_created_by_internal_user = models.ForeignKey(
        InternalUser, on_delete=models.SET_NULL, null=True, related_name='appointment_created_by')  # when null, it means its created by customer user
    appointment_created_at = models.DateTimeField(auto_now_add=True)
    appointment_last_updated_at = models.DateTimeField(auto_now=True)

    @property
    def appointment_full_name(self):
        return f"{self.appointment_first_name} {self.appointment_last_name}"

    class Meta:
        db_table = 'appointments'
        ordering = ['-appointment_id']

    def __str__(self):
        return f"Name: {self.appointment_first_name} {self.appointment_last_name}-Time: {self.appointment_requested_datetime}"

class AppointmentImages(models.Model):
    image_id = models.BigAutoField(primary_key=True)
    appointment = models.ForeignKey(AppointmentRequest, on_delete=models.SET_NULL,
                                    null=True, related_name='appointment_appointmentimages')
    appointment_image = models.FileField(
        upload_to='appointment_images')  # the bucket's subfolder
    uploaded_date = models.DateTimeField(auto_now_add=True)
    image_is_active = models.BooleanField(default=True)

    class Meta:

        db_table = 'appointment_images'
        ordering = ['-image_id']
        verbose_name = 'appointment_image'
        verbose_name_plural = 'appointment_images'


import os
import logging
from xdg.BaseDirectory import xdg_config_home, xdg_state_home
from typing import Dict

import yaml

from .log import LogManager
from cfancontrol import __version__ as VERSION

class Environment(object):

    APP_NAME: str = "cfancontrol"
    APP_FANCY_NAME: str = "Commander²"
    APP_VERSION: str = VERSION
    LOG_FILE: str = 'cfancontrol.log'
    CONFIG_FILENAME: str = 'config.yaml'
    SENSORS_FILE: str = 'sensors3.conf'

    is_root: bool = False
    log_path: str = ''
    log_full_name: str = ''
    settings_path: str = ''
    config_full_name: str = ''
    pid_path: str = ''
    sensors_config_file: str = ''

    @staticmethod
    def prepare_environment():
        if os.geteuid() == 0:
            Environment.is_root = True
            Environment.log_path = "/var/log"
            Environment.settings_path = os.path.join("/etc", Environment.APP_NAME)
            Environment.sensors_config_file = os.path.join("/etc", Environment.SENSORS_FILE)
            Environment.pid_path = "/var/run"
        else:
            Environment.log_path = os.path.join(xdg_state_home, Environment.APP_NAME)
            Environment.settings_path = os.path.join(xdg_config_home, Environment.APP_NAME)
            Environment.sensors_config_file = os.path.join(Environment.settings_path, Environment.SENSORS_FILE)
            Environment.pid_path = f"/var/run/user/{os.geteuid()}"
        if not os.path.isdir(Environment.log_path):
            os.makedirs(Environment.log_path, mode=0o755, exist_ok=True)
        if not os.path.isdir(Environment.settings_path):
            os.makedirs(Environment.settings_path, mode=0o755, exist_ok=True)
        if not os.path.isfile(Environment.sensors_config_file):
            os.mknod(Environment.sensors_config_file, mode=0o755)
        Environment.log_full_name = os.path.join(Environment.log_path, Environment.LOG_FILE)
        Environment.config_full_name = os.path.join(Environment.settings_path, Environment.CONFIG_FILENAME)

class Config(object):
    interval: float = 10.0
    auto_start: bool = False
    profile_file: str = ''
    log_level: int = logging.INFO
    theme: str = 'light'

    @classmethod
    def from_arguments(cls, **kwargs):
        for attr in kwargs:
            setattr(cls, attr, kwargs[attr])
        if cls.profile_file:
            if os.path.isfile(os.path.expanduser(cls.profile_file)):
                cls.profile_file = os.path.expanduser(cls.profile_file)
            else:
                cls.profile_file = ''
                cls.auto_start = False
        else:
            cls.auto_start = False

    @classmethod
    def get_settings(cls) -> Dict:
        return {name: value for name, value in vars(cls).items() if not callable(getattr(cls, name)) and not name.startswith("__")}

    @classmethod
    def load_settings(cls):
        if Environment.config_full_name:
            cls._load_from_file(Environment.config_full_name)

    @classmethod
    def _load_from_file(cls, file_name: str):
        if file_name is not None and os.path.isfile(file_name):
            LogManager.logger.debug(f'Loading configuration from {file_name}')
            with open(file_name) as config_file:
                config = yaml.safe_load(config_file)
                if config:
                    cls.from_arguments(**config)

    @classmethod
    def save_settings(cls):
        if Environment.config_full_name:
            cls._save_to_file(Environment.config_full_name)

    @classmethod
    def _save_to_file(cls, file_name: str):
        if file_name is not None:
            LogManager.logger.debug(f'Saving configuration: {repr(cls.get_settings())}')
            with open(file_name, 'w') as config_file:
                yaml.safe_dump(cls.get_settings(), config_file)


from __future__ import division

import scipy
import setupplots
setupplots.thesis_format()
import matplotlib.pyplot as plt
plt.ion()

import sys
sys.path.insert(0, '/Users/markchilenski/src/bayesimp')

import lines

lines.read_filter_file(
    '/Users/markchilenski/src/bayesimp/spectral_modeling/Be_filter_50_um.dat',
    plot=True,
    title=r'$\SI{50}{\micro m}$ Be filter',
    figsize=(0.5 * setupplots.TEXTWIDTH, 0.5 * setupplots.TEXTWIDTH / 1.618)
)
f = plt.gcf()
a = plt.gca()
a2 = a.twiny()
a2.set_xlim(a.get_xlim())
lam_locs = scipy.asarray([10, 1, 0.5, 0.25, 0.125], dtype=float)
lam_s = [r'$10\vphantom{0123456789}$', r'$1\vphantom{0123456789}$', r'$0.5\vphantom{0123456789}$', r'$0.25\vphantom{0123456789}$', r'$0.125\vphantom{0123456789}$']
E_locs = 1e-3 * scipy.constants.h * scipy.constants.c / (scipy.constants.e * lam_locs * 1e-9)
a2.set_xticks(E_locs)
a2.set_xticklabels(lam_s)
a2.set_xlabel(r"$\lambda$ [nm]")
a.set_title(r'$\SI{50}{\micro m}$ Be filter', y=1.275)
setupplots.apply_formatter(f)
f.savefig("XTOMO_filter.pdf", bbox_inches='tight')
f.savefig("XTOMO_filter.pgf", bbox_inches='tight')


from random import choice

from faker import Faker

bank_names_fr = [
    "Banque CIBC",
    "BMO Banque de Montréal",
    "Banque Desjardins",
    "Banque HSBC Canada",
    "Banque Laurentienne du Canada",
    "Banque Nationale du Canada",
    "Banque Royale du Canada",
    "Banque Scotia",
    "Banque TD Canada Trust",
]

bank_names_en = [
    "CIBC Bank",
    "BMO Montreal Bank",
    "Desjardins Bank",
    "HSBC Canada Bank",
    "Laurentian Bank of Canada",
    "National Bank of Canada",
    "Royal Bank of Canada",
    "Scotia Bank",
    "TD Canada Trust Bank",
]

class FinancingFaker:
    def __init__(self, locale: str) -> None:
        """
        A faker to fake a financing institution.

                locale (str): The locale language setting to use for simulation. Can either be `'fr_CA'` or `'en_CA'`.
        """
        self.locale = locale

        self.address_faker = Faker(locale=self.locale)

        if self.locale == "fr_CA":
            self.bank_name = bank_names_fr
        elif self.locale == "en_CA":
            self.bank_name = bank_names_en
        else:
            raise ValueError(f"The locale {locale} is not supporter. It can either be 'fr_CA' or 'en_CA'.")

    def financing(self) -> str:
        """
        Method to fake a financing details information. Namely, is name and address.

        Return:
            A string of the bank name and address in capitalize characters.
        """
        bank = choice(self.bank_name)
        address = self.address_faker.address()

        return f"{bank} {address}"


# -*- coding: utf-8 -*-
"""
Created on Thu Jan  3 23:47:45 2019

@author: LEX
"""

import time
import math
import torch
import os
import torch.onnx
from model import Languagemodel
from utils.data_utils import Vocab, Txtfile, Data2tensor, SaveloadHP, seqPAD, PAD, EOS, SOS
from utils.core_nns import RNNModel

# Load trained model
def load_model(model_source, use_cuda=False):
    """ Load pretrained model from source
            - model_source: link to '.args' file
            - use_cuda: set it to True if you have GPU
        Return: model, vocab
    """
    #model_args_source = './results/lm.args'
    model_args = SaveloadHP.load(model_source)
    model_args.use_cuda = use_cuda
    language_model = Languagemodel(model_args)
    language_model.model.load_state_dict(torch.load(model_args.trained_model))

    return language_model.model, model_args.vocab

def rev_gen( model, vocab, start_word=SOS):
    """ Generate a review starts with 'start_word', ends with '</s>'
    """
    print('Generating sample review .....................')
    with torch.no_grad():
        word_idx = vocab.w2i[start_word]
        all_words = []
        all_words.append(start_word)
        while word_idx != vocab.w2i[EOS]:
            word_tensor = Data2tensor.idx2tensor([[word_idx]])
            hidden = model.init_hidden(word_tensor.size(0))
            output, hidden = model(word_tensor, hidden)
            label_prob, label_pred = model.inference(output)
            word_idx = label_pred.data[0][0].data.numpy()[0]
            all_words.append(vocab.i2w[word_idx])

        return ' '.join(all_words)

def wd_pred(model, vocab, sentence):
    """ Predict next word
    """
    with torch.no_grad():
        words = sentence.split(' ')
        for i, word in enumerate(words):
            # transform word to tensor
            word_idx = vocab.w2i[word]
            word_tensor = Data2tensor.idx2tensor([[word_idx]])
            if i == 0:
                hidden = model.init_hidden(word_tensor.size(0))
            output, hidden = model(word_tensor, hidden)

    label_prob, label_pred = model.inference(output)
    word_idx = label_pred.data[0][0].data.numpy()[0]

    return vocab.i2w[word_idx]


import argparse
import numpy as np
import pandas as pd

import io_tools

BASE_TIMESTEP = 10
MAX_TIMESTEP = 120

parser = argparse.ArgumentParser(description="Reduce displacement data for remote processing.")

parser.add_argument("disp_file", help="displacements file")
parser.add_argument("outfile", help="output file")

args = parser.parse_args()

df = pd.read_csv(args.disp_file, dtype=io_tools.DTYPE_DICT)

df = io_tools.filter_displacement_data(df, remove_zeros=False, base_timestep=BASE_TIMESTEP)

df = df[df[io_tools.TIMESTEP] <= MAX_TIMESTEP]

df.to_csv(args.outfile)


#this is the server file

from flask import Flask, render_template, request, redirect, session
import random
from datetime import datetime

app = Flask(__name__)
app.secret_key = 'keep it secret, keep it safe' # set a secret key for security purposes

@app.route('/', methods=['get']) #per instructions:  Have the root route render this [the wireframe] page..an that is about all it does
def start():

    new_time=datetime.now().strftime('%Y-%m-%d %H:%M:%S%f')

    if 'total_gold' not in session:
        session['total_gold'] = 0
    if 'activity_list' not in session:
        session['activity_list'] = []

    return render_template("ninjagold.html", activity_results=session['activity_list'], gold_count=session['total_gold']) #these extra values are just for testing and will move to the other route

@app.route('/process_money', methods=['POST'])  #per video, html form key-values will be sent to this route per instructions:  Have the "/process_money" POST route increase/decrease the user's gold by an appropriate amount and redirect to the root route.  I think this means the html page's form sends its results to this /process money route
def process_money():
    new_time=datetime.now().strftime('%Y-%m-%d %H:%M:%S%f')
    location_visited=request.form['locationclick'] #possible values:  farm, cave, house, casino
    print("location visited:  " + location_visited)
    if (location_visited=="farm"):
        new_gold=random.randint(10,20)
        new_activity_text="
Earned "+ str(new_gold) + " golds from the farm! (" + new_time + ")
"
    elif (location_visited=="cave"):
        new_gold=random.randint(5,10)
        new_activity_text="
Earned "+ str(new_gold) + " golds from the cave! (" + new_time + ")
"
    elif (location_visited=="house"):
        new_gold=random.randint(2,5)
        new_activity_text="
Earned "+ str(new_gold) + " golds from the house! (" + new_time + ")
"
    else:
        new_gold=random.randint(-50,50)
        if (new_gold>0):
            new_activity_text="
Entered a casino and won "+ str(new_gold) + " golds ! (" + new_time + ")
"
        elif (new_gold == 0):
            new_activity_text="
Entered a casino and won "+ str(1) + " golds  ! (" + new_time + ")
"
        else:
            new_activity_text="
Entered a casino and lost "+ str(new_gold*-1) + " golds  Ouch! (" + new_time + ")
"

    print("new activity string:  " + new_activity_text)

    session['total_gold'] = str(int(session['total_gold']) + new_gold)
    #session['activity_list'] = [new_activity_text,new_activity_text,'erer','4545t']
    session['activity_list'].insert(0,new_activity_text)
    print(session['activity_list'])

    return redirect("/")

if __name__ == "__main__":
    app.run(debug=True)


import csv
import numpy as np
from pymc import Gamma, Normal, NoncentralT, Binomial, Uniform, invlogit, logit, deterministic, stochastic

### SETUP
# counts_pos, counts_total, batch_id, plate_id, row, col, treatment
rows = [tuple(row) for row in csv.reader(open('nephrine_fracs.csv'))]
pos_counts, total_counts, batch_ids, plate_ids, row_ids, col_ids, treatment_ids = [np.array(v) for v in zip(*rows)]
pos_counts = pos_counts.astype(int)
total_counts = total_counts.astype(int)
num_wells = len(pos_counts)

# batches
batch_names, batch_idxs = np.unique(batch_ids, return_inverse=True)
num_batches = len(batch_names)

# plates
plate_names, plate_idxs = np.unique(plate_ids, return_inverse=True)
num_plates = len(plate_names)

# batchrows, batchcols
batchrow_names, batchrow_idxs = np.unique(['batchrow_%s_%s'%(b, r) for b, r in zip(batch_ids, row_ids)], return_inverse=True)
batchcol_names, batchcol_idxs = np.unique(['batchcol_%s_%s'%(b, c) for b, c in zip(batch_ids, col_ids)], return_inverse=True)
num_batchrows = len(batchrow_names)
num_batchcols = len(batchcol_names)

# treatments
treatment_names, treatment_idxs = np.unique(treatment_ids, return_inverse=True)
num_treatments = len(treatment_names)

### MODEL
# base effect, uninformative prior
base_fx = Normal('base', mu=0, tau=0.001, size=1, value=np.zeros(1))

# batch effect, somewhat informative prior
batch_fx = Normal('batch_fx', mu=0, tau=0.1, size=num_batches, value=np.zeros(num_batches))

# plate effect, two-level prior, somewhat informative
plate_prec = Gamma('plate_prec', alpha=0.1, beta=0.1)
plate_fx = np.array([Normal('plate_fx_%s'%(name), mu=0, tau=plate_prec, value=0) for name in plate_names])

# batch row and column effects, two-level prior
batchrowcol_prec_base = Gamma('batchrowcol_prec_prior', alpha=0.01, beta=0.01)
batchrow_fx = np.array([Normal('batchrow_fx_%s'%(name), mu=0, tau=batchrowcol_prec_base, value=0) for name in batchrow_names])
batchcol_fx = np.array([Normal('batchcol_fx_%s'%(name), mu=0, tau=batchrowcol_prec_base, value=0) for name in batchcol_names])

def initial_guess(treatment):
    return np.median(logit((pos_counts[treatment_ids == treatment] + 1).astype(float) / (total_counts[treatment_ids == treatment] + 2)))

# treatment effect - individual precisions
# NB: these are the values we are interested in capturing.
treatment_prec = [Gamma('treatment_prec_%s'%(name), alpha=0.01, beta=0.01, value=0.5) for name in treatment_names]
treatment_fx = np.array([Normal('treatment_fx_%s'%(name), mu=0, tau=treatment_prec[idx], value=initial_guess(name)) for idx, name in enumerate(treatment_names)])

# # well effects - we want to allow outliers, so use a 3-parameter
# # Student's t distribution (see ARM, pg. 384, Gelman & Hill)
# # nu = degrees of freedom
# well_df_inv = Uniform('well_df_inv', lower=0.0, upper=0.5, value=0.25)
# @deterministic(plot=False)
# def well_df(well_df_inv=well_df_inv):
#     return 1.0 / well_df_inv
#
# #lam = scale
# @deterministic(plot=False)
# def well_lam(well_df=well_df):
#     return (well_df - 2) / well_df
#
# well_fx = np.array([NoncentralT('well_fx_%d'%(wellidx), mu=0, lam=well_lam, nu=well_df, value=0) for wellidx in range(num_wells)])

# Unnobserved probabilities per well
@deterministic(plot=False)
def p_wells(base_fx=base_fx,
            batch_fx=batch_fx,
            plate_fx=plate_fx,
            batchrow_fx=batchrow_fx,
            batchcol_fx=batchcol_fx,
            treatment_fx=treatment_fx):
    # use this ordering to make everything turn into an ArrayContainer
    return invlogit(treatment_fx[treatment_idxs] +
                    base_fx +
                    batch_fx[batch_idxs] +
                    plate_fx[plate_idxs] +
                    batchrow_fx[batchrow_idxs] +
                    batchcol_fx[batchcol_idxs])

# Likelihood
pos_counts_likelihood = Binomial('pos_counts', value=pos_counts, n=total_counts, p=p_wells, observed=True, verbose=0)


import sys

from api.hh_api import HeadHunterAPI
from config import EMPLOYEERS_VACANCY_ID
from database.db_manager import DBManager
from app.mixin_menu_app import MixinMenuAPP
from utils.сurrency_сonverter import get_currency_data
from app.job_search_meta import JobSearchAppMeta
from utils.loading_progress import show_loading_progress
from utils.generate_unique import generate_unique_four_letter_value

class JobSearchApp(MixinMenuAPP, metaclass=JobSearchAppMeta):
    """
        Главное приложение для поиска работы.

        Класс наследуется от миксина MixinMenuAPP и использует метакласс JobSearchAppMeta.

        Атрибуты:
            hh_api (HeadHunterAPI): Экземпляр класса HeadHunterAPI для работы с HeadHunter API.
            db_manager (DBManager): Экземпляр класса DBManager для работы с базой данных.
            existing_values (list): Список существующих значений для генерации уникальных идентификаторов.
    """
    hh_api = HeadHunterAPI()
    db_manager = DBManager()
    existing_values = []

    @classmethod
    def _interact_with_user(cls) -> None:
        """
            Взаимодействие с пользователем.

            Метод запускает взаимодействие с пользователем, предоставляя главное меню приложения и обрабатывая выбор
            пользователя.
        """
        cls.db_manager.connect()
        cls.db_manager.clear_tables()
        cls.__get_for_database_all_vacancies()
        cls.main_menu()
        cls.db_manager.disconnect()

    @classmethod
    def __get_for_database_all_vacancies(cls):
        """ Получение всех вакансий из API и запись в базу данных.

            Метод получает список всех вакансий от API, обрабатывает их и записывает в базу данных.
        """
        total_employers = len(EMPLOYEERS_VACANCY_ID)
        completed_employers = 0
        for employeer_name, employeer_id in EMPLOYEERS_VACANCY_ID.items():
            company_name = employeer_name
            company_vacancies = cls.hh_api.get_vacancies(employeer_id)
            for vacancy in company_vacancies:
                vacancy_name = vacancy["name"]
                vacancy_url = vacancy["alternate_url"]
                vacancy_from = int(vacancy["salary"]["from"]) if vacancy.get("salary") is not None and vacancy[
                    "salary"].get("from") is not None else 0
                vacancy_to = int(vacancy["salary"]["to"]) if vacancy.get("salary") is not None and vacancy[
                    "salary"].get("to") is not None else 0
                if vacancy.get("salary") and vacancy["salary"]["currency"] not in ["RUR", "RUB"]:
                    vacancy_from *= get_currency_data(vacancy["salary"]["currency"])
                    vacancy_to *= get_currency_data(vacancy["salary"]["currency"])
                vacancy_currency = "RUR"
                vacancy_id = generate_unique_four_letter_value(cls.existing_values)
                cls.db_manager.insert_vacancy_to_all(vacancy_id, company_name, vacancy_name, vacancy_from,
                                                     vacancy_to,
                                                     vacancy_currency,
                                                     vacancy_url)

                cls.db_manager.insert_vacancy_company(vacancy_id, company_name, vacancy_name, vacancy_from,
                                                      vacancy_to,
                                                      vacancy_currency,
                                                      vacancy_url)
            completed_employers += 1
            show_loading_progress(completed_employers, total_employers)
        sys.stdout.write("\rЗагрузка завершена!\n")

    @classmethod
    def _get_vacancies_with_keyword(cls, keyword):
        """ Получение списка вакансий с заданным ключевым словом.

           Метод получает список вакансий, в названии которых содержится заданное ключевое слово, из базы данных и
           выводит его на экран.

           Аргументы:
               keyword (str): Ключевое слово для поиска вакансий.
        """
        result_df = cls.db_manager.get_vacancies_with_keyword(keyword)
        result_str = result_df.to_string(index=False)
        print(result_str)

    @classmethod
    def _get_avg_salary(cls):
        """ Получение средней зарплаты по вакансиям.

            Метод получает среднюю зарплату по всем вакансиям из базы данных и выводит ее на экран.
        """
        print(cls.db_manager.get_avg_salary())

    @classmethod
    def _get_vacancies_with_higher_salary(cls):
        """ Получение списка вакансий с зарплатой выше средней.

           Метод получает список вакансий, у которых зарплата выше средней по всем вакансиям из базы данных и выводит
           его на экран.
        """
        result_df = cls.db_manager.get_vacancies_with_higher_salary()
        result_str = result_df.to_string(index=False)
        print(result_str)

    @classmethod
    def _get_companies_and_vacancies_count(cls):
        """ Получение списка всех компаний и количества вакансий у каждой компании.

            Метод получает список всех компаний и количество вакансий у каждой компании из базы данных и выводит его на
            экран.
        """
        result_df = cls.db_manager.get_companies_and_vacancies_count()
        result_str = result_df.to_string(index=False)
        print(result_str)

    @classmethod
    def _get_top_vacancies(cls):
        """ Получение списка топ-300 вакансий.

            Метод получает список топ-300 вакансий с указанием названия компании, названия вакансии и зарплаты, а также
            ссылки на вакансию из базы данных и выводит его на экран.
        """
        result_df = cls.db_manager.get_top_vacancies()
        result_str = result_df.to_string(index=False)
        print(result_str)


import unittest
import pathlib
from helpers import FakeWriter, a_wait

import grole

class TestHeader(unittest.TestCase):

    def test_header(self):
        res = grole.Response(None, 123, 'foo', {'foo': 'bar'}, 'bar')
        writer = FakeWriter()
        a_wait(res._write(writer))
        for line in writer.data.split(b'\r\n'):
            if line.startswith(b'bar'):
                self.assertEqual(line, b'bar 123 foo')
            elif line.startswith(b'Content-Type'):
                self.assertEqual(line, b'Content-Type: text/plain')
            elif line.startswith(b'Content-Length'):
                self.assertEqual(line, b'Content-Length: 0')
            elif line.startswith(b'foo'):
                self.assertEqual(line, b'foo: bar')
            elif line.startswith(b'Server'):
                self.assertEqual(line, b'Server: grole/' + grole.__version__.encode())
            else:
                if line != b'':
                    self.fail('Extra data: ' + line.decode())

class TestBody(unittest.TestCase):

    def test_headers(self):
        res = grole.ResponseBody(b'foo', content_type='bar')
        hdr = {}
        res._set_headers(hdr)
        self.assertDictEqual(hdr, {'Content-Length': 3,
                                   'Content-Type': 'bar'})

    def test_data(self):
        res = grole.ResponseBody(b'foo', content_type='bar')
        writer = FakeWriter()
        a_wait(res._write(writer))
        self.assertEqual(writer.data, b'foo')

    def test_bytes(self):
        res = grole.Response(b'foo')
        self.assertIsInstance(res.data, grole.ResponseBody)

    def test_string(self):
        res = grole.Response('foo')
        self.assertIsInstance(res.data, grole.ResponseString)

    def test_json(self):
        res = grole.Response(['foo'])
        self.assertIsInstance(res.data, grole.ResponseJSON)

    def test_file(self):
        res = grole.Response(grole.ResponseFile('foo'))
        self.assertIsInstance(res.data, grole.ResponseFile)

class TestString(unittest.TestCase):

    def setUp(self):
        self.res = grole.ResponseString('foo', content_type='bar')

    def test_headers(self):
        hdr = {}
        self.res._set_headers(hdr)
        self.assertDictEqual(hdr, {'Content-Length': 3,
                                   'Content-Type': 'bar'})

    def test_data(self):
        writer = FakeWriter()
        a_wait(self.res._write(writer))
        self.assertEqual(writer.data, b'foo')

class TestJSON(unittest.TestCase):

    def setUp(self):
        self.res = grole.ResponseJSON({'foo': 'bar'}, content_type='baz')

    def test_headers(self):
        hdr = {}
        self.res._set_headers(hdr)
        self.assertDictEqual(hdr, {'Content-Length': 14,
                                   'Content-Type': 'baz'})

    def test_data(self):
        writer = FakeWriter()
        a_wait(self.res._write(writer))
        self.assertEqual(writer.data, b'{"foo": "bar"}')

class TestFile(unittest.TestCase):

    def setUp(self):
        testfile = pathlib.Path(__file__).parents[0] / 'test.dat'
        self.res = grole.ResponseFile(str(testfile), content_type='baz')

    def test_headers(self):
        hdr = {}
        self.res._set_headers(hdr)
        self.assertDictEqual(hdr, {'Transfer-Encoding': 'chunked',
                                   'Content-Type': 'baz'})

    def test_data(self):
        writer = FakeWriter()
        a_wait(self.res._write(writer))
        self.assertEqual(writer.data, b'4\r\nfoo\n\r\n0\r\n\r\n')

class TestAuto(unittest.TestCase):

    def test_empty(self):
        res = grole.Response()
        self.assertTrue(isinstance(res.data, grole.ResponseBody))

    def test_bytes(self):
        res = grole.Response(b'foo')
        self.assertTrue(isinstance(res.data, grole.ResponseBody))
        self.assertEqual(res.data._data, b'foo')
        self.assertEqual(res.data._headers['Content-Type'], 'text/plain')

    def test_str(self):
        res = grole.Response('foo')
        self.assertTrue(isinstance(res.data, grole.ResponseString))
        self.assertEqual(res.data._data, b'foo')
        self.assertEqual(res.data._headers['Content-Type'], 'text/html')

    def test_json(self):
        res = grole.Response({'foo': 'bar'})
        self.assertTrue(isinstance(res.data, grole.ResponseJSON))
        self.assertEqual(res.data._data, b'{"foo": "bar"}')
        self.assertEqual(res.data._headers['Content-Type'], 'application/json')

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


import scrapy

# TF-IDF
# import StemmerFactory class
from Sastrawi.Stemmer.StemmerFactory import StemmerFactory
from math import log10

# create stemmer
factory = StemmerFactory()
stemmer = factory.create_stemmer()

class QuotesSpider(scrapy.Spider):
    name = "tubes_novel5"

    def start_requests(self):
        main_Url = 'https://www.worldnovel.online/'
        Novel = 'the-first-order/'

        # list 10 url tiap chapter di novel the first order
        urls = [
            '{}{}chapter-1-a-sickness-in-the-head/'.format(main_Url, Novel),
            '{}{}chapter-2-this-world-has-never-trusted-tears/'.format(main_Url, Novel),
            '{}{}chapter-3-a-palace/'.format(main_Url, Novel),
            '{}{}chapter-4-luck-is-a-type-of-skill-too/'.format(main_Url, Novel),
            '{}{}chapter-5-the-school/'.format(main_Url, Novel),
            '{}{}chapter-6-walls-and-science/'.format(main_Url, Novel),
            '{}{}chapter-7-substitute-teacher/'.format(main_Url, Novel),
            '{}{}chapter-8-something-really-is-wrong-with-his-head/'.format(main_Url, Novel),
            '{}{}chapter-9-ask-me-if-theres-anything-you-dont-understand/'.format(main_Url, Novel),
            '{}{}chapter-10-side-quest/'.format(main_Url, Novel)
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse) # metode Scrapy meminta request ke web url

    def parse(self, response):
    #    print(response.url)
        yield {
             'jdlChap' : response.css('#outer-wrapper > div > h3::text').extract(), # mengambil data Judul Chapter
             'textNovel' : response.css('#soop > p ::text').extract(), # mengambil data berupaa seluruh isi teks novel yang terdapat dalam tag p
        }

    # block untuk proses TF-IDF function
    def get_list_of_word(list_of_chapNovel):
        list_of_word = []

        for sentence in list_of_chapNovel:
            for word in stemmer.stem(sentence).split(' '):
                if word not in list_of_chapNovel:
                    list_of_word.append(word)

        return list_of_word

    # membuka file yang berupa store data dari hasil ouput Scrapy tadi yang dimasukkan ke dalam sebuah file berformat json
    # yang mana untuk store data ke berupa file itu dilakukkan command Scrapy tertentu ke cmd, lalu akan tebentuklah file tersebut

    # List yang berisi kumpulan teks chapter novel dan ukuran dari list tersebut
    list_of_chapNovel = [open('novel_the_first_order.json', encoding='utf-8').read()]
    length_of_chapNovel = len(list_of_chapNovel)

    # berisi kata-kata yang berasal dari list text chapNovel
    list_of_word = get_list_of_word(list_of_chapNovel)
    # print(list_of_word)
    print(list_of_word[25])
    print(list_of_word[688])
    print(list_of_word[702])
    print(list_of_word[899])
    print(list_of_word[917])
    print(list_of_word[918])
    print(list_of_word[1200])
    print(list_of_word[1400])
    print(list_of_word[1539])
    print(list_of_word[1993])


#!/usr/bin/env python3
import yaml
import rospy
import os
from uav_abstraction_layer.srv import TakeOff, GoToWaypoint, Land
from geometry_msgs.msg import PoseStamped

class WayPointTracker:
    def __init__(self):
        self.uav_namespace = rospy.get_param("~uav_namespace", "")
        self.file_path = rospy.get_param("~flight_plan_path", "")
	# Create the servies
        self.take_off_service_name = os.path.join("/", self.uav_namespace, "ual/take_off")
        self.go_to_service_name = os.path.join("/", self.uav_namespace, "ual/go_to_waypoint")
        self.land_service_name = os.path.join("/", self.uav_namespace, "ual/land")
        self.take_off_service = self.registerService(self.take_off_service_name, TakeOff)
        self.go_to_service = self.registerService(self.go_to_service_name, GoToWaypoint)
        self.land_service = self.registerService(self.land_service_name, Land)
        # Load flight plan
        self.raw_flight_plan = None
        self.flight_plan = None
        self.loop_waypoints = None
        self.loadFlightPlan()
        self.parseFlightPlan()
        # Exectute flight plan
        self.takeOff(self.take_off_service, self.flight_plan['TakeOff'])
        self.followPoints(self.go_to_service, self.flight_plan['Waypoints'])
        self.goToWaypoint(self.go_to_service, self.flight_plan['LandingPosition'])
        self.land(self.land_service)

    def loadFlightPlan(self):
        # Check file exists
        if not os.path.exists(self.file_path):
            raise ValueError("The file does not exist, please check the provided path.")

        with open(self.file_path, 'r') as wp_file:
            self.raw_flight_plan = yaml.safe_load(wp_file)

    def makeStampedPose(self, data, frame):
        waypoint = PoseStamped()
        waypoint.header.frame_id = frame
        waypoint.pose.position.x =    data[0]
        waypoint.pose.position.y =    data[1]
        waypoint.pose.position.z =    data[2]
        waypoint.pose.orientation.x = data[3]
        waypoint.pose.orientation.y = data[4]
        waypoint.pose.orientation.z = data[5]
        waypoint.pose.orientation.w = data[6]
        return waypoint

    def parseFlightPlan(self):
        self.loop_waypoints = self.raw_flight_plan['loop_waypoints']
        self.flight_plan = {}
        self.flight_plan['TakeOff'] = self.raw_flight_plan['take_off_altitude']
        self.flight_plan['LandingPosition'] = self.makeStampedPose(self.raw_flight_plan['landing_position'],
                                                              self.raw_flight_plan['frame_id'])
        self.flight_plan['Waypoints'] = []
        for i in self.raw_flight_plan['waypoints']:
            waypoint = self.makeStampedPose(i, self.raw_flight_plan['frame_id'])
            self.flight_plan['Waypoints'].append(waypoint)

    def followPoints(self, go_to_service, waypoints):
        if self.loop_waypoints:
            while (not rospy.is_shutdown()):
                for waypoint in waypoints:
                    self.goToWaypoint(go_to_service, waypoint)
        else:
            for waypoint in waypoints:
                self.goToWaypoint(go_to_service, waypoint)

    def registerService(self, service_path, service_type):
        rospy.wait_for_service(service_path)
        try:
            service = rospy.ServiceProxy(service_path, service_type)
        except rospy.ServiceException as e:
            print("Service registration failed: %s", e)
        return service

    def goToWaypoint(self, go_to_service, waypoint):
        try:
            go_to_service(waypoint, True)
        except rospy.ServiceException as e:
            print("Service call failed: %s", e)

    def takeOff(self, take_off_service, height):
        try:
            take_off_service(height, True)
        except rospy.ServiceException as e:
            print("Service call failed: %s", e)

    def land(self, land_service):
        try:
            land_service(True)
        except rospy.ServiceException as e:
            print("Service call failed: %s", e)

if __name__ == "__main__":
    rospy.init_node('waypoint_tracker')
    WPT = WayPointTracker()


import torch
import numpy as np

from ml.modules.losses.ordinal_regression_loss import OrdinalRegressionLoss

config_path = '../config/config_files/kitti_base.yaml'

ord_num = 90
gamma = -0.97
beta = 90
config = load_config(config_path)
config['model']['params']['discretization'] = "SID"

ordinal_regression_loss = OrdinalRegressionLoss(ord_num, beta)

val_loader, niter_val = build_loader(config, is_train=False)

rmses = []

for i, data in enumerate(val_loader):
    gt = data['target'].unsqueeze(0)

    _, gt_mask = ordinal_regression_loss._create_ord_label(gt)

    label = ord_num - torch.sum(gt_mask, dim=1)
    t0 = torch.exp(np.log(beta) * label.float() / ord_num)
    t1 = torch.exp(np.log(beta) * (label.float() + 1) / ord_num)

    depth_gt = (t0 + t1) / 2 - gamma

    depth_gt = np.squeeze(depth_gt.numpy())
    gt = np.squeeze(gt.numpy())

    gt_mask = gt > 0
    gt = gt[gt_mask]
    depth_gt = depth_gt[gt_mask]

    rmse = np.sqrt(np.mean((depth_gt - gt) ** 2)) * 1000

    rmses.append(rmse)
    print(f'{i + 1} / {len(val_loader)}, RMSE: {rmse}')

mean_rmse = np.mean(rmses)
print(f'Mean minimum RMSE: {mean_rmse}')