import tweepy
from textblob import TextBlob
import preprocessor as p
import statistics
from typing import List

from keys import consumer_key, consumer_secret

print(consumer_key)
print(consumer_secret)

auth = tweepy.AppAuthHandler(consumer_key, consumer_secret)
api = tweepy.API(auth)

def get_tweets(keyword: str) -> List[str]:

    all_tweets = []

    for tweet in tweepy.Cursor(api.search_tweets, q=keyword, tweet_mode='extended', lang='es').items(100):
        all_tweets.append(tweet.full_text)

   # for tweet in all_tweets:
    #    print(tweet)

    return all_tweets

def clean_tweets(all_tweets: List[str]) -> List[str]:

    tweets_clean = []
    for tweet in all_tweets:
        tweets_clean.append(p.clean(tweet))

    return tweets_clean

def get_sentiment(all_tweets: List[str]) -> List[float]:

    sentiment_scores = []

    for tweet in all_tweets:
        blob = TextBlob(tweet)
        sentiment_scores.append(blob.sentiment.polarity)

    return sentiment_scores

def generate_average_sentiment_score(keyword: str) -> int:

    tweets = get_tweets(keyword)
    tweets_clean = clean_tweets(tweets)
    sentiment_scores = get_sentiment(tweets_clean)

    average_score = statistics.mean(sentiment_scores)

    return average_score

if __name__ == "__main__":

    print("Primera Keyword:")
    first_thing = input()
    print("Segunda Keyword:")
    second_thing = input()
    print("\n")

    first_score = generate_average_sentiment_score(first_thing)
    second_score = generate_average_sentiment_score(second_thing)

    print(f"Puntuacion Primera Keyword: {first_score}")
    print(f"Puntuacion Segunda Keyword: {second_score}")


from django.shortcuts import render,redirect
from django.http import HttpResponse, JsonResponse
from django.template import loader
# from administracion.models import Producto, Varietal

def hola_tienda(request):
    return HttpResponse('Bienvenido a la Tienda')

def index(request):
   template = loader.get_template('tienda/index.html')
   context={'titulo':'Inicio'}
   return HttpResponse(template.render(context,request))

# def indexp(request):
#     template_name="index.html"
#     varietales=Varietal.objects.filter(activo=True)
#     productos=Producto.objects.filter(activo=True)
#     context ={"productos":productos, "varietales":varietales}
#     return render(request,template_name,context)

# def index(request):
#    template = loader.get_template('tienda/index.html')
#    varietales=Varietal.objects.filter(activo=True)
#    productos=Producto.objects.filter(activo=True)
#    context={'titulo':'Inicio','producto':productos,'varietal':varietales}
#    return HttpResponse(template.render(context,request))

# def producto(request):
#    template = loader.get_template('tienda/productos.html')
#    context={'titulo':'Producto'}
#    return HttpResponse(template.render(context,request))

def index(request):
    if(request.method=='GET'):
        titulo = 'Titulo cuando accedo por GET'
    else:
        titulo = 'Titulo cuando accedo por otro método'
    parametro_uno = request.GET.get('param')

    listado_cursos = [
        {'nombre': 'Diseño UX/UI',
         'descripcion': 'Diseño' ,
         'categoria': 'Diseño',
         },
         {'nombre':'Fullstack Java',
         'descripcion': 'Curso FullStack',
         'categoria': 'Programacion',
         },
         {'nombre': 'Big Data',
         'descripcion': 'test',
         'categoria': 'Analisis de Datos',
         },
         {'nombre': 'Big Data Avanzada',
         'descripcion': 'test',
         'categoria': 'Analisis de Datos',
         },
    ]

    return render(request,'tienda/index.html',
                  {'titulo':titulo,
                   'parametro_uno':parametro_uno,
                   'cursos':listado_cursos
                  })

#Create your views here.

def api_productos(request):
   productos = [{
       'nombre': 'D.V. catena - tinto histórico 2019',
       'varietal': 'Blend',
       'portada': 'https://vinotecaligier.com/media/catalog/product/cache/1/image/500x500/9df78eab33525d08d6e5fb8d27136e95/b/e/be72477.jpg',
       'bodega': 'catena zapata',
       'precio': '3500'
   },{
       'nombre': 'White Bones',
       'varietal': 'Chardonnay',
       'portada': 'https://vinotecaligier.com/media/catalog/product/cache/1/small_image/430x320/9df78eab33525d08d6e5fb8d27136e95/b/e/be76371_base.jpg',
       'bodega': 'catena zapata',
       'precio': '42200'
   },{
       'nombre': 'River',
       'varietal': 'Malbec',
       'portada': 'https://vinotecaligier.com/media/catalog/product/cache/1/image/500x500/9df78eab33525d08d6e5fb8d27136e95/b/e/be72477.jpg',
       'bodega': 'catena zapata',
       'precio': '45600'
    },{
       'nombre': 'Saint Felicien',
       'varietal': 'Rose',
       'portada': 'https://http2.mlstatic.com/D_NQ_NP_601614-MLA52995055033_122022-V.jpg',
       'bodega': 'catena zapata',
       'precio': '9300'
    },{
       'nombre': 'Saint Felicien',
       'varietal': 'Sauvignon Blanc',
       'portada': 'https://cepadevinos.com/wp-content/uploads/2017/07/Saint_Felicien_Sauvignon_Blanc_qbs3es.jpg',
       'bodega': 'catena zapata',
       'precio': '42200'
    },{
       'nombre': 'Nicasia Vineyard Doux',
       'varietal': 'Espumante',
       'portada': 'https://www.espaciovino.com.ar/media/default/0001/65/thumb_64247_default_big.jpeg',
       'bodega': 'catena zapata',
       'precio': '42200'
    },{
       'nombre': 'Paraiso',
       'varietal': 'Blend',
       'portada': 'https://cepadevinos.com/wp-content/uploads/2017/07/Saint_Felicien_Sauvignon_Blanc_qbs3es.jpg',
       'bodega': 'Luigi Bosca',
       'precio': '42200'
    },{
       'nombre': 'Los Nobles',
       'varietal': 'Chardonnay',
       'portada': 'https://vinotecaligier.com/media/catalog/product/cache/1/image/500x500/9df78eab33525d08d6e5fb8d27136e95/b/e/be72477.jpg',
       'bodega': 'Luigi Bosca',
       'precio': '42200'
    },]
   response = {'status':'Ok', 'code':200, 'message':'Listado de productos', 'data':productos}
   return JsonResponse(response,safe=False)

def productos(request):
    return render(request,'tienda/productos.html')


import cmath
import math
from scipy.fftpack import fft, ifft

class FourierTransform:
    count = 0

    @staticmethod
    def fft_convolution(self, sig1, sig2):
        self.count += len(sig1)
        return list(map(lambda x, y: x * y, sig1, sig2))

    @staticmethod
    def fft_correlation(self, sig1, sig2):
        self.count += len(sig1)
        return list(map(lambda x, y: x.conjugate() * y, sig1, sig2))

    @staticmethod
    def _fft(self, _in_values, direction):
        _out_values = self._fft_(self, _in_values, direction)

        if direction == -1:
            n = len(_in_values)
            for i in range(n):
                _out_values[i] /= n

        if direction == 1:
            return fft(_in_values)
        else:
            return ifft(_in_values)

    @staticmethod
    def _fft_(self, _values, direction):
        n = len(_values)

        if n == 1:
            return _values

        _values_even = [complex(0, 0)] * (int(n / 2))
        _values_odd = [complex(0, 0)] * (int(n / 2))

        for i in range(n):
            if i % 2 == 0:
                _values_even[int(i / 2)] = _values[i]
            else:
                _values_odd[int(i / 2)] = _values[i]

        _b_even = self._fft_(self, _values_even, direction)
        _b_odd = self._fft_(self, _values_odd, direction)

        w_n = complex(cmath.exp(direction * (-1) * 2 * cmath.pi * complex(0, 1) / n))
        w = 1
        y = [complex(0, 0)] * n

        for i in range(int(n / 2)):
            y[i] = _b_even[i] + _b_odd[i] * w
            y[i + int(n / 2)] = _b_even[i] - _b_odd[i] * w
            w *= w_n
            self.count += 1

        return y

    @staticmethod
    def _fft_reorder(self, _data, _len):
        if _len <= 2:
            return
        for x in range(_len):
            r = self.rev_next(x, _len)
            if r > x:
                temp = _data[x]
                _data[x] = _data[r]
                _data[r] = temp

        return _data

    @staticmethod
    def rev_next(x, n):
        step = math.log2(n)
        r = 0
        while step != 0:
            r <<= 1
            r += (x & 1)
            x >>= 1
            step -= 1

        return r


from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, redirect

from django.views import View, generic
from .models import Course, Opinion, Lesson, Contact
from users.models import User

class HomeView(View):
    def get(self, request, *args, **kwargs):
        courses = Course.objects.all()
        teachers = User.objects.filter(role="TEACHER")
        opinions = Opinion.objects.all()
        return render(request, 'index.html', context={
                                                "courses": courses,
                                                "teachers": teachers,
                                                "opinions": opinions,
                                                })

class CourseDetailView(View):
    def get(self, request, pk, *args, **kwargs):
        try:
            course = Course.objects.get(pk=pk)
        except:
            return redirect('home')
        if request.user.is_authenticated:
            enroll = True if request.user in course.students.all() else False
        else:
            enroll = False
        return render(request, 'detail.html', context={"course": course, 'enroll': enroll})

class CourseListView(generic.ListView):
    model = Course
    queryset = Course.objects.all()
    template_name = 'courses.html'

    # def get_queryset(self):
    #     user = self.request.user
    #     print(user)
    #     object_list = Course.objects.filter(students=user)
    #     print(object_list)
    #     return object_list

class AboutView(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'about.html')

class ContactView(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'contact.html')

    def post(self, request):
        n = request.POST.get('name')
        e = request.POST.get('email')
        s = request.POST.get('subject')
        m = request.POST.get('message')
        try:
            Contact.objects.create(name=n, email=e, subject=s, message=m)
        except:
            pass
        return redirect('home')

class EnrollCourseView(LoginRequiredMixin, View):
    def get(self, request, pk):
        try:
            course = Course.objects.get(pk=pk)
        except:
            return redirect('home')

        course.students.add(request.user)
        if request.user.is_authenticated:
            enroll = True if request.user in course.students.all() else False
        else:
            enroll = False

        return render(request, 'detail.html', context={"course": course, 'enroll': enroll})

    def post(self, request, pk):
        id=request.POST.get('id')
        try:
            course = Course.objects.get(id=id)
        except:
            return redirect('home')

        course.students.add(request.user)
        if request.user.is_authenticated:
            enroll = True if request.user in course.students.all() else False
        else:
            enroll = False

        return render(request, 'detail.html', context={"course": course, 'enroll': enroll})

class LessonsListView(LoginRequiredMixin, View):

    def get(self, request, pk, *args, **kwargs):
        lesson_id = self.request.GET.get('lesson', None)
        print(lesson_id)
        try:
            course = Course.objects.get(pk=pk)
        except:
            return redirect('home')
        object_list = Lesson.objects.filter(course_id=pk)

        if lesson_id:
            lesson = Lesson.objects.filter(id=lesson_id).first()
        else:
            lesson = Lesson.objects.filter(course=course, number=1)

        return render(request, 'course-lessons.html', {'lessons': object_list, 'course': course, 'lesson': lesson})


#!/usr/bin/python
import time
import picamera
import os
path=os.getenv("HOME")+""  #adjust path for location of this program
with picamera.PiCamera() as picam:
    picam.rotation=90 #adjust as necessary
    picam.start_preview()
    time.sleep(5)
    picam.capture('pic.jpg')
    # picam.capture(path+'/photo.jpg',resize=(640,480))
    # time.sleep(2)
    picam.stop_preview()
    picam.close()


import cv2
import numpy as np

