from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
from flask import Flask, request, abort
from dotenv import load_dotenv
import os
from os.path import join, dirname
from threading import Thread
import requests
import base64
from datetime import datetime

dotenv_path = join(dirname(__file__), '.env') # path per le var di ambiente
load_dotenv(dotenv_path)# carico le var di ambiente
api_key = os.environ.get('api_key') # settaggio dell'api key
app = Flask(__name__) # istanza flask

notify_users = [] # utenti che hanno richiesto la notifica
enabled_users = []# utenti abilitati alle notifiche
users_areas = [] # var di appoggio
final_diction = {}

def send_alert(id, img_bytes, info_cam):
    params = {'chat_id': id,
              'caption': str(info_cam)}
    files = {'photo': img_bytes}
    url = f'https://api.telegram.org/bot{api_key}/sendPhoto?chat_id={id}'
    requests.post(url, params, files=files)
    return '', 204

@app.route("/notify_telegram", methods=['POST'])
def notify_method():

    str_date_time = datetime.now().strftime("%d-%m-%Y, %H:%M:%S")
    info_cam = f"Data : {str(str_date_time)}\n"
    if not request.json or 'image' not in request.json:
        abort(400)

    im_b64 = request.json['image']
    caption = request.json['caption']

    for key,value in caption.items(): # JSON formatting
        info_cam += f"{key} : {value}\n"
        if key == "Area di competenza":
            area_value = value.upper()

    img_bytes = base64.b64decode(im_b64.encode('utf-8'))
    for id in final_diction[area_value]:
        for observer in notify_users:
            if observer['id'] == id:
                send_alert(id, img_bytes, info_cam)
    return '', 204

def load_file():
        with open('users_areas.txt') as f:
            contents = f.readlines()
            for element in contents:
                try:
                    splitting = element.split(" ")
                    clearing = splitting[1].strip()
                    enabled_users.append(int(splitting[0]))
                    users_areas.append((clearing.upper(), int(splitting[0])))
                except (IndexError, ValueError):
                    continue

        for i in users_areas:
            if i[0] in final_diction.keys():
                nuova_lista = []
                old = final_diction[i[0]]
                new = i[1]
                old.append(new)
                nuova_lista.append(old)
                nuova_lista.append(new)
                final_diction[i[0]] = old
            else:
                final_diction[i[0]] = ['a', i[1]]

        for key, value in final_diction.items():
            value.pop(0)

        #print(f"Enabled users {enabled_users}\n")
        #print(f"Users areas : {users_areas}\n")
        #print(f"final diction: {final_diction}\n")

# Funzione /start per il bot
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    user = update.effective_user
    await update.message.reply_text(f"Ciao {user['first_name']} premi /help per il menù dei comandi disponibili.")

# Funzione /help per il bot
async def help(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text("I comandi disponibili sono:\n "+\
                                    "/start -> Messaggio di Benvenuto\n"+\
                                    "/help -> Questo Messaggio\n"+\
                                    "/content -> Informazioni riguardanti il bot\n"+\
                                    "/notify -> Inizio invio notifiche\n"+\
                                    "/unnotify -> Termine invio notifiche\n")

# Funzione /content per il bot
async def content(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text("Questo Bot è progettato per allertare quando una telecamera riconosce un abbondono di rifiuti\n"+\
                                    "Con il comando /notify puoi attivare le notifiche;\n"+\
                                    "Con il comando /unnotify puoi disattivarle")

# Funzione /notify per il bot
async def notify(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    user = update.effective_user
    if user['id'] in enabled_users:
        if user in notify_users:
            await update.message.reply_text(f"Sei già presente nella lista dei notificabili")
        else:
            notify_users.append(user)
            await update.message.reply_text(f"Sei stato aggiunto nella lista dei notificabili")
    else:
        await update.message.reply_text(f"Lei non è presente nella lista dei notificabili")

# Funzione /unnotify per il bot
async def unnotify(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    user = update.effective_user
    if user['id'] in enabled_users:
        if user in notify_users:
            await update.message.reply_text("Sei Stato Rimosso dalla lista dei notificabili")
            notify_users.remove(user)
        else:
            await update.message.reply_text('Non sei presente nella lista degli osservatori, effettuare la /notify se si vuole ricevere le notifiche')
    else:
        await update.message.reply_text(f"Lei non è presente nella lista dei notificabili")

# Funzione echo dei messaggi per il bot
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text(update.message.text)

# debug Function
async def test(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    utenti = ''.join(str(notify_users))
    await update.message.reply_text(utenti)

def main() -> None:
    load_file()
    """Start del bot."""
    # Crea l'applicazione e gli passa l'api token del proprio bot
    application = Application.builder().token(str(api_key)).build()

    # Comandi che rispondono
    application.add_handler(CommandHandler("start", start))
    application.add_handler(CommandHandler("help", help))
    application.add_handler(CommandHandler("content", content))
    application.add_handler(CommandHandler("notify", notify))
    application.add_handler(CommandHandler("unnotify", unnotify))
    application.add_handler(CommandHandler("test", test))

    #Comando che fa una semplice echo
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))

    application.run_polling()

def task():
    # run the flask istance
    try:
        app.run()
    except:
        pass

if __name__ == "__main__":
    thread = Thread(target=task)
    thread.daemon = True
    thread.start()
    main()


import numpy as np
import os
import sys
import tensorflow as tf

import matplotlib.pyplot as plt
from PIL import Image
from timeit import default_timer as timer

from object_detection.utils import ops as utils_ops

# if tf.__version__ < '1.4.0':
#     raise ImportError(
#         'Please upgrade your tensorflow installation to v1.4.* or later!')

from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util

# MODEL_NAME = 'ssdlite_mobilenet_v2_coco'
# PATH_TO_FROZEN_GRAPH = MODEL_NAME + '/frozen_inference_graph.pb'
# PATH_TO_LABELS = MODEL_NAME + '/mscoco_label_map.pbtxt'
# NUM_CLASSES = 90

PATH_TO_FROZEN_GRAPH = './checkpoint/save_17958/frozen_inference_graph.pb'
PATH_TO_LABELS = './data/pascal_label_map.pbtxt'
NUM_CLASSES = 1

detection_graph = tf.Graph()
with detection_graph.as_default():
    od_graph_def = tf.GraphDef()
    with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
        serialized_graph = fid.read()
        od_graph_def.ParseFromString(serialized_graph)
        tf.import_graph_def(od_graph_def, name='')

label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(
    label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)

def load_image_into_numpy_array(image):
    (im_width, im_height) = image.size
    return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)

# For the sake of simplicity we will use only 2 images:
# image1.jpg
# image2.jpg
# If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.
PATH_TO_TEST_IMAGES_DIR = './test_images'
TEST_IMAGE_PATHS = [os.path.join(
    PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 2)]
print(TEST_IMAGE_PATHS)

# Size, in inches, of the output images.
# IMAGE_SIZE = (450, 300)

def run_inference_for_single_image(image, graph):
    with graph.as_default():
        with tf.Session() as sess:
            # Get handles to input and output tensors
            ops = tf.get_default_graph().get_operations()
            all_tensor_names = {
                output.name for op in ops for output in op.outputs}
            tensor_dict = {}
            for key in [
                'num_detections', 'detection_boxes', 'detection_scores',
                'detection_classes', 'detection_masks'
            ]:
                tensor_name = key + ':0'
                if tensor_name in all_tensor_names:
                    tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
                        tensor_name)
            if 'detection_masks' in tensor_dict:
                # The following processing is only for single image
                detection_boxes = tf.squeeze(
                    tensor_dict['detection_boxes'], [0])
                detection_masks = tf.squeeze(
                    tensor_dict['detection_masks'], [0])
                # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
                real_num_detection = tf.cast(
                    tensor_dict['num_detections'][0], tf.int32)
                detection_boxes = tf.slice(detection_boxes, [0, 0], [
                                           real_num_detection, -1])
                detection_masks = tf.slice(detection_masks, [0, 0, 0], [
                                           real_num_detection, -1, -1])
                detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
                    detection_masks, detection_boxes, image.shape[0], image.shape[1])
                detection_masks_reframed = tf.cast(
                    tf.greater(detection_masks_reframed, 0.5), tf.uint8)
                # Follow the convention by adding back the batch dimension
                tensor_dict['detection_masks'] = tf.expand_dims(
                    detection_masks_reframed, 0)
            image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')

            # Run inference
            output_dict = sess.run(tensor_dict, feed_dict={
                                   image_tensor: np.expand_dims(image, 0)})

            # all outputs are float32 numpy arrays, so convert types as appropriate
            output_dict['num_detections'] = int(
                output_dict['num_detections'][0])
            output_dict['detection_classes'] = output_dict[
                'detection_classes'][0].astype(np.uint8)
            output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
            output_dict['detection_scores'] = output_dict['detection_scores'][0]
            if 'detection_masks' in output_dict:
                output_dict['detection_masks'] = output_dict['detection_masks'][0]
    return output_dict

if True:
    import cv2
    video_path = './keras-yolo3-master/1_720.mp4'
    vid = cv2.VideoCapture(video_path)
    if not vid.isOpened():
        raise IOError("Couldn't open webcam or video")
    video_FourCC    = int(vid.get(cv2.CAP_PROP_FOURCC))
    video_fps       = vid.get(cv2.CAP_PROP_FPS)
    video_size      = (int(vid.get(cv2.CAP_PROP_FRAME_WIDTH)),
                        int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT)))
    accum_time = 0
    curr_fps = 0
    fps = "FPS: ??"
    prev_time = timer()

    isOutput = False
    if isOutput:
        out = cv2.VideoWriter('./out.mp4', video_FourCC, video_fps, video_size)

    count = 0

    while True:
        return_value, frame = vid.read()
        image = Image.fromarray(frame)
        image_np = load_image_into_numpy_array(image)

        if True:
        # if curr_fps == 12 :
            image_np_expanded = np.expand_dims(image_np, axis=0)
            output_dict = run_inference_for_single_image(image_np, detection_graph)
            vis_util.visualize_boxes_and_labels_on_image_array(
                image_np,
                output_dict['detection_boxes'],
                output_dict['detection_classes'],
                output_dict['detection_scores'],
                category_index,
                instance_masks=output_dict.get('detection_masks'),
                use_normalized_coordinates=True,
                line_thickness=7,
                min_score_thresh=0.3)

            curr_time = timer()
            exec_time = curr_time - prev_time
            prev_time = curr_time
            accum_time = accum_time + exec_time

        count = count + 1
        curr_fps = curr_fps + 1
        if accum_time > 1:
            accum_time = accum_time - 1
            fps = "FPS: " + str(curr_fps)
            curr_fps = 0

        result = image_np

        red, green, blue = result.T
        result = np.array([blue, green, red])
        result = result.transpose()

        im = Image.fromarray(result).convert('RGB')
        im.save("./out_images/out" + str(count) + ".jpeg")

        # cv2.putText(result, text=fps, org=(3, 15), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.50, color=(255, 0, 0), thickness=2)
        # cv2.namedWindow("result", cv2.WINDOW_NORMAL)
        # cv2.imshow("result", result)
        if isOutput:
            out.write(result)
        # if cv2.waitKey(1) & 0xFF == ord('q'):
        #     break

