import matplotlib.pyplot as plt
import numpy as np

def ploting(datax, datay, model,model_2,num_examples=6):
    fig, ax = plt.subplots(nrows=num_examples, ncols=4, figsize=(18,4*num_examples))
    m = datax.shape[0]
    for row_num in range(num_examples):
        image_indx = np.random.randint(m)
        image_arr = model(datax[image_indx:image_indx+1]).squeeze(0).detach().cpu().numpy()
        image_arr_nested = model_2(datax[image_indx:image_indx+1]).squeeze(0).detach().cpu().numpy()
        ax[row_num][0].imshow(np.transpose(datax[image_indx].cpu().numpy(), (1,2,0))[:,:,0])
        ax[row_num][0].set_title("Orignal Image")
        ax[row_num][1].imshow(np.squeeze((image_arr > 0.40)[0,:,:].astype(int)))
        ax[row_num][1].set_title("Segmented Image localization, Unet")
        ax[row_num][2].imshow(np.squeeze((image_arr_nested > 0.40)[0,:,:].astype(int)))
        ax[row_num][2].set_title("Segmented Image localization, Unet++")
        ax[row_num][3].imshow(np.transpose(datay[image_indx].cpu().numpy(), (1,2,0))[:,:,0])
        ax[row_num][3].set_title("Target image")
    plt.show()


import io
import sys
import os
from common import *
from dotenv import load_dotenv

def parse_alipay(filename):
    account = "Liabilities:CreditCard:CITIC"
    account_alipay = "Assets:VirtualCard:Alipay:ZZS"
# 交易号 ,商家订单号 ,交易创建时间 ,付款时间 ,最近修改时间 ,交易来源地 ,类型 ,交易对方 ,商品名称 ,金额（元） ,收/支 ,交易状态 ,服务费（元） ,成功退款（元） ,备注,资金状态 ,

    with open(filename, 'r', encoding="gbk") as f:
        for line in f.readlines()[5:-8]:
            line = line.strip()
            data = line.split(',')

            date = data[2].split(' ')[0] # 付款时间
            counterpart = data[7].strip() # 交易对方
            description = data[8].strip() # 商品名称
            currency = "CNY"
            money_status = data[15].strip()
            amount = float(data[9])
            if money_status == "资金转移": # 资金状态
                if data[11] == "还款成功":
                    print("还款成功")
                    print(line)
                elif data[11] == "交易成功" and description == "余额宝-自动转入":
                    continue
                else:
                    print(line)
            elif money_status == "已支出":
                print(get_notsure(date, counterpart, description, amount, currency, account))
            elif money_status == "已收入":
                if "余额宝" in description:
                    print(get_yuebao(date, description, amount, currency, account_alipay))
                elif data[11].strip() == "退款成功": # 退款
                    print(get_notsure(date, counterpart, description, -1 * amount, currency, account))
                else: # 二手
                    print(sell_something(date, description, amount, currency, account_alipay))
                    print(line)
            elif data[11].strip() == "交易关闭": # 交易状态
                continue
            else:
                print(line)

if __name__ == '__main__':
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
    load_dotenv()
    alipay_path = os.getenv("ALIPAYPATH")
    parse_alipay(alipay_path)


#큐 구현

# 고정크기 큐 구현(포인터를 활용해 보겟음)
queue = [None] *3
ptr = 0

def enqueue(item):
  global ptr
  queue[ptr] = item
  ptr = ptr + 1

def dequeue():
  global ptr
  pop_left = queue[0]

  #[1,2] ptr = 2
  for i in range(ptr-1):
    queue[i] = queue[i+1]
  ptr = ptr -1
  queue[ptr] = None

  return pop_left

enqueue(1)
enqueue(2)
enqueue(3)
print(queue)
dequeue()
print(queue)
print(ptr)


def diferencia21(a,b):
  global diferencia
  val1=True
  val2=True
  if b == 21:
      val2 = True
  elif b == 20:
      val2 = False
  if a==int:
     val1 = True
  elif a==str or a== float:
      val1=False
      print("Incorrecto, has ingresado un decimal, por favor ingresa un entero:")
      consignas()
  #else:
   #   val1=False
    #  print("Incorrecto, has ingresado un texto, por favor ingresa un entero:")
     # consignas()

  if val1 and val2:
    if b>a :
       cond1=b-a
       diferencia=(cond1)
    elif b==a:
  #elif val1 and val2 and a==b:
      diferencia=(0)
    return print("Su resultado es: ",diferencia)

def consignas():
    consigna1 =int(input("Ingresa un valor entero:"))
    b = 21
    diferencia21(consigna1,b)
consignas()


"""
flask app handle bitcoin wallet
can add remove addresses, and sync data for them(transactions, balance)
"""

import os

from dotenv import load_dotenv
from flask import Flask, request

from db_methods.init_tables import init_method
from db_methods.queries_methods import add_address_to_db, remove_address_from_db, sync_addresses_in_db

load_dotenv()
app = Flask(__name__)

@app.route('/api/v1/<address>', methods=["POST"])
def add_address(address):
    """
    add bitcoin address to wallet
    @param address: bitcoin address
    @type address: str
    @rtype: str
    """
    if request.method == 'POST':
        add_address_to_db(address)
        return "success"

    return "nothing saved to db"

@app.route('/api/v1/<address>/remove', methods=["POST"])
def remove_address(address):
    """
    remove bitcoin address from wallet
    @param address: bitcoin address
    @type address: str
    @rtype: str
    """
    if request.method == 'POST':
        remove_address_from_db(address)
        return "success"

    return "nothing saved to db"

@app.route('/api/v1/sync', methods=["POST"])
def sync_addresses():
    """
    sync addresses last transaction and balance
    @rtype: str
    """
    if request.method == 'POST':
        sync_addresses_in_db()

    return "success"

if __name__ == "__main__":
    port = int(os.getenv('FLASK_PORT', 5000))
    init_method()
    app.run(debug=True, host="0.0.0.0", port=port)


import glob
import numpy as np
import sys
import os.path
import os
import random

from PIL import Image

import cv2
import time
import json

import multiprocessing.dummy as mp

from ..library.class_tracklet import *
from ..library.parallel_save import *

def is_into(min, value, max):
    return min<=value and value<=max

def box1_into_box2(boxA, boxB):
    xA0 = int(boxA[0])
    yA0 = int(boxA[1])
    xA1 = int(boxA[2])
    yA1 = int(boxA[3])
    xB0 = int(boxB[0])
    yB0 = int(boxB[1])
    xB1 = int(boxB[2])
    yB1 = int(boxB[3])
    #A into B
    if is_into(xB0,xA0,xB1) and is_into(xB0,xA1,xB1):
        if is_into(yB0,yA0,yB1) and is_into(yB0,yA1,yB1):
            return True
    return False

# bb_IOU (Intersection Over Union) output values between 0 and 1
def bb_IOU(boxA, boxB):
    if box1_into_box2(boxA,boxB) or box1_into_box2(boxB,boxA):
        return 1
    xA = max(int(boxA[0]), int(boxB[0]))
    yA = max(int(boxA[1]), int(boxB[1]))
    xB = min(int(boxA[2]), int(boxB[2]))
    yB = min(int(boxA[3]), int(boxB[3]))

    interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)

    boxAArea = (int(boxA[2]) - int(boxA[0]) + 1) * (int(boxA[3]) - int(boxA[1]) + 1)
    boxBArea = (int(boxB[2]) - int(boxB[0]) + 1) * (int(boxB[3]) - int(boxB[1]) + 1)
    iou = interArea / float(boxAArea + boxBArea - interArea)
    return iou

# find_biggest_id find the biggest ID
def max_id(initBoundingBox):
    tmp = int(-999)
    for u_id in initBoundingBox.keys():
        if int(u_id) > int(tmp):
            tmp = u_id
    return int(tmp)

def setbox2str(bbox):
    return str(int(bbox[1]))+'_'+str(int(bbox[3]))+'_'+str(int(bbox[0]))+'_'+str(int(bbox[2]))
    # return str(int(bbox[1]))+','+str(int(bbox[3]))+','+str(int(bbox[0]))+','+str(int(bbox[2]))

def create_path_crop(dir_gallery, key, save_separate=False):
    base_path =''
    if save_separate:
        base_path = join_path(dir_gallery, str(key))
        create_dir(base_path, show_msg=False)
    else:
        base_path = dir_gallery
    return base_path

def crop_frame(frame, bbox):
    # frame is type numpy array (imagen RGB)
    # bbox is a list = [x0,y0, x1,y1]
    return frame[y0:y1, x0,x1]


from allauth.account.models import EmailAddress

from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
from django.core.mail import send_mail
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse_lazy, reverse
from django.db.models import Q
from django.shortcuts import render, get_list_or_404, get_object_or_404, Http404
from django.views.generic import (
    CreateView, ListView,
    UpdateView, DeleteView,
    DetailView, RedirectView,)
from django.utils import timezone

from quests.models import UserProfileImage, Quest

from .models import (
    Education, WorkExperience,
    DefuseMessage, ContactUs)
from .forms import (
    EducationForm, WorkExperienceForm,
    SendMessageForm, ContactUsForm,
    ReplyForm)
from .mixins import CheckingUserPermissionMixin, UserExperiencePermissionMixin

# Create your views here.

class ContactUsFormView(CreateView):
    '''contact form'''
    model = ContactUs
    form_class = ContactUsForm
    success_url = reverse_lazy('homepage')

@login_required
def profile_list_view(request):
    """A page where users can view their own profile"""
    user = get_object_or_404(User, username=request.user.username)
    email = get_object_or_404(EmailAddress, user=user, primary=True)
    profile_img = get_object_or_404(UserProfileImage, user=user)
    experience = ''

    try:
        experience = get_list_or_404(WorkExperience, user=user)
    except:
        pass

    context = {
        'user': user,
        'email': email,
        'experiences': experience,
        'profile_img': profile_img,
    }

    return render(request, 'profiles/profile_list.html', context)

@login_required
def user_quest_list_view(request):
    """A page where users can view their collection of quests"""
    user_quest_list = ''

    try:
        user_quest_list = Quest.objects.filter(user=request.user, explosion_datetime__gte=timezone.now())
        user_quest_list_count = user_quest_list.count()
        all_quest = Quest.objects.all()
        defused_quests = all_quest.filter(interested_users=request.user)
        defused_quests_count = defused_quests.count()
    except ObjectDoesNotExist:
        msg = "No quest"
        raise ObjectDoesNotExist(msg)

    context = {
        'list': user_quest_list,
        'count': user_quest_list_count,
        'def_quests': defused_quests,
        'def_quest_count': defused_quests_count,
    }
    return render(request, 'profiles/user_quest_list.html', context)

@login_required
def user_dashboard(request):
    """User dashboard"""
    profile_pic = UserProfileImage.objects.get(user=request.user)
    received = DefuseMessage.objects.filter(
        receiver=request.user, viewed_by_receiver=False, trash_by_receiver=False).count()
    template_name = 'profiles/user_dashboard.html'
    context = {
        'profile_pic': profile_pic,
        'new': received,
    }
    return render(request, template_name, context)