def imRead(loc,mode):
    type=''
    if(mode=='Gray'):
        type=cv2.IMREAD_GRAYSCALE
    elif(mode=='Color'):
        type=cv2.IMREAD_ANYCOLOR
    else:
        type=cv2.IMREAD_ANYCOLOR

    return cv2.imread(loc,type)

def subMat(img, rect):
    x=rect[0]
    y=rect[1]
    width=rect[2]
    height=rect[3]
    crop=img[y:y+height,x:x+width]
    return crop

def coorTemplateMatch(img,tmp,threshold):
    res = cv2.matchTemplate(img,tmp,cv2.TM_CCOEFF_NORMED)
    minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(res)
    loc = np.where(res >= threshold) #좌표값 따기
    w, h = tmp.shape[::-1]

    for pt in zip(*loc[::-1]):
        cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2) #박스표시하기
        result_X=pt[0]
        result_Y=pt[1]
        return result_X,result_Y,img

def bTemplateMatch(img,tmp,threshold):
    try:
        res = cv2.matchTemplate(img,tmp,cv2.TM_CCOEFF_NORMED)
    except:
        tmp=cv2.cvtColor(tmp,cv2.COLOR_RGB2GRAY)
        res = cv2.matchTemplate(img,tmp,cv2.TM_CCOEFF_NORMED)

    minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(res)
    threshold = 0.8
    #loc = np.where(res >= threshold) #좌표값 따기
    #for pt in zip(*loc[::-1]):
    #cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2) #박스표시하기
    return True if maxVal>threshold else False

def Resize(img,mul):
    resize=cv2.resize(img, dsize=(0, 0), fx=mul, fy=mul, interpolation=cv2.INTER_LINEAR)
    return resize

def Sharpening(img,mode,arg):
    sharpening_mask1 = np.array([[-1, -1, -1], [-1, arg, -1], [-1, -1, -1]])
    sharpening_mask2 = np.array([[0, -1, 0], [-1, arg, -1], [0, -1, 0]])
    sharpening_out1 = cv2.filter2D(img, -1, sharpening_mask1)
    sharpening_out2 = cv2.filter2D(img, -1, sharpening_mask2)
    if mode==1:
        return sharpening_out1
    else:
        return sharpening_out2


#! /usr/bin/env python3
import argparse
import random
import numpy as np
import torch
import os
import cv2
from tqdm import tqdm
from datasets import collate_fn, CorrespondencesDataset
from utils import (compute_pose_error, pose_auc, estimate_pose_norm_kpts, estimate_pose_from_E)

from model import CLNet
from config import get_config, print_usage

torch.set_grad_enabled(False)
torch.manual_seed(0)

def test(opt, thr=1e-4, use_ransac=True):
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    print('Running inference on device \"{}\"'.format(device))

    test_dataset = CorrespondencesDataset(opt.data_te, opt)

    test_loader = torch.utils.data.DataLoader(
            test_dataset, batch_size=1, shuffle=False,
            num_workers=8, pin_memory=True, collate_fn=collate_fn)

    model = CLNet(opt)
    checkpoint = torch.load(opt.model_path, map_location=torch.device('cpu'))

    state_dict = {}

    '''Load a parallelly trained model'''
    for key in checkpoint['state_dict'].keys():
        key_new = key.split('module')[1][1:]
        state_dict[key_new] = checkpoint['state_dict'][key]

    '''Load a model trained on a single GPU'''
#    state_dict = checkpoint['state_dict']

    model.load_state_dict(state_dict)
    model.cuda()
    model.eval()

    err_ts, err_Rs, precisions, matching_scores, num_corrects = [], [], [], [], []
    for idx, test_data in enumerate(tqdm(test_loader)):
        xs = test_data['xs'].to(device)
        ys = test_data['ys'].to(device)

        _, _, e_hat, y_hat = model(xs, ys)

        mkpts0 = xs.squeeze()[:, :2].cpu().detach().numpy()
        mkpts1 = xs.squeeze()[:, 2:].cpu().detach().numpy()

        mask = y_hat.squeeze().cpu().detach().numpy() < thr
        mask_kp0 = mkpts0[mask]
        mask_kp1 = mkpts1[mask]

        if use_ransac == True:
            file_name = '/aucs.txt'
            ret = estimate_pose_norm_kpts(mask_kp0, mask_kp1)
        else:
            file_name = '/aucs_DLT.txt'
            e_hat = e_hat[-1].view(3, 3).cpu().detach().numpy()

            ret = estimate_pose_from_E(mkpts0, mkpts1, mask, e_hat)

        if ret is None:
            err_t, err_R = np.inf, np.inf
        else:
            R, t, inliers = ret
            R_gt, t_gt = test_data['Rs'], test_data['ts']
            T_0to1 = torch.cat([R_gt.squeeze(), t_gt.squeeze().unsqueeze(-1)], dim=-1).numpy()
            err_t, err_R = compute_pose_error(T_0to1, R, t)

        err_ts.append(err_t)
        err_Rs.append(err_R)

    # Write the evaluation results to disk.
    out_eval = {'error_t': err_ts,
                'error_R': err_Rs
                }

    pose_errors = []
    for idx in range(len(out_eval['error_t'])):
        pose_error = np.maximum(out_eval['error_t'][idx], out_eval['error_R'][idx])
        pose_errors.append(pose_error)

    thresholds = [5, 10, 20]
    aucs = pose_auc(pose_errors, thresholds)
    aucs = [100.*yy for yy in aucs]

    print('Evaluation Results (mean over {} pairs):'.format(len(test_loader)))
    print('AUC@5\t AUC@10\t AUC@20\t')
    print('{:.2f}\t {:.2f}\t {:.2f}\t'.format(aucs[0], aucs[1], aucs[2]))

    np.savetxt(opt.output_dir + file_name, np.asarray(aucs))
    return np.asarray(aucs)

if __name__ == '__main__':
    opt, unparsed = get_config()

    if not os.path.exists(opt.output_dir):
        os.makedirs(opt.output_dir)

    aucs = test(opt, thr=opt.thr, use_ransac=opt.use_ransac)


import requests
from bs4 import BeautifulSoup

def scrape(url):
    try:
        res = requests.get(url)
        soup = BeautifulSoup(res.text, features="lxml")
    except:
        soup = ''

    return soup

def get_data(url):
    soup = scrape(url)
    try:
        company_name = soup.select('.fn')
        company_name = company_name[0].text
    except AttributeError:
        company_name = ''

    try:
        company_code_tag = soup.find('td', text='Įmonės kodas')
        company_code = company_code_tag.find_next_sibling('td')
        company_code = company_code.text.strip()
    except AttributeError:
        company_code = ''

    try:
        company_address_elem = soup.find('td', {'itemprop': 'address'})
        company_address = company_address_elem.get_text(strip=True)
    except AttributeError:
        company_address = ''

    try:
        company_boss_tag = soup.find('td', text='Vadovas')
        company_boss = company_boss_tag.find_next_sibling('td')
        company_boss = company_boss.text.strip()
    except AttributeError:
        company_boss = ''

    extra_info = ''

    return [company_name, company_code, company_address, company_boss,
            extra_info]