if  False:
    # image = Image.open(image_path)
    image = Image.open('./test_images/image5.jpg')
    image_np = load_image_into_numpy_array(image)

    image_np_expanded = np.expand_dims(image_np, axis=0)

    output_dict = run_inference_for_single_image(image_np, detection_graph)
    # print(output_dict['detection_scores'])
    vis_util.visualize_boxes_and_labels_on_image_array(image_np,
                                                       output_dict['detection_boxes'],
                                                       output_dict['detection_classes'],
                                                       output_dict['detection_scores'],
                                                       category_index,
                                                       instance_masks=output_dict.get(
                                                           'detection_masks'),
                                                       use_normalized_coordinates=True,
                                                       line_thickness=8,
                                                       min_score_thresh=0.1)

    # plt.figure(figsize=IMAGE_SIZE)
    plt.imshow(image_np)
    # plt.imshow(image)
    plt.show()

# floyd run --gpu --env tensorflow-1.9 --data tigerfloyd/datasets/tf_lebronjames/1:/data --data tigerfloyd/datasets/sdd_mobilenet/1:/model --data tigerfloyd/datasets/tf_ob/3:tf_ob --tensorboard 'bash ./run.sh'


#!/usr/bin/env python
import os
import sys

from django.core.management.templates import TemplateCommand
from django.core.management.utils import get_random_secret_key

CURRENT_PYTHON = sys.version_info[:2]
REQUIRED_PYTHON = (3, 7)

if CURRENT_PYTHON < REQUIRED_PYTHON:
    sys.stderr.write(
        "This version of CjkCMS requires Python {}.{} or above - you are running {}.{}\n".format(
            *(REQUIRED_PYTHON + CURRENT_PYTHON)
        )
    )
    sys.exit(1)

class CreateProject(TemplateCommand):
    """
    Based on django.core.management.startproject
    """

    help = (
        "Creates the directory structure for a new CjkCMS project. "
        "Provide a slug-styled project name as an argument."
    )
    missing_args_message = "You must provide a project name."

    def add_arguments(self, parser):
        parser.add_argument(
            "--sitename",
            help='Human readable name of your website or brand, e.g. "Nano Corp Inc."',
        )
        parser.add_argument(
            "--domain",
            help='Domain that will be used for your website in production, e.g. "www.nanocorp.com"',
        )
        super().add_arguments(parser)

    def handle(self, **options):
        # pop standard args
        project_name = options.pop("name")
        target = options.pop("directory")

        # create Uppercase-first and full uppercase versions of project name
        options["uf_project"] = project_name[0].upper() + project_name[1:]
        options["uc_project"] = project_name.upper()
        options["lc_project"] = project_name.lower()

        # Make sure given name is not already in use by another python package/module.
        try:
            __import__(project_name)
        except ImportError:
            pass
        else:
            sys.exit(
                "'%s' conflicts with the name of an existing "
                "Python module and cannot be used as a project "
                "name. Please try another name." % project_name
            )

        # Create a random SECRET_KEY to put it in the main settings.
        options["secret_key"] = get_random_secret_key()

        # Handle custom template logic
        import cjkcms

        cms_path = os.path.dirname(cjkcms.__file__)
        if not options["template"]:
            options["template"] = "basic"
        template_path = os.path.join(
            os.path.join(cms_path, "project_template"), options["template"]
        )

        # Check if provided template is built-in to the cms,
        # otherwise, do not change it.
        if os.path.isdir(template_path):
            options["template"] = template_path

        # Treat these files as Django templates to render the boilerplate.
        options["extensions"] = ["py", "md", "txt"]
        options["files"] = ["Dockerfile"]

        # Set options
        message = "Creating a CjkCMS project called %(project_name)s"

        if options.get("sitename"):
            message += " for %(sitename)s"
        else:
            options["sitename"] = project_name

        if options.get("domain"):
            message += " (%(domain)s)"
            # Strip protocol out of domain if it is present.
            options["domain"] = options["domain"].split("://")[-1]
            # Figure out www logic.
            if options["domain"].startswith("www."):
                options["domain_nowww"] = options["domain"].split("www.")[-1]
            else:
                options["domain_nowww"] = options["domain"]
        else:
            options["domain"] = "localhost"
            options["domain_nowww"] = options["domain"]

        # Add additional custom options to the context.
        options["cjkcms_version"] = cjkcms.VERSION  # type: ignore

        # Print a friendly message
        print(
            message
            % {
                "project_name": project_name,
                "sitename": options.get("sitename"),
                "domain": options.get("domain"),
            }
        )

        # Run command
        super().handle("project", project_name, target, **options)

        # Be a friend once again.
        print(
            "Success! %(project_name)s has been created"
            % {"project_name": project_name}
        )

        nextsteps = """
Next steps:
    1. cd %(directory)s/
    2. python manage.py migrate
    3. python manage.py createsuperuser
    4. python manage.py runserver
    5. Go to http://localhost:8000/backend/ and start editing!
"""
        print(nextsteps % {"directory": target or project_name})

COMMANDS = {
    "start": CreateProject(),
}

def prog_name():
    return os.path.basename(sys.argv[0])

def help_index():
    print(
        "Type '%s help <subcommand>' for help on a specific subcommand.\n" % prog_name()
    )
    print("Available subcommands:\n")
    for name, cmd in sorted(COMMANDS.items()):
        print(f"    {name.ljust(20)}{cmd.help}")

def unknown_command(command):
    print(f"Unknown command: '{command}'")
    print(f"Type '{prog_name()} help' for usage.")
    sys.exit(1)

def main():
    try:
        command_name = sys.argv[1]
    except IndexError:
        help_index()
        return

    if command_name == "help":
        try:
            help_command_name = sys.argv[2]
        except IndexError:
            help_index()
            return

        try:
            command = COMMANDS[help_command_name]
        except KeyError:
            unknown_command(help_command_name)
            return

        command.print_help(prog_name(), help_command_name)
        return

    try:
        command = COMMANDS[command_name]
    except KeyError:
        unknown_command(command_name)
        return

    command.run_from_argv(sys.argv)

if __name__ == "__main__":
    main()


import cv2
import numpy as np

circles = []  # cember koordinatlarini alacak bos liste tanimlandi

img = cv2.imread(r"C:\Users\suley\Desktop\software\materials\opencv_materials\golgeler.jpg")
row, col, hc = img.shape
# img = cv2.resize(img, (int(col / 4), int(row / 4)))
r, c, h = img.shape
print("r", r)
print("c", c)
print("h", h)

def mouse(event, x, y, flags, params):  # farede sag tusa tiklandiginda o anki koordinati donduren fonskiyon tanimlandi
    if event == cv2.EVENT_LBUTTONDOWN:  # sag tusa basilinca bos listeye koordinatlar tupple olarak gonderildi
        circles.append((x, y))
        print(x, y)
        print(circles)

cv2.namedWindow("img")  # mouse islevinin caliacagi pencere tanimlandi
cv2.setMouseCallback("img", mouse)  # pencere uzerinde mouse hareketleri

cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

print(circles)

solust = np.array([[circles[0][0], circles[0][1]]])
sagust = np.array([[circles[1][0], circles[1][1]]])
solalt = np.array([[circles[2][0], circles[2][1]]])
sagalt = np.array([[circles[3][0], circles[3][1]]])

print("solust", solust)
print("sagust", sagust)
print("solalt", solalt)
print("sagalt", sagalt)

mypoints = np.array([solust, sagust, solalt, sagalt])
print(mypoints)
mypoints = np.float32(mypoints)
pts2 = np.float32([[0, 0], [891, 0], [0, 630], [891, 630]])
matrix = cv2.getPerspectiveTransform(mypoints, pts2)

dst = cv2.warpPerspective(img, matrix, (891, 630))

cv2.imshow("dst", dst)
cv2.waitKey(0)
cv2.destroyAllWindows()


#-*- coding: utf-8 -*-
from contextlib import closing
from flask import Flask, render_template, g, url_for, redirect, request, abort
from models import Post, PostRoot
from datetime import datetime, timedelta
import time

app = Flask(__name__)
app.config.from_object('config')

def getMessage():
	heekPost = PostRoot(key_name='heek', version=2)

	query = Post.all()
	query.ancestor(heekPost)
	query.order('-datetime')

	for post in query.run(limit=1):
        	return post.text

def getSatTimedelta():
	now = datetime.now()
	sat = datetime(2017, 11, 16, 8, 40)
	interval = sat - now

	# if interval < timedelta(0):
	# 	sat = datetime(2016, 11, 17, 8, 40)
	# 	interval = sat - now

	return interval

def formatTime(interval):
	days = interval.days
	hours = interval.seconds / 60 / 60
	minutes = interval.seconds / 60 % 60
	seconds = interval.seconds % 60
	ms = interval.microseconds / 1000

	return u"%d일 %d시간 %d분 %d초 %d" % (days, hours, minutes, seconds, ms)

@app.route('/')
def index():
	msg = getMessage()

	interval = getSatTimedelta()
	time = formatTime(interval)

	blue = interval.total_seconds() / (365 * 24 * 60 * 60) * 255
	red = 255 - blue
	theme_color = '#%02x%02x%02x' % (red, blue, 0)

	return render_template('index.html',
						   entry=msg,
						   time=time,
						   theme_color=theme_color)

@app.route('/submit_entry', methods=['POST'])
def submit_entry():
	heekPost = PostRoot(key_name='heek', version=2)

	post = Post(parent=heekPost)
	post.text = request.form['message'][0:128]
	post.datetime = datetime.now()

	post.put()

	return redirect(url_for('index'))

@app.route('/history', methods=['GET'])
def history():
	show_count = 50
	startPage = int(request.args.get('page', 1))

	prevpage = startPage - 1
	if prevpage <= 0:
		prevpage = None
	nextpage = startPage + 1

	startOffset = startPage * show_count - show_count
	nextOffset = nextpage * show_count - show_count

	heekPost = PostRoot(key_name='heek', version=2)
	query = Post.all()
	query.ancestor(heekPost)
	query.order('-datetime')

	rows = [dict(text=post.text) for post in query.run(offset=startOffset, limit=show_count)]

	next_cnt = query.count(offset=nextOffset, limit=show_count)
	if next_cnt == 0:
		nextpage = None

	return render_template('history.html', contents=rows, prevpage=prevpage, nextpage=nextpage)


import rq
from datetime import datetime, timedelta
import settings
from sqlalchemy import engine
import pandas as pd
from typing import(
	Callable,
	List,
	Optional,
	Tuple
)
from . import rqu
from . import settings
from . import task
from multiprocessing import Process