class MessageInboxView(LoginRequiredMixin, ListView):
    """Message Inbox page"""
    model = DefuseMessage
    context_object_name = 'messages'
    template_name = 'profiles/inbox_pages.html'

    def get_context_data(self, *args, **kwargs):
        # for each in context['sender']:
        #     each_reply_count = each.replies.all()
        #     print(each_reply_count)
        #     count_unread = [unread for unread in each_reply_count if unread.viewed_by_receiver == False]
        #     print(len(count_unread))
        context = super().get_context_data(*args, **kwargs)
        every_message = DefuseMessage.objects.prefetch_related('replies')
        unread_count, created_unread_count = {}, {}
        context['receiver'] = every_message.filter(
            receiver=self.request.user, trash_by_receiver=False, parent__isnull=True).order_by('-send_at')
        for each in context['receiver']:
            unread_count[each.id] = each.replies.all().filter(
                receiver=self.request.user, viewed_by_receiver=False).count()
        context['unread_count'] = unread_count
        context['total_count'] = sum(unread_count.values())
        context['sender'] = every_message.filter(
            sender=self.request.user, trash_by_sender=False, parent__isnull=True).order_by('-send_at')
        for each in context['sender']:
            created_unread_count[each.id] = each.replies.all().filter(
                receiver=self.request.user, viewed_by_receiver=False).count()
        context['created_unread_count'] = created_unread_count
        context['created_unread_total_count'] = sum(created_unread_count.values())
        return context

class MessageDetailView(LoginRequiredMixin, CheckingUserPermissionMixin, DetailView):
    """message detail"""
    template_name = 'profiles/defusemessage_detaill.html'
    model = DefuseMessage
    context_object_name = 'message'

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        particular_message = get_object_or_404(DefuseMessage, pk=self.kwargs['pk'])
        context['sender_email'] = get_object_or_404(EmailAddress, user=particular_message.sender)
        context['sender_profile'] = get_object_or_404(UserProfileImage, user=particular_message.sender)
        context['receiver_profile'] = get_object_or_404(UserProfileImage, user=particular_message.receiver)
        context['quest'] = get_object_or_404(Quest, slug=particular_message.related_quest.slug)
        context['children'] = particular_message.replies.all().order_by('send_at')
        context['reply_form'] = ReplyForm()
        context['create_url'] = reverse('dashboard:message_reply', kwargs={'pk': particular_message.pk})
        context['interested_url'] = reverse('dashboard:interested_message_reply', kwargs={'pk': particular_message.pk})
        return context

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        current_user = get_object_or_404(User, username=self.request.user.username)
        particular_message = get_object_or_404(DefuseMessage, pk=self.kwargs['pk'])
        replies = DefuseMessage.objects.filter(parent=particular_message)
        if self.object.receiver == current_user:
            self.object.read_by_receiver()
            print(self.object)
        for reply in replies:
            if reply.receiver == current_user:
                reply.read_by_receiver()
        return self.render_to_response(context)

class MessageDelete(LoginRequiredMixin, CheckingUserPermissionMixin, RedirectView):
    """delete message button"""
    def get_redirect_url(self, *args, **kwargs):
        msg_pk = self.kwargs.get('pk')
        msg = get_object_or_404(DefuseMessage, pk=msg_pk)
        msg_sender = get_object_or_404(User, username=msg.sender.username)
        msg_receiver = get_object_or_404(User, username=msg.receiver.username)
        url_ = reverse_lazy("dashboard:message_inbox")
        user = self.request.user
        if user.is_authenticated():
            if msg_sender == user:
                if not msg.trash_by_sender:
                    msg.trash_by_sender = True
                    msg.save()
            elif msg.receiver == user:
                if not msg.trash_by_receiver:
                    msg.trash_by_receiver = True
                    msg.save()
            else:
                Http404
        return url_

class SentPageMessageReply(LoginRequiredMixin, CreateView):
    """Reply to a specific message"""
    # can't think straight today just gonna be lazy and not think too much about it
    form_class = ReplyForm
    # success_url = reverse_lazy("dashboard:message_detail", kwargs={'pk': })

    def form_valid(self, form):
        particular_message = get_object_or_404(DefuseMessage, pk=self.kwargs['pk'])
        receiver = get_object_or_404(User, username=particular_message.receiver.username)
        quest = get_object_or_404(Quest, slug=particular_message.related_quest.slug)
        self.object = form.save(commit=False)
        self.object.sender = self.request.user
        self.object.receiver = receiver
        self.object.related_quest = quest
        if particular_message.parent:
            self.object.parent = particular_message.parent
        else:
            self.object.parent = particular_message
        self.object.subject = "Re: " + particular_message.subject
        self.object.save()
        return super().form_valid(form)

    def get_success_url(self):
        if 'pk' in self.kwargs:
            pk = self.kwargs['pk']
        return reverse_lazy('dashboard:message_detail', kwargs={'pk': pk})

class InterestedPageMessageReply(LoginRequiredMixin, CreateView):
    """Reply to a specific message"""
    form_class = ReplyForm

    def form_valid(self, form):
        particular_message = get_object_or_404(DefuseMessage, pk=self.kwargs['pk'])
        receiver = get_object_or_404(User, username=particular_message.sender.username)
        quest = get_object_or_404(Quest, slug=particular_message.related_quest.slug)
        self.object = form.save(commit=False)
        self.object.sender = self.request.user
        self.object.receiver = receiver
        self.object.related_quest = quest
        if particular_message.parent:
            self.object.parent = particular_message.parent
        else:
            self.object.parent = particular_message
        self.object.subject = "Re: " + particular_message.subject
        self.object.save()
        return super().form_valid(form)

    def get_success_url(self):
        if 'pk' in self.kwargs:
            pk = self.kwargs['pk']
        return reverse_lazy('dashboard:message_detail', kwargs={'pk': pk})

class WorkExperienceCreateView(LoginRequiredMixin, CreateView):
    """adding experience to profile"""
    model = WorkExperience
    form_class = WorkExperienceForm
    success_url = reverse_lazy("dashboard:my_profile")

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return super().form_valid(form)

class WorkExperienceUpdateView(LoginRequiredMixin, UserExperiencePermissionMixin, UpdateView):
    """updating an experience"""
    template_name = 'profiles/workexperience_update_form.html'
    model = WorkExperience
    form_class = WorkExperienceForm

class WorkExperienceDeleteView(LoginRequiredMixin, UserExperiencePermissionMixin, DeleteView):
    """deleting an experience"""
    model = WorkExperience
    template_name = 'profiles/delete_experience.html'
    success_url = reverse_lazy('dashboard:my_profile')


# import packages
import math
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras

# import pyspark
# import findspark
# import os
# from pyspark import SparkContext

# spark_location = '/spark'       # Set your own
# java8_location = '/usr/lib/jvm/java-8-openjdk-amd64'  # Set your own
# os.environ['JAVA_HOME'] = java8_location
# findspark.init(spark_home=spark_location)
# sc = SparkContext()

# define parameters
filename = "Eluvio_DS_Challenge.csv"
chunksize = 100000
dictsize = 1000
maxlen = 30
embedsize = 5

fulldf = pd.read_csv(filename)#, nrows=chunksize)
# create tokenizer object (convert words to integers)
tokenizer = keras.preprocessing.text.Tokenizer(num_words=dictsize)
tokenizer.fit_on_texts(fulldf["title"])

# build empty RNN model
rnnmodel = keras.Sequential()
# add embedding layer (convert integers to vectors)
rnnmodel.add( keras.layers.Embedding(input_dim=dictsize, output_dim=embedsize, input_length=maxlen) )
# add LSTM layer outputs at every time
rnnmodel.add( keras.layers.LSTM(units=10, return_sequences=True, activation="sigmoid") )
# add LSTM layer outputs at every time
rnnmodel.add( keras.layers.LSTM(units=10, return_sequences=True, activation="sigmoid") )
# add LSTM layer outputs at every time
rnnmodel.add( keras.layers.LSTM(units=5, return_sequences=False, activation="sigmoid") )
# add fully connected layer to return 0/1
rnnmodel.add( keras.layers.Dense(units=5, activation="relu") )
# add fully connected layer to return value
rnnmodel.add( keras.layers.Dense(units=1) )
# compile RNN model
rnnmodel.compile(loss="mse", optimizer=keras.optimizers.Adam(lr=1e-3))
# check RNN model summary
rnnmodel.summary()

# read in dataframe in chunks
i = 0
for df in pd.read_csv(filename, chunksize=chunksize):
    print("reading chunk", i)
    i = i + 1

    # pre-process data (df_x, df_y)
    # tokenize words to integers by pre-defined tokenizer
    df_token = tokenizer.texts_to_sequences(df["title"])
    # convert to same length to be used as x in tensorflow
    df_x = keras.preprocessing.sequence.pad_sequences(df_token, maxlen=maxlen, padding="pre", truncating="pre")
    # use log of upvotes as y value
    df_uv = np.add(df["up_votes"], 1)
    df_y = np.log(df_uv)

    # split data into train and test (train_x, train_y, test_x, test_y)
    ind = np.random.rand(len(df)) < 0.8
    train_x = df_x[ind]
    test_x = df_x[~ind]
    train_y = np.asarray(df_y[ind])
    test_y = np.asarray(df_y[~ind])
    # train / update RNN model in current chunk
    rnnmodel.fit(train_x, train_y, batch_size=100, epochs=5, validation_split=0.05)

# evaluate RNN model
result = rnnmodel.evaluate(test_x, test_y)
print("MSE: ", result)

mean = sum(df_y)/len(df_y)
var = sum(np.square(np.add(df_y, - mean)))/len(df_y)
print("compare:", var)
# predict RNN model
# result = rnnmodel.predict(pred_x)


from airflow.hooks.postgres_hook import PostgresHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
from airflow.contrib.hooks.aws_hook import AwsHook

class StageToRedshiftOperator(BaseOperator):
    ui_color = '#358140'

    template_fields = ("s3_key",)
    copy_sql = """
        COPY {}
        FROM '{}'
        ACCESS_KEY_ID '{}'
        SECRET_ACCESS_KEY '{}'
        REGION '{}'
        {}
        {}
        {}
        {}
        {}
    """

    @apply_defaults
    def __init__(self,
                 redshift_conn_id="",
                 aws_credentials_id="",
                 table="",
                 s3_bucket="",
                 s3_key="",
                 region="us-west-2",
                 data_format="",
                 data_format_args=None,
                 data_format_kwargs=None,
                 file_compression="",
                 data_conversion_args=None,
                 data_conversion_kwargs=None,
                 data_load_args=None,
                 data_load_kwargs=None,
                 del_existing=True,
                 *args, **kwargs):

        super(StageToRedshiftOperator, self).__init__(*args, **kwargs)
        self.redshift_conn_id = redshift_conn_id
        self.aws_credentials_id = aws_credentials_id
        self.table = table
        self.s3_bucket = s3_bucket
        self.s3_key = s3_key
        self.region = region
        self.data_format = data_format
        self.data_format_args = data_format_args or []
        self.data_format_kwargs = data_format_kwargs or {}
        self.file_compression = file_compression
        self.data_conversion_args = data_conversion_args or []
        self.data_conversion_kwargs = data_conversion_kwargs or {}
        self.data_load_args = data_load_args or []
        self.data_load_kwargs = data_load_kwargs or {}
        self.del_existing = del_existing

    def execute(self, context):
        self.log.info(f'StageToRedshiftOperator table: {self.table} {self.s3_bucket}/{self.s3_key}')
        aws_hook = AwsHook(self.aws_credentials_id)
        credentials = aws_hook.get_credentials()
        redshift = PostgresHook(postgres_conn_id=self.redshift_conn_id)

        if self.del_existing:
            self.log.info("Clearing data from destination Redshift table")
            redshift.run("DELETE FROM {}".format(self.table))

        self.log.info("Copying data from S3 to Redshift")
        rendered_key = self.s3_key.format(**context)
        s3_path = "s3://{}/{}".format(self.s3_bucket, rendered_key)
        data_format_options = ''
        data_conversion = ''
        data_load_ops = ''
        if self.data_format_args != None:
            if type(self.data_format_args) is str:
                data_format_options += self.data_format_args
            else:
                data_format_options += ' '.join(self.data_format_args)
            data_format_options += ' '
        if self.data_format_kwargs != None:
            data_format_options += ' '.join([k + ' ' + str(v) for k,v in self.data_format_kwargs.items()])
        if self.data_conversion_args != None:
            if type(self.data_conversion_args) is str:
                data_conversion += self.data_conversion_args
            else:
                data_conversion += ' '.join(self.data_conversion_args)
            data_conversion += ' '
        if self.data_conversion_kwargs != None:
            data_conversion += ' '.join([k + ' ' + str(v) for k,v in self.data_conversion_kwargs.items()])
        if self.data_load_args != None:
            if type(self.data_load_args) is str:
                data_load_ops += self.data_load_args
            else:
                data_load_ops += ' '.join(self.data_load_args)
            data_load_ops += ' '
        if self.data_load_kwargs != None:
            data_load_ops += ' '.join([k + ' ' + str(v) for k,v in self.data_load_kwargs.items()])

        formatted_sql = StageToRedshiftOperator.copy_sql.format(
            self.table,
            s3_path,
            credentials.access_key,
            credentials.secret_key,
            self.region,
            self.data_format,
            data_format_options,
            self.file_compression,
            data_conversion,
            data_load_ops
        )
        redshift.run(formatted_sql)