"""
# Sample code to perform I/O:

name = input()                  # Reading input from STDIN
print('Hi, %s.' % name)         # Writing output to STDOUT

# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""

# Write your code here
t = int(input())
for _ in range(t):
    n, x, y = map(int, input().strip().split())
    a = list(map(int, input().strip().split()))
    if n <= x or n <= y:
        print(n)
    else:
        tot = ln = mx = 0
        for i in range(n):
            tot += a[i]
            if a[i] < x and tot <= x:
                ln += 1
            elif a[i] < x:
                ln = 1
                tot = a[i]
            else:
                tot = ln = 0
            mx = max(mx, ln)
        print(mx + y)


#!/usr/bin/python
#coding=utf-8
"""
*文件说明:bak_check.py
*作者:高小调
*创建时间:2017年08月16日 星期三 09时37分38秒
*开发环境:Kali Linux/Python v2.7.13
"""
import sys
sys.path.append("..")
from lib import Downloader
import urlparse
def get_parent_paths(path):
    paths = []
    if not path or path[0] != '/':
        #path为None 或 path为/
        return paths
    paths.append(path)
    tmp = path
    if path[-1] == '/':
        #path 为 /a/b/c/d/e/
        tmp = path[:-1] #tmp = /a/b/c/d/e

    while tmp:  #tmp = /a/b/c/d/e
        tmp = tmp[:tmp.rfind('/')+1]   #tmp = /a/b/c/d/
        paths.append(tmp);
        tmp = tmp[:-1]                      #tmp = /a/b/c/d
    return paths

DIR_PROBE_EXTS = ['.tar.gz', '.zip', '.rar', '.tar.bz2']
FILE_PROBE_EXTS = ['.bak', '.swp', '.1']

def run(url):
    urlobj = urlparse.urlparse(url)
    paths = get_parent_paths(urlobj.path)
    web_paths = []
    for path in paths:
        if path == '/':
            #网站根目录
            for ext in DIR_PROBE_EXTS:
                url = "%s://%s%s%s" % (urlobj.scheme,urlobj.netloc,path,urlobj.netloc+ext)
                web_paths.append(url)
        else:
            if path[-1] == '/':
                #网站子目录
                for ext in DIR_PROBE_EXTS:
                    url = "%s://%s%s%s" % (urlobj.scheme,urlobj.netloc,path[:-1],ext)
                    web_paths.append(url)
            else:
                #非目录
                for ext in FILE_PROBE_EXTS:
                    url = "%s://%s%s%s"%(urlobj.scheme,urlobj.netloc,path,ext)
                    web_paths.append(url)
    downloader = Downloader.Downloader()
    found = False
    for path in web_paths:
        #print("[bak_check]:%s"%path)
        if((downloader.get(path) is not None)):
            found = True
            print("[bak_check]:bak found!%s"%path)
    if found is False:
        print ("[bak_check]:not found!")


temp = []
princ = []
maior = menor = 0
while True:
    temp.append(str(input("Nome: ")))
    temp.append(float(input("Peso: ")))
    if len(princ) == 0:
        maior = menor = temp[1]
    else:
        if temp[1] > maior:
            maior = temp[1]
        if temp[1] < menor:
            menor = temp[1]
    princ.append(temp[:])
    temp.clear()
    decisao = input("Deseja continuar? ").strip().upper()
    if decisao in "N":
        break
print("-="*30)
print(f"Os dados foram {princ}")
print(f"Ao todo voce cadastrou {len(princ)} pessoas")
print(f"O maior peso foi de {maior} kg. Peso(s) de ", end = "")
for peso in princ:
    if peso[1] == maior:
        print(f"{peso[0]}", end= " e ")
print(f"\nO menor peso foi de {menor} kg. Peso(s) de ", end= "")
for peso in princ:
    if peso[1] == menor:
        print(f"{peso[0]}", end=" e ")

Mundo 3/ex084 lista composta e analise de dados.py


from django.http import HttpResponse,Http404
from django.shortcuts import render,redirect
from .models import FoodStall,Review
from .forms import UserRegisterForm,ReviewForm
from django.contrib import messages
from datetime import date

# Home page
def index(request):
    return render(request,"yummyNUS/index.html")

#Stalls Page
def stalls(request):
    context = { 'stalls' : FoodStall.objects.all()}
    return render(request,"yummyNUS/stalls.html",context)

#Navigation Page
def navigate(request):
    return render(request,"yummyNUS/navi.html")

#Login Page
def login(request):
    return render(request,"yummyNUS/login.html")

#SignUp Page
def signup(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request,f'Account created for {username}!')
            return redirect('login')
    else:
        form = UserRegisterForm()
    return render(request,"yummyNUS/signup.html",{'form':form})

#individual stall
def stall(request,stall_id):
    try:
        stall =FoodStall.objects.get(id = stall_id)
    except FoodStall.DoesNotExist:
      raise Http404("Foodstall does not exist")
    if request.method == 'POST':

        form = ReviewForm(request.POST)
        form.foodstall_id = stall_id

        if form.is_valid():
            name = form.cleaned_data.get('Name')
            rating = form.cleaned_data.get('Rating')
            comment = form.cleaned_data.get('Comment')
            rev = Review(Name=name,Rating = rating,Comment = comment)
            rev.save()
            stall.review.add(rev)
            stall.save()
            context= {'stall':stall, 'menus': stall.menus.all(), 'form':form, 'reviews':stall.review.all()}
            return render(request,'yummyNUS/stall.html',context)
    else:

        form = ReviewForm()

    context= {'stall':stall, 'menus': stall.menus.all(), 'form':form, 'reviews':stall.review.all()}
    return render(request,'yummyNUS/stall.html',context)


import numpy as np
import csv
from threading import Thread
import os
from tensorflow.keras.utils import img_to_array, load_img
import cv2
import random
import math
import tensorflow as tf
import argparse

DATA_WIDTH = 1280
DATA_HEIGHT = 720
WIDTH = 768
HEIGHT = 432
GRID_COLS = 48
GRID_ROWS = 27
IMGS_PER_INSTANCE = 5
GRID_SIZE_COL = DATA_WIDTH / GRID_COLS
GRID_SIZE_ROW = DATA_HEIGHT / GRID_ROWS
BATCH_SIZE = 50

currBatchIdx = batchCount = numTestInstances = numTrainInstances = 0

parser = argparse.ArgumentParser(description='Argument Parser for GridTrackNet')

parser.add_argument('--input_dir', required=True, type=str, help="Input directory of the folder containing all folders with names with the prefix 'match'.")
parser.add_argument('--export_dir', required=True, type=str, help="Export directory where the data will be saved.")
parser.add_argument('--augment_data', required=False, type=int,  choices=range(0, 2), default=1, help='Boolean indicating whether or not the data should be augmented as well (flipped horizontally). 1 for augmentations, 0 for no augmentations. No augmented instances will be used as validation instances. Default = 1')
parser.add_argument('--val_split', required=False, type=float, default=0.2, help='Fraction of instances to be used for validation: must be greater than 0.0 and less than 1.0. Note this only affects the validation:non-augmented-data ratio, not the total validation:train-instances ratio. Default = 0.2')
parser.add_argument('--next_img_index', required=False, type=int, default=2, choices=range(1,IMGS_PER_INSTANCE+1), help='Specifies the overlap of images between instances; specifically the integer to be used for selecting the index of the first image of the next instance relative to the index of the first image of the previous instance. For example, if set to 2, the first instance will contain images with indices [0,1,2,3,4] and the second instance will contain images with indices [2,3,4,5,6].Default = 2')

args = parser.parse_args()

INPUT_DIR = args.input_dir
EXPORT_DIR = args.export_dir
AUGMENT_DATA = bool(args.augment_data)
VAL_SPLIT = args.val_split
NEXT_IMG_INDEX = args.next_img_index

if(VAL_SPLIT <= 0.0 or VAL_SPLIT >= 1.0):
    print("\nPARSE ERROR: Input argument 'val_split' must be greater than 0.0 and less than 1.0.")
    exit(1)

#Helper function to convert data into raw bytes
def bytesFeature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

#Stores image and label instances together by serialization
def serializeExample(image, label):
    feature = {
        'image': bytesFeature(image.tobytes()),
        'label': bytesFeature(label.tobytes()),
    }
    exampleProto = tf.train.Example(features=tf.train.Features(feature=feature))
    return exampleProto.SerializeToString()

#Turns images with target's coordinates into data and label instances
#Also augmentates data by horizontal flipping if specified
def getDataAndLabels(imgs,xCoords,yCoords,visibilities):
    global IMGS_PER_INSTANCE
    global GRID_SIZE_COL
    global GRID_SIZE_ROW

    dataEntry = []
    labelEntry = []
    for k in range(0, IMGS_PER_INSTANCE):
        img = imgs[k]
        currX = xCoords[k]
        currY = yCoords[k]

        confGrid = np.zeros((GRID_ROWS, GRID_COLS),dtype=np.float32)
        xOffsetGrid = np.zeros((GRID_ROWS, GRID_COLS),dtype=np.float32)
        yOffsetGrid = np.zeros((GRID_ROWS, GRID_COLS),dtype=np.float32)

        xPos = currX / GRID_SIZE_COL
        yPos = currY / GRID_SIZE_ROW

        xCellIndex = math.floor(xPos)
        yCellIndex = math.floor(yPos)
        xOffset = xPos - xCellIndex
        yOffset = yPos - yCellIndex

        #if(visibilities[k] == 1):
        if(not ((visibilities[k] == 0) and xCoords[k] == 0 and yCoords[k] == 0)):
            confGrid[yCellIndex, xCellIndex] = 1
            xOffsetGrid[yCellIndex, xCellIndex] = xOffset
            yOffsetGrid[yCellIndex, xCellIndex] = yOffset

        labelEntry.append(np.stack((confGrid, xOffsetGrid, yOffsetGrid),axis=-1))

        img = cv2.resize(img, (WIDTH,HEIGHT))
        img = img.astype(np.float32)
        img = img / 255
        img = np.moveaxis(img, -1, 0)
        dataEntry.append(img[0])
        dataEntry.append(img[1])
        dataEntry.append(img[2])

    dataEntry = np.asarray(dataEntry).astype(np.float32)
    labelEntry = np.asarray(labelEntry).astype(np.float32)

    if(AUGMENT_DATA):
        dataEntryAugmented = np.flip(dataEntry,axis=2)
        confGrid, xOffsetGrid, yOffsetGrid = np.split(labelEntry, 3, axis=-1)
        confGrid = np.squeeze(confGrid, axis=-1)
        confGridFlipped = np.flip(confGrid, axis=2)

        #For horizontal flipping, only x-offset values must be adjusted to (1 - original offset)
        xOffsetGrid = np.squeeze(xOffsetGrid, axis=-1)
        xOffsetGridFlipped = np.flip(xOffsetGrid, axis=2)
        xOffsetGridFlippedAdjusted = np.where(xOffsetGridFlipped > 0.00, 1 - xOffsetGridFlipped, xOffsetGridFlipped)

        yOffsetGrid = np.squeeze(yOffsetGrid, axis=-1)
        yOffsetGridFlipped = np.flip(yOffsetGrid, axis=2)

        labelEntryAugmented = np.stack((confGridFlipped, xOffsetGridFlippedAdjusted, yOffsetGridFlipped,),axis=-1)

        return np.stack((dataEntry, dataEntryAugmented), axis=0).astype(np.float32), np.stack((labelEntry, labelEntryAugmented), axis=0).astype(np.float32)

    return dataEntry, labelEntry

#Randomly determines if an instance is a training instance or a validation instance
def isValInstance():
    return(random.random() < VAL_SPLIT)

numMatchFolders = len([f for f in os.listdir(INPUT_DIR) if os.path.isdir(os.path.join(INPUT_DIR, f)) and f.startswith("match")])

if(not numMatchFolders >= 1):
    print("\nERROR: No folders starting with 'match' were found in directory: " + str(INPUT_DIR))
    exit(1)

if(not os.path.exists(EXPORT_DIR)):
    os.mkdir(EXPORT_DIR)

trainFileName = EXPORT_DIR + '/train0.tfrecord'
valFileName = EXPORT_DIR + '/val.tfrecord'

trainWriter = tf.io.TFRecordWriter(trainFileName)
valWriter = tf.io.TFRecordWriter(valFileName)

#Loops through all match folders' images and annotations and stores generated instances in TFRecord files
for m in range(1, numMatchFolders+1):
    matchPath = os.path.join(INPUT_DIR, "match" + str(m))
    if(not os.path.exists(matchPath)):
        print("\nERROR: The following directory does not exist: " + str(matchPath))
        exit(1)
    framesPath = os.path.join(matchPath, "frames")
    if(not os.path.exists(os.path.join(matchPath, 'Labels.csv'))):
        print("\nERROR: No 'Labels.csv' file found at path: " + str(os.path.join(matchPath, 'Labels.csv')))
        exit(1)
    with open(os.path.join(matchPath, 'Labels.csv')) as csvfile:
        reader = csv.DictReader(csvfile)
        readerList = list(reader)
        i = 0
        while(i + IMGS_PER_INSTANCE - 1 < len(readerList)):
            currInstanceIndex = i
            visibilities = []
            xCoords = []
            yCoords = []
            imgs = []

            for j in range(0,IMGS_PER_INSTANCE):
                imgPath = os.path.join(framesPath, str(int(readerList[i+j]['Frame'])) + '.png')

                if(not os.path.exists(imgPath)):
                    print("\nERROR: Image not found at path: " + str(imgPath))
                    exit(1)

                img = load_img(imgPath)
                img = img_to_array(img)

                visibilities.append(int(readerList[i+j]['Visibility']))
                xCoords.append(int(readerList[i+j]['X']))
                yCoords.append(int(readerList[i+j]['Y']))

                imgs.append(img)

            dataEntry, labelEntry = getDataAndLabels(imgs, xCoords, yCoords, visibilities)

            if(AUGMENT_DATA):
                #Adding the augmented version to train data.
                example = serializeExample(dataEntry[1], labelEntry[1])
                currBatchIdx += 1
                numTrainInstances += 1
                trainWriter.write(example)
                if(currBatchIdx == BATCH_SIZE):
                    batchCount += 1
                    trainFileName = EXPORT_DIR + '/train' + str(batchCount) + '.tfrecord'
                    trainWriter = tf.io.TFRecordWriter(trainFileName)
                    currBatchIdx = 0

                example = serializeExample(dataEntry[0], labelEntry[0])
            else:
                example = serializeExample(dataEntry, labelEntry)

            if(isValInstance()):
                numTestInstances += 1
                valWriter.write(example)
            else:
                currBatchIdx += 1
                numTrainInstances += 1
                trainWriter.write(example)
                if(currBatchIdx == BATCH_SIZE):
                    batchCount += 1
                    trainFileName = EXPORT_DIR + '/train' + str(batchCount) + '.tfrecord'
                    trainWriter = tf.io.TFRecordWriter(trainFileName)
                    currBatchIdx = 0

            #Prints progress bar
            percent_complete = int(round(m * 100 / (numMatchFolders+1), 0))
            bar = "#" * int(percent_complete / 10)
            space = " " * (10 - int(percent_complete / 10))
            print("\rProcessing Match {}: |{}{}| {}%. Training instances: {}, validation instances: {}.".format(m, bar, space, percent_complete,numTrainInstances,numTestInstances), end="")

            i = currInstanceIndex + NEXT_IMG_INDEX

print("\nDone.")


#!/usr/bin/python
__author__ = 'ar'

import sys
import cv2
import numpy as np
import boto3

def getImageFromS3Object(s3Object):
    img_array = np.asarray(bytearray(s3Object['Body'].read()), dtype=np.uint8)
    ret=cv2.imdecode(img_array, cv2.CV_LOAD_IMAGE_UNCHANGED)
    return ret

########################
if __name__=='__main__':
    s3=boto3.resource('s3')
    s3b=s3.Bucket('imlab')
    for oo in s3b.objects.all():
        print(oo)
        o1=s3b.Object(oo.key).get()
        winName="win"+oo.key
        try:
            cv2.imshow(winName, getImageFromS3Object(o1))
        except:
            pass
    cv2.waitKey()


import time
from typing import TYPE_CHECKING

import signal
from subprocess import Popen, PIPE
from threading import Thread

if TYPE_CHECKING:
    # pylint: disable=ungrouped-imports
    from typing import BinaryIO
    from queue import SimpleQueue
    from threading import Lock
    from ...devices.structure import Structure
    # pylint: enable=ungrouped-imports

def loadController(program_path: str, ship: 'Structure', json_info: str,
                   debug_queue: 'SimpleQueue', lock: 'Lock') -> 'Thread':

    return ControllerLoader().load(program_path, ship, json_info,
                                   debug_queue, lock)

class ControllerLoader:

    def load(self, program_path: str, ship: 'Structure', json_info: str,
             debug_queue: 'SimpleQueue', lock: 'Lock') -> 'Thread':

        process = Popen([program_path, json_info], stdin=PIPE, stdout=PIPE,
                        stderr=PIPE)

        Thread(target=self.__controllerThreadWatcher,
               args=(process, ship, lock)).start()

        Thread(target=self.__controllerThreadDebugMessages, daemon=True,
               args=(process.stderr, debug_queue)).start()

        return Thread(target=self.__controllerThread, daemon=True,
                      args=(process.stdout, process.stdin, ship, lock))

    @staticmethod
    def __controllerThreadWatcher(process: 'Popen', device: 'Structure',
                                  lock: 'Lock') -> None:

        while True:
            with lock:
                if device.isDestroyed():
                    break
            time.sleep(1)

        process.send_signal(signal.SIGHUP)

    @staticmethod
    def __controllerThreadDebugMessages(pstderr: 'BinaryIO',
                                        debug_queue: 'SimpleQueue') -> None:

        try:
            while True:
                text = pstderr.readline().decode()
                if not text:
                    return
                debug_queue.put(text[:-1])

        except BrokenPipeError:
            pass

    @staticmethod
    def __controllerThread(pstdout: 'BinaryIO', pstdin: 'BinaryIO',
                           device: 'Structure', lock: 'Lock') -> None:

        try:
            while True:
                question = pstdout.readline().decode()

                if question and question[-1] == '\n':
                    question = question[:-1]

                with lock:
                    answer = device.communicate(question)

                pstdin.write(answer.encode())
                pstdin.write(b'\n')
                pstdin.flush()

        except BrokenPipeError:
            pass


import pygame
from pygame import image
# from pygame.sprite import Sprite
from block import Block

class Floor(Block):

    def __init__(self, screen, settings, is_underground=False):
        super(Floor, self).__init__(screen, settings, is_underground=is_underground)
        self.screen = screen
        self.settings = settings
        self.image = None

        if is_underground:
            self.image = pygame.transform.scale(
                image.load(settings.floor_ug_image),
                (self.settings.brick_width,
                 self.settings.brick_height)
            )
        else:
            self.image = pygame.transform.scale(
                image.load(settings.floor_image),
                (self.settings.brick_width,
                 self.settings.brick_height)
        )
        self.rect = self.image.get_rect()
        self.collision_pts = self.get_collision_points()

    def draw(self):
        self.screen.blit(self.image, self.rect)


# 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#        o     o   o             o        o
CONST_INT_MAX = 105

T = int(input())

for test_case in range(T):
    result = 0
    K, N, M = map(int, input().split())
    station_list = list(map(int, input().split()))
    station_status = [0 for i in range(CONST_INT_MAX)]
    for i in station_list:
        station_status[i] = 1

    current = 0
    while True:
        next_position = -1

        if current + K >= N:
            break;

        for i in range(K):
            current += 1
            if station_status[current] == 1:
                next_position = current

        if next_position == -1:
            result = 0
            break;
        else:
            current = next_position
            result += 1

    print("#{0} {1}".format(test_case+1, result))


from pyhcl import *

class MemDemo(Module):
    io = IO(
        i=Input(U.w(8)),
        o=Output(U.w(8)),
    )

    m = Mem(10, U.w(8))
    m[U(2)] @= io.i
    io.o @= m[U(2)]

def main():
    f = Emitter.dump(Emitter.emit(MemDemo()), "mem.fir")
    Emitter.dumpVerilog(f)

if __name__ == '__main__':
    main()


def read_input(file_name="day08.txt"):
    with open(file_name) as file:
        return [line.strip() for line in file.readlines()]

def decoded_difference(line):
    decoded_line = bytes(line, "utf-8").decode("unicode_escape")
    return len(line) - len(decoded_line) + 2 # account for the quotes

def encoded_difference(line):
    index = 0

    res = 4 + len(line)
    while index < len(line):
        c = line[index]

        if c == '\\':
            c2 = line[index + 1]

            if c2 == "x":
                res += 1
                index += 3
            else:
                res += 2
                index += 2
        else:
            index += 1

    return res - len(line)

def part_one():
    data = read_input()
    total_difference = sum(decoded_difference(line) for line in data)
    print(total_difference)

def part_two():
    data = read_input()
    total_difference = sum(encoded_difference(line) for line in data)
    print(total_difference)

if __name__ == '__main__':
    # part_one()
    part_two()


import os
from celery import Celery
from celery.schedules import crontab

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'modo.settings')

app = Celery('modo')

app.config_from_object('django.conf:settings', namespace='CELERY')

app.autodiscover_tasks()

app.conf.beat_schedule = {
    'pull_articles': {
        'task': 'modo.news.management.tasks.pull_articles',
        'schedule': crontab(hour='*/2')
    },
    'update_sources': {
        'task': 'modo.news.management.tasks.update_sources',
        'schedule': crontab(day_of_month=1)
    },
    'show_time': {
        'task': 'modo.news.management.tasks.show_time',
        'schedule': 10
    },
}


import discord
import logging
import yaml
import os
from discord.ext import commands

# Enable intents at the discord developer portal for the bot to work.
intents = discord.Intents.all()
intents.messages = True
intents.members = True
intents.presences = True

baselogger = logging.getLogger(__name__)
config = yaml.safe_load(open('config.yml'))
client = commands.Bot(command_prefix=config['prefix'], intents=intents)
basecolor = 0x330091

for i in os.listdir('/cogs'):
    if i[-3:] == '.py':
        try:
            baselogger.info(f'loading extension (cog) cogs.{i[0:-3]}')
            client.load_extension(f"cogs.{i[0:-3]}")
        except Exception as e:
            baselogger.exception(f'Exception when attempting to load extension {i[0:-3]}')

client.run(config["token"])


import pickle
import numpy as np

def load_data(block_idx, pos_files, neg_files):
    with open(f"../cascade_data/Train/pos/{block_idx}.pkl", 'rb') as f:
        data = pickle.load(f)
    pos_data = [data[f] for f in pos_files]
    with open(f"../cascade_data/Train/neg1/{block_idx}.pkl", 'rb') as f:
        data = pickle.load(f)
    neg_data = [data[f] for f in neg_files]

    train_data = pos_data + neg_data
    labels = np.concatenate((np.full((len(pos_data)), 1), np.full((len(neg_data)), 0)))

    return train_data, labels


from RNN_GCN import *
from graph_calculations import *
from RNN_GCN_clique import RNNGCNClique

logger = logging.getLogger("NNI_logger")

def run_trial(params, v, p, cs, d):
    features = params["input_vec"]

    # model
    reg_term = params["regularization"]
    lr = params["learning_rate"]
    optimizer = Adam if params["optimizer"] == "ADAM" else SGD
    epochs = int(params["epochs"])
    rnn_cycles = int(params["recurrent_cycles"])
    class_weights = {0: (float(v) / (v - cs)) ** params["class_weights"],
                     1: (float(v) / cs) ** params["class_weights"]}

    input_params = {
        "epochs": epochs,
        "lr": lr,
        "regularization": reg_term,
        "class_weights": class_weights,
        "optimizer": optimizer,
        "recurrent_cycles": rnn_cycles
    }
    model = RNNGCNClique(v, p, cs, d, features=features, nni=True)
    model.train(input_params)

def main(v, p, cs, d):
    try:
        # get parameters form tuner
        params = nni.get_next_parameter()
        logger.debug(params)
        run_trial(params, v, p, cs, d)
    except Exception as exception:
        logger.error(exception)
        raise

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-n", type=int)
    parser.add_argument("-p", type=float, default=0.5)
    parser.add_argument("-cs", type=int)
    parser.add_argument("-d", type=bool, default=False)
    args = vars(parser.parse_args())
    main(args['n'], args['p'], args['cs'], args['d'])


#!/usr/bin/env python

import os, sys, glob

# LADSPA_UID, EFFECT_NAME, FILES
effects_info = [
('2602',    'Noisegate',        ['Noisegate.cc']),
('1772',    'Compress',         ['Compress.cc']),
('2598',    'CompressX2',       ['Compress.cc']),
('2589',    'ToneStack',        ['ToneStack.cc']),
('2592',    'AmpVTS',           ['Amp.cc','ToneStack.cc']),
('2601',    'CabinetIII',       ['CabIII.cc']),
('2606',    'CabinetIV',        ['CabIV.cc']),
('1779',    'Plate',            ['Reverb.cc']),
('1795',    'PlateX2',          ['Reverb.cc']),
('1771',    'Saturate',         ['Saturate.cc']),
('2603',    'Spice',            ['Saturate.cc']),
('2607',    'SpiceX2',          ['Saturate.cc']),
('1767',    'ChorusI',          ['Chorus.cc']),
('2586',    'PhaserII',         ['Phaser.cc']),
('2593',    'AutoFilter',       ['AutoFilter.cc']),
('2588',    'Scape',            ['Scape.cc']),
('1773',    'Eq10',             ['Eq.cc']),
('2594',    'Eq10X2',           ['Eq.cc']),
('2608',    'Eq4p',             ['Eq.cc']),
('2609',    'EqFA4p',           ['Eq.cc']),
('1788',    'Wider',            ['Pan.cc']),
('2595',    'Narrower',         ['Pan.cc']),
('1781',    'Sin',              ['Sin.cc']),
('1785',    'White',            ['White.cc']),
('1774',    'Fractal',          ['Fractals.cc']),
('1769',    'Click',            ['Click.cc']),
('1770',    'CEO',              ['Click.cc'])
]

interface_code = """
#include "version.h"
#include "basics.h"