def enqueue_process(func, func_input, task_name:str, log_filepath:str, queue, queue_type:str="rq"):
	"""
	enqueue the function process and save 'out' and 'error' logs to respective log file.

	Args:
		func: function to be executed
		func_input: parameters the above function needs
		log_file: path to the respective log file.
		queue_type: the type of task queue that the function is joining for execution

	Raises:
		OError if log file cannot be created

	Returns:
		a job object of the particular queue.
	"""

	metadata = {'progress': 0}
	try:
		if queue_type == "rq":
			job = queue.enqueue(func, func_input, meta=metadata)

	except OSError as exc:
		raise exc

	return(job)

def execute_job(func, func_input, log_filepath:str, job_name:str, task_name:str, now:datetime, queue, queue_type:str="rq"):
	"""
	Interface for running a job:
		-> launch a process
		-> write job execution log.

	Args:
		func: function to be executed
		func_input: parameters the above function needs
		log_file: path to the respective log file.
		job_name: name generated for the job.
		now: datetime.now()
		queue_type: the type of task queue that the function is joining for execution

	Returns:
		a job object of the particular queue.
	"""
	job = enqueue_process(func, func_input, log_filepath, queue, queue_type)
	return(job)

def schedule_process_job(func, func_input, job_name:str, task_name:str, start:datetime, interval_duration:timedelta, weekdays:Optional[List[str]], execution_frequency:str, execution_type:str, queue, queue_type:str="rq"):
	"""
	Launch a scheduler process that spawns job execution processes if launch conditions are met.
	Checks for current date. If date criterion is met -> start the process with command execution.

	Args:
		func: function to be executed
		func_input: parameters the above function needs
		job_name: name generated for the job.
		start: execution datetime.
		interval_duration: interval to wait before before scheduling the next job execution.
		weekdays: (optional) list with selected weekdays.
		execution_frequency: frequency of execution: "Interval" / "Daily"
		execution_type: type of execution schedule: is execution "Scheduled" or not.
		queue_type: the type of task queue that the function is joining for execution

	"""
	stdout_log_file = f"{settings.BASE_LOG_DIR}/{job_name}_stdout.txt"
	if execution_frequency == "Once":
		job = execute_job(func=func, func_input=func_input, log_filepath=stdout_log_file, job_name=job_name, task_name=task_name, now=datetime.now(), queue=queue, queue_type=queue_type)
		return(job)

	# If process must be executed now, decrease start date by interval timedelta:
	# this way 'match_duration' will return True in the 'process_should_execute' check.
	if execution_frequency == "Now":
		start -= interval_duration

	while True:
		now = datetime.now()
		if process_should_execute(now, start, interval_duration, weekdays):
			job = execute_job(func=func, func_input=func_input, log_filepath=stdout_log_file, job_name=job_name, task_name=task_name, now=datetime.now(), queue=queue, queue_type=queue_type)
			start += interval_duration
		else:
			time.sleep(1)

def start_scheduler_process(func, func_input, job_name:str, task_name:str, start: datetime, interval_duration:timedelta, weekdays: Optional[List[str]], execution_frequency: str, execution_type:str, queue_type:str="rq") -> (int, int):
	"""
	Run a process with the selected parameters.

	Args:
		func: function to be executed
		func_input: parameters the above function needs
		job_name: name generated for the job.
		start: execution datetime.
		interval_duration: interval to wait before before scheduling the next job execution.
		weekdays: (optional) list with selected weekdays.
		execution_frequency: frequency of execution: "Interval" / "Daily"
		execution_type: type of execution schedule: is execution "Scheduled" or not.
		queue_type: the type of task queue that the function is joining for execution

	Returns:
		ID of the started process and the job

	"""
	log_filepath = f"{settings.BASE_LOG_DIR}/{job_name}_redis_server_log.txt"
	conn, q = rq.start_redis_queue(log_filepath)
	job = schedule_process_job(func, func_input, job_name, task_name, start, interval_duration, weekdays, execution_frequency, execution_type, q, queue_type)
	process = Process(target=run_worker, kwargs=dict(conn=conn, q=q))
	process.start()
	return(q, process, job)

def submit_job(func, func_input, job_name:str, task_name:str, start:datetime, interval_duration:timedelta, weekdays:Optional[List[str]], execution_type:str, task_id:int, sql_engine:engine, queue_type:str="rq", execution_frequency:str="Once"):
	"""
	Run a process job and save related process information to an SQL alchemy file.

	Args:
		func: function to be executed
		func_input: parameters the above function needs
		job_name: name generated for the job.
		start: execution datetime.
		interval_duration: interval to wait before before scheduling the next job execution.
		weekdays: (optional) list with selected weekdays.
		execution_frequency: frequency of execution: "Interval" / "Daily"
		execution_type: type of execution schedule: is execution "Scheduled" or not.
		task_id: task ID
		sql_engine: sql engine to use for saving DF information to sql.
		queue_type: the type of task queue that the function is joining for execution

	"""
	return(start_scheduler_process(func, func_input, job_name, task_name, start, interval_duration, weekdays, execution_frequency, execution_type, queue_type))

def create_process_info_dataframe(func, func_input, job_name: str, pid: int, task_id: int) -> pd.DataFrame:
	"""
	Generate a dataframe with process information in the following format:

	{
		'task_id': [],
		'created': [],
		'process id': [],
		'job name': [],
		'task': [],
		'last update': [],
		'running': []
	}

	Args:
		func: function to be executed
		func_input: parameters the above function needs
		job_name: name generated for the job.
		pid: process ID.
		task_id: task ID.

	Returns:
		pandas DF with process related information.
	"""
	created = datetime.now()
	return pd.DataFrame(
		{
			'task_id': [task_id],
			'created': [created],
			'process id': [pid],
			'job name': [job_name],
			'task': [func.__str__()],
			'last update': [None],
			'running': [None]
		}
	)

def save_df_to_sql(df: pd.DataFrame, sql_engine: engine) -> None:
	"""
	Save dataframe with process information to a local sql alchemy DB file.
	Args:
		df: process information df.
		sql_engine:  sql alchemy engine to use.

	Raises:
		OperationalError: if any sqlalchemy errors have been thrown.
	"""
	try:
		df.to_sql("processes", con=sql_engine, if_exists="append", index=False)
	except OperationalError as exc:
		raise exc

def read_log(filename: str) -> List[str]:
	"""
	Utility function to read a logfile.

	Args:
		filename: name of the log file to be read.
	Raises:
		FileNotFoundError if respective log file is missing.

	Returns:
		list of strings, with each string representing a line.
	"""
	try:
		with open(filename, "r", encoding="utf-8") as reader:
			return reader.readlines()
	except FileNotFoundError as exc:
		raise exc

def write_job_execution_log(job_name: str, command:str, now: datetime, msg: str) -> None:
	"""
	Save job execution information to a log file.
	Args:
		func: function to be executed
		func_input: parameters the above function needs
		job_name: name of the job for which to write the log.
		now: datetime object with current timestamp.
		msg: message to be logged.

	Raises:
		OSError if log file creation fails.
	"""
	now_str = now.strftime(settings.DATE_FORMAT)
	for suffix in [".txt", "_stdout.txt"]:
		try:
			with open(f"{settings.BASE_LOG_DIR}/{job_name}{suffix}", "a") as file:
				if suffix == "_stdout.txt" and command != "":
					file.write(f"\n{'=' * 70} \n")
				file.write(f"{now_str} {msg} {command}\n")
		except OSError as exc:
			raise exc


from os import path
from setuptools import setup, find_packages

with open('requirements.txt') as reqs_file:
    requirements = reqs_file.read().splitlines()

with open('test-requirements.txt') as reqs_file:
    test_requirements = reqs_file.read().splitlines()

# Get the long description from the relevant file
long_description = 'PyDriller is a Python framework that helps developers on ' \
                   'mining software repositories. With PyDriller' \
                   ' you can easily extract information from any Git ' \
                   'repository, such as commits, developers, ' \
                   'modifications, diffs, and source codes, and ' \
                   'quickly export CSV files.'

def get_version():
    with open(path.join(path.dirname(__file__), 'pydriller', '__init__.py')) as f:
        for line in f:
            if line.startswith('__version__'):
                delim = '"' if '"' in line else "'"
                return line.split(delim)[1]
        raise RuntimeError("Unable to find version string.")

setup(
    name='PyDriller',
    description='Framework for MSR',
    long_description=long_description,
    author='Davide Spadini',
    author_email='spadini.davide@gmail.com',
    version=get_version(),
    packages=find_packages('.', exclude=['tests*']),
    url='https://github.com/ishepard/pydriller',
    license='Apache License',
    package_dir={'pydriller': 'pydriller'},
    python_requires='>=3.5',
    install_requires=requirements,
    tests_require=requirements + test_requirements,
    classifiers=[
            # How mature is this project? Common values are
            #   3 - Alpha
            #   4 - Beta
            #   5 - Production/Stable
            'Development Status :: 5 - Production/Stable',
            'Environment :: Console',
            'Intended Audience :: Developers',
            'Intended Audience :: Science/Research',
            'License :: OSI Approved :: Apache Software License',
            'Programming Language :: Python :: 3.6',
            'Programming Language :: Python :: 3.7',
            'Programming Language :: Python :: 3.8',
            'Programming Language :: Python :: 3.9',
            'Topic :: Software Development :: Libraries :: Python Modules',
            "Operating System :: OS Independent",
            "Operating System :: POSIX",
            "Operating System :: Microsoft :: Windows",
            "Operating System :: MacOS :: MacOS X",
            ]
)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 19 09:49:02 2018