# -*- coding: utf-8 -*-
from openerp import models, fields, api
from openerp.tools.translate import _
from openerp.exceptions import except_orm, ValidationError
import time, datetime
import openerp.addons.decimal_precision as dp
from docutils.nodes import line

class wiz_intervention_quotation(models.TransientModel):
    """
        Wiz intervention quotation
    """
    _name = 'wiz.intervention.quotation'
    _description = 'Wiz intervention quotation'

    @api.model
    def default_get(self, fields_list):
        res = super(wiz_intervention_quotation, self).default_get(fields_list=fields_list)
        res['intervention_id'] = self._context.get('active_id')
        return res

    @api.one
    @api.depends('park_id')
    def _all_operation_compute(self):
        """
            All resource pour le domaine
        """
        self.all_operation_ids = [x.maintenance_operation_id.id for x in self.park_id.maintenance_operation_ids]

    #===========================================================================
    # COLUMNS
    #===========================================================================
    intervention_id = fields.Many2one('intervention', string='Intervention', required=False, ondelete='cascade')
    customer_id = fields.Many2one('res.partner', string='Customer', required=False, ondelete='cascade')
    line_ids = fields.One2many('wiz.intervention.quotation.line', 'intervention_quotation_id',  string='Lines')
    date = fields.Date(string='Date', default=lambda self: fields.Date.today(), required=False)
    no_order_line_ids = fields.One2many('wiz.intervention.quotation.noorder', 'intervention_quotation_id',  string='Lines')

    #===========================================================================
    # Button
    #===========================================================================
    @api.multi
    def action_validation(self):
        sol_obj = self.env['sale.order.line']
        so_obj = self.env['sale.order']
        product_obj = self.env['product.product']
        for wiz in self:
            if not wiz.line_ids:
                raise except_orm(_('Error'), _('There are not lines.'))

            if wiz.intervention_id.sale_id:
                sale_rcs = wiz.intervention_id.sale_id
                if sale_rcs.state != 'draft':
                    raise except_orm(_('Error'), _('The sale has to be in the state draft.'))

            else:
                sale_rcs = so_obj.create_sale(customer=wiz.customer_id.id, so_line=None, date=wiz.date, other_data={'requested_date': wiz.date, 'type': 'sav'}, forced_qty=False)
#                                                                                'sale_account_invoice_trigger': 'manual',
#                                                                                'sale_account_invoiced_on': 'order'
                wiz.intervention_id.write({'sale_id': sale_rcs.id})

            currency_rcs = sale_rcs.currency_id
#             sale_rcs.write({'sale_account_invoice_trigger': 'manual', 'sale_account_invoiced_on': 'order'})
            for line in wiz.line_ids:
                if currency_rcs.id != line.currency_id.id:
                    price = product_obj._calcul_price_rate_devise(currency_rcs, line.price, line.currency_id)
                else:
                    price = line.price

                values = {'name': line.description,
                          'uom_id': line.uom_id.id,
                          'sec_uom_id': line.uom_id.id,
                          'uoi_id': line.uom_id.id,
                          'uom_qty': line.qty,
                          'sec_uom_qty': line.qty,
                          'uoi_qty': line.qty,
                          'requested_date': wiz.date,
                          'intervention_id': wiz.intervention_id.id,
                        }
                if (line.pmi_id and not line.pmi_id.sale_line_id or not line.pmi_id) and (line.qi_id and not line.qi_id.sale_line_id or not line.qi_id):
                    sol_rc = sol_obj.create_sale_order_line(sale=sale_rcs, product=line.product_id, values=values, forced_qty=True, forced_price_unit=price)
                    if line.pmi_id:
                        line.pmi_id.write({'sale_line_id': sol_rc.id})

                    if line.qi_id:
                        line.qi_id.write({'sale_line_id': sol_rc.id})

                elif line.pmi_id.sale_line_id:
                    values['price_unit'] = price
                    line.pmi_id.sale_line_id.write(values)
                elif line.qi_id.sale_line_id:
                    values['price_unit'] = price
                    line.pmi_id.sale_line_id.write(values)

            wiz.intervention_id.write({'is_create_quotation': True})
            return {'name': _('Sale order'),
                    'view_type': 'form',
                    'view_mode': 'form',
                    'res_model': 'sale.order',
                    'type': 'ir.actions.act_window',
                    'target': 'current',
                    'res_id': sale_rcs.id,
                    'nodestroy': True,
                    }

        return {'type': 'ir.actions.act_window_close'}

class wiz_intervention_quotation_line(models.TransientModel):
    """
        Wiz intervention quotation line
    """
    _name = 'wiz.intervention.quotation.line'
    _description = 'Wiz intervention quotation line'
    _rec_name = 'product_id'

    @api.one
    @api.depends('product_id')
    def _uom_category_compute(self):
        """
            Category UoM
        """
        uom_category_id = False
        if self.product_id:
            uom_category_id = self.uom_id.category_id.id

        self.uom_category_id = uom_category_id

    #===========================================================================
    # COLUMNS
    #===========================================================================
    intervention_quotation_id = fields.Many2one('wiz.intervention.quotation', string='Intervention quotation', required=False, ondelete='cascade')
    description = fields.Text(string='Description')
    product_id = fields.Many2one('product.product', string='Product', required=False, ondelete='cascade')
    qty = fields.Float(string='Qty', default=0.0, required=True, digits=dp.get_precision('Product quantity'))
    price = fields.Float(string='Invoice price', default=0.0, required=True, digits=dp.get_precision('Product price'))
    uom_id = fields.Many2one('product.uom', string='UoM', required=True, ondelete='cascade')
    currency_id = fields.Many2one('res.currency', string='Currency', required=True, ondelete='cascade', default=lambda self: self.env.user.company_id.currency_id)
    uom_category_id = fields.Many2one('product.uom.category', compute='_uom_category_compute', string="UOM category", readonly=True)
    pmi_id = fields.Many2one('piece.maintenance.intervention', string='PMI', required=False, ondelete='cascade')
    qi_id = fields.Many2one('quotation.intervention', string='QI', required=False, ondelete='cascade')

    #===========================================================================
    # Onchange
    #===========================================================================
    @api.onchange('product_id')
    def _onchange_product_id(self):
        """
            Onchange du produit
        """
        uom_id = False
        category_id = False
        if self.product_id:
            uom_id = self.product_id.uom_id.id
            category_id = self.product_id.uom_id.category_id.id

        self.uom_id = uom_id
        self.uom_category_id = category_id

class wiz_intervention_quotation_noorder(models.TransientModel):
    """
        Wiz intervention quotation noorder
    """
    _name = 'wiz.intervention.quotation.noorder'
    _description = 'Wiz intervention quotation noorder'
    _rec_name = 'product_id'

    #===========================================================================
    # COLUMNS
    #===========================================================================
    intervention_quotation_id = fields.Many2one('wiz.intervention.quotation', string='Intervention quotation', required=False, ondelete='cascade')
    description = fields.Text(string='Description')
    product_id = fields.Many2one('product.product', string='Product', required=False, ondelete='cascade')


# _*_coding: utf-8 _*_

#import <string>

def removerZeros(numero1, numero2):
    soma = numero1 + numero2
    stringSoma = str(soma)

    novoNumero = []

    for x in stringSoma:
        if(int(x)!=0):
            novoNumero.append(x)

    novoNumero = "".join(novoNumero)
    novoNumero = int(novoNumero)
    return novoNumero

#ENTRADAS do usuário

n1 = int(input("Digite o primeiro número: "))
n2 = int(input("Digite o segundo número: "))

semZero = removerZeros(n1, n2)

print("Resultado: ", semZero)


from .Layer import Layer

class Conv2dLayer(Layer):
    def __init__(self, layer_keras, layer_name):
        super().__init__(layer_keras, layer_name)
        self.evaluate_layer()

    def evaluate_layer(self):
        layer = self.layer_keras

        filter_rows = layer.weights[0].shape[0]
        filter_columns = layer.weights[0].shape[1]
        filter_channels = layer.weights[0].shape[2]

        n_filters = layer.weights[0].shape[3]

        input_rows = layer.input_shape[1]
        input_columns = layer.input_shape[2]
        input_channels = layer.input_shape[3]

        stride = layer.strides

        n_macc = n_filters * (filter_rows * filter_columns + 1) * filter_channels * \
                 (((input_rows - filter_rows) / stride[0]) + 1) * \
                 (((input_columns - filter_columns) / stride[1]) + 1)

        n_flops = ((input_rows - filter_rows) / stride[0] + 1) * \
                  ((input_columns - filter_columns) / stride[1] + 1) * \
                  (input_channels * (2 * filter_rows * filter_channels + 1) * n_filters)

        self.operations = {
            'flops': n_flops,
            'maccs': n_macc,
            'divisions': 0,
            'sums': 0,
            'comparisons': 0
        }


def setup():
    size(600,600)
    frameRate(50)
    stroke(150,0,150)
    strokeWeight(2)
    global x, y, kolor
    x = 300
    y = 25
    kolor = 0

def draw():
    global x, y, kolor
    ellipse(x, y, 40, 40)
    kolor = kolor + 1
    stroke(150 + kolor,0 + kolor,150 - kolor)
    x = x + 1
    y = y + 1
    if y > 300:
        x = x - 2
        kolor = kolor - 2
    if x < 300:
        y = y - 2
def mousePressed():
    exit()

# 1,25pkt, brakje kolekcji, co bardzo zmniejsza możliwości w zakresie zmiany kolorów, ale już jest ok, możesz przejść dalej


'''8. Матрица 5x4 заполняется вводом с клавиатуры, кроме последних элементов строк.
Программа должна вычислять сумму введенных элементов каждой строки и записывать ее
в последнюю ячейку строки. В конце следует вывести полученную матрицу.
'''

a = [[0 for j in range(4)] for i in range(5)]

# организуем ввод
for i in range(4):
    for j in range(4):
        a[i][j] = float(input("Введите очередное число: "))
    print()

# вычисляем элементы пятой строки
for j in range(4):
    t = 0
    for i in range(4):
        t += a[i][j]
    a[4][j] = t

# распечатываем получившуюся 'матрицу'
for i in range(5):
    for j in range(4):
        print(a[i][j], end="\t")
    print()


import sys

input = sys.stdin.readline