#include "Cabinet.h"
#include "Chorus.h"
#include "Phaser.h"
#include "Sin.h"
#include "Fractals.h"
#include "Reverb.h"
#include "Compress.h"
#include "Click.h"
#include "Eq.h"
#include "Saturate.h"
#include "White.h"
#include "AutoFilter.h"
#include "Amp.h"
#include "Pan.h"
#include "Scape.h"
#include "ToneStack.h"
#include "Noisegate.h"

#include "Descriptor.h"

LV2_SYMBOL_EXPORT
const LV2_Descriptor *
lv2_descriptor(uint32_t i)
{
    static const Descriptor<__EFFECT__> lv2_descriptor(CAPS_URI "__EFFECT__");
    return i == 0 ? static_cast<const LV2_Descriptor*>(&lv2_descriptor) : 0;
}
"""

manifest = """\
@prefix dct:  <http://purl.org/dc/terms/> .
@prefix lv2:  <http://lv2plug.in/ns/lv2core#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .

<http://moddevices.com/plugins/caps/__EFFECT__>
    a lv2:Plugin ;
    dct:replaces <urn:ladspa:__LADSPA_UID__> ;
    lv2:binary <__EFFECT__.so> ;
    rdfs:seeAlso <__EFFECT__.ttl> ,
                 <modgui.ttl> .