@author: MarioAntao
"""
import pickle
import random
import numpy as np
import pandas as pd
class Review(object):
    """Class represents tweet from Twitter.

    Attributes:
        reviewer_id: A unique identifier.
        product_id : A unique identifier.
        ReviewTime: A date-time, describing when the review was created.
        reviewText: A string, containing the text of the review.
        overall: A float, stating the rating of the product.
        summary: A string, containing the summary of the review.
        helpful: An integer, stating the number of favorites.
        category: A list, containing the helpfulness rating of the review.
    """

    def __init__(self, reviewer_id, product_id, ReviewTime, reviewText, overall, summary, helpful, category):
        """Initialzes Review class with defined content."""
        self.reviewer_id = reviewer_id
        self.product_id = product_id
        self.ReviewTime = ReviewTime
        self.reviewText = reviewText
        self.overall = overall
        self.summary = summary
        self.helpful = helpful
        self.category = category
        self.cleaning_log = dict()
    def __str__(self):
        """Creates user-friendly string representation of review."""

        return "reviewer_id: {}\nProduct_id: {}\nReviewTime: {}\nreviewText: {}\noverall: {}\nsummary: {}\nhelpful: {}\ncategory: {}".\
            format(self.reviewer_id, self.product_id, self.ReviewTime, self.reviewText, self.overall,
                   self.summary, self.helpful, self.category)

    def __eq__(self, other):
        """
        Determines if review is equal to other review.

        Compares the reviewer_id value. Returns True if reviewer_ids are equal.
        """
        return self.reviewer_id == other.reviewer_id

    def __hash__(self):
        """
        Returns a unique hash value.
        """
        return hash(self.reviewer_id)

    def count_number_of_words(self):
        """
        Counts the words in the review.

        Retrieves the text from the week_3.tweet, splits it by spaces and counts
        the length of the list.

        Returns:
            An interger value, corresponding to the number of words in the week_3.tweet.
        """
        word_list = self.reviewText.split()
        return len(word_list)

def create_review_from_dict(review_dict):
    """
    Creates a review object from dictionary.

    Extracts reviewer_id, helpful, reviewText, overall,
    summary,unixReviewTime, product_id and category from dictionary.

    Args:
        review_dict: A dictionary, containing review information.

    Returns:
        A review object.
    """

    # Extract parameters from dictionary
    reviewer_id = review_dict.get('reviewer_id')
    helpful = review_dict.get('helpful')
    reviewText = review_dict.get('reviewText')
    overall = review_dict.get('overall')
    summary = review_dict.get('summary')
    ReviewTime = review_dict.get('unixReviewTime')
    category = review_dict.get('category')
    product_id = review_dict.get('product_id')

    # Create review object
    review = Review(reviewer_id, product_id, ReviewTime, reviewText, overall, summary, helpful, category)

    return review

def make_review_set(filename):
    """
    Creates set of tweets from week_3.data/01_raw/trump_tweets.json.
    Returns:
        Set of week_3.tweet objects.
    """

    # Create set and review.Review objects.
    review_set = set()

    for revieww in sample_review:
        review = create_review_from_dict(revieww)
        review_set.add(review)

    return review_set

import pickle
import pandas as pd

merged_dic=pd.read_pickle('merged_dic.pickle')

sample_review=random.sample(merged_dic,1000)

review_set=make_review_set(merged_dic)

review_train_set=make_review_set(review_train)
review_test_set=make_review_set(review_test)

review_sample_set=make_review_set(sample_review)

l= list(review_train_set)

from sklearn.cross_validation import train_test_split

review_train,review_test=train_test_split(merged_dic,test_size=0.3)

"""Export Data with pickle"""
with open('review_test_set.pickle', 'wb') as handle:
    pickle.dump(review_test_set, handle, protocol=pickle.HIGHEST_PROTOCOL)

"""Export Data with pickle"""
with open('merged_test.pickle', 'wb') as handle:
    pickle.dump(merged_test, handle, protocol=pickle.HIGHEST_PROTOCOL)

review_test_set=pd.read_pickle('review_test_set.pickle')
review_train_set=pd.read_pickle('review_train_set.pickle')
review_sample_set=pd.read_pickle('review_sample_set.pickle')

calculate_average_reviews_per_day(review_sample_set)

calculate_average_word_count(review_test_set)

get_top_mentions(review_set)

review_sample_set['overall']

#Convert set to List
test_list = list(review_sample_set)

#Flat List
test_list = [" ".join(item) for Review in test_list for item in Review.text_cleaned]

flat_list = [item for sublist in test_list for item in sublist]
#Merge List String

test_list_merge = ' '.join([word for word in review_sample_list])


from PIL import ImageFont, ImageDraw
import PIL
import datetime
import os
import tkinter
from tkinter import filedialog, messagebox

class Application:

    def __init__(self):

        self.date_font = ImageFont.truetype('./conf/OpenSans-Bold.ttf', 150) # ustawienie czcionki dla daty

        self.okno = tkinter.Tk()  # tworzenie okna głównego
        self.okno.geometry("600x200") # ustawienie wymiarów okna
        self.okno.title("Date2JPG")  # ustawienie tytułu okna głównego

        self.naglowek = tkinter.Label(self.okno, text = "Program nanosi na zdjęcie datę wyciągniętą z jego EXIF.\n"
                                                        "Zdjęcia są pobierane z katalogu źródłowego i po naniesieniu\n"
                                                        "daty zapisywane w katalogu docelowym.\n")
        self.naglowek.pack()

        self.kz = os.getcwd()  # katalog źródłowy
        self.kd = os.getcwd()  # katalog docelowy

        self.ramka1 = tkinter.Frame(self.okno)
        self.ramka1.pack(fill=tkinter.BOTH, expand=True)

        self.wkz_button = tkinter.Button(self.ramka1, width=20, text="Wybierz katalog źródłowy:",
                                    command=self.wybierz_katalog_zrodlowy)
        self.wkz_button.pack(side=tkinter.LEFT)
        self.wkz_label = tkinter.Label(self.ramka1, text=self.kz)
        self.wkz_label.pack(side=tkinter.LEFT)

        self.ramka2 = tkinter.Frame(self.okno)
        self.ramka2.pack(fill=tkinter.BOTH, expand=True)

        self.wkd_button = tkinter.Button(self.ramka2, width=20, text="Wybierz katalog docelowy:",
                                    command=self.wybierz_katalog_docelowy)
        self.wkd_button.pack(side=tkinter.LEFT)

        self.wkd_label = tkinter.Label(self.ramka2, text=self.kd)
        self.wkd_label.pack(side=tkinter.LEFT)

        self.ramka3 = tkinter.Frame(self.okno)
        self.ramka3.pack(fill=tkinter.BOTH, expand=True)

        self.uruchom_button = tkinter.Button(self.ramka3, width=20, text="Uruchom!",
                                    command=self.wykonaj_dzialania)
        self.uruchom_button.pack(side=tkinter.LEFT)

        self.uruchom_label = tkinter.Label(self.ramka3, text="")
        self.uruchom_label.pack(side=tkinter.LEFT)

        self.etykieta = tkinter.Label(self.okno, text="by AdrianSo")
        self.etykieta.pack()

        self.okno.mainloop()

    def wybierz_katalog_zrodlowy(self):

        katalog = tkinter.filedialog.askdirectory()
        if katalog:
            self.kz = katalog
            self.wkz_label.configure(text=self.kz)

    def wybierz_katalog_docelowy(self):

        katalog = tkinter.filedialog.askdirectory()
        if katalog:
            self.kd = katalog
            self.wkd_label.configure(text=self.kd)

    def wykonaj_dzialania(self):

        if self.kd == self.kz:
            tkinter.messagebox.showinfo("Info", "Katalog docelowy musi być inny niż źródłowy.")  # info o błędzie
            return
        else:
            lista = list(os.listdir(self.kz))
            lista.sort()
            for i in lista:
                if os.path.isfile("{}/{}".format(self.kz,i)) and os.path.splitext(i)[1].upper()[1:] == "JPG":
                    self.uruchom_label.configure(text = "Przetwarzam {}".format(i))
                    self.uruchom_label.update_idletasks()
                    self.date2img(i)
                self.uruchom_label.configure(text = "Skończyłem przetwarzać")

    def date2img(self,i):

        # otwieranie zdjęcia i konwertowanie do RGBA

        self.img = PIL.Image.open("{}/{}".format(self.kz,i)).convert("RGBA")

        # wyciąganie daty z EXIF zdjęcia i formatowanie jej

        self.img_exif = dict(self.img.getexif())
        self.img_date = str(self.img_exif[36867])
        self.img_date_obj = datetime.datetime.strptime(self.img_date, "%Y:%m:%d %H:%M:%S")
        self.img_date_obj = self.img_date_obj.strftime("%d-%m-%Y")

        # tworzenie obrazu z datą

        self.img_text = PIL.Image.new('RGBA', self.img.size, (255, 255, 255, 0))
        self.img_text_draw = PIL.ImageDraw.Draw(self.img_text)
        self.img_text_draw.text(
            (self.img.size[0] - 1000,
            self.img.size[1] - 300),
            self.img_date_obj,
            font=self.date_font,
            fill=(255, 255, 255, 255)
        )

        # łączenie zdjęcia z obrazem z datą i konwertowanie do RGB

        self.img_with_date = PIL.Image.alpha_composite(self.img, self.img_text).convert("RGB")

        # zapisywanie zdjęcia z datą

        self.img_with_date.save("{}/{}".format(self.kd,i), quality=98)

app = Application()


import cv2
import os

face_cascade = cv2.CascadeClassifier("C:/Users/bhara/AppData/Local/Programs/Python/Python311/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml")
cap = cv2.VideoCapture(0)

person_name = input("Enter the name of the person: ")
save_path = f'./dataset/{person_name}'

if not os.path.exists(save_path):
    os.makedirs(save_path)

count = 0
while True:
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
        count += 1

        # Save the captured image into the datasets folder
        cv2.imwrite(f"{save_path}/User_{str(count)}.jpg", gray[y:y+h, x:x+w])

    cv2.imshow('Image Capture', frame)

    # Break when 100 images have been captured
    if cv2.waitKey(1) & 0xFF == ord('q') or count >= 100:
        break

cap.release()
cv2.destroyAllWindows()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import tensorflow as tf
import io, time
import framework.tools as tools

# =============================================================================
# Target BPE
# Embedding: Feed forward
# Emission: Bi-LSTM
# Transition: Bi-LSTM
# =============================================================================

#==============================================================================
# Extra vocabulary BPE symbols
unk_token_bpe = 0
start_token_bpe = 1
end_token_bpe = 2
#==============================================================================
from model.model_hmm_based.model_hmm import Model

class Model(Model):

    def __init__(self, FLAGS, session, log):

        super(Model, self).__init__(FLAGS, session, log)

    def build_model(self):
        self.get_reference_BPE_idx()

        self.initialize_transition_parameter_nn()

        self.build_optimizer()
        self.build_initializer()

        self.build_word_model_placeholders()

        self.build_emission()
        self.build_transition()
        self.build_forward_backward_nn()

        self.build_update_emission()
        self.build_update_transition()

# =============================================================================
#
# =============================================================================

    def build_word_model_placeholders(self):

        self.sources = tf.placeholder(dtype=self.tf_int_dtype,
                                      shape=(None,None),
                                      name='sources')

        self.targets = tf.placeholder(dtype=self.tf_int_dtype,
                                      shape=(None,None),
                                      name='targets')

        self.source_lengths = tf.placeholder(dtype=self.tf_int_dtype,
                                             shape=(None),
                                             name='source_lengths')

        self.target_lengths = tf.placeholder(dtype=self.tf_int_dtype,
                                             shape=(None),
                                             name='target_lengths')

        self.targets_null = tf.placeholder(dtype=self.tf_int_dtype,
                                          shape=(1),
                                          name='targets_null')

    def assign_variable_training_transition(self):
        self.assign_variable_training_transition_()

# =============================================================================
#
# =============================================================================

    def get_emission(self):
        # NN parameters Null
        target_embedding= tf.get_variable(name='targetEmbedding',
                                                shape=[self.FLAGS.target_vocabulary_size,
                                                       self.FLAGS.embedding_size],
                                                initializer=self.initializer,
                                                dtype=self.tf_float_dtype)

        target_embedded_null = tf.nn.embedding_lookup(params=target_embedding,
                                                      ids=self.targets_null)

        target_embedded_word = tf.nn.embedding_lookup(params=target_embedding,
                                                      ids=self.targets)

        nnLayer = tf.layers.Dense(units=self.FLAGS.hidden_units,
                                    activation=tf.nn.tanh,
                                    use_bias=True,
                                    name='nnLayer')

        target_state_null = nnLayer(target_embedded_null)

        lstm_cell_fw = tf.contrib.rnn.LSTMCell(num_units=self.FLAGS.hidden_units)
        lstm_cell_bw = tf.contrib.rnn.LSTMCell(num_units=self.FLAGS.hidden_units)

        with tf.variable_scope('lstmTarget'):

                (output_fw, output_bw),\
                (output_state_fw, output_state_bw) = \
                tf.nn.bidirectional_dynamic_rnn(cell_fw=lstm_cell_fw,
                                                cell_bw=lstm_cell_bw,
                                                inputs=target_embedded_word,
                                                sequence_length=self.target_lengths,
                                                dtype=self.tf_float_dtype)

                target_state = tf.concat([output_fw, output_bw], axis=2)

                nnLayer_lstm = tf.layers.Dense(units=self.FLAGS.hidden_units,
                                    activation=None,
                                    use_bias=False,
                                    name='nnLayerLSTM')

                target_state = nnLayer_lstm(target_state)

        #----------------------------------------------------------------------
        #target_state = nnLayer(target_state)

        target_state = tf.nn.dropout(x=target_state,
                                       keep_prob=self.keep_prob,
                                       name='nnDropoutNonNull')

        target_state_null = tf.nn.dropout(x=target_state_null,
                                       keep_prob=self.keep_prob,
                                       name='nnDropoutNull')

        nnLayerVocabulary = tf.layers.Dense(units=self.FLAGS.source_vocabulary_size,
                                 name='nnLayerVocabulary')

        target_state = nnLayerVocabulary(target_state)
        target_state_null = nnLayerVocabulary(target_state_null)

        target_state = tf.nn.softmax(target_state)
        self.target_state_null = tf.nn.softmax(target_state_null)

        input_scan = (target_state, self.sources)

        def get_source(value):
            target_state = value[0]
            sources = value[1]

            target_state = tf.gather(target_state, sources, axis=-1)
            target_state_null = tf.gather(self.target_state_null, sources, axis=-1)

            target_state_null = tf.tile(target_state_null, [tf.shape(target_state)[0], 1])

            emission_prob = tf.concat([target_state, target_state_null], axis=0)

            return emission_prob, 0

        emission_prob, _ = tf.map_fn(get_source,input_scan, dtype=(self.tf_float_dtype,
                                                                       tf.int32))

        return emission_prob

    def get_transition(self):
        # NN parameters Null
        target_embedding= tf.get_variable(name='targetEmbedding',
                                                shape=[self.FLAGS.target_vocabulary_size,
                                                       self.FLAGS.embedding_size],
                                                initializer=self.initializer,
                                                dtype=self.tf_float_dtype)

        target_embedded_null = tf.nn.embedding_lookup(params=target_embedding,
                                                      ids=self.targets_null)

        target_embedded_word = tf.nn.embedding_lookup(params=target_embedding,
                                                      ids=self.targets)

        nnLayer = tf.layers.Dense(units=self.FLAGS.hidden_units,
                                    activation=tf.nn.tanh,
                                    use_bias=True,
                                    name='nnLayer')

        target_state_null = nnLayer(target_embedded_null)

        lstm_cell_fw = tf.contrib.rnn.LSTMCell(num_units=self.FLAGS.hidden_units)
        lstm_cell_bw = tf.contrib.rnn.LSTMCell(num_units=self.FLAGS.hidden_units)

        with tf.variable_scope('lstmTarget'):

                (output_fw, output_bw),\
                (output_state_fw, output_state_bw) = \
                tf.nn.bidirectional_dynamic_rnn(cell_fw=lstm_cell_fw,
                                                cell_bw=lstm_cell_bw,
                                                inputs=target_embedded_word,
                                                sequence_length=self.target_lengths,
                                                dtype=self.tf_float_dtype)

                target_state = tf.concat([output_fw, output_bw], axis=2)

                nnLayer_lstm = tf.layers.Dense(units=self.FLAGS.embedding_size,
                                    activation=None,
                                    use_bias=False,
                                    name='nnLayerLSTM')

                target_state = nnLayer_lstm(target_state)

        #----------------------------------------------------------------------
        target_state = nnLayer(target_state)

        target_state = tf.nn.dropout(x=target_state,
                                       keep_prob=self.keep_prob,
                                       name='nnDropoutNonNull')

        target_state_null = tf.nn.dropout(x=target_state_null,
                                       keep_prob=self.keep_prob,
                                       name='nnDropoutNull')

        nnLayerJumpWidth = tf.layers.Dense(units=self.size_jump_width_set_nn,
                                 name='nnLayerJumpWidth')

        jump_width = nnLayerJumpWidth(target_state)
        jump_width_prob = tf.nn.softmax(jump_width)

        nnLayerP0 = tf.layers.Dense(units=1,activation=tf.nn.sigmoid,
                                            name='nnLayerP0')

        p0 = tf.squeeze(nnLayerP0(target_state), axis=-1)

        self.length_target = tf.shape(self.targets)[1]
        def get_jump_width_word(value):
            jump_width = value[0]
            sentence_length = value[1]
            word_idx = value[2]
            jump_width_idx = tf.range(self.max_jump_width-word_idx,
                                      self.max_jump_width+sentence_length-word_idx)
            return tf.gather(jump_width, jump_width_idx),jump_width_idx,0

        def get_jump_width_sentence(value):
            jump_width = value[0]
            p0 = value[1]
            sentence_length = tf.ones([self.length_target],
                                      dtype=tf.int32)*self.length_target
            word_idx = tf.range(0,self.length_target)
            input_scan = (jump_width, sentence_length, word_idx)
            jump_width_word,jump_width_idx,_ = tf.map_fn(get_jump_width_word,
                                        input_scan,
                                        (self.tf_float_dtype, tf.int32,tf.int32))

            transition = tf.concat([jump_width_word, tf.diag(p0)], axis=1)
            transition = tf.concat([transition, transition], axis=0)

            transition_log = tf.concat([tf.log(jump_width_word), tf.diag(tf.log(p0))], axis=1)
            transition_log = tf.concat([transition_log, transition_log], axis=0)
            return transition, transition_log

        transition, transition_log = tf.map_fn(get_jump_width_sentence, (jump_width_prob, p0), (self.tf_float_dtype, self.tf_float_dtype) )

        return transition, transition_log

    def train_batch(self,
                  sources,
                  source_lengths,
                  targets,
                  targets_null,
                  target_lengths):

        input_feed = {}
        input_feed[self.keep_prob.name] = self.FLAGS.keep_prob
        input_feed[self.sources.name] = sources
        input_feed[self.targets.name] = targets
        input_feed[self.source_lengths.name] = source_lengths
        input_feed[self.target_lengths.name] = target_lengths

        input_feed[self.targets_null.name] = targets_null

        output_feed = [self.updates_emission,
                       self.cost_emission,
                       self.updates_transition,
                       self.cost_transition
                       ]

        outputs = self.sess.run(output_feed, input_feed)

        cost = outputs[1] + outputs[3]

        return cost

    def eval(self,
             sources,
             source_lengths,
             targets,
             targets_null,
             target_lengths):

        target_length = target_lengths[0]
        source_length = source_lengths[0]
        source = sources[0][:source_length]

        input_feed = {}
        input_feed[self.keep_prob.name] = 1.0
        input_feed[self.sources.name] = sources
        input_feed[self.targets.name] = targets
        input_feed[self.source_lengths.name] = source_lengths
        input_feed[self.target_lengths.name] = target_lengths

        input_feed[self.targets_null.name] = targets_null

        output_feed = [self.emission_prob,
                       self.transition_prob]
        #----------------------------------------------------------------------
        outputs = self.sess.run(output_feed, input_feed)

        emission_final = np.array(outputs[0][0])
        transition_final = np.array(outputs[1][0])

        initial_transition, transition = self.get_transition_evaluation_nn(transition_final,
                                                                        target_length)

        state_seq, likelihood_seq = self.viterbi(np.array(source),
                                        target_length*2,
                                        initial_transition,
                                        transition,
                                        emission_final)

        return [state_seq], [likelihood_seq], [emission_final]

# =============================================================================
#
# =============================================================================

    def prepare_batch(self, seqs_x, seqs_y):

        x_lengths = np.array([len(s) for s in seqs_x])
        y_lengths = np.array([len(s) for s in seqs_y])
        x_lengths_max = np.max(x_lengths)
        y_lengths_max = np.max(y_lengths)

        self.batch_size = len(seqs_x)
        self.update_freq = len(seqs_x)

        y_null = [self.FLAGS.target_vocabulary_size - 1]

        word_x = np.ones((self.batch_size,
                     x_lengths_max),
                    dtype=self.int_dtype) * end_token_bpe

        word_x_lengths = np.ones((self.batch_size),
                                    dtype=self.int_dtype)

        word_y = np.ones((self.batch_size,
                     y_lengths_max),
                    dtype=self.int_dtype) * end_token_bpe

        word_y_lengths = np.ones((self.batch_size),
                                    dtype=self.int_dtype)

        for idx, s_x in enumerate(seqs_x):
            word_x[idx, :x_lengths[idx]] = s_x
            word_x_lengths[idx] = x_lengths[idx]

        for idx, s_y in enumerate(seqs_y):
            word_y[idx, :y_lengths[idx]] = s_y
            word_y_lengths[idx] = y_lengths[idx]

        return word_x, word_x_lengths, word_y, y_null, word_y_lengths

# =============================================================================
#
# =============================================================================

    def train(self):
        # Training loop
        self.log.info('TRAINING %s', tools.get_time_now())

        self.evaluate()
        for epoch_idx in range(self.FLAGS.max_epochs):
            self.log.info('----------------')
            if self.global_epoch_step.eval() >= self.FLAGS.max_epochs:
                self.log.info('Training is complete. Reach the max epoch number: %d ', self.global_epoch_step.eval())
                break

            for train_seq in self.train_set:
                start_time = time.time()
                batch = self.prepare_batch(*train_seq)
                update_info = self.train_batch(*batch)

                self.print_log(update_info, start_time)

                self.evaluate()
                self.save_model()

                # Update emission fixed parameters for each batch, emission_update_freq < 0:
                if self.emission_update_freq < 0 and \
                self.global_step.eval() % self.emission_update_freq == 0:
                    self.assign_variable_training_emission()

                # Update transition discrete parameters for each batch, jump_width_update_freq < 0:
                if self.jump_width_update_freq < 0 and \
                self.global_step.eval() % self.jump_width_update_freq == 0:
                    self.assign_variable_training_transition()

            # Update emission fixed parameters for each epoch, emission_update_freq > 0:
            if self.emission_update_freq > 0 and \
            self.global_step.eval() % self.emission_update_freq == 0:
                self.assign_variable_training_emission()

            # Update transition discrete parameters for each epoch, jump_width_update_freq > 0:
            if self.jump_width_update_freq > 0 and \
            self.global_step.eval() % self.jump_width_update_freq == 0:
                self.assign_variable_training_transition()

            #------------------------------------------------------------------
            #------------------------------------------------------------------
            # Increase the epoch index of the model
            self.log.info('Epoch %d done at %s',
                          self.global_epoch_step.eval(),
                          tools.get_time_now())
            self.global_epoch_step_op.eval()

    def evaluate(self):
        # Execute a validation step
        if self.FLAGS.valid_freq!= 0 and self.global_step.eval() % self.FLAGS.valid_freq == 0:
            start_time = time.time()

            #------------------------------------------------------------------
            #------------------------------------------------------------------

            alignment_set = []
            likelihood_set = []
            emission_set = []

            for valid_seq in self.valid_set:
                batch = self.prepare_batch(*valid_seq)
                eval_info = self.eval(*batch)

                #--------------------------------------------------------------

                for idx in range(1):
                    source_length = batch[1][idx]
                    target_length = batch[4][idx]
                    alignment = []
                    for index_source, index_target in enumerate(eval_info[0][idx]):
                        if index_source < source_length and index_target < target_length:
                            # Check alignment reference: Start from 0 or 1 ?
                            alignment.append(str(index_source+self.evaluate_alignment_start_from) \
                            + "-" + str(index_target+self.evaluate_alignment_start_from))
                            #alignment.append(str(index_source) + "-" + str(index_target))

                    alignment_set.append(alignment)

                likelihood_set.append(eval_info[1])
                emission_set.append(eval_info[2])

            alignment_set = self.converse_BPE_to_word(alignment_set)

            AER = self.calculate_AER(alignment_set)
            likelihood_score = np.mean(likelihood_set)

            self.log.info('VALIDATION: Epoch %d , Step %d , Likelihood: %.10f , AER: %.5f in %ds at %s',
                          self.global_epoch_step.eval(),
                          self.global_step.eval() ,
                          likelihood_score,
                          AER,
                          time.time() - start_time,
                          tools.get_time_now())

            if AER < self.best_AER:
                with io.open(self.get_file_path('result'), 'w') as file_handler:
                    for sent_alignment in alignment_set:
                        sent_alignment = u'{}\n'.format(sent_alignment)
                        sent_alignment = sent_alignment.replace('[','')
                        sent_alignment = sent_alignment.replace(']','')
                        sent_alignment = sent_alignment.replace(',','')
                        sent_alignment = sent_alignment.replace('\'','')
                        file_handler.write(sent_alignment)

            self.start_time = time.time()

# =============================================================================
#
# =============================================================================

    def get_reference_BPE_idx(self):
        source_idx_batch = []
        target_idx_batch = []

        source_file = open(self.FLAGS.source_idx_data)
        source_lines = source_file.readlines()

        target_file = open(self.FLAGS.target_idx_data)
        target_lines = target_file.readlines()

        for i in source_lines:
            source_idx_batch.append(i.split())

        for i in target_lines:
            target_idx_batch.append(i.split())

        self.source_idx_batch = source_idx_batch
        self.target_idx_batch = target_idx_batch

    def converse_BPE_to_word(self, alignment_set):
        word_alignments = []
        for subword_alignment, ref_s, ref_t in zip(alignment_set, self.source_idx_batch, self.target_idx_batch):
            word_alignment = []
            for subword in subword_alignment:
                subword_src = subword.split('-')[0]
                subword_tgt = subword.split('-')[1]
                word_src = 0
                word_tgt = 0
                for s in ref_s:
                    word_src_ref = s.split('-')[0]
                    subword_src_ref = s.split('-')[1]
                    if subword_src == subword_src_ref:
                        word_src = word_src_ref
                for t in ref_t:
                    word_tgt_ref = t.split('-')[0]
                    subword_tgt_ref = t.split('-')[1]
                    if subword_tgt == subword_tgt_ref:
                        word_tgt = word_tgt_ref
                if word_src + '-'+ word_tgt not in word_alignment:
                    word_alignment.append(word_src + '-'+word_tgt)
            word_alignments.append(word_alignment)

        return word_alignments

# =============================================================================
#
# =============================================================================

    def print_model_info(self):
        self.log.info('Source word vocabulary size: %s', self.FLAGS.source_vocabulary_size)
        self.log.info('Target word vocabulary size: %s', self.FLAGS.target_vocabulary_size)
        self.log.info('Word hidden units: %s', self.FLAGS.hidden_units)
        self.log.info('Word embedding size: %s', self.FLAGS.embedding_size)


import sys
from urllib import urlencode

# Zope imports
from AccessControl import ClassSecurityInfo
from AccessControl.Permissions import view
from DocumentTemplate.sequence import sort
from Globals import InitializeClass
from OFS.Folder import Folder
import Products
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from zLOG import LOG, DEBUG

# Naaya imports
from Products.NaayaBase.constants import MESSAGE_SAVEDCHANGES, \
                                         PERMISSION_EDIT_OBJECTS
from Products.NaayaCore.managers.utils import slugify, genRandomId, genObjectId
from naaya.i18n.LocalPropertyManager import LocalPropertyManager, LocalProperty

import statistics
from statistics.BaseStatistic import manage_addStatistic

STATISTICS = dict([(statistic.meta_type, statistic) for statistic in statistics.AVAILABLE_STATISTICS])

def manage_addSurveyReport(context, id="", title="", REQUEST=None, **kwargs):
    """
    ZMI method that creates an object of this type.
    """
    if not id:
        id = slugify(title)

    idSuffix = ''
    while id+idSuffix in context.objectIds():
        idSuffix = genRandomId(p_length=4)
    id = id + idSuffix

    # Get selected language
    lang = REQUEST and REQUEST.form.get('lang', None)
    lang = lang or kwargs.get('lang', context.gl_get_selected_language())

    ob = SurveyReport(id, lang=lang, title=title)
    context.gl_add_languages(ob)
    context._setObject(id, ob)
    if REQUEST is not None:
        context.manage_main(context, REQUEST, update_menu=1)
    return id

class SurveyReport(Folder, LocalPropertyManager):
    """Survey Report"""

    meta_type = 'Naaya Survey Report'

    manage_options=(
        {'label':'Contents', 'action':'manage_main',
         'help':('OFSP','ObjectManager_Contents.stx')},
        {'label':'View', 'action':'index_html'},
        {'label':'Security', 'action':'manage_access',
         'help':('OFSP', 'Security.stx')},
        )

    _constructors = (manage_addSurveyReport,)

    _properties=()

    icon = 'misc_/NaayaSurvey/NySurveyReport.gif'

    security = ClassSecurityInfo()

    title = LocalProperty('title')
    description = LocalProperty('description')

    def __init__(self, id, lang=None, **kwargs):
        Folder.__init__(self, id=id)
        self.set_localproperty('title', 'string', lang)
        self.set_localproperty('description', 'text', lang)
        self.saveProperties(lang=lang, **kwargs)

    #
    # global methods used in naaya site context
    #
    def _object_add_language(self, language, **kwargs):
        for doc in self.objectValues():
            doc.add_language(language)

    def _object_del_language(self, language, **kwargs):
        for doc in self.objectValues():
            doc.del_language(language)

    #
    # Self edit methods
    #
    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'saveProperties')
    def saveProperties(self, REQUEST=None, **kwargs):
        """Update properties"""
        if REQUEST:
            kwargs.update(REQUEST.form)
        local_properties = self.getLocalProperties()
        local_properties = filter(None, [x.get('id', None) for x in local_properties])
        # Update local properties
        lang = kwargs.get('lang', self.get_selected_language())
        for local_property in local_properties:
            prop_value = kwargs.get(local_property, '')
            self.set_localpropvalue(local_property, lang, prop_value)
        kwargs = dict([(key, value) for key, value in kwargs.items()
                       if key not in local_properties])
        self.manage_changeProperties(**kwargs)
        if REQUEST:
            query = {'lang': lang}
            query = urlencode(query)
            REQUEST.RESPONSE.redirect('%s/edit_html?%s' % (self.absolute_url(), query))
        return True

    security.declareProtected(view, 'getStatistics')
    def getStatistics(self):
        """Return the statistics"""
        return self.objectValues()

    #security.declareProtected(view, 'getSortedStatistics')
    security.declarePublic('getSortedStatistics')
    def getSortedStatistics(self, sort_by='sortorder'):
        """Return the statistics in sorted order"""
        return sort(self.getStatistics(), ((sort_by, 'cmp', 'asc'), ))

    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'deleteStatistics')
    def addStatistic(self, REQUEST, question=None, meta_type=None):
        """Add a statistic for question.

            @param question: id of the question
            @param meta_type: metatype of the statistic
        """
        err = []
        if not question:
            err.append('Please select a question')
        if not meta_type:
            err.append('Please select a statistic type')
        if err:
            self.setSessionErrorsTrans(err)
            return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)

        statistic_cls = STATISTICS[meta_type]
        question = self.getWidget(question)
        try:
            return manage_addStatistic(statistic_cls,
                                       self,
                                       genObjectId(question.title),
                                       question=question,
                                       REQUEST=REQUEST)
        except TypeError:
            if not REQUEST:
                raise
            err = sys.exc_info()
            LOG('NaayaSurvey.statistics.manage_addStatistic', DEBUG,
                'Error creating statistic %s for question %s' % (statistic_cls, question.absolute_url()), error=err)
            self.setSessionErrorsTrans('"${meta_label}" can\'t be used for question "${title}"',
                meta_label=statistic_cls.meta_label, title=question.title)
            return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)

    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'deleteStatistics')
    def deleteStatistics(self, ids=[], REQUEST=None):
        """ Delete statistics by ids"""
        if not ids:
            self.setSessionErrorsTrans('Please select one or more items to delete.')
        else:
            try: self.manage_delObjects(ids)
            except: self.setSessionErrorsTrans('Error while deleting data.')
            else: self.setSessionInfoTrans('Item(s) deleted.')
        REQUEST.RESPONSE.redirect('%s/index_html' % self.absolute_url())

    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'setSortOrder')
    def setSortOrder(self, order={}, REQUEST=None):
        """Set the order of the statistics"""
        if REQUEST:
            order.update(REQUEST.form)
        for id, neworder in order.items():
            ob = self._getOb(id, None)
            if id not in self.objectIds():
                continue
            ob.sortorder = neworder
        if REQUEST:
            self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES, date=self.utGetTodayDate())
            return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)

    def getAvailableStatistics(self):
        """Return the available statistics"""
        return statistics.AVAILABLE_STATISTICS

    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'index_html')
    index_html = PageTemplateFile('zpt/surveyreport_index', globals())

    security.declareProtected(view, 'edit_html')
    edit_html = PageTemplateFile('zpt/surveyreport_edit', globals())

    security.declareProtected(view, 'view_report_html')
    view_report_html = PageTemplateFile('zpt/surveyreport_view_report', globals())

InitializeClass(SurveyReport)


import os
import discord
import random
from discord.ext import commands
import asyncio
from datetime import datetime
from dotenv import load_dotenv
import traceback
from discord.ext import tasks
import json

class jsonfile(object):
	"""docstring for jsonfile"""

	def __init__(self, file:str = "0"): #file is an actual argument
		super(jsonfile, self).__init__() #idk what this does but i feel like it might break if i remove
		self.file = file #makes the argument file a class var

		if file == "0": #alternate option to make it not write to file and reset on shutdown
			self.data = {} #sets the data class var up

		else: #if a file was input
			try: #attempts to load said file (will always fail if the file doesnt exist..yet)
				with open(self.file) as file: #attempts to load the file that was inputted
					self.data = json.load(file) # parses the JSON data in the file and returns a dictionary assigned to class var data
			except: #if the file doesnt exist yet
				try:
					file = file.name #IODataWrapper preventer
				except:
					file = file #throwaway except function so that except runs something

				self.data = {"null": 1} #still makes sure data exists to not error out
				self.write(self.data) #invokes the local write function to write out the file
		self.timer = {"null": 1} #initilizes the timer class var

	#overrides the json with input
	def write(self, input):
		if self.file != "0": #checks if a file was input
			with open(self.file, "w") as file: #opens up the file for writing
				file.write(json.dumps(input, indent=4)) # formats and beautifies the JSON as a string and overwrites the file contents with it
		self.data = input #updates the data var to make sure its uptodate\

	#local timer funct

	#editing function
	def edit(self, entry:str, inp):
		self.data[entry] = inp #replaces the <entry> with input
		self.update() #invokes write function

	#a simpler version of write that just writes the current state of data to the file
	def update(self):
		self.write(self.data) #write function invoked

	def append(self, inp):
		self.data[len(self.data)] = inp
		self.update()

intents = discord.Intents.default() #sets up the intents obj
intents.members = True #flips the member inperwhatever it is to true

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN') #retrieves the stuff needed from a *hidden* env file yall aint gettin

bot = commands.Bot(command_prefix='am!', intents=intents) #initilizes the bot
#bot.obj = [] #initilizes list of games
bot.obj = jsonfile('games.json')

#flavorie text to make sure its working good
@bot.event
async def on_ready(): #initilization

    guild = discord.utils.get(bot.guilds, name='bot tester') #gets the guild that i put in to kinda add some flavor text

    print(discord.utils.get(bot.guilds))

    print(
    	f'{bot.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

    await bot.change_presence(activity=discord.Game(name='amogus bot :)')) #:)

#the react-to-join section
@bot.event
async def on_reaction_add(reaction, user):
	y = {} #initilizes a dict
	for x in range(len(bot.obj.data)): #for every entry in bot.obj (counting 0 - num)
		y[bot.obj.data[x]] = bot.obj.data[x].latestmsg #store the key of the instance as the latest message of it

	if user != bot.user and reaction.emoji == u"\U0001F44D" and reaction.message in y.values(): #if not bot and reaction is thumbs up and the message is correct
		for key, value in y.items(): #for every single entry in the dictionary
			if reaction.message == value: #if the message is the same as the value
				obj = key #stores the correct instance into obj
		ctx = await bot.get_context(reaction.message) #obtains the ctx from the message sent
		await obj.add_user(ctx, user) #adds the user to the obj it belongs to

''' testing stuff
@bot.command(name='test')
async def react(ctx):
	bot.reactmsg = ctx.message
	bot.ogmsg = await ctx.send('reaction msg')
	await bot.ogmsg.add_reaction(u"\U0001F44D") #thumbs up

@bot.command(name='add')
async def add(ctx, game=0):
	game = bot.obj[game]
	await game.add_user(ctx, ctx.author)
'''

#initilizes a new instance of the game class
@bot.command(name='init')
async def init(ctx, name, code):
	bot.obj.append(gameobj(ctx, name, code)) #appends an instance to bot.obj

''' another testing thing bc im lonely
@bot.command(name='fill')
async def fill(ctx):
	for x in {"user1#9833", "user2#2383", "user3#9742", "user4#8269", "user5#1048", "user6#7862", "user7#3452", "user8#3821", "user9#3490"}:
		await bot.obj[0].add_user(ctx, x)
'''

#listing command (both overall and individual)
@bot.command(name='list')
async def list(ctx, game = -1):

	try:
		msg = 'Game listing: \n\n' #nice little flavoring text

		if game == -1 and len(bot.obj.data) > 1: #if the game var was not provided and there is more than one instance
			for x in range(len(bot.obj.data)): #for the number of entries in bot.obj
				game = bot.obj.data[x] #stores the instance of the thing
				msg += f'<game {x}>, <name \'{game.name}\'>, <players {len(game.active)}/{len(game.wait)}>, <code \'{game.code}\'>\n' #flavor text and informacione
			await ctx.send(msg) #sends the message
		elif game == -1: #if there is only one instance and the game wasnt provided
			await bot.obj.data[0].statusmsg(ctx, 1) #just gets 0
		else:
			try:
				await bot.obj.data[game].statusmsg(ctx, 1) #gets the game input
			except:
				await ctx.send('Please send a valid game number') #if the game input was invalid
	except:
		ctx.send("Please initilize a game")

#change code funct
@bot.command(name='code')
async def chncode(ctx, game = -1, code:str = "error"):
	if game == -1 and len(bot.obj.data) > 1: ctx.send('Please specify a game') #if the game is left as default and there is more than one instance warn
	else:
		if game == -1: game = 0 #moves the default game int up one
		sudo = await chkrl(ctx, ctx.author)
		if ctx.author == bot.obj.data[game].host: sudo = 1
		if sudo == 1:
			bot.obj.data[game].code = code #sets the corresponding game's code
			bot.obj.update()
		else: await ctx.send('Sorry bud, you don\'t have the perms to do that')

#leave queue funct
@bot.command(name='leave')
async def leave(ctx, game = 0, member:discord.Member = None):
		if member == None: member = ctx.author
		if member != None:
			sudo = await chkrl(ctx, ctx.author)
			if ctx.author == bot.obj.data[game].host: sudo = 1
			if sudo == 1:
				try:
					await bot.obj.data[game].leave(ctx, member)
					await bot.obj.data[game].statusmsg(ctx)
				except Exception as e:
					print(e)
					await ctx.send('Whoops, that user isn\'t in that game')
			else:
				await ctx.send('Sorry bud, you don\'t have the perms to do that')
		elif game == -1: #very special case
			for x in bot.obj.data: #for every entry in bot.obj
				await x.leave(ctx, member) #runs leave in the instance
				await x.statusmsg(ctx, member) #updates the message
		else:
			await bot.obj.data[game].leave(ctx, member) #runs leave in the inst
			await bot.obj.data[game].statusmsg(ctx, member) #updates message

@bot.command(name='close')
async def close(ctx, game = -1):
	if game == -1:
		ctx.send('No game specified.')
	else:
		sudo = await chkrl(ctx, ctx.author)
		if ctx.author == bot.obj.data[game].host: sudo = 1
		if sudo == 1:
			try:
				bot.obj.data.pop(game)
				await ctx.send('Game successfully closed')
			except:
				await ctx.send('There was an error closing the game. Please check you are reffering to a valid game')
		else:
			await ctx.send('Sorry bud, you don\'t have the perms to do that')

class gameobj(object): #heres where like half the magic happens
	"""docstring for gameobj"""
	def __init__(self, ctx, name:str, code:str):
		super(gameobj, self).__init__()
		self.code = code #fils in all the default values
		self.active = []
		self.wait = []
		self.name = name
		self.host = ctx.author
		self.latestmsg = 0
		asyncio.ensure_future(self.statusmsg(ctx)) #triggers the status message

	#adds user
	async def add_user(self, ctx, user):
		if user not in self.active and len(self.active) <= 9: #if the user isnt already in the list of active players and there is an empty spot
			self.active.append(user) #appends the user to the list
			await self.statusmsg(ctx) #updates info msg
		else: #no room in self.active or they're already in
			if user in self.active: msg = await ctx.send("You're already in the game") #if they're already in
			elif len(self.active) >= 9:  #if theres no room left
				msg = await ctx.send('There is no room left, adding you to the waiting list..') #msg letting you know
				self.wait.append(user) #adds the user to the waiting list
				await self.statusmsg(ctx) #updates the info msg
			await asyncio.sleep(3) #wait 3 seconds
			await msg.delete() #delete the status message

	#updates/creates new status message
	async def statusmsg(self, ctx, new:int = 0):
		try:
			msg = f'Host: {self.host} \nCode: {self.code} \nGame name: {self.name} \n\n' #header flavor text

			for x in range(10): #loops through below code 10 times
				try:
					if self.active[x].nick != None: nick = f'({self.active[x].nick}) '
					else: nick = ''
					msg += f'{x + 1}: {str(self.active[x])} {nick}\n' #if theres a user in the specific spot, print it
				except:
					msg += '[Empty] \n' #if the above fails due to index out of range, print empty

			if len(self.wait) > 0: #if theres ppl in the waiting list
				msg += '\n Waiting List \n' #seperator
				for x in range(len(self.wait)): #for the number of entries in the waiting list
					if self.active[x].nick != None: nick = f'({self.active[x].nick}) '
					else: nick = ''
					msg +=  f'{x + 1}: {str(self.wait[x])} {nick}\n' #adds the user to msg
					if x == 10: #10 entry limit
						msg += "...\n" #...

						break #breaks the for loop
				msg += "\n\n"

			msg += 'React with :thumbsup: to join!' #flavor texto

			#await bot.wait_until_ready() #something something keeps the loop from breaking

			try:
				if self.latestmsg and new == 0: await self.latestmsg.edit(content=msg) #if latestmsg exists and the flag isnt set, edit content
				else: raise Exception('expected manual exception, im too lazy to rewrite this code') #i just have this here so if new isnt 0 it cancels the try
			except Exception as e:
				print(e)
				self.latestmsg = await ctx.send(msg) #creates new message

			await self.latestmsg.add_reaction(u"\U0001F44D") #adds the thumbs up reaction

		except Exception as e:
			await ctx.send('There are no games running currently, run init to start one!') #hopefully this only triggers if there isnt an init for this instance
			await ctx.send(e)

	#leave funct
	async def leave(self, ctx, member = None):
		if member == None: member = ctx.author
		if member in self.active: #if the person leaving is in the active list
			self.active.remove(member) #removes from active list
			if len(self.wait) > 0: #if there are people waiting
				new = self.wait[0] #sets the first person in the waiting list to "new"
				self.wait.remove(new) #removes them from wait
				self.active.append(new) #adds to active
				await ctx.send(f'{new.mention}, {member.mention} has given you a spot!') #flavor text
			else: #if there is nobody waiting
				await ctx.send(f'{member.mention} has left the game') #simple 'has left' message
		elif member in self.wait: #if the person is in the waiting list
			self.wait.remove(member) #removes from waiting list
			await ctx.send(f'{member} has left the queue') #message of confirmation
		else:
			x = x
			await ctx.send(f'You need to be in a queue to leave, {member}') #if the triggerer is not in any list, then just send back this

async def chkrl(ctx, user: discord.Member):
		modrl = [ #list of roles that are "elevated"
			742937828425465899
		]
		blacklist = [ #list of member roles
			"User",
			"user",
			813469324328173608
		]

		for x in modrl:
			if isinstance(x, str): x = discord.utils.find(lambda r: r.name == x, ctx.guild.roles) #if its a string, use utils.find to get the role obj
			elif isinstance(x, int): x = ctx.guild.get_role(x) #if not string, but is an int, simply use get_role to get role obj
			if x in user.roles: return 1 #checks if the input user has the role from blacklist, if yes, returns -1
		for x in blacklist: #for every entry in blacklist
			if isinstance(x, str): x = discord.utils.find(lambda r: r.name == x, ctx.guild.roles) #if its a string, use utils.find to get the role obj
			elif isinstance(x, int): x = ctx.guild.get_role(x) #if not string, but is an int, simply use get_role to get role obj
			if x in user.roles: return -1 #checks if the input user has the role from blacklist, if yes, returns -1

bot.run(TOKEN) #runs everything else


import pygame
import sys
from random import randint

"""----------------------------------FLAPPY BIRD-----------------------------------------
------------------------------------BY: DANIEL SAGI-----------------------------------"""
Score = 0
exit = False
FrameRate = 0
#
pygame.font.init()
score_font = pygame.font.SysFont('Comic Sans MS', 30)
game_over_font = pygame.font.SysFont('Comic Sans MS', 45)
background = pygame.image.load("images/bg.png")

gameDisplay = None
Clock = None
#
BLACK = (0,0,0)
WHITE = (255,255,255)
SKY_BLUE = (0, 153, 204)
#
H = 650
W = 800
#
BLOCKS_WIDTH = 60
BLOCKS_SPACE = 350
PIPE_HEAD_HEIGHT = 30
PIPE_HEAD_OFFSET = 4
PIPE_HEAD_WIDTH = BLOCKS_WIDTH + PIPE_HEAD_OFFSET
#

"""-----------Control Panel------------"""
FPS = 120
BLOCKS_SPEED = 3
BACK_MOVIE_SPEED = 1
BIRD_ANDGLE_FACTOR = 3.1
BIRD_FLAP_FORCE = 5
MIN_PIPE_OPENING = 135
MAX_PIPE_OPENING = 160
"""------------------------------------"""

class Bird:
    def __init__(self):
        self.bird_image = pygame.image.load("images/flappybird.png")
        self.flap_force = BIRD_FLAP_FORCE
        self.speed = 0
        self.tilt = 0
        self.rect = pygame.Rect(W/3, H/4, 36, 28)

    def do_flap(self):
        self.speed = self.flap_force

    def draw(self):
        picture = pygame.transform.scale(self.bird_image, (self.rect.width,self.rect.height))
        picture = pygame.transform.rotate(picture, self.tilt)
        gameDisplay.blit(picture, (self.rect.x, self.rect.y, self.rect.width, self.rect.height))

    def is_collided_with_blocks(self, pipeSet):
        return

class Pipe:
    def __init__(self, height, isUp):
        self.body_height = height - PIPE_HEAD_HEIGHT

        # loading images and resizing them
        self.body = pygame.image.load("images/pipeBody.png")
        self.body = pygame.transform.scale(self.body, (BLOCKS_WIDTH, height))

        self.head = pygame.image.load("images/pipeHead.png")
        self.head = pygame.transform.scale(self.head, (BLOCKS_WIDTH + PIPE_HEAD_OFFSET, PIPE_HEAD_HEIGHT))

        self.isUp = isUp

    def draw(self, x):
        if self.isUp:
            gameDisplay.blit(self.body, (x, 0, BLOCKS_WIDTH, self.body_height))
            gameDisplay.blit(self.head, (x - PIPE_HEAD_OFFSET /2,
                                         self.body_height,
                                         PIPE_HEAD_WIDTH,
                                         PIPE_HEAD_HEIGHT))
        else:
            gameDisplay.blit(self.body, (x, H - self.body_height, BLOCKS_WIDTH, self.body_height))
            gameDisplay.blit(self.head, (x - (PIPE_HEAD_OFFSET/2),
                                         H-self.body_height-PIPE_HEAD_HEIGHT,
                                         PIPE_HEAD_WIDTH,
                                         PIPE_HEAD_HEIGHT))

class PipeSet:
    def __init__(self):
        self.opening_size = randint(MIN_PIPE_OPENING, MAX_PIPE_OPENING)
        self.behind_bird = False

        # calculating random opening, Both of down block and up block.
        self.up_height = randint(0, H-self.opening_size)
        self.down_height = H - self.up_height - self.opening_size

        # creating pipes
        self.up_pipe = Pipe(self.up_height, True)
        self.down_pipe = Pipe(self.down_height, False)

        #starting from edge
        self.X = W + PIPE_HEAD_WIDTH

        self.up_pipe_rect = pygame.Rect(self.X, 0, BLOCKS_WIDTH, self.up_height)
        self.down_pipe_rect = pygame.Rect(self.X, H - self.down_height, BLOCKS_WIDTH, self.down_height)

    def draw_blocks(self):
        self.up_pipe.draw(self.X)
        self.down_pipe.draw(self.X)

    def move_block(self, offset):
        self.X -= offset
        self.up_pipe_rect.x -= offset
        self.down_pipe_rect.x -= offset

    def is_colliding_bird(self, bird):
        return self.up_pipe_rect.colliderect(bird.rect) or self.down_pipe_rect.colliderect(bird.rect)

    def is_behind_bird(self, bird):
        if self.X + BLOCKS_WIDTH < bird.rect.x and self.behind_bird == False:
            self.behind_bird = True
            return True
        else:
            return False

class Movie:
    def __init__(self, image):
        self.source_image = image
        self.source_rect = image.get_rect(y=H-image.get_rect().height)
        self.tape = []
        self.tape.append(self.source_rect)
    def roll_display(self):
        for image_rect in self.tape:
            # adding image to back when first starts to go off screen
            if image_rect.x < 0 and len(self.tape) < 2:
                # new_rect = self.source_image.get_rect(x=self.source_image.get_rect().width)
                new_rect = pygame.Rect(self.source_rect.width-1, self.source_rect.y, self.source_rect.width, self.source_rect.height)
                self.tape.append(new_rect)

            if image_rect.x < 0 - image_rect.width:
                self.tape.remove(image_rect)

            image_rect.x -= BACK_MOVIE_SPEED
            gameDisplay.blit(self.source_image, image_rect)

def events(bird):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            return "QUIT"
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                bird.do_flap()
                return "CLAP"

def do_physics(bird):
    velocity = 0.15

    # bird falling and flapping physics
    bird.speed -= velocity
    bird.rect.y -= bird.speed

    if bird.speed > -90:
        bird.tilt = bird.speed * BIRD_ANDGLE_FACTOR

def game_over_stall(bird):
    global Score
    while True:
        gameover_surface = game_over_font.render("Game Over!", False, (0, 255, 0))
        gameDisplay.blit(gameover_surface, (W/2 - 120, H/3))
        pygame.display.update()
        event = events(bird)
        if event == "QUIT":
            pygame.quit()
            sys.exit()
        elif event == "CLAP":
            Score = 0
            bird.y = H/3
            break

def init_pygame():
    global gameDisplay, Clock
    gameDisplay = pygame.display.set_mode((W, H))
    Clock = pygame.time.Clock()
    pygame.display.set_caption("Flappy Bird - Daniel Sagi")
    icon = pygame.image.load("images/icon.png")
    pygame.display.set_icon(icon)

    pygame.init()

"""------------ MAIN --------------"""
def main():
    global Score, FrameRate
    init_pygame()
    bird = Bird()
    back_movie = Movie(background)

    pipeSets = []
    while True:
        FrameRate += 1
        if events(bird) == "QUIT": break
        elif FrameRate % 99 == 0:
            pipeSets.append(PipeSet())

        # if bird is out of boundaries of screen
        if bird.rect.y >= H + bird.rect.height:
            game_over_stall(bird)
            pipeSets = []

        gameDisplay.fill(SKY_BLUE)

        back_movie.roll_display()
        do_physics(bird)

        bird.draw()

        score_surface = score_font.render(" " +str(Score), False, (0, 0, 0))
        gameDisplay.blit(score_surface, (0, 0))

        for pipeSet in pipeSets:
            if pipeSet.is_behind_bird(bird):
                Score += 1
            if pipeSet.X <= 0 - BLOCKS_WIDTH:
                pipeSets.remove(pipeSet)
            else:
                pipeSet.move_block(BLOCKS_SPEED)
                pipeSet.draw_blocks()
                if pipeSet.is_colliding_bird(bird):
                    game_over_stall(bird)
                    pipeSets = []

        pygame.display.update()
        Clock.tick(FPS)

    pygame.quit()
    sys.exit()

main()


# util.py
from discord.ext import commands
import discord

from cogfactory import make_cog, GroupCog
from colors import random_color

class Util(commands.Cog, name='Util'):
    def __init__(self, bot):
        self.bot = bot

    async def cog_check(self, ctx: commands.Context):
        return ctx.author.permissions_in(ctx.channel).administrator

    @commands.command(
        name='clear-msgs',
        help='Clears all messages in channel.',
        description='Clears all messages in channel.'
    )
    async def clear_msgs(self, ctx):
        channel = ctx.channel
        await channel.purge()

    @commands.command(
        name='clear-groups',
        help='Clears all categories, channels, and roles associated with groups.',
        description='Clears all groups, channels, and roles associated with groups.'
    )
    async def clear_groups(self, ctx):
        guild = ctx.guild
        names = ''
        # Go through cogs
        cogs = list(filter(lambda c: isinstance(c[1], GroupCog), self.bot.cogs.items()))
        for c in cogs:
            name = c[1].name
            cat = discord.utils.get(guild.categories, id=c[1].group_id)
            for _c in cat.channels:
                await _c.delete()
            await cat.delete()
            member_role = discord.utils.get(guild.roles, name=f'{name} Member')
            if member_role:
                await member_role.delete()
            gm_role = discord.utils.get(guild.roles, name=f'{name} GM')
            if gm_role:
                await gm_role.delete()
            if not names:
                names = name
            else:
                names += f', {name}'
            self.bot.remove_cog(c[0])

        # Go through category channels
        for c in guild.categories:
            name = c.name
            for _c in c.channels:
                await _c.delete()
            await c.delete()
            member_role = discord.utils.get(guild.roles, name=f'{name} Member')
            if member_role:
                await member_role.delete()
            gm_role = discord.utils.get(guild.roles, name=f'{name} GM')
            if gm_role:
                await gm_role.delete()
            if not names:
                names = name
            else:
                names += f', {name}'

        # Go through roles
        for r in list(filter(lambda r: r.name.endswith('Member'), guild.roles)):
            name = r.name.replace(' Member', '')
            await r.delete()
            gm_role = discord.utils.get(guild.roles, name=f'{name} GM')
            if gm_role:
                await gm_role.delete()
            if not names:
                names = name
            else:
                names += f', {name}'
        for r in list(filter(lambda r: r.name.endswith('GM'), guild.roles)):
            name = r.name.replace(' GM', '')
            await r.delete()
            if not names:
                names = name
            else:
                names += f', {name}'
        await ctx.send(f'Deleted channels: {names}')

def setup(bot):
    bot.add_cog(Util(bot))