for _ in range(int(input())):

    n,a,b = map(int,input().split())

    g = [[] for i in range(n+1)]

    for i in range(n-1):

        u,v,w = map(int,input().split())

        g[u].append((v,w))

        g[v].append((u,w))

    fa = [0]

    fb = []

    def dfs(u, p, x, vals, dis):

        for v,w in g[u]:

            if v == p: continue

            if v == dis: continue

            dfs(v, u, w^x, vals, dis)

            vals.append(w^x)

    dfs(a, a, 0, fa, b)

    dfs(b, b, 0, fb, -1)

    s = set(fb)

    ans = "NO"

    for i in fa:

        if i in s:

            ans = "YES"

            break

    print(ans)


import keras
from keras.layers.convolutional import Convolution2D
from keras.layers.pooling import MaxPooling2D
from keras.layers.convolutional import Deconvolution2D
from keras.layers.normalization import BatchNormalization

from keras.layers.convolutional import UpSampling2D
from keras.layers import Input, Concatenate, Conv2D
from keras.models import Model, model_from_json
from keras.optimizers import *
import numpy as np

class DispNet:
    def __init__(self):
        super().__init__()
        self.model = None

    # Initialize the model
    def init_model(self):
        Input_2 = Input(shape=(128, 256, 2), name='Input_2')  # 6,768,384

        Convolution2D_1 = Conv2D(name='Convolution2D_1', nb_col=7, nb_filter=64, border_mode='same',
                                 activation='relu', nb_row=7)(Input_2)

        MaxPooling2D_1 = MaxPooling2D(name='MaxPooling2D_1')(Convolution2D_1)
        Convolution2D_3 = Convolution2D(name='Convolution2D_3', nb_col=5, nb_filter=128, border_mode='same',
                                        activation='relu', nb_row=5)(MaxPooling2D_1)
        MaxPooling2D_3 = MaxPooling2D(name='MaxPooling2D_3')(Convolution2D_3)
        Convolution2D_17 = Convolution2D(name='Convolution2D_17', nb_col=5, nb_filter=256, border_mode='same',
                                         activation='relu', nb_row=5)(MaxPooling2D_3)
        MaxPooling2D_8 = MaxPooling2D(name='MaxPooling2D_8')(Convolution2D_17)
        Convolution2D_4 = Convolution2D(name='Convolution2D_4', nb_col=3, nb_filter=256, border_mode='same',
                                        activation='relu', nb_row=3)(MaxPooling2D_8)
        Convolution2D_9 = Convolution2D(name='Convolution2D_9', nb_col=3, nb_filter=512, border_mode='same',
                                        activation='relu', nb_row=3)(Convolution2D_4)
        MaxPooling2D_5 = MaxPooling2D(name='MaxPooling2D_5')(Convolution2D_9)
        Convolution2D_10 = Convolution2D(name='Convolution2D_10', nb_col=3, nb_filter=512, border_mode='same',
                                         activation='relu', nb_row=3)(MaxPooling2D_5)
        Convolution2D_11 = Convolution2D(name='Convolution2D_11', nb_col=3, nb_filter=512, border_mode='same',
                                         activation='relu', nb_row=3)(Convolution2D_10)
        MaxPooling2D_6 = MaxPooling2D(name='MaxPooling2D_6')(Convolution2D_11)
        Convolution2D_12 = Convolution2D(name='Convolution2D_12', nb_col=3, nb_filter=512, border_mode='same',
                                         activation='relu', nb_row=3)(MaxPooling2D_6)
        Convolution2D_13 = Convolution2D(name='Convolution2D_13', nb_col=3, nb_filter=1024, border_mode='same',
                                         activation='relu', nb_row=3)(Convolution2D_12)
        MaxPooling2D_7 = MaxPooling2D(name='MaxPooling2D_7')(Convolution2D_13)
        Convolution2D_14 = Convolution2D(name='Convolution2D_14', nb_col=3, nb_filter=1024, border_mode='same',
                                         activation='relu', nb_row=3)(MaxPooling2D_7)
        Convolution2D_18 = Convolution2D(name='Convolution2D_18', nb_col=3, nb_filter=1, border_mode='same',
                                         activation='relu', nb_row=3)(Convolution2D_14)
        UpSampling2D_1 = UpSampling2D(name='UpSampling2D_1')(Convolution2D_18)
        Deconvolution2D_4 = Deconvolution2D(name='Deconvolution2D_4', nb_col=4, border_mode='same', strides=(2, 2),
                                            nb_filter=512, activation='relu', nb_row=4)(
            Convolution2D_14)  # output_shape=(None, 512, 24, 12),
        BatchNormalization_1 = BatchNormalization(name='BatchNormalization_1')(Deconvolution2D_4)
        merge_2 = Concatenate(axis=3)([Convolution2D_12, BatchNormalization_1, UpSampling2D_1, ])
        Convolution2D_19 = Convolution2D(name='Convolution2D_19', nb_col=3, nb_filter=512, border_mode='same',
                                         activation='relu', nb_row=3)(merge_2)

        Convolution2D_20 = Convolution2D(name='Convolution2D_20', nb_col=3, nb_filter=1, border_mode='same',
                                         activation='relu', nb_row=3)(Convolution2D_19)
        UpSampling2D_2 = UpSampling2D(name='UpSampling2D_2')(Convolution2D_20)
        Deconvolution2D_5 = Deconvolution2D(name='Deconvolution2D_5', nb_col=4, nb_row=4, strides=(2, 2),
                                            padding='same',
                                            activation='relu', nb_filter=256)(Convolution2D_19)
        BatchNormalization_2 = BatchNormalization(name='BatchNormalization_2')(Deconvolution2D_5)
        merge_3 = Concatenate(axis=3)([Convolution2D_10, BatchNormalization_2, UpSampling2D_2])
        Convolution2D_21 = Convolution2D(name='Convolution2D_21', nb_col=3, nb_filter=256, border_mode='same',
                                         activation='relu', nb_row=3)(merge_3)
        Deconvolution2D_24 = Deconvolution2D(name='Deconvolution2D_24', nb_col=4, border_mode='same',
                                             strides=(2, 2), nb_filter=128, activation='relu', nb_row=4)(
            Convolution2D_21)  # output_shape=(None, 128, 96, 48)
        BatchNormalization_3 = BatchNormalization(name='BatchNormalization_3')(Deconvolution2D_24)
        Convolution2D_22 = Convolution2D(name='Convolution2D_22', nb_col=3, nb_filter=1, border_mode='same',
                                         activation='relu', nb_row=3)(Convolution2D_21)
        UpSampling2D_3 = UpSampling2D(name='UpSampling2D_3')(Convolution2D_22)
        merge_4 = Concatenate(axis=3)([Convolution2D_4, BatchNormalization_3, UpSampling2D_3, ])
        Convolution2D_23 = Convolution2D(name='Convolution2D_23', nb_col=3, nb_filter=128, border_mode='same',
                                         activation='relu', nb_row=3)(merge_4)
        Convolution2D_24 = Convolution2D(name='Convolution2D_24', nb_col=3, nb_filter=1, border_mode='same',
                                         activation='relu', nb_row=3)(Convolution2D_23)
        UpSampling2D_4 = UpSampling2D(name='UpSampling2D_4')(Convolution2D_24)
        Deconvolution2D_7 = Deconvolution2D(name='Deconvolution2D_7', nb_col=4, border_mode='same',
                                            strides=(2, 2), nb_filter=64, activation='relu', nb_row=4)(
            Convolution2D_23)  # output_shape=(None, 64, 192, 96)
        BatchNormalization_4 = BatchNormalization(name='BatchNormalization_4')(Deconvolution2D_7)
        merge_5 = Concatenate(axis=3)([MaxPooling2D_3, BatchNormalization_4, UpSampling2D_4])
        Convolution2D_25 = Convolution2D(name='Convolution2D_25', nb_col=3, nb_filter=64, border_mode='same',
                                         activation='relu', nb_row=3)(merge_5)
        Convolution2D_26 = Convolution2D(name='Convolution2D_26', nb_col=3, nb_filter=1, border_mode='same',
                                         activation='relu', nb_row=3)(Convolution2D_25)
        UpSampling2D_5 = UpSampling2D(name='UpSampling2D_5')(Convolution2D_26)
        Deconvolution2D_8 = Deconvolution2D(name='Deconvolution2D_8', nb_col=4, nb_row=4, strides=(2, 2),
                                            padding='same',
                                            activation='relu', nb_filter=32)(
            Convolution2D_25)  # output_shape=(None, 64, 384, 192)
        BatchNormalization_5 = BatchNormalization(name='BatchNormalization_5')(Deconvolution2D_8)
        merge_6 = Concatenate(axis=3)([MaxPooling2D_1, BatchNormalization_5, UpSampling2D_5])
        Convolution2D_27 = Convolution2D(name='Convolution2D_27', nb_col=3, nb_filter=32, border_mode='same',
                                         activation='relu', nb_row=3)(merge_6)
        Convolution2D_28 = Convolution2D(name='Convolution2D_28', nb_col=3, nb_filter=1, border_mode='same',
                                         activation='relu', nb_row=3)(Convolution2D_27)

        model = Model([Input_2], [Convolution2D_28])

        print(model.summary())
        self.model = model
        return model

    # Return the model optimizer
    def get_optimizer(self):
        return Adam()

    # Return the model Loss function
    def get_loss_function(self):
        return 'mean_squared_error'

    # Return the Batch size
    def get_batch_size(self):
        return 32

    # Return the default number of epochs
    def get_num_epoch(self):
        return 100

    # Load model and weights from disk
    def load_model_and_weight(self, model_name):
        # load model
        json_file = open(model_name + '.json', 'r')
        model = json_file.read()
        json_file.close()
        model = model_from_json(model)
        # load weights into model
        model.load_weights(model_name + ".h5")
        print("Loaded model from disk")
        self.model = model

    # Save model and weights into model directory
    def save_model_and_weight(self, model_name):
        # serialize model to JSON
        model_json = self.model.to_json()
        with open(model_name + '.json', "w") as json_file:
            json_file.write(model_json)
        # serialize weights to HDF5
        self.model.save_weights(model_name + '.h5')
        print("Saved model to disk")

    # Compile the model
    def compile(self):
        self.model.compile(optimizer=self.get_optimizer(), loss=self.get_loss_function(), metrics=['accuracy'])
        return self.model

    # Train the model
    def train(self, x, y, x_vl, y_vl, n_epoch=20, batch_size=1):
        self.model.fit([x], y, epochs=n_epoch, batch_size=batch_size, verbose=1,validation_split = 0.2)

    # Check the error rate on its input test data (x_test & y_test) and print the result in consule
    def get_error_rate(self, x_ts, y_ts):
        p = self.model.predict(x_ts, batch_size=self.get_batch_size(), verbose=0)
        mse = np.mean(np.square(y_ts - p))
        print("Error rate is " + str(mse))
        return mse


import random
import networkx as nx
import matplotlib.pyplot as plt
from reachable import reachable_nodes

def cascade(G, A, p):

    nodes = list(G)
    edges = G.edges

    GX = nx.DiGraph()
    GX.add_nodes_from(nodes)

    liveArcs = []
    for edge in edges:
        edgeIsActive = random.random() < p
        if edgeIsActive == True:
            liveArcs.append(edge)

    GX.add_edges_from(liveArcs)

    num_nodes_reached = 0
    for n in A:
        num_nodes_reached = num_nodes_reached + len(reachable_nodes(GX,n))

    return num_nodes_reached, GX


from flask import Flask
from flask import render_template
from flask import *
import keras
import numpy as np
import cv2
import os
from keras.preprocessing import image

model = keras.models.load_model("model/model.h5")
app = Flask(__name__)

folder = "uploads"