"""

if __name__ == "__main__":
    with open("Makefile.single", 'r') as fh:
        makefile_single = fh.read()

    def get_source(fx_name):
        for fx in effects_info:
            if fx_name == fx[1]:
                return ' '.join(fx[2])

    for ladspa_uid, effect_name, sources in effects_info:
        sources.append("dsp/polynomials.cc")
        sources  = "../../%s" % (" ../../".join(sources))
        sources += " interface.cc"
        bundlepath = "plugins/mod-caps-%s.lv2" % effect_name

        # Create dir
        if not os.path.exists(bundlepath):
            os.mkdir(bundlepath)

        # Create interface.cc
        with open(os.path.join(bundlepath, "interface.cc"), 'w') as fh:
            fh.write(interface_code.replace("__EFFECT__", effect_name))

        # Create manifest.ttl
        with open(os.path.join(bundlepath, "manifest.ttl"), 'w') as fh:
            fh.write(manifest.replace("__LADSPA_UID__", ladspa_uid).replace("__EFFECT__", effect_name))

        # Create Makefile
        with open(os.path.join(bundlepath, "Makefile"), 'w') as fh:
            fh.write(makefile_single.replace("__EFFECT__", effect_name).replace("__SOURCES__", sources))


from src.event import *
from src.coin import *
from src.util import *
import logging
import threading

HOUR = 60 * 60
MONITORING_INTERVAL = 10 # 10 sec

SELL_MARGIN = [1.01, 1.03, 1.04, 1.06] # 1% 3% 4% 6%
TIME_INTERVAL_UNIT = 8 * HOUR
MIN_TIME_INTERVAL = 8 * HOUR
MAX_TIME_INTERVAL = 56 * HOUR

# basis to judge rise or fall tendency
BASIS_JUDGE_TENDENCY = 3

class EventInfinite(Event, threading.Thread):
    def __init__(self, idx, account, socket, report, coin_name, balance, interval):
        threading.Thread.__init__(self)
        self.ev_id = idx
        self.account = account
        self.socket = socket
        # self.ui_control = main_window
        self.report = report
        self.coin_name = coin_name

        self.coin = Coin(self.coin_name)
        self.RATIO_BUY = 1/(PER_BUY*2)

        # Dynamic interval changes
        self.up_down_cnt = 0  # counter to check whether now is bull makret or bear market
        self.check_cur_price = self.check_last_price = 0  # for comparing between prev price and current price during INTERVAL

        self.interval = (interval * HOUR) // MONITORING_INTERVAL
        self.balance = balance
        self.buy_count = 0
        self.avg_price = 0
        self.total_amount = 0

        self.t_condition = threading.Condition()

        self.running = False
        self.threads = [
            threading.Thread(target=self.__trading, daemon=True),
            # threading.Thread(target=self.__show_info, daemon=True),
        ]

        self.sold_flag = False
        self.sold_price = 0
        self.trade_flag = False
        logging.info(f'{coin_name} : 무한 매수 event created!')

    def do_buy(self, price, amount):
        try:
            ret = self.account.buy(self.coin.ticker, price, amount)
            if ret == None:
                return False
            uuid = ret['uuid']

            for sec in range(TIME_OUT+1):
                if self.account.order_status(uuid) == 'done':
                    self.buy_count += 0.5
                    self.total_amount += amount
                    self.avg_price = get_avg_price(self.avg_price, price, self.buy_count)
                    return True
                time.sleep(1)
            self.account.cancel_order(uuid)
            return False
        except Exception as e:
            self.send_log(f"do buy : {ret['error']['message']}")
            self.buy_count += 1
            return False

    def init_trade(self):
        if self.balance <= 0:
            self.send_log('잔고 부족')
            return None
        each_asset = round(self.balance * self.RATIO_BUY, 2)
        self.send_log(f'분할 매수액 : {each_asset}')

        cur_price = self.check_last_price = self.coin.get_current_price()
        self.avg_price = cur_price = get_above_tick_price(cur_price)  # 호가 위 매수
        buying_amount = get_buying_amount(each_asset, cur_price, 1)
        if self.do_buy(cur_price, buying_amount) != True:
            self.close(False)
            return None
        # self.update_progress(PER_BUY, self.buy_count)
        # to do -> asset update
        # self.ui_control.show_asset_info()
        return each_asset

    def order_sell(self):
        # order sell
        # until progess / sell margin
        #        0-25%  /          6%
        #        5-50%  /          4%
        #       50-75%  /          3%
        #      75-100%  /          1%
        if self.buy_count > ((PER_BUY // 4) * 3) :
            selling_price = price_round(self.avg_price * SELL_MARGIN[0]) # sell margin 1%
        elif self.buy_count > ((PER_BUY // 4) * 2) :
            selling_price = price_round(self.avg_price * SELL_MARGIN[1]) # sell margin 3%
        elif self.buy_count > ((PER_BUY // 4) * 1) :
            selling_price = price_round(self.avg_price * SELL_MARGIN[2]) # sell margin 4%
        else:
            selling_price = price_round(self.avg_price * SELL_MARGIN[3]) # sell margin 6%
        ret = self.do_sell(self.coin.ticker, selling_price, self.total_amount)  # 매도
        return ret['uuid']

    def order_buy(self, buying_asset):
        # order buy
        ret = False
        cur_price = self.check_cur_price = self.coin.get_current_price()  # 현재 가격
        above_tick_price = get_above_tick_price(cur_price)  # 현재 가격보다 1호가 위 (바로 매수하기 위해)
        if self.buy_count > PER_BUY // 2:
            BUY_PERCENT = [1, 1]  # AVG_PRICE, AVG_PRICE
        else:
            BUY_PERCENT = [1, 1.05]  # AVG_PRICE, AVG_PRICE * 5%

        for percent in BUY_PERCENT:
            if cur_price <= (self.avg_price * percent):
                buying_amount = get_buying_amount(buying_asset, above_tick_price, 1)
                ret = self.do_buy(above_tick_price, buying_amount)
                self.send_log(f'매수 성공, 진행 : {self.buy_count}' if ret == True else f'매수 실패 : 타임아웃')
            else:
                self.send_log(f'매수 진행 불가 : 현재가 : {cur_price} > 매수 조건가 : {self.avg_price * percent}')

    def __check_sold_status(self, uuid):
        while self.trade_flag :
            if self.account.order_status(uuid) == 'done':
                self.trade_flag = False
                break
            time.sleep(10) # check order_status per 10 seconds

    def get_change_interval(self, prev_price, cur_price, interval):
        if prev_price < cur_price:
            self.up_down_cnt = self.up_down_cnt + 1
        elif prev_price > cur_price:
            self.up_down_cnt = self.up_down_cnt - 1

        # continuosly fall price over 3 times, it jugdes to be into bear market
        if self.up_down_cnt == -BASIS_JUDGE_TENDENCY:
            self.up_down_cnt = 0
            if MAX_TIME_INTERVAL >= (interval + TIME_INTERVAL_UNIT):
                interval = interval + TIME_INTERVAL_UNIT
                logging.info(f'{self.coin_name} : time interval change to {interval}')

        # continuosly rise price over 3 times, it jugdes to be into bear market
        if self.up_down_cnt == BASIS_JUDGE_TENDENCY:
            self.up_down_cnt = 0
            if MIN_TIME_INTERVAL <= (interval - TIME_INTERVAL_UNIT):
                interval = interval - TIME_INTERVAL_UNIT
                logging.info(f'{self.coin_name} : time interval change to {interval}')

        return interval

    def __trading(self):
        buying_asset = self.init_trade()
        if buying_asset == None:
            self.close(False)
            return

        while self.running and self.buy_count < PER_BUY:
            uuid = self.order_sell()
            # trade_interval = self.interval
            sell_status = False
            self.trade_flag = True

            sold_check_th = threading.Thread(target=self.__check_sold_status, daemon=True, args=(uuid, ))
            sold_check_th.start()

            for sec in range(0, self.interval): # wait and check flag during trade_interval
                if self.trade_flag == False:
                    sell_status = True
                    break
                else :
                    time.sleep(MONITORING_INTERVAL)

            self.trade_flag = False # kill the thread
            sold_check_th.join() # wait for complete exit of thread

            if sell_status == True :
                self.send_log('매도 성공')
                # save report in close() with flag True
                self.close(True)
            else:
                self.account.cancel_order(uuid)
                time.sleep(1)
                self.order_buy(buying_asset)
                # change time interval according to rise / fall of price
                self.interval = self.get_change_interval(self.check_last_price, self.check_cur_price, self.interval)
                self.check_last_price = self.check_cur_price

        if self.buy_count >= PER_BUY:
            logging.info(f'{self.coin_name} is going to endless selling')
            uuid = self.do_sell(self.coin.ticker, price_round(self.avg_price), self.total_amount) # 평단 본절
            while True: # 본절가에서 영혼법 지속.
                if self.account.order_status(uuid) == 'done':
                    self.close(True)
                    break
                time.sleep(HOUR)

    def reset_list(self):
        cur_price = self.coin.get_current_price()
        if self.sold_flag:
            cur_price = self.sold_price
        self.update_info(cur_price, self.avg_price, self.total_amount, get_increase_rate(cur_price, self.avg_price),
                         self.buy_count)

    def __show_info(self):
        while self.running:
            cur_price = self.coin.get_current_price()
            self.update_info(cur_price, self.avg_price, self.total_amount, get_increase_rate(cur_price, self.avg_price), self.buy_count)
            time.sleep(0.5)

    def close(self, sold_flag):
        self.send_log('무한 매수 종료')
        self.running = False
        if sold_flag == False:
            self.sold_price = self.avg_price = self.buy_count = self.total_amount = self.up_down_cnt = self.check_cur_price = self.check_last_price = 0
        elif sold_flag == True:
            self.sold_flag = True
            self.sold_price = self.coin.get_current_price()
            self.report.save_report(self.coin_name, self.sold_price, self.avg_price,
                                    self.total_amount, get_increase_rate(self.sold_price, self.avg_price), self.buy_count)
        with self.t_condition:
            self.t_condition.notifyAll()

    def close_thread(self):
        self.close(False)

    def run(self):
        if self.interval == None:
            return
        self.running = True
        self.sold_flag = False
        self.send_log(f'무한 매수 시작 : {self.coin.name}, Interval : {(self.interval * MONITORING_INTERVAL)// HOUR} 시간, 투자금액 : {self.balance} 원')
        for t in self.threads:
            t.start()

        with self.t_condition:
            self.t_condition.wait()

        logging.info('exit main thread of infinite trade')


import cv2 as cv
from skimage.draw import line as skidline
from scipy.signal import argrelextrema, savgol_filter
import numpy as np
import matplotlib.pyplot as plt

img = cv.imread("./data/CRBD/Images/crop_row_200.JPG", flags=cv.IMREAD_COLOR)

h_low = 40
h_upper = 80
s_low = 50
s_upper = 215
v_low = 60
v_upper = 200

hsv_image = cv.cvtColor(img, cv.COLOR_BGR2HSV)
hsv_binary_image = cv.inRange(
    hsv_image,
    (h_low, s_low, v_low),
    (h_upper, s_upper, v_upper)
)

# adaptive_img = cv.adaptiveThreshold(hsv_image, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 11, 2)

(height, width) = hsv_binary_image.shape[:2]
print(height, width)

mask = np.zeros((height, width))
best_count = np.zeros(width)
best_top = np.zeros(width)
# best_rr = np.zeros((width, height))
# best_cc = np.zeros((width, height))

for bottom in range(width):
    for top in range(width):
        rr, cc = skidline(height - 1, bottom, 0, top)
        count = cv.countNonZero(hsv_binary_image[rr,cc])
        if count > best_count[bottom]:
            best_top[bottom] = top
            best_count[bottom] = count

    # if best_count[bottom] > 60:
    # mask[best_rr, best_cc] = best_count[bottom]
    img[best_rr, best_cc] = (0, 0, best_count[bottom]*2)
    # print(best_count[bottom])

peaks = argrelextrema(savgol_filter(best_count, 10, 3), np.greater, order=20)
print(peaks)

for bottom_peak in peaks[0]:
    cv.line(img, (int(bottom_peak), height - 1), (int(best_top[int(bottom_peak)]), 0), (0,0,255), 4)
    # cv.line(mask, (height - 1, int(bottom_peak)), (0, int(best_top[int(bottom_peak)])), (0,0,255), 4)

# # Define criteria = ( type, max_iter = 10 , epsilon = 1.0 )
# criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 10, 1.0)
# # Set flags (Just to avoid line break in the code)
# flags = cv.KMEANS_RANDOM_CENTERS
# # Apply KMeans

# print(np.float32(best_count))
# compactness,labels,centers = cv.kmeans(np.float32(best_count),4,None,criteria,20,flags)

# print(centers)

# mask[0, centers] = 255

cv.imshow("Display window", img)
cv.imshow("hsv_binary window", hsv_binary_image)
cv.imshow("mask", mask)

# plt.plot(best_count)
# plt.show()

k = cv.waitKey(0)  # Wait for a keystroke in the window

# for bottompoint, toppoint in enumerate(top):
#     cv.line(img, (bottompoint, height - 1), (int(toppoint), 0), (0,0,count[bottompoint]*260), 1)


#!/usr/bin/python3

from datetime import datetime
from datetime import timedelta
from dateutil.rrule import rrule, YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY, MO, TU, WE, TH, FR, SA, SU

class Event:
    """basic input of a Schedule"""

    def __init__(self, title, description, start, duration, repeating = None):
        """Build an event.

        title -- short string identifying the event
        description -- string describing the event in detail
        start -- datetime.datetime of the event's activation
        duration -- datetime.timedelta as long as one occurrence of that event
        repeating -- dateutil.rrule.rrule for recurring events (None if unique)
        """
        self._title = title
        self._description = description
        self._start = start
        self._duration = duration
        self._repeating = repeating

    def __repr__(self):
        """Give the event's string representation."""
        return """otto.Event("{0}", "{1}", {2}, {3}, {4})""".format(self._title, self._description, repr(self._start), repr(self._duration), 'dateutil.rrule.rrulestr("{}")'.format(self._repeating) if self._repeating != None else "None")

    def __str__(self):
        """Give the event's user-friendly string representation"""
        return """Event "{0}" ("{1}")
Start date: {2};
Duration: {3};
{4}""".format(self._title, self._description, self._start, self._duoration, "Unique." if self._repeating == None else "Repeating:\n{}".format(self._repeating))

class Task (Event):
    """basic unit of a user's work to fit in a Schedule"""

    def __init__(self, title, description, start, duration, priority, due, repeating = None):
        """Build a task

        title -- short string identifying the event
        description -- string describing the event in detail
        start -- datetime.datetime of the event's activation
        duration -- datetime.timedelta as long as one occurrence of that event
        priority -- integer representing the importance of the task
        due -- datetime.datetime before when the task has to be done
        repeating -- dateutil.rrule.rrule for recurring events (None if unique)
        """
        super(Task, self).__init__(title, description, start, duration, repeating)
        self._priority = priority
        self._due = due

    def __repr__(self):
        """Give string representation of the task."""
        return """otto.Task("{0}", "{1}", {2}, {3}, {4}, {5}, {6})""".format(self._title, self._description, repr(self._start), repr(self._duration), self._priority, repr(self._due), 'dateutil.rrule.rrulestr("{}")'.format(self._repeating) if self._repeating != None else "None")

    def __str__(self):
        """Give user-friendly string representation of the task."""
        return """Task "{0}" ("{1}")
Start date: {2};
Duration: {3};
Priority: {4};
Due date: {5};
{6}""".format(self._title, self._description, self._start, self._duration, self._priority, self._due, "Unique." if self._repeating == None else "Repeating:\n{}".format(self._repeating))

class Occurrence:
    """Occurrence of an Event inside a Schedule"""

    def __init__(self, event, start, duration):
        """Build an Occurrence.

        event -- Event the Occurrence is an instance of
        start -- datetime.datetime of when the Occurrence starts
        duration -- datetime.timedelta length of the Occurrence
        """
        self._event = event
        self._start = start
        self._duration = duration
    def __repr__(self):
        """Give string representation of the Occurrence."""
        return "otto.Occurrence({0}, {1}, {2})".format(repr(self._event), repr(self._start), repr(self._duration))

class Schedule:
    """Auto-organizing Schedule"""

    def __init__(self, events, tasks, start=None):
        """Build a Schedule.

        events -- list of events sorted by start date
        tasks -- list of tasks sorted by start date
        start -- datetime.datetime of beginning of the Schedule (default to the earliest event of the list)
        """
        #in case we want to sort it: events_, tasks_ = sorted(events, key=lambda e: e.start), sorted(tasks, key=lambda t: t.start)

        self._start = start if start != None else events[0]._start
        self._timeline = list()

        #finding the due date of the last task
        self._end = tasks[0]._due
        for t in tasks[1:]:
            if t._due > self._end:
                self._end = t._due
        for e in events: self._add_event(e)

        #truncating the part of the timeline before start
        if self._timeline[0]._start < self.start:
            tronc = 0
            for i, o in enumerate(self._timeline):
                if o._start + o._duration <= self.start:
                    tronc = i #identify where the start is;
            del self._timeline[:i+1] #remove what ends before;
            for o in self._timeline: #and shave what starts before.
                if o._start < self._start:
                    o._duration -= (self._start - o._start)
                    o._start = self._start
    def __repr__(self):
        """Give the string representation of the timeline's content"""
        return "list({0})".format(",\n".join(repr(o) for o in self._timeline))

    def __str__(self):
        """Give the user-friendly string representation of the Schedule"""
        return '\n'.join("from {0} to {1}: {2}".format(o._start, o._start + o._duration, o._event._title) for o in self._timeline)

    def _add_event(self, event):
        if event._repeating == None:
            self._add_occ(Occurrence(event, event._start, event._duration))
        else:
            #will probably be better with rrule.replace()
            for d in event._repeating.between(self._start, self._end, inc=True):
                self._add_occ(Occurrence(event, d, event._duration))

    def _add_occ(self, occ):
        self._timeline.append(occ)
        self._timeline.sort(key=lambda o: o._start)

    def get_free_time(self,after, before=None):
        """Return a datetime.timedelta of the free time between two dates in this schedule.

        after -- datetime.datetime after which looking for free time
        before -- datetime.datetime before which looking for free time
        """
        if before == None: before = self._end
        #time to invest overall minus free time after "before"
        if before < self._end:
            return self.get_free_time(start, self._end) - self.get_free_time(end, self._end)
        free_time = timedelta(0)
        for i, occ in enumerate(self._timeline):
            if occ._start+occ._duration >= after:
                if i < len(self._timeline)-1:
                    free_time += (self._timeline[i+1]._start - (occ._start+occ._duration)) if (self._timeline[i+1]._start > occ._start+occ._duration) else timedelta(0)
                else:
                    free_time += before - (occ._start+occ._duration) if before > occ._start+occ._duration else timedelta(0)
        return free_time

    def get_free_intervals(self, after, before=None):
        """Return a list of tuples (datetime.datetime, datetime.datetime) representing the intervals of free time of this schedule.

        after -- datetime.datetime after which looking for free time
        before -- datetime.datetime before which looking for free time
        """
        intervals = list()
        #entire list of intervals
        for i, occ in enumerate(self._timeline):
                if i < len(self._timeline)-1:
                    if occ._start+occ._duration < self_timeline[i+1]._start:
                        intervals.append(tuple((occ._start+occ._duration, self_timeline[i+1]._start)))
                else:
                    if before > occ._start+occ._duration:
                        intervals.append(tuple((occ._start+occ._duration, before)))

        #cutting before start and after end
        for i, t in enumerate(intervals):
            if t[1] <= after:
                trimstart = i
            elif trimend != None and t[0] >= before:
                trimend = i
        del intervals[:trimstart+1]
        del intervals[trimend+1:]

        #trimming first and last if needed
        if intervals[0][0] > after and intervals[0][1] < after:
            intervals.insert(1, tuple((after, intervals[0][1])))
            del intervals[0]
        if intervals[-1][1] > before and intervals[-1][0] < before:
            intervals.append(tuple((intervals[-1][0], before)))
            del intervals[-2]

        return intervals

#tests
if __name__ == "__main__":
    print(str(Task("a task", "description of it", datetime.now(), timedelta(0,360), 99, datetime.now()+timedelta(1), rrule(DAILY, dtstart=datetime.now()))))


# coding=utf-8
"""Product listing urls."""

from django.conf.urls import patterns, include, url

urlpatterns = patterns("product.views",
    url(r"^all$", "all"),
    url(r"^(?P<pk>\d+)$", "view_product"),
    url(r"^(?P<pk>\d+)/tweets$", "view_tweets"),
    url(r"^manage$", "management"),
    url(r"^add$", "add"),
    url(r"^edit/(?P<pk>\d+)$", "edit"),
    url(r"^search/(?P<pk>\d+)$", "searches"),
    url(r"^search/(?P<pk>\d+)/add$", "add_search"),
    url(r"^search/(?P<pk>\d+)/view$", "view_search"),
    url(r"^search/(?P<pk>\d+)/delete$", "delete_search"),
)


# -*- coding: utf-8 -*-
import os
import shutil

def change_folder_name(folder_path):

    os.chdir(folder_path)
    dirs = os.listdir(folder_path)
    count = 1

    for folders in dirs:

        new_folder_name = 's' + str(count)
        os.rename(folders, new_folder_name)
        count += 1

def extract_image(folder_path):

    os.chdir(folder_path)
    dirs = os.listdir(folder_path)
    for folders in dirs:
        sub_folder = folder_path + "/" + folders
        sub_folder_name = os.listdir(sub_folder)
        for images in sub_folder_name:
            oldname = sub_folder + "/" + images
            newname = 'C:/Users/kiokh/Desktop/OpenCV/data0' + '/' + images
            shutil.copyfile(oldname, newname)

change_folder_name('C:/Users/kiokh/Desktop/OpenCV/data')
extract_image('C:/Users/kiokh/Desktop/OpenCV/data')


from collections import deque
from datetime import datetime
from functools import lru_cache

def parse_input(data):
    lines = [line.strip().split() for line in data.splitlines()]
    grid = [list(line[0]) for line in lines]
    for i in range(len(grid)):
        for j in range(len(grid[i])):
            grid[i][j] = grid[i][j]
    return grid

@lru_cache(maxsize=None)
def get_current_height(char: str):
    if char == "S":
        return ord("a")
    elif char == "E":
        return ord("z")
    else:
        return ord(char)

@lru_cache(maxsize=None)
def get_neighbors(x, y):
    current_height = get_current_height(grid[x][y])
    h, w = len(grid), len(grid[0])
    possible_positions = [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]
    postions = []
    for pos in possible_positions:
        if 0 <= pos[0] < h and 0 <= pos[1] < w:
            position_height = get_current_height(grid[pos[0]][pos[1]])
            if position_height <= current_height + 1:
                postions.append(pos)
    return postions

def step(source, destination):
    queue = deque([(0, source)])
    visited = set()
    while queue:
        distance, rc = queue.popleft()
        if rc == destination:
            return distance
        if rc not in visited:
            visited.add(rc)
            neighbors = get_neighbors(rc[0], rc[1])
            for n in neighbors:
                if n not in visited:
                    queue.append((distance + 1, n))

    return float("inf")

def part_1(grid: list[list[str]]):
    starting_pos = [
        (i, j)
        for i in range(len(grid))
        for j in range(len(grid[i]))
        if grid[i][j] == "S"
    ][0]
    end_pos = [
        (i, j)
        for i in range(len(grid))
        for j in range(len(grid[i]))
        if grid[i][j] == "E"
    ][0]
    steps = step(starting_pos, end_pos)
    return steps

def part_2(grid: list[list[str]]):
    starting_pos = [
        (i, j)
        for i in range(len(grid))
        for j in range(len(grid[i]))
        if grid[i][j] in ["a", "S"]
    ]
    end_pos = [
        (i, j)
        for i in range(len(grid))
        for j in range(len(grid[i]))
        if grid[i][j] == "E"
    ][0]
    min_steps = float("inf")
    for pos in starting_pos:
        steps = step(pos, end_pos)
        if steps < min_steps:
            min_steps = steps
    return min_steps