def predict():
    try:
        test_img = image.load_img('uploads/1.jpg',target_size = (150,150))
        test_img = image.img_to_array(test_img)
        test_img = np.expand_dims(test_img,axis = 0)
        # return 100
        ans = model.predict(test_img)
        ans = np.argmax(ans)
        if ans == 0:
            return "Actinic keratoses"

        elif ans == 1:
            return "Basal cell carcinoma"

        elif ans == 2:
            return "Benign keratosis-like lesions "

        elif ans == 3:
            return "Melanocytic nevi"

        elif ans == 4:
            return "Melanoma"

        elif ans == 5:
            return "Dermatofibroma"

        elif ans == 6:
            return "Vascular lesions"

        return "normal"
    except:
        return "Please choose jpg or png file only"
@app.route("/",methods = ["GET","POST"])
def upload_predict():
    if request.method == "POST":
        image_file = request.files["image"]
        if image_file:
            location = os.path.join(
                folder,
                "1.jpg"
            )
            image_file.save(location)
            ans = predict()
            return render_template("index.html",prediction=ans)
    return render_template("index.html",prediction="None")

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


from flask import Flask, jsonify
import sqlite3

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
app.config['DEBUG'] = True

def db_connect(query):
    connection = sqlite3.connect('netflix.db')
    cursor = connection.cursor()
    cursor.execute(query)
    result = cursor.fetchall()
    connection.close()
    return result

@app.route('/movie/<title>')
def search_by_title(title):
    query = f"""
        SELECT
            title
            , country
            , release_year
            , listed_in AS genre
            , description
        FROM netflix
        WHERE title = '{title}'
        ORDER BY release_year DESC
        LIMIT 1
    """
    response = db_connect(query)[0]
    response_json = {
        'title': response[0],
        'country': response[1],
        'release_year': response[2],
        'genre': response[3],
        'description': response[4].strip(),
    }
    return jsonify(response_json)

@app.route('/movie/<int:start>/to/<int:end>')
def search_by_period(start, end):
    query = f"""
        SELECT
            title
            , release_year
        FROM netflix
        WHERE release_year BETWEEN {start} AND {end}
        ORDER BY release_year
        LIMIT 100
    """
    response = db_connect(query)
    response_json = []
    for film in response:
        response_json.append({
            'title': film[0],
            'release_year': film[1],
        })
    return jsonify(response_json)

@app.route('/rating/<group>')
def search_by_rating(group):
    levels = {
        'children': ['G'],
        'family': ['G', 'GB', 'PG-13'],
        'adult': ['R', 'NC-17'],
    }

    if group in levels:
        level = '\", \"'.join(levels[group])
        level = f'\"{level}\"'
    else:
        return jsonify([])

    query = f"""
            SELECT
                title
                , rating
                , description
            FROM netflix
            WHERE rating IN ({level})
        """
    print(query)

    response = db_connect(query)
    response_json = []
    for film in response:
        response_json.append({
            'title': film[0],
            'rating': film[1],
            'description': film[2].strip(),
        })
    return jsonify(response_json)

@app.route('/genre/<genre>')
def search_by_genre(genre):
    query = f"""
            SELECT
                title
                , description
            FROM netflix
            WHERE listed_in LIKE '%{genre}%'
            ORDER BY release_year DESC
            LIMIT 10
        """

    response = db_connect(query)
    response_json = []
    for film in response:
        response_json.append({
            'title': film[0],
            'description': film[1],
        })
    return jsonify(response_json)

app.run()


from threading import Thread, Condition
import time
import random

prateleiraMercado = []
controladorFila = Condition()

class Produto(Thread):
    def run(self):
        produtos = ["carne", "ovo", "arroz", "feijão", "macarrão", "banana",
                    "maça", "miojo", "abacaxi", "laranja", "cerveja", "vinho",
                    "cachaça", "creme de leite", "leite condensado", "frango",
                    "café", "óleo", "açucar", "leite", "sal", "detergente",
                    "chocolate", "batata", "cenoura", "quiabo", "acerola",
                    "agua", "suco", "refrigerante", "xuxu", "pepino"]
        global prateleiraMercado
        while True:
            produto = random.choice(produtos)
            controladorFila.acquire()
            prateleiraMercado.append(produto)
            print("Funcionário: Repositor incluiu", produto, "na prateleira.")
            controladorFila.notify()
            controladorFila.release()
            time.sleep(random.random())

class Consumidor(Thread):
    def run(self):
        global prateleiraMercado
        while True:
            controladorFila.acquire()
            if not prateleiraMercado:
                print("Prateleira sem produtos, cliente aguardando repositor.")
                controladorFila.wait()
            produto = prateleiraMercado.pop(0)
            print("Consumidor: Cliente pegou", produto, "da prateleira.")
            controladorFila.release()
            time.sleep(random.random())


#!/usr/bin/env python3
# statistic.py [file_path]

import sys
from collections import defaultdict

file_path = sys.argv[1]
with open(file_path) as f:
    hist = defaultdict(int)
    sum_ = 0
    line_ = 0
    max_ = 0
    for l in f:
        n = int(l.strip())
        hist[n] += 1
        sum_ += n
        line_ += 1
        if max_ < n:
            max_ = n
    average = sum_ / line_
    print('avarage =', average)
    print('sum = ', sum_)
    print('line = ', line_)
    print('max = ', max_)
    print('hist = ', hist)


import argparse
import pandas as pd
import itertools
import os

from ast import literal_eval

from helper_functions import comorbidity_indicator

# Computes basic stats for a data segment; takes in a Pandas Dataframe with
# appropriate fields (sum_costs and num_comorbidities).
def segment_stats(data):
  row_dict = {}
  row_dict['avg_cost'] = data.sum_costs.mean()
  row_dict['std_cost'] = data.sum_costs.std()
  row_dict['num_person_years'] = data.shape[0]
  row_dict['avg_num_com'] = data.no_comorbidities.mean()
  row_dict['std_num_com'] = data.no_comorbidities.std()

  return row_dict

def main(args):
  df_merged = pd.read_csv(args.input_file)
  df_merged.classes = df_merged.classes.apply(lambda x: literal_eval(x))
  df_merged.agg_indices = \
    df_merged.agg_indices.fillna('None').apply(lambda x: literal_eval(x))

  df_merged.sex.fillna('Not provided')
  pop_N = df_merged.shape[0] # grab total number of person-years

  # IMPORT DESCRIPTION INDEX
  desc_dict = pd.read_excel(args.disease_dict).long.to_dict()

  # We will be grouping by pairs of comorbid diseases.
  disease_dyads = [i for i in itertools.combinations(range(len(desc_dict)), 2)]
  # Ancillary function to convert pairs of disease indices to pairs of
  # disease descriptions.
  def map_dyad(d_dyad):
    return [desc_dict[d_dyad[0]], desc_dict[d_dyad[1]]]

  bins = [0,18,35,50,65,150]
  age_labels = ['0-18','18-35','35-50','50-65','65+']
  df_merged['age_bin'] = pd.cut(df_merged.age, bins=bins, labels=age_labels)

  sexes = ['F','M']

  # convert comorbidity list to boolean columns
  ## comorbidity_indicator()
  for i in range(len(desc_dict)):
    df_merged[desc_dict[i]] = comorbidity_indicator(df_merged,[str(i)])

  # disease stats
  diseases_df = pd.DataFrame()
  for i in range(len(desc_dict)):
    temp = df_merged[df_merged[desc_dict[i]]]
    diseases_df = diseases_df.append(pd.Series(segment_stats(temp), name=i))
  diseases_df['frequency'] = diseases_df.num_person_years / pop_N
#  diseases_df.to_csv(os.path.join(args.output_path, 'diseases_all_pop.csv'))

  # comorbid disease dyad stats
  d_dyad_df = pd.DataFrame()

  for i in disease_dyads:
    d_dyad = map_dyad(i)
    d_dyad_segment = df_merged[df_merged[d_dyad[0]] & df_merged[d_dyad[1]]]
    d_dyad_df = d_dyad_df.append(
      pd.Series(segment_stats(d_dyad_segment), name=i)
    )

  expected_df = pd.DataFrame()

  for i in d_dyad_df.index.tolist():
    expected_df = expected_df.append(pd.Series(
      {'expected': (diseases_df.iloc[i[0]].frequency *\
                    diseases_df.iloc[i[1]].frequency) },
      name = i
    ))

  d_dyad_df = pd.concat([d_dyad_df, expected_df], axis = 1)
  d_dyad_df['observed'] = d_dyad_df.num_person_years / pop_N
  d_dyad_df['O/E'] = d_dyad_df.observed / d_dyad_df.expected
  d_dyad_df['diseases'] = d_dyad_df.index.map(map_dyad)
  d_dyad_df['total_cost'] = d_dyad_df.avg_cost * d_dyad_df.num_person_years

  # Filter by minimum number of person-years
  d_dyad_df = d_dyad_df[d_dyad_df.num_person_years >= args.py_filter]

  d_dyad_df.sort_values(by=args.sort_type, ascending=False).to_csv(
    os.path.join(args.output_path, 'disease_dyads_all_pop.csv'),
    index=False, float_format='%.2f'
  )

  if not (args.age_bucket or args.gender_bucket): return
  # diseases + population segments
  buckets = [list(map(lambda x: map_dyad(x), disease_dyads))]
  if args.age_bucket:
    buckets.append(age_labels)
  if args.gender_bucket:
    buckets.append(sexes)
  segments = list(itertools.product(*buckets))

  segments_df = pd.DataFrame()

  for idx, segment in enumerate(segments):
    segment_df = df_merged[df_merged[segment[0][0]] & df_merged[segment[0][1]]]
    if args.age_bucket:
      segment_df = segment_df[segment_df.age_bin == segment[1]]
    if args.gender_bucket:
      segment_df = segment_df[segment_df.sex == segment[-1]]
    stats = segment_stats(segment_df)
    stats['segment'] = segment
    segments_df = segments_df.append(pd.Series(stats, name=idx))

  # Filter by minimum number of person-years
  segments_df = segments_df[segments_df.num_person_years >= args.py_filter]
  segments_df['total_cost'] = segments_df.avg_cost * segments_df.num_person_years

  segments_df.sort_values(by=args.sort_type, ascending=False).to_csv(
    os.path.join(args.output_path, 'disease_dyads_segmented.csv'),
    index=False, float_format='%.2f'
  )

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--disease_dict', default='data/disease_dictionary.xls',
                      help='Dictionary of diseases/conditions to segment by')
  parser.add_argument('--py_filter', default=1, type=int,
                      help='Minimum number of person-years per population ' +
                      'segment to include in results')
  parser.add_argument('--gender_bucket', action='store_true',
                      help='Bucket by gender')
  parser.add_argument('--age_bucket', action='store_true',
                      help='Bucket by age group')
  parser.add_argument('--sort_type', default='total_cost',
                      choices=['total_cost', 'avg_cost', 'num_person_years'],
                      help='Sort results by: total_cost, avg_cost, '
                      'or num_person_years]')
  parser.add_argument('--input_file', type=str, required=True,
                      help='Location of input CSV file containing claims by ' +
                      'person-year')
  parser.add_argument('--output_path', default='output',
                      help='Directory to put output files in')

  args = parser.parse_args()

  if not os.path.exists(args.output_path):
    os.mkdir(args.output_path)

  main(args)


SEED = 0
WORDVECTOR_DIM = 256
WORDVECTOR_WINDOW = 7
WORDVECTOR_MIN_COUNT = 3
WORDVECTOR_N_ITER = 30

DENSE_DROPOUT_RATE = 0.2
RNN_DROPOUT_RATE = 0.3

BATCH_SIZE = 256
EPOCHS = 50
VALIDATION_SPLIT = 0.1