if __name__ == "__main__":
    with open("input.txt") as fin:
        grid = parse_input(fin.read().strip())
    start_time = datetime.now()
    part_1_ans = part_1(grid)
    print(
        f"Part One: {part_1_ans}, elapsed time: {(datetime.now() - start_time).total_seconds()*1000} ms"
    )
    start_time2 = datetime.now()
    part_2_ans = part_2(grid)
    print(
        f"Part Two: {part_2_ans}, elapsed time: {(datetime.now() - start_time2).total_seconds()*1000} ms"
    )


import os
import sys
import time
import json
import socket
import threading
from tkinter import Tk, Menu, Listbox, Label, Scrollbar, Entry, StringVar, SINGLE, END, CENTER, ACTIVE, LEFT, N, S, E, W, TclError
from tkinter.ttk import Button, Style
from tkinter.messagebox import showinfo, showerror, askquestion
from tkinter.filedialog import askopenfilename, asksaveasfilename

from playsound import playsound

from eth import ETHConnection

MY_NAME = ''
OTHER_IP = ''
IS_SERVER = False
EXITED = False

def threaded(fn):
    def wrapper(*args, **kwargs):
        thread = threading.Thread(target=fn, args=args, kwargs=kwargs)
        thread.start()
        return thread
    return wrapper

class SetupWindow(Tk):
    """
    Little GUI for setting user's name, the partner's ip and that
    the PC is a server or not.
    """

    def __init__(self, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)

        try:  # Set icon
            self.iconbitmap('icon.ico')
        except Exception:
            pass

        self.wm_title('TinyChat')
        self.resizable(False, False)
        try:
            self.eval('tk::PlaceWindow %s center' % self.winfo_pathname(self.winfo_id()))
        except TclError:
            pass

        self.name = 'anonymous'
        self.other_ip = socket.gethostbyname(socket.gethostname())
        self.is_server = True

        # Read last config from file
        if os.path.isfile('config.json'):
            with open('config.json', 'r') as file:
                config = json.load(file)
                self.name = config['name']
                self.other_ip = config['other_ip']
                self.is_server = config['is_server']

        self.name_label = Label(self, text='Name')
        self.other_ip_label = Label(self, text='IP')
        self.server_label = Label(self, text='Server')

        self.name_entry = Entry(self, textvariable=StringVar(), bd=1, width=30, bg='white', fg='black')
        self.other_ip_entry = Entry(self, textvariable=StringVar(), bd=1, width=30, bg='white', fg='black')
        self.server_button = Button(self, text='Yes' if self.is_server else 'No', width=22, command=lambda: self.set_is_server())
        self.apply_button = Button(self, text='Start', width=7, command=self.apply)

        self.name_entry.config(textvariable=StringVar(self, self.name))
        self.other_ip_entry.config(textvariable=StringVar(self, self.other_ip))
        self.other_ip_entry.config(state='disabled' if self.is_server else 'normal')

        self.name_label.grid(padx=1, pady=2, row=0, column=0)
        self.name_entry.grid(padx=1, pady=2, row=0, column=1)
        self.other_ip_label.grid(padx=1, pady=2, row=1, column=0)
        self.other_ip_entry.grid(padx=1, pady=2, row=1, column=1)
        self.server_label.grid(padx=1, pady=2, row=2, column=0)
        self.server_button.grid(padx=1, pady=2, row=2, column=1)
        self.apply_button.grid(padx=1, pady=5, row=3, column=1)

        self.mainloop()

    def set_is_server(self):
        self.is_server = not self.is_server
        self.server_button.config(text='Yes' if self.is_server else 'No')
        self.other_ip_entry.config(state='disabled' if self.is_server else 'normal')

    def apply(self):
        global MY_NAME, OTHER_IP, IS_SERVER

        if self.name_entry.get() and self.other_ip_entry.get():
            MY_NAME = self.name_entry.get()
            OTHER_IP = self.other_ip_entry.get()
            IS_SERVER = self.server_button.cget('text') == 'Yes'

            config = {
                'name': MY_NAME,
                'other_ip': OTHER_IP,
                'is_server': IS_SERVER
            }
            with open('config.json', 'w+') as file:
                json.dump(config, file)

            self.destroy()

class TinyChat(Tk):

    def __init__(self, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)

        try:  # Set icon
            self.iconbitmap('icon.ico')
        except Exception:
            pass

        self.wm_title('TinyChat')
        self.resizable(False, False)

        try:
            self.eval('tk::PlaceWindow %s center' % self.winfo_pathname(self.winfo_id()))
        except TclError:
            pass

        self.bind('<Key>', self.keypress)

        self.sound_played_for_notification = False
        self.new_notification = False
        self.line_width = 42

        self.msg_list = Listbox(self, selectmode=SINGLE, height=10, width=self.line_width, borderwidth=0)
        self.msg_scb = Scrollbar(self, orient='vertical')
        self.msg_scb.grid(padx=0, pady=0, row=0, column=1, sticky=N + S)
        self.msg_list.config(yscrollcommand=self.msg_scb.set)
        self.msg_scb.config(command=self.msg_list.yview)

        self.entry_box = Entry(self, textvariable=StringVar(), bd=0, width=self.line_width, bg='white', fg='black')
        self.entry_button = Button(self, text='→', width=3, command=self.send_msg)

        self.msg_list.grid(padx=0, pady=0, row=0, column=0)
        self.entry_box.grid(padx=0, pady=0, row=1, column=0)
        self.entry_button.grid(padx=0, pady=0, row=1, column=1)

        # Connect on the ethernet port
        self.ETH = ETHConnection(OTHER_IP, IS_SERVER)

        # self.msg_recv_thread = Thread(target=self.recv_msg)
        # self.msg_recv_thread.start()
        # self.notifications_thread = Thread(target=self.notifications)
        # self.notifications_thread.start()
        self.msg_recv_thread = self.recv_msg()
        self.notifications_thread = self.notifications()

        self.wm_attributes('-topmost', 1)
        self.bind('<FocusIn>', self.handle_focus)
        self.protocol('WM_DELETE_WINDOW', self.on_closing)
        self.mainloop()

    def send_msg(self):
        global MY_NAME, OTHER_IP, IS_SERVER
        msg_to_send = self.entry_box.get()
        self.entry_box.delete(0, END)

        if msg_to_send:
            if msg_to_send[0] == '/':  # Commands
                cmd = msg_to_send.split(' ')

                if cmd[0] == '/?':
                    self.msg_list.insert(END, ' ')
                    self.msg_list.insert(END, 'HELP:')
                    self.msg_list.insert(END, '/setname NAME - Sets your name for the given NAME.')
                    self.msg_list.insert(END, '/re - Tries to reconnect.')
                    self.msg_list.insert(END, '/ip IP - Sets the partner\'s ip to IP.')
                    self.msg_list.insert(END, ' ')
                if cmd[0] == '/setname':
                    MY_NAME = cmd[1].strip()
                if cmd[0] == '/re':
                    self.ETH.reconnect()
                if cmd[0] == '/ip':
                    OTHER_IP = cmd[1].strip()

                return

            msg_to_send = MY_NAME + ': ' + msg_to_send
            self.add_msg(msg_to_send)

            try:
                self.ETH.send(msg_to_send)
            except:
                self.msg_list.insert(END, 'There is noone on the other end  ¯\\_(ツ)_/¯.')

                # Try to reestabilish connection
                self.ETH.reconnect()
                self.msg_recv_thread = self.recv_msg()
                self.msg_recv_thread.start()

    def add_msg(self, msg):
        if len(msg) > self.line_width:
            for i in range(int(len(msg) / self.line_width) + 1):
                self.msg_list.insert(END, msg[i * self.line_width:(i + 1) * self.line_width])
        else:
            self.msg_list.insert(END, msg)

        self.msg_list.yview_moveto('1')  # Scroll down to the last message

    def handle_focus(self, e):
        self.new_notification = False

    @threaded
    def recv_msg(self):
        global EXITED
        while not EXITED:
            time.sleep(0.1)

            if not self.ETH:
                continue

            data = self.ETH.recv(1024)
            if data:
                self.add_msg(data)
                self.new_notification = True
                self.sound_played_for_notification = False

    @threaded
    def notifications(self):
        global EXITED
        while not EXITED:
            time.sleep(0.1)

            if self.new_notification:
                if not self.sound_played_for_notification:
                    playsound('audio/notification.wav')
                    self.sound_played_for_notification = True

    def on_closing(self):
        """
        if self.ETH.is_connected:
            self.ETH.send(MY_NAME + ' has left the chat.')
            self.ETH.close()
        """
        global EXITED
        EXITED = True
        self.notifications_thread.join()
        self.msg_recv_thread.join()
        self.destroy()

    def keypress(self, event):
        # print(repr(event.char))
        # Turned off because \x08 == Ctrl + h and \x08 == Backspace
        # if event.char == '\x08':  # Ctrl + h
            # self.help()

        if event.char == '\r':
            self.send_msg()
            self.msg_list.yview_moveto('1')  # Scroll down to the last message

if __name__ == '__main__':
    SetupWindow()

    if MY_NAME:
        TinyChat()


try:
    print('try......')
    r = 10 / int('2')
    print('Result:', r)
except ValueError as e:  # Python的错误其实也是class，所有的错误类型都继承自BaseException，所以在使用except时需要注意的是，它不但捕获该类型的错误，还把其子类也“一网打尽
    print('Value Error:', e)
except ZeroDivisionError as e:  # 如果没有错误发生，except语句块不会被执行，但是finally如果有，则一定会被执行（可以没有finally语句）
    print('ZeroDivisionError:', e)
else:
    print('No error')
finally:
    print('finally....')
print('END')
# 捕获错误时，如果想精确的捕获错误，就把小错误的类写在前面，如果把父类错误写在前面，就永远也不可能捕获子类错误
# 使用try...except捕获错误还有一个巨大的好处，就是可以跨越多层调用，比如函数main()调用bar()，bar()调用foo()，结果foo()出错了，这时，只要main()捕获到了，就可以处理
#  不需要在每个可能出错的地方去捕获错误，在合适的层次捕获错误就行

#  如果错误没有被捕获，它就会一直往上抛，最后被Python解释器捕获，打印一个错误信息，然后程序退出
#  出错的时候，一定要分析错误的调用栈信息，才能定位错误的位置
#  既然我们能捕获错误，就可以把错误堆栈打印出来，然后分析错误原因，同时，让程序继续执行下去
# 记录错误
import logging

def foo(s):
    return 10 / int(s)

def bar(s):
    return foo(s) * 2

def main():
    try:
        bar('0')
    except Exception as e:  # 同样是出错，但程序打印完错误信息后会继续执行，并正常退出
        logging.exception(e)

print(main())
print('END')

'''# 抛出错误
def foo1(s):
    n = int(s)
    if n == 0:
        raise ValueError('invalid value:%s' % s)
    return 10 / n

def bar1():
    try:
        foo1('0')
    except ValueError as e:
        print('ValueError')
        raise

#   raise语句如果不带参数，就会把当前错误原样抛出

print(bar1())
#  在bar()函数中，我们明明已经捕获了错误，但是，打印一个ValueError!后，又把错误通过raise语句抛出去了，这不有病么？
#   其实这种错误处理方式不但没病，而且相当常见。捕获错误目的只是记录一下，便于后续追踪。但是，由于当前函数不知道应该怎么处理该错误，所以，最恰当的
#   方式是继续往上抛，让顶层调用者去处理。好比一个员工处理不了一个问题时，就把问题抛给他的老板，如果他的老板也处理不了，就一直往上抛，最终会抛给CEO去处理
'''


def getFactors(n):
    todo, combis = [(n, 2, [])], []
    while todo:
        n, idx, combi = todo.pop()
        while idx * idx <= n:
            if n % idx == 0:
                quotient = n/idx
                combis += combi + [idx, quotient],
                rest = combi+[idx]
                todo += (quotient, idx, rest),
            idx += 1
    return combis
getFactors(12)