RNN_MODEL_CHECKPOINT_PATH = './rnn.hdf5'
SEMISUPERVISED_RNN_MODEL_CHECKPOINT_PATH = './semirnn.hdf5'
BOW_MODEL_CHECKPOINT_PATH = './bow.hdf5'
PUNCTUATION_MODEL_CHECKPOINT_PATH = './punc.hdf5'
HW5_MODEL_PATH = './hw5.pickle'

SEMISUPERVISED_THRESHOLD = 0.9

BOW_MAX_NUM_WORDS = 5000

STOPWORDS = set(['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you',
'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself',
'she', 'her', 'hers', 'herself', 'it', 'its', 'itself',
'they', 'them', 'their', 'theirs', 'themselves', 'what', 'which',
'who', 'whom', 'this', 'that', 'these', 'those', 'am', 'is', 'are',
'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had',
'having', 'do', 'does', 'did', 'doing', 'a', 'an', 'the', 'and',
'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at',
'by', 'for', 'with', 'about', 'against', 'between', 'into',
'through', 'during', 'before', 'after', 'above', 'below', 'to',
'from', 'up', 'down', 'in', 'out', 'on', 'off', 'under',
'again', 'further', 'then', 'once', 'here', 'there', 'when',
'where', 'all', 'both', 'each', 'few', 'more',
'most', 'other', 'some', 'own',
'same', 'so', 'than', 's', 't', 'now'])


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr  5 08:59:37 2022
## Examples:

    print(convert(value='10:08:06:12',framerate=25,start='10:00:00:00').timecode_to_frames())

    print(convert(value=600,framerate=25,start=500).frames_to_timecode())

    print(convert(value='00:08:06:12',framerate=25,start='00:00:00:00')())

based on the work found in https://stackoverflow.com/a/34607115

#### TODO:
    - consider usiong the meemoo logger