def getFactors(n):
    def factorRec(n, i, combi, combis):
        while i * i <= n:
            if n % i == 0:
                combis += combi + [i, n/i],
                factorRec(n/i, i, combi+[i], combis)
            i += 1
        return combis
    return factorRec(n, 2, [], [])


import discord
from discord.ext import commands

#Compreendo que foi falta de profissionalismo meu nos codigos ou versões anteriores de não verificar antes de enviar.
#Deixando claro que sou um desenvolvedor Brasileiro e que "kkkkk" independe da quantidade aqui significa risada.

prefix = '?'
intents = discord.Intents().all()
bot = commands.Bot(command_prefix=prefix, intents=intents)

# Funções Passivas
@bot.event
async def on_ready():
    guild = bot.guilds[0]
    nick_name = bot.user.name
    member = guild.get_member(bot.user.id)
    print(f'Logado em {nick_name}') # Diz que está logado no console
    await bot.change_presence(activity=discord.Game("exemplo de jogo")) # Aqui diz oq ele esta jogando
    await member.edit(nick=f'[{prefix}]{nick_name}') # Nome fixo do bot com prefixo desde o inicio

# Daqui em diante é apenas comando, estou pensando em por um sistema de classes
@bot.command()
async def oi(msg):
    await msg.send('Olá!')

# Aqui é só o Token
bot.run('Digite seu token')


import random
guess_word = ['python', 'java', 'kotlin', 'javascript']
pick_word = random.choice(guess_word)
print("H A N G M A N")
store_word = []
for i in range(len(pick_word)):
    if i < 3:
        store_word.append(pick_word[i])
    else:
       store_word.append('-')
stored_word = "".join(store_word)
word = input(f"Guess the word {stored_word}: ")
if word == pick_word:
    print("You survived!")
else:
    print("You lost!")


def mine_sweeper(bombs, num_rows, num_cols):
    # creates new two-dimensional array initialized by zeros
    field = [[0 for i in range(num_cols)] for j in range(num_rows)]

    for bomb in bombs:
        (bomb_row, bomb_col) = bomb

        field[bomb_row][bomb_col] = -1

        for row in range(bomb_row - 1, bomb_row + 2):
            if row < 0 or row >= num_rows:
                continue
            for col in range(bomb_col - 1, bomb_col + 2):
                if 0 <= col < num_cols and field[row][col] is not -1:
                    field[row][col] += 1

    return field

def test():
    assert mine_sweeper([[0, 2], [2, 0]], 3, 3) == [[0, 1, -1], [1, 2, 1], [-1, 1, 0]]
    assert mine_sweeper([[0, 0], [0, 1], [1, 2]], 3, 4) == [[-1, -1, 2, 1], [2, 3, -1, 1], [0, 1, 1, 1]]
    assert mine_sweeper([[1, 1], [1, 2], [2, 2], [4, 3]], 5, 5) == [[1, 2, 2, 1, 0], [1, -1, -1, 2, 0],
                                                                    [1, 3, -1, 2, 0], [0, 1, 2, 2, 1], [0, 0, 1, -1, 1]]

if __name__ == "__main__":
    test()


from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('<int:movie_id>/',views.detail ,name='detail'),
    path('signup/',views.signUp,name='signup'),
    path('login/',views.Login,name='login'),
    path('recommend/',views.recommend,name='recommend'),
    path('logout/',views.Logout,name='logout'),
    path('msignup/',views.msignUp,name='msignup'),
    path('mlogin/',views.mLogin,name='mlogin'),
    path('mlogout/',views.mLogout,name='mlogout'),
    path('getlistfilm/',views.getListFilm,name='getlistfilm'),
    path('searchmovie/',views.searchMovie,name='searchmovie'),
    path('uploadrating/',views.uploadRating,name='uploadrating'),

]


import math
ETHERNET = (0.1,1,10,40,100)

def routing(ring,dept,dest):
	idx1=ring.index(dept)
	idx2=ring.index(dest)
	return min([[idx1,idx2],[idx2,idx1]],key=lambda e:(e[1]-e[0])%len(ring))

def checkio(ring,*flows):
	ring=[ord(c)-65 for c in ring]
	cost=[0]*len(ring)
	for e in flows:
		route=routing(ring,*[ord(c)-65 for c in e[0]])
		i=route[0]
		while i!=route[1]:
			cost[i]+=e[1]
			i=(i+1)%len(ring)
	result=[0]*len(ETHERNET)
	for c in cost:
		if c==0: continue
		for i,e in enumerate(ETHERNET):
			if e>=c:
				result[i]+=1
				break
		else:
			result[-1]+=math.ceil(float(c)/ETHERNET[-1])
	return list(reversed(result))

if __name__ == '__main__':
	assert checkio("AEFCBG", ("AC", 5), ("EC", 10), ("AB", 60)) == [2, 2, 1, 0, 0]
	assert checkio("ABCDEFGH", ("AD", 4)) == [0, 0, 3, 0, 0]
	assert checkio("ABCDEFGH", ("AD", 4), ("EA", 41)) == [4, 0, 3, 0, 0]


"""
==================================================
Andrés Felipe García Albarracín
2021-06-28
==================================================

Reads csv data and tests an LSTM forecast model
using adam as optimizer
"""
import matplotlib.pyplot as plt
import numpy as np

"""
==================================================
1. Load libraries
==================================================
"""
import tensorflow as tf
import csv
import time, os
import matplotlib.pyplot as plt

train_portion = 0.8
window_size = 30
batch_size = 128
"""
==================================================
2. Load data
==================================================
"""
filePath = "../Datasets/daily-min-temperatures.csv"
series = []
with open(filePath, 'r') as file:
    reader = csv.reader(file, delimiter = ',')
    next(reader)
    for line in reader:
        series.append(float(line[1]))

series = np.array(series)

fig = plt.figure(figsize=(10,6))
ax = fig.add_subplot(1,1,1)
ax.plot(series)
plt.savefig('97_Imags/TimeSeries_10_01.jpg')

"""
==================================================
3. Splitting
==================================================
"""
splitLength = int(len(series)*train_portion)
train_series = series[:splitLength]
eval_series = series[splitLength:]

train_ds = tf.data.Dataset.from_tensor_slices(train_series)
eval_ds = tf.data.Dataset.from_tensor_slices(eval_series)

"""
==================================================
4. Preprocessing
==================================================
"""
def preprocessing(dsData: tf.data.Dataset, batch_size, window_size):
    dsData = dsData.window(window_size+1, shift = 1, drop_remainder=True)
    dsData = dsData.flat_map(lambda w: w.batch(window_size+1))
    dsData = dsData.map(lambda x: (x[:-1], x[-1]))
    dsData = dsData.shuffle(1000)
    dsData = dsData.batch(batch_size).prefetch(1)
    return dsData

train_ds = preprocessing(dsData=train_ds, batch_size=batch_size, window_size=window_size)
eval_ds = preprocessing(dsData=eval_ds, batch_size=batch_size, window_size=window_size)

"""
==================================================
5. Callbacks
==================================================
"""
es_cb = tf.keras.callbacks.EarlyStopping(
    patience=25,
    restore_best_weights=True,
    monitor='val_loss'
)

tb_cb = tf.keras.callbacks.TensorBoard(
    log_dir=os.path.join('99_TensorBoard_logs', time.strftime('run_tseries_10_%Y%m%d_%H%M%S'))
)

"""
==================================================
5. Model
==================================================
"""
def createAndCompile(optimizer = tf.keras.optimizers.Adam()):
    model = tf.keras.Sequential([
        tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1), input_shape=[None]),
        tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32, return_sequences=True)),
        tf.keras.layers.LSTM(32),
        tf.keras.layers.Dense(16, activation='relu'),
        tf.keras.layers.Dense(1)
    ])

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

    return model

model = createAndCompile()
model.fit(
    train_ds,
    validation_data = eval_ds,
    epochs = 300,
    callbacks = [es_cb, tb_cb]
)


import os
from cv2 import cv2
import matplotlib.pyplot as plt
import numpy as np
import pickle
from skimage.io import imread
from skimage.transform import resize

def crop_images(img):

    output = 1
    label = 0
    values = []
    # Convert into grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Load the cascade(create your own path as  in every pc its different)
    face_cascade = cv2.CascadeClassifier(r'C:\Users\thete\Desktop\ML-major project\haarcascade_frontalface_default.xml')

    # Detect faces
    faces = face_cascade.detectMultiScale(gray, minNeighbors = 15, minSize=(100, 100))

    # Draw rectangle around the faces and crop the faces
    for (x, y, w, h) in faces:

        faces = img[y:y + h, x:x + w]

        if len(faces)>=1:
            output = 0
            new_path = 'cropped/'+str(label)+'.jpg'
            cv2.imwrite(new_path, faces)
            values.append([x,y,w,h])

    return output,values

def addon(img):

    flat_data = []
    model = pickle.load(open('img_model.p','rb'))

    img_resized = resize(img,(40,40,3))
    flat_data.append(img_resized.flatten())

    flat_data = np.array(flat_data)
    targets = model.predict(flat_data)
    return targets

def skin_tone():

    img_path = 'cropped/0.jpg'
    img = cv2.imread(img_path)

    skin_data = img.mean()

    if skin_data< 94:
        tone = 1

    elif skin_data>94 and skin_data< 112:
        tone = 2

    elif skin_data>112:
        tone =3

    return tone

def write_img(query1,query2,img,faces):

    for (x, y, w, h) in faces:

        if query1==0:
            cv2.putText(img,'Indian',(x+W+6,y+h-6), cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255),2)
            if query2==1:
                cv2.putText(img,'Dark skin tone',(x+w+6,y+h-36), cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255),2)
            elif query2==2:
                cv2.putText(img,'Mild skin tone',(x+w+6,y+h-36), cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255),2)
            elif query3==3:
                cv2.putText(img,'Fair skin tone',(x+w+6,y+h-36), cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255),2)
        elif query1==1:
            cv2.putText(img,'Non Indian',(x+w+6, y+h-6), cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255),2)

    cv2.imshow('Webcam', img)

def main():

    values=[]
    vid = cv2.VideoCapture(0)

    while(True):

        ret, frame = vid.read()
        target = 0
        tone = 0
        output,values = crop_images(frame)

        if output == 0:

            target = addon(frame)

            if target == 0:
                tone = skin_tone()
        write_img(target,tone,frame,values)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    vid.release()

    cv2.destroyAllWindows()

if __name__ == '__main__':
   main()


#graph

import pygame, sys, math
pygame.init()

font1 = pygame.font.SysFont('Verdana', 16)
font2 = pygame.font.SysFont('Serif', 24)
font3 = pygame.font.SysFont('Serif', 14)
white = (255,255,255)
black = (0,0,0)
colour = (200,0,200)

width, height = 800, 800
extraW = 400
screen = pygame.display.set_mode((width+extraW, height))
pygame.display.set_caption("Peter's grapher")
screen.fill(white)

def graphSet():
    point = pygame.PixelArray(screen)
    for x0 in range(width):
        for y0 in range(height):
            x = (x0 - float(width)/2-100)/300
            y = (y0 - float(height)/2)/300

            cx, cy = x, y
            for n in range(200):
                mx = x*x-y*y+cx
                my = 2*x*y + cy
                x, y = mx, my
                a = abs(x + y)
                if a > 100:
                    break
            if a <= 2:
                point[x0,y0] = (0,0,200)

def graphMain():
    global k
    k = 25
    title = font2.render("The Mandelbrot Set",1,black)
    subTitle = font3.render("by Peter Halldestam", 1, black)
    text = pygame.image.load('mathtext.png')

    screen.blit(title,(width+extraW-300,20))
    screen.blit(subTitle,(width+extraW-260, 60))
    screen.blit(text, (width+extraW-380, 100))
    graphSet()
    pygame.draw.rect(screen,black, (0,0,width,height),10)
    active = True
    while active:
        pygame.display.update()

        #user input, events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                active = False

    pygame.quit()
    sys.exit()

if __name__ == '__main__':
    graphMain()