@author: tina
"""
import argparse
import logging
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
logger = logging.getLogger(__name__)  # root logger
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    filename='exporter.log',
                    filemode='a')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('__main__').addHandler(console)

def _timecode(seconds, framerate):
    return '{h:02d}:{m:02d}:{s:02d}:{f:02d}' \
            .format(h=int(seconds/3600),
                    m=int(seconds/60%60),
                    s=int(seconds%60),
                    f=round((seconds-int(seconds))* framerate))

def _frames(seconds, framerate):
    return seconds * framerate

def _seconds(value,framerate):
    if isinstance(value, str):
        _zip_ft = zip((3600, 60, 1, 1/framerate), value.split(':'))
        return sum(f * float(t) for f,t in _zip_ft)
    elif isinstance(value, (int, float)):  # frames
        return value / framerate
    else:
        return 0

class convert(object):
    def __init__(self, value, framerate,start=0):
        self.framerate = framerate
        self.value = value
        self.start = start

    def __call__(self):
        if isinstance(self.value, str):
            timecode = self.value
            return _frames(_seconds(timecode,
                                    self.framerate) - _seconds(self.start,
                                                               self.framerate),
                                                               self.framerate)
        elif isinstance(self.value, (int, float)):
            frames = self.value
            return _timecode(_seconds(frames,
                                      self.framerate) + _seconds(self.start,
                                                                 self.framerate),
                                                                 self.framerate)
    def timecode_to_frames(self,start=None):
        timecode = self.value
        return _frames(_seconds(timecode,
                                self.framerate) - _seconds(self.start,
                                                           self.framerate),
                                                           self.framerate)
    def frames_to_timecode(self,start=None):
        frames = self.value
        return _timecode(_seconds(frames,
                                  self.framerate) + _seconds(self.start,
                                                             self.framerate),
                                                             self.framerate)

def main():
    """## Description:

        - convert a timecode string to frames or frames to timecode

    Args:
         value: string or int

        start: ofset start time eg 10:00:00:00

        framerate: nr of frames / second

    """
    parser = argparse.ArgumentParser(description="export mediahaven partial from browse")
    parser.add_argument(
      "-v",
      "--value",
      help="10:00:00:00 or int 600",
      required=True,
      )
    parser.add_argument(
      "-s",
      "--start",
      help="start frame",
      required=True,
      )
    parser.add_argument(
      "-r",
      "--framerate",
      help="nr of frames / seconds",
      required=True,
      )
    args = parser.parse_args()
    logger.info(str(args))
    o = convert(value=args.value,framerate=int(args.framerate),start=args.start)()
    o = int(round(o))
    print(str(o))
    logger.info(str(o))
    return o

if __name__ == '__main__':
    main()


from matplotlib import pyplot as plt

stat_files = [
    ('Libre', [
        'stats_dtlz1_3.txt',
        ]),
    ('NSGA2', [
        'stats_dtlz1_3__nsga2_1.txt',
        'stats_dtlz1_3__nsga2_2.txt',
        'stats_dtlz1_3__nsga2_3.txt',
    ]),
]

# Get color
def get_color():
    for color in ['b', 'g', 'r']:
        yield color
clrs = get_color()

def show_stats_for_one_file(alg, stats):  # evals, hv, uni
    plt.plot([e[0] for e in stats], [e[1] for e in stats], clrs.next() + '-', label=alg, linewidth=2)

def show_stats_for_files(alg, stats):  # (evals, [hvs], [uni])
    clr = clrs.next()
    plt.plot([e[0] for e in stats], [min(e[1]) for e in stats], clr + '-', label=alg, linewidth=2)
    plt.plot([e[0] for e in stats], [sum(e[1])/len(e[1]) for e in stats], clr + '-', label=alg)
    plt.plot([e[0] for e in stats], [max(e[1]) for e in stats], clr + '-', label=alg, linewidth=2)
    plt.fill_between([e[0] for e in stats], [min(e[1]) for e in stats], [max(e[1]) for e in stats], color=clr, alpha='0.3')

def parse_stats_for_one_file(files):
    open_f = open(files[0], 'r')
    stats = []
    for line in open_f:
        stats.append([float(e) for e in line.split()])
    open_f.close()
    return stats

def parse_stats_for_files(fs):
    stats = []     # [ev, hv, uni]  [ev, hv, uni]  [ev, hv, uni]
    for f in fs:
        stats.append(parse_stats_for_one_file([f]))
    merged = []
    for i in range(len(stats[0])):
        merged.append((stats[0][i][0], [s[i][1] for s in stats], [s[i][2] for s in stats]))
    return merged

if __name__ == '__main__':
    for alg, files in stat_files:
        print('Showing', alg)
        if len(files) == 1:
            show_stats_for_one_file(alg, parse_stats_for_one_file(files))
        else:
            show_stats_for_files(alg, parse_stats_for_files(files))
    plt.ylabel('Hyper volume')
    plt.xlabel('Trials')
    plt.show()


import re
from datetime import datetime, time

from city_scrapers_core.constants import COMMISSION
from city_scrapers_core.items import Meeting
from city_scrapers_core.spiders import CityScrapersSpider

class CookLocalRecordsSpider(CityScrapersSpider):
    name = "cook_local_records"
    agency = "Cook County Local Records Commission"
    timezone = "America/Chicago"
    start_urls = [
        "https://cyberdriveillinois.com/departments/archives/records_management/lrc_cook_county_meeting_schedule.html"  # noqa
    ]
    location = {
        "name": "James R Thompson Center",
        "address": "100 W Randolph St, Room 9-035 Chicago, IL 60601",
    }

    def parse(self, response):
        """
        `parse` should always `yield` Meeting items.

        Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping
        needs.
        """
        description = response.css(".content > p::text").extract_first()
        if not re.search(r"100 W(est)? Randolph", description):
            raise ValueError("Meeting location has changed")
        for item in response.css(".content > ul li"):
            meeting = Meeting(
                title="Local Records Commission",
                description="",
                classification=COMMISSION,
                start=self._parse_start(item),
                end=None,
                all_day=False,
                time_notes="",
                location=self.location,
                links=self._parse_links(item, response),
                source=response.url,
            )

            meeting["status"] = self._get_status(
                meeting, text=" ".join(item.css("*::text").extract())
            )
            meeting["id"] = self._get_id(meeting)

            yield meeting

    def _parse_start(self, item):
        """Parse start datetime as a naive datetime object."""
        day_str = item.xpath("./text()").extract_first()
        date_str = re.search(r"\w+\s+\d{1,2},\s+\d{4}", day_str).group()
        date_obj = datetime.strptime(date_str, "%B %d, %Y")
        return datetime.combine(date_obj.date(), time(11))

    def _parse_links(self, item, response):
        """Parse or generate links."""
        links = []
        for link in item.css("a"):
            links.append(
                {
                    "title": link.xpath("./text()").extract_first().strip(),
                    "href": response.urljoin(link.xpath("@href").extract_first()),
                }
            )
        return links


class Node:
    def __init__(self,data):
        self.data=data
        self.left=None
        self.right=None

def getLevelAndParent(root,key):
    if(root == None):
        return 0,None
    if(root.left != None and root.left.data == key):
        return 1,root
    if(root.right != None and root.right.data == key):
        return 1,root
    llvl,p=getLevelAndParent(root.left,key)
    if(p == None):
        rlvl,p=getLevelAndParent(root.right,key)
        if(p == None):
            return 0,None
        return (rlvl+1),p
    return (llvl+1),p

def inorder(root):
    if(root == None):
        return
    inorder(root.left)
    print(root.data,end=" ")
    inorder(root.right)

def isCousin(root, a, b):
    # inorder(root)
    # print()
    alvl,ap=getLevelAndParent(root,a)
    # print("alvl:{0}, ap:{1}".format(alvl,ap.data))
    blvl,bp=getLevelAndParent(root,b)
    # print("blvl:{0}, bp:{1}".format(blvl,bp.data))

    if(ap != bp and alvl == blvl):
        return 1
    else:
        return 0

def construct(data):
    if(len(data) == 0):
        return None

    root=Node(data.pop(0))
    q=[root]

    while(len(q) > 0):
        n=q.pop(0)
        if(n.left == None and len(data) > 0):
            n.left=Node(data.pop(0))
            q.append(n.left)
        if(n.right == None and len(data) > 0):
            n.right=Node(data.pop(0))
            q.append(n.right)

    return root

def inorder(root):
    if(root == None):
        return
    inorder(root.left)
    print(root.data,end=" ")
    inorder(root.right)

def main(data,a,b):
    root=construct(data)
    inorder(root)
    print()
    print(isCousin(root,a,b))

main([1,2,3,4,5,6,7],4,6)


'''
*****************************************************************************************
*
*                ===============================================
*                   Nirikshak Bot (NB) Theme (eYRC 2020-21)
*                ===============================================
*
*  This script is to implement Task 5 of Nirikshak Bot (NB) Theme (eYRC 2020-21).
*
*  This software is made available on an "AS IS WHERE IS BASIS".
*  Licensee/end user indemnifies and will keep e-Yantra indemnified from
*  any and all claim(s) that emanate from the use of the Software or
*  breach of the terms of this agreement.
*
*  e-Yantra - An MHRD (now MOE) project under National Mission on Education using ICT (NMEICT)
*
*****************************************************************************************
'''

# Team ID:          [ Team-ID ]
# Author List:      [ Names of team members worked on this file separated by Comma: Name1, Name2, ... ]
# Filename:         task_5.py
# Functions:
#                   [ Comma separated list of functions in this file ]
# Global variables:
#                     [ List of global variables defined in this file ]

# NOTE: Make sure you do NOT call sys.exit() in this code.

####################### IMPORT MODULES #######################
## You are not allowed to make any changes in this section. ##
##############################################################
import numpy as np
import cv2
import os, sys
import traceback
import time
import math
import json

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

start_coord_4 = (0, 5)
start_coord_1, end_coords_1, end_coord_4 = (0, 0), (0, 0), (0, 0)
gate = True

# Importing the sim module for Remote API connection with CoppeliaSim
try:
    import sim

except Exception:
    print('\n[ERROR] It seems the sim.py OR simConst.py files are not found!')
    print('\n[WARNING] Make sure to have following files in the directory:')
    print(
        'sim.py, simConst.py and appropriate library - remoteApi.dll (if on Windows), remoteApi.so (if on Linux) or remoteApi.dylib (if on Mac).\n')

# Import 'task_1b.py' file as module
try:
    import task_1b

except ImportError:
    print('\n[ERROR] task_1b.py file is not present in the current directory.')
    print('Your current directory is: ', os.getcwd())
    print('Make sure task_1b.py is present in this current directory.\n')

except Exception as e:
    print('Your task_1b.py throwed an Exception. Kindly debug your code!\n')
    traceback.print_exc(file=sys.stdout)

# Import 'task_1a_part1.py' file as module
try:
    import task_1a_part1

except ImportError:
    print('\n[ERROR] task_1a_part1.py file is not present in the current directory.')
    print('Your current directory is: ', os.getcwd())
    print('Make sure task_1a_part1.py is present in this current directory.\n')

except Exception as e:
    print('Your task_1a_part1.py throwed an Exception. Kindly debug your code!\n')
    traceback.print_exc(file=sys.stdout)

# Import 'task_2a.py' file as module
try:
    import task_2a

except ImportError:
    print('\n[ERROR] task_2a.py file is not present in the current directory.')
    print('Your current directory is: ', os.getcwd())
    print('Make sure task_2a.py is present in this current directory.\n')

except Exception as e:
    print('Your task_2a.py throwed an Exception. Kindly debug your code!\n')
    traceback.print_exc(file=sys.stdout)

# Import 'task_2b.py' file as module
try:
    import task_2b

except ImportError:
    print('\n[ERROR] task_2b.py file is not present in the current directory.')
    print('Your current directory is: ', os.getcwd())
    print('Make sure task_2b.py is present in this current directory.\n')

except Exception as e:
    print('Your task_2b.py throwed an Exception. Kindly debug your code!\n')
    traceback.print_exc(file=sys.stdout)

# Import 'task_3.py' file as module
try:
    import task_3

except ImportError:
    print('\n[ERROR] task_3.py file is not present in the current directory.')
    print('Your current directory is: ', os.getcwd())
    print('Make sure task_3.py is present in this current directory.\n')

except Exception as e:
    print('Your task_3.py throwed an Exception. Kindly debug your code!\n')
    traceback.print_exc(file=sys.stdout)

# Import 'task_4a.py' file as module
try:
    import task_4a

except ImportError:
    print('\n[ERROR] task_4a.py file is not present in the current directory.')
    print('Your current directory is: ', os.getcwd())
    print('Make sure task_4a.py is present in this current directory.\n')

except Exception as e:
    print('Your task_4a.py throwed an Exception. Kindly debug your code!\n')
    traceback.print_exc(file=sys.stdout)

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

# NOTE:    YOU ARE NOT ALLOWED TO MAKE ANY CHANGE TO THIS FUNCTION
#
# Function Name:    send_color_and_collection_box_identified
#        Inputs:    ball_color and collection_box_name
#       Outputs:    None
#       Purpose:    1. This function should only be called when the task is being evaluated using
#                        test executable.
#                    2. The format to send the data is as follows:
#                       'color::collection_box_name'
def send_color_and_collection_box_identified(ball_color, collection_box_name):
    global client_id

    color_and_cb = [ball_color + '::' + collection_box_name]
    inputBuffer = bytearray()
    return_code, retInts, retFloats, retStrings, retBuffer = sim.simxCallScriptFunction(client_id,
                                                                                'evaluation_screen_respondable_1',
                                                                                sim.sim_scripttype_childscript,
                                                                                'color_and_cb_identification',
                                                                                [], [], color_and_cb,
                                                                                inputBuffer,
                                                                                sim.simx_opmode_blocking)

################# ADD UTILITY FUNCTIONS HERE #################
## You can define any utility functions for your code.      ##
## Please add proper comments to ensure that your code is   ##
## readable and easy to understand.                         ##
##############################################################
def get_start_end_coord(data, cl):
    global start_coord_1, end_coord_1, end_coord_4
    tmp = data[cl][0]
    del data[cl][0]
    if tmp == "T1_CB1":
        end_coord_4 = (5, 9)
        start_coord_1 = (5, 0)
        end_coord_1 = (0, 4)
    elif tmp == "T1_CB2":
        end_coord_4 = (5, 9)
        start_coord_1 = (5, 0)
        end_coord_1 = (4, 9)
    elif tmp == "T1_CB3":
        end_coord_4 = (5, 9)
        start_coord_1 = (5, 0)
        end_coord_1 = (9, 5)

    return tmp

def draw_setpoint(client_id, coords, table):
    coppelia_coord = []

    for element in coords:
        coppelia_coord.append(((10 * element) - 45) / 100)

    inputBuffer = bytearray()

    return_code, retInts, retFloats, retStrings, retBuffer = sim.simxCallScriptFunction(client_id,
                                                                                "top_plate_respondable_t" + str(table) + "_1",
                                                                                sim.sim_scripttype_customizationscript,
                                                                                "drawSetpoint", [],
                                                                                coppelia_coord, [],
                                                                                inputBuffer,
                                                                                sim.simx_opmode_blocking)

def send_data_to_draw_path(client_id, path, n):
    coppelia_sim_coord_path = []

    for coord in path:
        for element in coord:
            coppelia_sim_coord_path.append(((10 * element) - 45) / 100)

    inputBuffer = bytearray()

    return_code, retInts, retFloats, retStrings, retBuffer = sim.simxCallScriptFunction(client_id,
                                                                                "top_plate_respondable_t" + str(n) + "_1",
                                                                                sim.sim_scripttype_customizationscript,
                                                                                'drawPath', [],
                                                                                coppelia_sim_coord_path, [],
                                                                                inputBuffer,
                                                                                sim.simx_opmode_blocking)

    ##################################################
def convert_path_to_pixels(path):
    pixel_path = []
    for coord in path:
        pixel_path.append((coord[0] * 128 + 64, coord[1] * 128 + 64))

    return pixel_path

def convert_pixel_to_path(coord):
    coord = [(coord[0] - 64) / 128, (coord[1] - 64) / 128]

    return coord

def traverse_path(pixel_path, table):
    global gate

    turns = []
    prev_turn = pixel_path[0]
    n = len(pixel_path)
    signx, signy = 1, 1
    tmp = 30
    for i in range(1, len(pixel_path) - 1):
        signx = -1 * np.sign(pixel_path[i][0] - pixel_path[i - 1][0])
        signy = -1 * np.sign(pixel_path[i][1] - pixel_path[i - 1][1])
        if (pixel_path[i][0] == pixel_path[i - 1][0] and pixel_path[i][1] == pixel_path[i + 1][1]) or \
                (pixel_path[i][1] == pixel_path[i - 1][1] and pixel_path[i][0] == pixel_path[i + 1][0]):
            turns.append([pixel_path[i][1] + signy * tmp, pixel_path[i][0] + signx * tmp])
            prev_turn = pixel_path[i]
        elif abs(prev_turn[0] - pixel_path[i][0]) > 100 or abs(prev_turn[1] - pixel_path[i][1]) > 100:
            turns.append([pixel_path[i][1] + signy * tmp, pixel_path[i][0] + signx * tmp])
            prev_turn = pixel_path[i]

    for i in range(0, len(turns)):
        if turns[i][0] < 70:
            turns[i][0] = turns[i][0] + 30
        if turns[i][0] > 1200:
            turns[i][0] = turns[i][0] - 35
        if turns[i][1] < 70:
            turns[i][1] = turns[i][1] + 30
        if turns[i][1] > 1200:
            turns[i][1] = turns[i][1] - 35

    turns.append([pixel_path[n - 1][1] + signy * 25, pixel_path[n - 1][0] + signx * 25])
    t1, t2 = 0, 0

    print("\nTurns array generated!", len(turns))

    cnt = 0
    for i in range(0, len(turns)):
        cnt = 0
        task_3.change_setpoint(turns[i])
        gate = True
        #draw_setpoint(client_id, convert_pixel_to_path(turns[i]), table)

        flag = 0
        while True:
            vision_sensor_image, image_resolution, return_code = task_2a.get_vision_sensor_image(client_id,
                table)

            transformed_image = task_2a.transform_vision_sensor_image(vision_sensor_image, image_resolution)
            warped_img = task_1b.applyPerspectiveTransform_vs(transformed_image)

            if warped_img is None:
                continue

            shapes = task_1a_part1.scan_image(warped_img, True)

            print(shapes)
            print("Current setpoint: ", turns[i])
            print("\n")
            if len(shapes) == 0:
                continue

            center_x = shapes['Circle'][1]
            center_y = shapes['Circle'][2]
            return_code_signal, t1_string = sim.simxGetStringSignal(client_id, 'time', sim.simx_opmode_streaming)

            if return_code_signal == 0:
                t1 = float(t1_string)

            if turns[i][0] + 30 > center_x > turns[i][0] - 30 and turns[i][
                1] + 30 > center_y > turns[i][1] - 30:
                while turns[i][0] + 30 > center_x > turns[i][0] - 30 and turns[i][
                    1] + 30 > center_y > turns[i][1] - 30:

                    print("\nInside safe zone!\n")

                    return_code_signal, t2_string = sim.simxGetStringSignal(client_id, 'time', sim.simx_opmode_buffer)

                    if return_code_signal == 0:
                        t2 = float(t2_string)

                    vision_sensor_image, image_resolution, return_code = task_2a.get_vision_sensor_image(client_id,
                        table)
                    transformed_image = task_2a.transform_vision_sensor_image(vision_sensor_image, image_resolution)
                    warped_img = task_1b.applyPerspectiveTransform_vs(transformed_image)

                    if warped_img is None:
                        continue

                    shapes = task_1a_part1.scan_image(warped_img, True)
                    if len(shapes) == 0:
                        continue

                    center_x = shapes['Circle'][1]
                    center_y = shapes['Circle'][2]

                    if t2 - t1 > 0.3:
                        print("Hue hue hue")
                        flag = 1
                        break
                    else:
                        print("Calling control logic 1!")

                        if gate:
                            print("Waiting1")
                            time.sleep(0)
                            gate = False
                            previous_error_x = turns[i][1] - center_x
                            previous_error_y = turns[i][0] - center_y
                            task_3.control_logic(center_x, center_y, table, client_id, previous_error_x, previous_error_y)
                        else:
                            task_3.control_logic(center_x, center_y, table, client_id, 0, 0)
            else:
                print("Calling control logic 2!")

                if gate:
                    print("Waiting2")
                    time.sleep(0)
                    gate = False
                    previous_error_y = turns[i][0] - center_x
                    previous_error_x = turns[i][1] - center_y
                    task_3.control_logic(center_x, center_y, table, client_id, previous_error_x, previous_error_y)
                else:
                    task_3.control_logic(center_x, center_y, table, client_id, 0, 0)

            if flag == 1:
                break

            print(i)
            if len(turns) -1 == i and cnt == 20:
                break
            else:
                cnt = cnt +1

def main(rec_client_id):
    maze_t4 = cv2.imread('maze_t4.jpg')
    maze_t1 = cv2.imread('maze_t1.jpg')
    print("Maze images read!\n")

    warped_img_t4 = task_1b.applyPerspectiveTransform(maze_t4)
    warped_img_t1 = task_1b.applyPerspectiveTransform(maze_t1)
    maze_array_t4 = task_1b.detectMaze(warped_img_t4)
    maze_array_t1 = task_1b.detectMaze(warped_img_t1)
    print("Maze array detected: \nT4: ", maze_array_t4, "T1: ", maze_array_t1)

    return_code = task_2b.send_data(rec_client_id, maze_array_t4, "top_plate_respondable_t4_1")
    return_code = task_2b.send_data(rec_client_id, maze_array_t1, "top_plate_respondable_t1_1")
    print("\nMaze generated!\n")

    with open("ball_details.json") as f:
        data = json.load(f)
    print(data)

    return_code = task_2a.start_simulation(rec_client_id)
    print("Simulation started!\n")

    task_3.init_setup(rec_client_id)

    shapes = {}
    while shapes.get("Circle") is None:
        img_vs5, res, _ = task_2b.get_vision_sensor_image(rec_client_id, 5)
        img = task_2b.transform_vision_sensor_image(img_vs5, res)
        shapes = task_1a_part1.scan_image(img, False)

    cl = shapes["Circle"][0]
    print(cl)
    tmp = get_start_end_coord(data, cl)
    send_color_and_collection_box_identified(cl, tmp)
    print(start_coord_1, end_coord_1, end_coord_4, start_coord_4)

    # start coord and end coord from json ---- for t_4 start coord = (0, 4) end coord depends on cl end coord = (5, 9)
    # for t_4
    path_t4 = task_4a.find_path(maze_array_t4, start_coord_4, end_coord_4)
    send_data_to_draw_path(rec_client_id, path_t4, 4)

    path_t1 = task_4a.find_path(maze_array_t1, start_coord_1, end_coord_1)
    send_data_to_draw_path(rec_client_id, path_t1, 1)

    print("\nPath sent to CoppeliaSim\n")
    pixel_path_t4 = convert_path_to_pixels(path_t4)
    print("Entering traverse path\n")
    traverse_path(pixel_path_t4, 4)
    print("Ball traversed!")
    time.sleep(1) # why this addition
    # for t_1 ----- for t_1 start coord = (0, 5) end coord depend on cl end coord = (0, 4)
    print("Path sent to CoppeliaSim")
    pixel_path_t1 = convert_path_to_pixels(path_t1)
    print("Entering traverse path\n")
    traverse_path(pixel_path_t1, 1)
    print("Ball traversed!")

    return_code = task_2a.stop_simulation(rec_client_id)

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

# Function Name:    main (built in)
#        Inputs:    None
#       Outputs:    None
#       Purpose:    To call the main(rec_client_id) function written by teams when they
#                    run task_5.py only.

# NOTE: Write your solution ONLY in the space provided in the above functions. This function should not be edited.
if __name__ == "__main__":
    client_id = task_2a.init_remote_api_server()
    main(client_id)


#!/usr/bin/env python3

""" A script to convert a video downloaded with yt-dlp to an audio format"""

import argparse
import os
import subprocess
import sys
from shutil import which

parser = argparse.ArgumentParser(description="Convert audio files to mp3")
parser.add_argument("audio_file", help="audio file to convert")
args = parser.parse_args()

# Checking if ffmpeg is installed
if not which("ffmpeg"):
    print("ffmpeg is not installed")
    sys.exit(1)

formats = [".m4a", ".webm", ".opus", ".mkv", ".ogg", ".wav", ".flac"]
# auto-detect file extension
# formats = []
# for format in subprocess.run(["ffmpeg", "-formats"], capture_output=True).stdout.decode().splitlines():
#     if format.startswith(" D "):
#         formats.append(format.split()[1])

file_path = os.path.dirname(args.audio_file)

def mp3_convert(audio_file):
    """Convert file to mp3. If file is already mp3, do nothing"""

    if not os.path.isfile(audio_file):
        print("::: File not specified.")
        sys.exit(1)

    if audio_file.endswith(".mp3"):
        print("::: File is already mp3. Exiting...")
        sys.exit(0)
    else:
        file_name = os.path.splitext(audio_file)[0]
        file_ext = os.path.splitext(audio_file)[1]
        if file_ext in formats:
            new_file = file_name + ".mp3"
            subprocess.run(
                [
                    "ffmpeg",
                    "-i",
                    audio_file,
                    "-c:a",
                    "libmp3lame",
                    "-b:a",
                    "320k",
                    new_file,
                ],
                check=True,
            )
            os.remove(audio_file)
        else:
            print("\nFile doesn't match any of the supported formats:")
            # print formats as bullet points
            for f in formats:
                print(f"* {f}")
            sys.exit(1)

if __name__ == "__main__":
    mp3_convert(args.audio_file)


import json
import requests
import query as ep

class server(ep):

  global endpoint_url
  endpoint_url = f"https://api.spotify.com/v1/users/{ep.user_id}/playlists"

  def request_generator(self,name = "unnamed", desc = "unnamed", is_public = False):

    request_body = json.dumps({
      "name": name,
      "description": desc,
      "public": is_public
      })

    return request_body

  def playlist_id_generator(self, request_body):

    response = requests.post(url = server.endpoint_url, data = request_body, headers={
      "Content-Type":"application/json",
      "Authorization":f"Bearer {ep.token}"})

    if response.status_code != 201:
      return "HTTP Error"

    url = response.json()['external_urls']['spotify']

    return (response.json()['id'], url)

  def playlist_run(self):
    req  = self.request_generator("demop_playlist","playlist created with python",False)
    playlist_id, playlist_url = self.playlist_id_generator(req)
    playist_endpoint_url = f"https://api.spotify.com/v1/playlists/{playlist_id}/tracks"

    request_body = json.dumps({
          "uris" : ep.uris
        })
    response = requests.post(url = endpoint_url, data = request_body, headers={"Content-Type":"application/json",
                        "Authorization":f"Bearer {ep.token}"})

    if response.status_code != 201:
          print("HTTP Error")
    return playlist_url


from __future__ import unicode_literals
from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin
from django.core.validators import (
    RegexValidator,
    )
from django.db import models
from django.urls import reverse
from django.conf import settings
from .managers import UserManager
from django.utils.translation import ugettext_lazy as _
from django_resized import ResizedImageField

NAME_REGEX = '^[a-zA-Z ]*$'

GENDER_CHOICE = (
    ("Male", "Male"),
    ("Female", "Female"),
    ("Prefer not to say", "Prefer not to say"),
    )

class User(AbstractBaseUser, PermissionsMixin):

    email = models.EmailField(unique=True)
    first_name = models.CharField(
        max_length=256,
        blank=False,
        validators=[
                RegexValidator(
                    regex=NAME_REGEX,
                    message='Name must be Alphabetic',
                    code='invalid_first_name'
                    )
                ]
        )
    last_name = models.CharField(
        max_length=256,
        blank=False,
        validators=[
                RegexValidator(
                    regex=NAME_REGEX,
                    message='Name must be Alphabetic',
                    code='invalid_last_name'
                    )
                ]
        )

    gender = models.CharField(max_length=25, choices=GENDER_CHOICE,help_text="Select gender")
    date_joined = models.DateTimeField(auto_now_add=True)
    balance = models.DecimalField(
        default=0,
        max_digits=12,
        decimal_places=2
        )

    bonus = models.DecimalField(
        default=0,
        max_digits=12,
        decimal_places=2
        )

    picture = ResizedImageField(
        size=[128, 128],
        crop=['top','left'],
        quality=80,
        upload_to="media-root/",
        null=True,
        blank=False,
        )

    is_staff = models.BooleanField(_("is staff"), default=False)
    is_active = models.IntegerField(default = 1,
                                   blank = True,
                                    null = True,
                                    help_text ='1->Active, 0->Inactive',
                                    choices =(
                                    (1, 'Active'), (0, 'Inactive')
                                    ))
    email_confirmed = models.BooleanField(default=False)

    objects = UserManager()

    # USERNAME_FIELD = 'email'  # use email to log in
    USERNAME_FIELD = 'email'  # use email to log in
    REQUIRED_FIELDS = []  # required when user is created

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_full_name(self):
        fullname = '%s %s' %(self.first_name, self.last_name)
        return fullname.strip()

    def get_short_name(self):
        return self.first_name

    def Save(self, *args, **kwargs):
        super(User, self).save(*args, **kwargs)

    def __str__(self):
        return str(self.last_name+' '+self.first_name)


from splinter import Browser
from bs4 import BeautifulSoup
import pandas as pd
import time

def init_browser():

    executable_path = {"executable_path": "/usr/local/bin/chromedriver"}
    return Browser("chrome", **executable_path, headless=False)

def scrape():
    browser = init_browser()

    title, body = scrape_news()

    mars_data={"news_title":title,
                "paragraph":body,
                "main_image":featured_image(),
                "Mars_Facts":mars_facts(),
                "Hemisphere_urls":mars_images()
    }

    browser.quit()
    return mars_data

def scrape_news():

    browser = init_browser()

    url = 'https://mars.nasa.gov/news'
    browser.visit(url)

    time.sleep(1)

    html = browser.html

    soup = BeautifulSoup(html, 'html.parser')

    try:
        results = soup.find_all('div', class_='content_title')
        title = results[1].text
        results1 = soup.find_all('div', class_='article_teaser_body')
        body = results1[0].text
    except AttributeError:
        return None, None

    browser.quit()

    return title, body

def featured_image():

    browser = init_browser()

    url2 = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars'
    browser.visit(url2)

    time.sleep(1)

    image_element = browser.find_by_id("full_image")
    image_element.click()

    more_info_element = browser.links.find_by_partial_text('more info')
    more_info_element.click()

    html2 = browser.html
    soup2 = BeautifulSoup(html2, 'html.parser')

    try:
        image1 = soup2.select_one('figure.lede a img').get("src")
        url3 = "https://www.jpl.nasa.gov"
        featured_image_url = url3 + image1
    except AttributeError:
        return None, None
    browser.quit()
    return featured_image_url

def mars_facts():
    browser = init_browser()

    url3 = 'https://space-facts.com/mars/'
    tables = pd.read_html(url3)
    df1 = tables[1]
    df1.set_index(["Mars - Earth Comparison"],inplace=True)
    html_table = df1.to_html()

    browser.quit()
    return html_table

def mars_images():
    browser = init_browser()
    mars_urls = ['https://astrogeology.usgs.gov/search/map/Mars/Viking/cerberus_enhanced','https://astrogeology.usgs.gov/search/map/Mars/Viking/schiaparelli_enhanced','https://astrogeology.usgs.gov/search/map/Mars/Viking/syrtis_major_enhanced','https://astrogeology.usgs.gov/search/map/Mars/Viking/valles_marineris_enhanced']
    hemisphere_image_urls = []
    for mars in mars_urls:
        #url_mars = mars
        browser.visit(mars)
        html_mars = browser.html
        soup_mars = BeautifulSoup(html_mars, 'html.parser')
        results4 = soup_mars.find('div', class_='downloads')
        image_url = results4.a['href']
        mars_title = soup_mars.find('h2', class_='title').text

        hemisphere_image_urls.append({'title': mars_title,'image_url': image_url})

    browser.quit()
    return hemisphere_image_urls


import discord

class Number:
    def __init__(self, number, claimed=False):
        self.number: int | None = number
        self.claimed: bool = claimed

class Player:
    def __init__(self, member, board):
        self.member: discord.Member = member
        self.board: list[list[Number]] = board

    def get_number_coordinates(self, number: int):
        x_cords, y_cords = 0, 0

        for y in self.board:
            for x in y:
                if x is not None:
                    if x.number == number:
                        return x_cords, y_cords

                x_cords += 1

            y_cords += 1

        return None, None

    def claim(self, number: int):
        x, y = self.get_number_coordinates(number)

        if x is None or y is None:
            return

        self.board[y][x].claimed = True

class Winner:
    def __init__(self, player, win_type):
        self.player: Player = player
        self.win_type: str = win_type