from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    page = '
Powers of two
\n'
    for i in range(32):
        line = '2^{} = {}
\n'.format(i, 2**i)
        page += line
    return page

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


from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import messages
from django.db import IntegrityError
from mainadminapp.views import login
import datetime
from mainadminapp.models import Agent, Floor, Roomcatg, Room, Badmin, Booki

def bagent(request):
    usersession = Badmin.objects.get(badminid=request.session['badminid'])
    showbagent = Agent.objects.all()
    if request.method == 'POST' and 'bagentadd' in request.POST:
        if request.POST.get('bagentname') and request.POST.get('bagentaddress') and request.POST.get(
                    'bagentcontact') and request.POST.get('bagentemail'):
            bagentobj = Agent()
            bagentobj.agentname = request.POST.get('bagentname').title()
            bagentobj.agentaddress = request.POST.get('bagentaddress')
            bagentobj.agentcontactno = request.POST.get('bagentcontact')
            bagentobj.agentemailid = request.POST.get('bagentemail')
            try:
                bagentobj.save()
            except IntegrityError:
                messages.error(request, 'The ' + bagentobj.agentcontactno + ' is already exist')
            else:
                messages.success(request, "Successfully Added " + bagentobj.agentname + " 's Record")
        else:
            messages.error(request, 'Error while adding the record')
    return render(request, 'bagent.html', {'bagentdata': showbagent, 'usersession': usersession})

def bagentdelete(request, agentid):
    delbagent = Agent.objects.get(agentid=agentid)
    delbagent.delete()
    messages.success(request, "Deleted " + delbagent.agentname + "'s Record")
    return redirect('/branchadmin/bagent')

def bagentedit(request, agentid):
    usersession = Badmin.objects.get(badminid=request.session['badminid'])
    bagu = Agent.objects.get(agentid=agentid)
    if request.method == 'POST' and 'updatebag' in request.POST:
        obbag = Agent.objects.get(agentid=request.POST.get('updatebag'))
        obbag.agentname = request.POST.get('updatebagname').title()
        obbag.agentaddress = request.POST.get('updatebagaddress')
        obbag.agentcontactno = request.POST.get('updatebagcontact')
        obbag.agentemailid = request.POST.get('updatebagemail')

        obbag.save()
        messages.success(request, "Successfully Updated " + obbag.agentname + "'s Record")
        return redirect('/branchadmin/bagent')
    else:
        return render(request, 'editbagent.html', {'bagentdata': bagu, 'usersession': usersession})

def brooms(request):
    usersession = Badmin.objects.get(badminid=request.session['badminid'])
    roomobj1 = Floor.objects.all()
    roomobj2 = Roomcatg.objects.all()
    roomobj = Room.objects.all()
    if request.method == 'POST' and 'broomadd' in request.POST:
        if request.POST.get('floord') and request.POST.get('catd'):
            roomob = Room()
            roomob.roomid = request.POST.get('roomno')
            category_obj = Roomcatg.objects.get(catid=int(request.POST.get('catd')))
            roomob.category = category_obj
            room_obj = Floor.objects.get(id=int(request.POST.get('floord')))
            roomob.roomfloor = room_obj
            try:
                roomob.save()
            except IntegrityError:
                messages.error(request, 'The ' + roomob.roomid + ' is Already Exist')
            else:
                messages.success(request, 'Successfully Added ' + roomob.roomid)
        else:
            messages.error(request, 'Error while Adding')
    return render(request, 'brooms.html', {'usersession': usersession,'roome': roomobj2, 'room': roomobj1, 'roomobj': roomobj})

def editbroom(request,roomid):
    usersession = Badmin.objects.get(badminid=request.session['badminid'])
    uproom = Room.objects.get(roomid=roomid)
    floorobj = Floor.objects.all()
    catobj = Roomcatg.objects.all()
    if request.method == 'POST' and 'updateroomdt' in request.POST:
        if request.POST.get('updateroomfloor') and request.POST.get('updateroomcategory'):
            roomcat = Roomcatg.objects.get(catid=int(request.POST.get('updateroomcategory')))
            roomfloor = Floor.objects.get(id=int(request.POST.get('updateroomfloor')))
            obj = Room.objects.get(roomid=request.POST.get('updateroomdt'))
            obj.category = roomcat
            obj.roomfloor = roomfloor
            obj.save()
            messages.success(request, "Successfully Updated Your Record")
            return redirect('/branchadmin/broom')
    return render(request, 'editbroom.html', {'usersession': usersession, 'uroom': uproom, 'floorobj': floorobj, 'catobj': catobj})

def broomdelete(request, roomid):
    delbroom= Room.objects.get(roomid=roomid)
    delbroom.delete()
    messages.success(request, "Deleted successfully")
    return redirect('/branchadmin/broom')

def bindex(request):
    usersession = Badmin.objects.get(badminid=request.session['badminid'])
    roomavailable = Room.objects.filter(status='available').count
    totalbooking = Room.objects.filter(status='Booked').count
    formatedDate = datetime.date.today()
    checkintoday = Booki.objects.filter(checkin=formatedDate).count()
    checkouttoday = Booki.objects.filter(checkout=formatedDate).count()
    totalguest = Booki.objects.all().count()
    return render(request, 'badashboard.html',
                  {'usersession': usersession, 'countroom': roomavailable, 'checkintoday': checkintoday,
                   'checkouttoday': checkouttoday, 'totalbooking': totalbooking, 'totalguest': totalguest})

def bguest(request):
    usersession = Badmin.objects.get(badminid=request.session['badminid'])
    guestbad = Booki.objects.all()
    return render(request, 'bguest.html', {'guestbad': guestbad, 'usersession': usersession})

def badroomavail(request,roomid):
    roomav = Room.objects.get(roomid=roomid)
    roomav.status = 'available'
    try:
        roomav.save()
    except Exception:
        messages.error(request, " Error while Adding ")
    else:
        messages.success(request, "Availability Confirmed")
    return redirect('/branchadmin/bsettings')

def badbookingavail(request):
    usersession = Badmin.objects.get(badminid=request.session['badminid'])
    roomob = Room.objects.filter(status='Booked')
    return render(request, 'bsett.html', {'usersession': usersession, 'roomob': roomob})

def badminprofile(request):
    usersession = Badmin.objects.get(badminid=request.session['badminid'])
    if request.method == 'POST' and 'badminprofile' in request.POST:
        badminname = request.POST.get('badminname')
        badminaddress = request.POST.get('badminaddress')
        badmincontactno = request.POST.get('badmincontact')
        badminemailid = request.POST.get('badminemail')
        badminpass = request.POST.get('badminpass')
        print(badminpass)
        obbd = Badmin.objects.get(badminid=request.session['badminid'])
        obbd.badminname = badminname
        obbd.badminaddress = badminaddress
        obbd.badmincontactno = badmincontactno
        obbd.badminemail = badminemailid
        obbd.badminpass = badminpass
        obbd.save()
        messages.success(request, 'Successfully Updated Your Record')
        return redirect('bindex')
    return render(request, 'updateprofile.html', {'usersession': usersession})

def bbooking(request):
    usersession = Badmin.objects.get(badminid=request.session['badminid'])
    bbook = Booki.objects.all()
    agentob = Agent.objects.all()
    roysuiteval = Roomcatg.objects.filter(catname='ROYAL SUITE')
    presuiteval = Roomcatg.objects.filter(catname='PREMIUM SUITE')
    exesuiteval = Roomcatg.objects.filter(catname='EXECUTIVE SUITE')
    tensuiteval = Roomcatg.objects.filter(catname='TENT CAMPING')

    roomob1 = Room.objects.filter(category=1).filter(status='available')
    roomob2 = Room.objects.filter(category=2).filter(status='available')
    roomob3 = Room.objects.filter(category=3).filter(status='available')
    roomob4 = Room.objects.filter(category=4).filter(status='available')

    now = datetime.date.today()
    formatedate = now.strftime("%Y %B, %d")

    if request.method == 'POST' and 'searchbag' in request.POST:
        agentob = Agent.objects.all()
        agc = Agent.objects.filter(agentid=request.POST.get('agid'))
        return render(request, 'bbooking.html', context={'usersession': usersession,'roomob4':roomob4,'roomob3':roomob3,'roomob1':roomob1,'roomob2':roomob2,'agc': agc, 'agentob': agentob, 'roysuiteval': roysuiteval, 'presuitval': presuiteval, 'exesuitval': exesuiteval, 'tensuiteval': tensuiteval })
    if request.method == 'POST' and 'bookingsubmit' in request.POST:
        objbb = Booki()
        bguestname = request.POST.get('bfname').title()
        bguestcontactno = request.POST.get('bcont')
        bguestemail = request.POST.get('bemailid')
        bguestage = request.POST.get('bage')
        bguestgen = request.POST.get('bgender')
        bguestmar = request.POST.get('bmard')
        bguestaddress = request.POST.get('baddress')
        bgcountry = request.POST.get('bcountry')
        bgcity = request.POST.get('bcity')
        bgpin = request.POST.get('bpincode', default=000000)
        bguestagent = Agent.objects.get(agentid=(request.POST.get('agid1')))
        bguestnoofrooms = request.POST.get('numberofrooms')
        bguestnoofadults = request.POST.get('numberofadults')
        bguestnoofchild = request.POST.get('numberofchildrens', default=0)
        bguestproof = request.POST.get('proof')
        bguestgrc = request.POST.get('grcno')
        bguestcheckin = request.POST.get('checkin')
        bguestcheckout = request.POST.get('checout')
        bguesttotalamount = request.POST.get('totalamount')
        bguestadvanceamount = request.POST.get('advanceamount')
        bguestbalance = request.POST.get('balanceamount')
        bguestpay = request.POST.get('adamount')
        v200 = request.POST.get('selectedrooms')
        vvv = v200.split(',')  # string to list split by commas
        vvvv = set(vvv)  # list to set to avoid duplication
        vvvvv = list(vvvv)  # set to lst
        str1 = ','.join(vvvvv)  # list to string to save
        str2 = str1.lstrip(',')  # remove left comma of string
        v20 = str2

        objbb.agentid = bguestagent
        objbb.fullname = bguestname
        objbb.contactno = bguestcontactno
        objbb.emailg = bguestemail
        objbb.age = bguestage
        objbb.gender = bguestgen
        objbb.marital = bguestmar
        objbb.address = bguestaddress
        objbb.country = bgcountry
        objbb.city = bgcity
        objbb.pincode = bgpin
        objbb.noofrooms = bguestnoofrooms
        objbb.roomid = v20
        objbb.noofadults = bguestnoofadults
        objbb.noofchild = bguestnoofchild
        objbb.proof = bguestproof
        objbb.grc = bguestgrc
        objbb.checkin = bguestcheckin
        objbb.checkout = bguestcheckout
        objbb.totalamount = bguesttotalamount
        objbb.adamount = bguestadvanceamount
        objbb.balanceamount = bguestbalance
        objbb.payementmode = bguestpay
        try:
            objbb.save()
        except Exception:
            messages.error(request, " Error while Adding ")
        else:
            messages.success(request, "Booking Successfull")

        roomval = Booki.objects.last().roomid
        print(roomval)
        tolist = roomval.split(',')
        for i in tolist:
            if i != '':
                print(tolist.index(i), i)
                v = Room.objects.get(roomid=i)
                v.status = 'Booked'
                v.save()
                print(v)

        return redirect('bbooking')
    return render(request, 'bbooking.html', {'bbook': bbook,'usersession': usersession, 'agentob': agentob, 'roysuiteval': roysuiteval, 'presuitval': presuiteval, 'exesuitval': exesuiteval, 'tensuiteval': tensuiteval})

def editbbooking(request,bookingid):
    usersession = Badmin.objects.get(badminid=request.session['badminid'])
    upbbook = Booki.objects.get(bookingid=bookingid)
    bagentob = Agent.objects.all()
    roysuiteval = Roomcatg.objects.filter(catname='ROYAL SUITE')
    presuiteval = Roomcatg.objects.filter(catname='PREMIUM SUITE')
    exesuiteval = Roomcatg.objects.filter(catname='EXECUTIVE SUITE')
    tensuiteval = Roomcatg.objects.filter(catname='TENT CAMPING')

    roomob1 = Room.objects.filter(category=1).filter(status='available')
    roomob2 = Room.objects.filter(category=2).filter(status='available')
    roomob3 = Room.objects.filter(category=3).filter(status='available')
    roomob4 = Room.objects.filter(category=4).filter(status='available')

    formatda = upbbook.checkin
    chekd = formatda.strftime("%Y-%m-%d")
    formatda1 = upbbook.checkout
    cheko = formatda1.strftime("%Y-%m-%d")

    if request.method == 'POST' and 'searchbag' in request.POST:
        bagentob = Agent.objects.all()
        agc = Agent.objects.filter(agentid=request.POST.get('uagid'))
        return render(request, 'editbbooking.html', context={ 'cheko' :cheko, 'chekd': chekd,'upbbook': upbbook, 'agentob': bagentob,'usersession': usersession,'roomob4':roomob4,'roomob3':roomob3,'roomob1':roomob1,'roomob2':roomob2,'agc': agc, 'roysuiteval': roysuiteval, 'presuitval': presuiteval, 'exesuitval': exesuiteval, 'tensuiteval': tensuiteval })
    if request.method == 'POST' and 'updatebbook' in request.POST:
        buguestagent = Agent.objects.get(agentid=(request.POST.get('uagid1')))
        uobjbb = Booki.objects.get(bookingid=bookingid)
        bfullname = request.POST.get('ubfname').title()
        print(bfullname)
        print('hi')
        bcontact = request.POST.get('ubcont')
        bemail = request.POST.get('ubemailid')
        bage = request.POST.get('ubbage')
        bgender = request.POST.get('upbgender')
        bmarital = request.POST.get('ubdatemarital')
        baddress = request.POST.get('ubbaddress')
        bcity = request.POST.get('ubbcity').upper()
        bcountry = request.POST.get('ubcountry').upper()
        bpincode = request.POST.get('ubpincode')
        bnoofroom = request.POST.get('numberofrooms')
        bnoofadults = request.POST.get('unumberofadults')
        bnoofchild = request.POST.get('unumberofchildrens')
        bproofsub = request.POST.get('uproof')
        bgrc = request.POST.get('ugrcno')
        bcheckin = request.POST.get('ucheckin')
        bcheckout = request.POST.get('uchecout')
        btotal = request.POST.get('totalamount')
        badvanceamount = request.POST.get('advanceamount')
        bbalance = request.POST.get('balanceamount')
        paymentmode = request.POST.get('paymentmode')
        v200 = request.POST.get('selectedrooms')
        vvv = v200.split(',')  # string to list split by commas
        vvvv = set(vvv)  # list to set to avoid duplication
        vvvvv = list(vvvv)  # set to lst
        str1 = ','.join(vvvvv)  # list to string to save
        str2 = str1.lstrip(',')  # remove left comma of string
        v20 = str2

        uobjbb.agentid = buguestagent
        uobjbb.fullname = bfullname
        uobjbb.contactno = bcontact
        uobjbb.emailg = bemail
        uobjbb.age = bage
        uobjbb.gender = bgender
        uobjbb.marital = bmarital
        uobjbb.address = baddress
        uobjbb.country = bcountry
        uobjbb.city = bcity
        uobjbb.pincode = bpincode
        uobjbb.noofrooms = bnoofroom
        uobjbb.roomid = v20
        uobjbb.noofadults = bnoofadults
        uobjbb.noofchild = bnoofchild
        uobjbb.proof = bproofsub
        uobjbb.grc = bgrc
        uobjbb.checkin = bcheckin
        uobjbb.checkout = bcheckout
        uobjbb.totalamount = btotal
        uobjbb.adamount = badvanceamount
        uobjbb.balanceamount = bbalance
        uobjbb.payementmode = paymentmode
        uobjbb.save()
        roomval = Booki.objects.last().roomid
        print(roomval)
        tolist = roomval.split(',')
        for i in tolist:
            if i != '':
                print(tolist.index(i), i)
                v = Room.objects.get(roomid=i)
                v.status = 'Booked'
                v.save()
                print(v)
        return redirect('breciept',bookingid=bookingid)
    return render(request,'editbbooking.html',context={'cheko': cheko, 'chekd': chekd,'upbbook':upbbook,'agentob': bagentob})

def blogout(request):
    request.session['badminid'] = {}
    messages.success(request,"Logged out")
    return redirect(login)

def breciept(request,bookingid):
    recbook = Booki.objects.get(bookingid=bookingid)
    return render(request,"breciept.html",{'recbook': recbook})


def main():
    N, K = map(int, input().split())
    list_a = list(map(int, input().split()))
    list_b = list(map(int, input().split()))

    tmp_list = [True, True]
    for i in range(N-1):
        # print(tmp_list)
        a0 = list_a[i]
        a1 = list_a[i + 1]
        b0 = list_b[i]
        b1 = list_b[i + 1]
        new_tmp_list = [False, False]
        for j, check_open in enumerate(tmp_list):
            if check_open == True:
                # 開いている方を検証
                if j == 0:
                    num_now = a0
                else:
                    num_now = b0
                # print(num_now, a1, b1, K)
                if abs(num_now - a1) <= K:
                    # 更新
                    # print("if abs(num_now - a1) <= K")
                    new_tmp_list[0] = True
                if abs(num_now - b1) <= K:
                    # 更新
                    new_tmp_list[1] = True
                # print(new_tmp_list)
        if (new_tmp_list[0] == False) and (new_tmp_list[1] == False):
            print("No")
            return
        tmp_list = new_tmp_list

    print("Yes")
    return

main()


arrs1 = [-1, 3, -1, 5]
arrs2 = [-5, -3, -1]
arrs3 = [2, 4, -2, -3, 8]

def find_max_num(arr):
    maxSum = arr[0]
    currentSum = arr[0]
    for i in range(len(arr)):
        currentSum = max(currentSum + arr[i], arr[i])
        maxSum = max(currentSum, maxSum)
    return maxSum

print(find_max_num(arrs2))


# 文字列と N 個の整数の出力 (paizaランク C 相当)
# https://paiza.jp/works/mondai/stdout_primer/stdout_primer__specific_format_step2

# 解答例1
# 入力
n, a, b = map(int, input().split())
# "(a, b)" 形式の文字列を生成
s = f"({a}, {b})"
# 要素 s が n 個の配列を生成
ary = [s] * n
# 出力
print(", ".join(ary))

# 解答例2
# 入力
n, a, b = map(int, input().split())
# 出力
print(", ".join([f"({a}, {b})"] * n))


import numpy as np
import pandas as pd
import os

FILENAME = "final_data_set.csv"

df = pd.read_csv("data31.csv")
df.head()
df.columns = ['waste']
df_done = df.waste.str.split(',', n=1, expand=True)
df_done.columns = ['polarity', 'text']
if not os.path.exists(FILENAME):
    df_done.to_csv(FILENAME)
print("done")


from __future__ import annotations

from dataclasses import dataclass

from pants.backend.codegen.soap.soap_subsystem import SoapSubsystem
from pants.backend.codegen.soap.target_types import WsdlSourcesGeneratorTarget
from pants.core.goals.tailor import (
    AllOwnedSources,
    PutativeTarget,
    PutativeTargets,
    PutativeTargetsRequest,
)
from pants.engine.fs import PathGlobs, Paths
from pants.engine.internals.selectors import Get
from pants.engine.rules import collect_rules, rule
from pants.engine.unions import UnionRule
from pants.util.dirutil import group_by_dir
from pants.util.logging import LogLevel

@dataclass(frozen=True)
class PutativeWsdlTargetsRequest(PutativeTargetsRequest):
    pass

@rule(level=LogLevel.DEBUG, desc="Determine candidate WSDL targets to create")
async def find_putative_targets(
    req: PutativeWsdlTargetsRequest,
    all_owned_sources: AllOwnedSources,
    soap_subsystem: SoapSubsystem,
) -> PutativeTargets:
    if not soap_subsystem.tailor:
        return PutativeTargets()

    all_wsdl_files = await Get(Paths, PathGlobs, req.path_globs("*.wsdl"))
    unowned_wsdl_files = set(all_wsdl_files.files) - set(all_owned_sources)
    pts = [
        PutativeTarget.for_target_type(
            WsdlSourcesGeneratorTarget,
            path=dirname,
            name=None,
            triggering_sources=sorted(filenames),
        )
        for dirname, filenames in group_by_dir(unowned_wsdl_files).items()
    ]
    return PutativeTargets(pts)

def rules():
    return [
        *collect_rules(),
        UnionRule(PutativeTargetsRequest, PutativeWsdlTargetsRequest),
    ]


from .model import ImageEncoder, ImageDecoder128
import torch

class AE(torch.nn.Module):
    def __init__(self):
        super().__init__()

        self.encoder = ImageEncoder([1, 128, 256, 512, 1024, 2048, 4096], kernel_size=3, stride=2)
        self.decoder = ImageDecoder128()

        self.tanh = torch.nn.Tanh()
#         self.gelu = torch.nn.GELU()
        self.sigmoid = torch.nn.Sigmoid()

        self.range = 1024.0

    def forward(self, image):
        x = image / self.range
        x = self.encoder(x)
        # activate here if u want, tho prob bad idea :(
        x = self.tanh(x) #maybe not so bad idea, enforces latent space to be between -1 and 1
        x = self.decoder(x)

        x = self.sigmoid(x) * self.range

        return x


import math
import time

from selenium import webdriver

def calc(x):
    return str(math.log(abs(12 * math.sin(int(x)))))

link = 'http://suninjuly.github.io/redirect_accept.html'
try:
     browser = webdriver.Chrome()
     browser.get(link)
     time.sleep(4)
     # browser.execute_script("document.getElementsByTagName('button')[0].classList.remove('trollface');")
     browser.find_element_by_css_selector('[type="submit"]').click()
     lst_win = browser.window_handles
     current_win = lst_win[1]
     browser.switch_to.window(current_win)
     print(browser.current_url)
     x = browser.find_element_by_id('input_value')
     print(x.text)

     browser.find_element_by_id('answer').send_keys(calc(x.text))
     browser.find_element_by_css_selector("[type='submit']").click()
     print(browser.switch_to.alert.text)
     time.sleep(2)
     browser.switch_to.alert.accept()

finally:
     browser.quit()


"""Base audio class"""

class BaseAudio(object):
    """Contain an audio data and methods to clean it and extract feature.

    Attributes
    ----------
    sampling_rate : frequency of the recording

    stroke_length : length of a stroke to determin onsets

    audio_fname : path of the audio file

    audio : numpy array of the audio signal
    """

    def __init__(self, **kwargs):
        """
        Load the audio file and determin the features
        """
        # Some parameters
        # sampling rate 44100 is essentia's default
        self.sampling_rate = kwargs.get('sampling_rate', 44100)
        self.audio_fname = None

if __name__=="__main__":
    a = BaseAudio()
    print(a)


import os

from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.md')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()

requires = [
    'django'
    ]

setup(name='djinn',
      version="1.0.0-snapshot",
      description='PythonUnited Intranet',
      long_description=README + '\n\n' +  CHANGES,
      classifiers=[
        "Development Status :: 3 - Alpha",
        "Framework :: Django",
        "Intended Audience :: Developers",
        "License :: Freely Distributable",
        "Programming Language :: Python",
        "Topic :: Internet :: WWW/HTTP :: Site Management",
        "Topic :: Software Development :: Libraries :: Application Frameworks"
        ],
      author='PythonUnited',
      author_email='info@pythonunited.com',
      license='beer-ware',
      url='https://github.com/PythonUnited/djinn',
      keywords='Djinn Core',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      install_requires = requires,
      tests_require= requires,
      test_suite="djinn",
      entry_points = """\
      """
      )


import csv

students_list, master_list = [], []
speaking_gain, speaking_regress, speaking_same = [], [], []
listening_gain, listening_regress, listening_same = [], [], []
reading_gain, reading_regress, reading_same = [], [], []
writing_gain, writing_regress, writing_same = [], [], []
speaking_delta_list, listening_delta_list, reading_delta_list, writing_delta_list = [], [], [], []

# create dictionary from csv file

with open('/home/ben/access.csv') as access_comp:
    csv_reader = csv.reader(access_comp, delimiter=',')
    i = 1
    while i < 23:
        access_comp.seek(0)
        score_list = []
        for row in csv_reader:
            score_list.append(row[i])
        i += 1
        students_list.append(score_list)

    for student in students_list:
        score_dict = {'name': student[0], 2019: {'composite': student[1], 'comprehension': student[2],
            'listening': student[3], 'literacy': student[4], 'oral': student[5], 'reading': student[6],
            'speaking': student[7], 'writing': student[8]}, 2020: {'composite': student[10],
            'comprehension': student[11], 'listening': student[12], 'literacy': student[13],
            'oral': student[14], 'reading': student[15], 'speaking': student[16], 'writing': student[17]}}
        master_list.append(score_dict)
    # print(master_list)

# filter through dictionaries and sort students into gain/regress/no-change lists

    for student in master_list:
        if student[2019]['speaking'] < student[2020]['speaking']:
            speaking_gain.append(student['name'])
        elif student[2019]['speaking'] > student[2020]['speaking']:
            speaking_regress.append(student['name'])
        else:
            speaking_same.append(student['name'])
    print("\n\nSpeaking results:\n\nGained: {}\n{}\n\nNo change: {}\n{}\n\nRegressed: {}\n{}\n\n".format(len(speaking_gain),
          speaking_gain, len(speaking_same), speaking_same, len(speaking_regress), speaking_regress))

    for student in master_list:
        if student[2019]['listening'] < student[2020]['listening']:
            listening_gain.append(student['name'])
        elif student[2019]['listening'] > student[2020]['listening']:
            listening_regress.append(student['name'])
        else:
            listening_same.append(student['name'])
    print("Listening results:\n\nGained: {}\n{}\n\nNo change: {}\n{}\n\nRegressed: {}\n{}\n\n".format(len(listening_gain),
          listening_gain, len(listening_same), listening_same, len(listening_regress), listening_regress))

    for student in master_list:
        if student[2019]['reading'] < student[2020]['reading']:
            reading_gain.append(student['name'])
        elif student[2019]['reading'] > student[2020]['reading']:
            reading_regress.append(student['name'])
        else:
            reading_same.append(student['name'])
    print("Reading results:\n\nGained: {}\n{}\n\nNo change: {}\n{}\n\nRegressed: {}\n{}\n\n".format(len(reading_gain),
          reading_gain, len(reading_same), reading_same, len(reading_regress), reading_regress))

    for student in master_list:
        if student[2019]['writing'] < student[2020]['writing']:
            writing_gain.append(student['name'])
        elif student[2019]['writing'] > student[2020]['writing']:
            writing_regress.append(student['name'])
        else:
            writing_same.append(student['name'])
    print("Writing results:\n\nGained: {}\n{}\n\nNo change: {}\n{}\n\nRegressed: {}\n{}\n\n".format(len(writing_gain),
          writing_gain, len(writing_same), writing_same, len(writing_regress), writing_regress))

# but how much did students regress

    for student in master_list:
        speaking_delta = float(student[2019]['speaking']) - float(student[2020]['speaking'])
        if speaking_delta > 0:
            neg_speaking_delta = {'name': student['name'], 'loss': speaking_delta}
            speaking_delta_list.append(neg_speaking_delta)

    # this second for loop isn't necessary; it should be built into the above loop
    total_speaking_loss_list = []
    for score in speaking_delta_list:
        total_speaking_loss_list.append(score['loss'])
    total_speaking_loss = sum(total_speaking_loss_list)
    avg_speaking_loss = total_speaking_loss / len(speaking_delta_list)
    print("\n\nSpeaking losers: {}\n{}".format(len(speaking_delta_list), speaking_delta_list))
    print("Average loss: {}".format(avg_speaking_loss))

    for student in master_list:
        listening_delta = float(student[2019]['listening']) - float(student[2020]['listening'])
        if listening_delta > 0:
            neg_listening_delta = {'name': student['name'], 'loss': listening_delta}
            listening_delta_list.append(neg_listening_delta)
    total_listening_loss_list = []
    for score in listening_delta_list:
        total_listening_loss_list.append(score['loss'])
    total_listening_loss = sum(total_listening_loss_list)
    avg_listening_loss = total_listening_loss / len(listening_delta_list)
    print("\n\nListening losers: {}\n{}".format(len(listening_delta_list), listening_delta_list))
    print("Average loss: {}".format(avg_listening_loss))

    for student in master_list:
        reading_delta = float(student[2019]['reading']) - float(student[2020]['reading'])
        if reading_delta > 0:
            neg_reading_delta = {'name': student['name'], 'loss': reading_delta}
            reading_delta_list.append(neg_reading_delta)
    total_reading_loss_list = []
    for score in reading_delta_list:
        total_reading_loss_list.append(score['loss'])
    total_reading_loss = sum(total_reading_loss_list)
    avg_reading_loss = total_reading_loss / len(reading_delta_list)
    print("\n\nReading losers: {}\n{}".format(len(reading_delta_list), reading_delta_list))
    print("Average loss: {}".format(avg_reading_loss))

    for student in master_list:
        writing_delta = float(student[2019]['writing']) - float(student[2020]['writing'])
        if writing_delta > 0:
            neg_writing_delta = {'name': student['name'], 'loss': writing_delta}
            writing_delta_list.append(neg_writing_delta)
    total_writing_loss_list = []
    for score in writing_delta_list:
        total_writing_loss_list.append(score['loss'])
    total_writing_loss = sum(total_writing_loss_list)
    avg_writing_loss = total_writing_loss / len(writing_delta_list)
    print("\n\nWriting losers: {}\n{}".format(len(writing_delta_list), writing_delta_list))
    print("Average loss: {}".format(avg_writing_loss))


import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error
from math import sqrt
from utils import mape

def baseline(df):
    # predict next year by just taking the values from last year
    predicted = df.loc['2016-01-01':'2016-12-31']
    actual = df.loc['2017-01-01':'2017-12-31']
    # and padding the missing values with the last datapoint
    actual.loc[actual < 1] = np.nan
    actual = actual.fillna(method='pad')
    # transform df to series
    predicted = pd.Series(predicted)
    actual = pd.Series(actual)
    print("Number of actual days:", len(actual))
    print('Number of predicted days:', len(predicted))
    rmse = sqrt(mean_squared_error(actual, predicted))
    print('For 12 Months RMSE: %.3f' % rmse)
    mape_value = mape(actual, predicted)
    print ("For 12 Months MAPE :", mape_value)

def calculate_baseline(path):
    df = pd.read_pickle(path)
    baseline(df)

# Call Baseline Method
calculate_baseline("data/preprocessed/branch1.pkl")


"""
Настройка админки
"""
import logging
from typing import Dict

import toml

from django.conf import settings
from django.contrib import admin
from django.contrib.admin.apps import AdminConfig
from django.http import HttpRequest
from django.template.response import TemplateResponse
from django.urls import path

class CustomAdmin(admin.AdminSite):
    site_header = f"{settings.SLOGAN}"
    index_title = f"{settings.INDEX_TITLE}"

    def __init__(self, *args, **kwargs):
        self.version_file = "version.toml"
        self.changelog_file = "CHANGELOG.md"
        super().__init__(*args, **kwargs)

    def get_versions(self) -> Dict:
        """Получение информации о версии релиза"""
        try:
            return toml.load(self.version_file)
        except (toml.TomlDecodeError, FileNotFoundError) as error:
            logging.error(
                "Ошибка при загрузке файла %s: %s", self.version_file, error
            )
            return {}

    def each_context(self, request):
        site_data = super().each_context(request)
        release_data = self.get_versions()
        return {
            **site_data,
            "version": release_data.get("version"),
            "release_url": release_data.get("release_url"),
            "release_date": release_data.get("release_date"),
        }

    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path("release/", self.admin_view(self.changelog), name="release")
        ]
        return custom_urls + urls

    def changelog(self, request: HttpRequest) -> TemplateResponse:

        try:
            with open(self.changelog_file, "r", encoding="utf-8") as file:
                changelog = file.read()
        except (FileNotFoundError, UnicodeEncodeError) as error:
            logging.error(
                "Ошибка при загрузке файла %s: %s", self.changelog_file, error
            )
            changelog = "Ошибка при загрузке истории изменений"

        context = dict(self.each_context(request), changelog=changelog)
        return TemplateResponse(request, "admin/changelog.html", context)

class MainAdminConfig(AdminConfig):
    """Переопределение класса админки"""

    default_site = "main.admin_config.CustomAdmin"


import numpy as np

def gcd(a, b):
    while b != 0:
        a, b = b, a%b
    return a

def extended_euclides(a, b):
    x0, x1, y0, y1 = 0, 1, 1, 0
    while a != 0:
        (q, a), b = divmod(b, a), a
        y0, y1 = y1, y0 - q * y1
        x0, x1 = x1, x0 - q * x1
    return x0, y0, b

def mod_inverse(n, p):
    s, t, r = extended_euclides(n, p)
    return s % p

def find_coprime(n):
    for j in range(n//2+2, n):
        if gcd(j, n) == 1:
            yield j

def discrete_logarithm(alpha, beta, p): # alpha ^ x = beta (mod p)
    m = int(np.ceil(p**0.5))

    table = {0: 1}
    for j in range(1, m):
        table[j] = (table[j-1]*alpha) % p

    alpha_m = pow(alpha, -m, p)
    y = beta

    for i in range(m):
        j = next(filter(lambda tup: tup[1] == y, zip(table.keys(), table.values())), (None, None))[0]
        if j is not None:
            return i*m+j
        else:
            y = y*alpha_m % p

    return None

def fast_exponentation(a, n):
    ans = 1
    while n:
        if n%2==1:
            ans = ans * a
        a = a*a
        n = n//2
    return ans

def is_power(n):
    if (n == 1): return (None,1)
    lgn = 1 + ( len( bin ( abs ( n ) ) ) - 2)
    for b in range(2,lgn):
        lowa = 1
        higha = 1 << (lgn // b + 1)
        while lowa < higha - 1:
            mida = (lowa + higha) >> 1
            ab = fast_exponentation(mida,b)
            if ab > n:
                higha = mida
            elif ab < n:
                lowa  = mida
            else:
                return (mida, b)
    return False


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df=pd.read_csv("publications.csv")
rows= len(df.axes[0])

def success_percent(title):
    total_count=0
    success_count=0
    for i in range(0,rows):
        if(df['Titre/Title'][i]==title):
            total_count+=1
            if(df['Réponse/ Answer'][i]=='Yes'):
                success_count+=1
    if(total_count==0):
        return 0
    percentage=(success_count/total_count)*100
    return percentage

title=input("Enter event name:")
print("Effective percentage is:",success_percent(title))

Success percentage of event/track_effectioness_by_publication.py


#写一个类实现复数的加减乘除
#python3.4
#作者：代*

class Rational:
   def __init__(self,m=1,n=1):
      self.m=m
      self.n=n
   #加法运算符重载
   def __add__(self,k):
      F=Rational()
      F.m=self.m+k.m
      F.n=self.n+k.n
      return F
   #减法运算符重载
   def __sub__(self,k):
      F=Rational()
      F.m=self.m-k.m
      F.n=self.n-k.n
      return F
   #乘法运算符的重载
   def __mul__(self,k):
      F=Rational()
      F.m=self.m*k.m-self.n*k.n
      F.n=self.m*k.n+self.n*k.m
      return F
   #除法运算符的重载
   def __truediv__(self,k):
      F=Rational()
      F.m=(self.m*self.n+self.n*k.n)/(self.n*self.n+k.n*k.n)
      F.n=(self.n*self.n-self.m*k.n)/(self.n*self.n+k.n*k.n)
      return F

#_____________________主程序________________________
f1=input('请输入第一个复数:a+bi=')
if f1.find('+')>=0:
     L=f1.split('+')
     a=int(L[0])#实部
     b=int(L[1].split('i')[0])#虚部
else:
   L=f1.split('-')
   a=-int(L[1])#实部
   b=-int(L[2].split('i')[0])#虚部
x=Rational(a,b)

f2=input('请输入第二个复数:a+bi=')
if f2.find('+')>=0:
     L=f2.split('+')
     c=int(L[0])#实部
     d=int(L[1].split('i')[0])#虚部
else:
   L=f2.split('-')
   c=-int(L[1])#实部
   d=-int(L[2].split('i')[0])#虚部
y=Rational(c,d)

#加法_________
z=x+y
if z.n<0:
   print("加：",z.m,z.n,"i")
else:
   print ("加：",z.m,"+",z.n,"i")
#减法_________
z=x-y
if z.n<0:
   print("减：",z.m,z.n,"i")
else:
   print ("减：",z.m,"+",z.n,"i")
#乘法_________
z=x*y
if z.n<0:
   print("乘：",z.m,z.n,"i")
else:
   print ("乘：",z.m,"+",z.n,"i")
#除法_________
z=x/y
if z.n<0:
   print("除：",z.m,z.n,"i")
else:
   print ("除：",z.m,"+",z.n,"i")


import numpy as np
import bruges as bg
import segyio
import random
import os
from tensorflow.keras.utils import Sequence

def read_odt_pts(fname):
    """
    Author of function was https://github.com/kwinkunks
    """
    data = np.loadtxt(fname, skiprows=6, comments='!', usecols=[0,1,2])
    return data

def pts_to_ixt(fname, dt=0.004):
    """
    Author of function was https://github.com/kwinkunks
    """
    f3_corners_xy = np.array([
    [605835.5, 6073556.3],
    [629576.3, 6074219.9],
    [629122.5, 6090463.2]
    ])

    f3_corners_ix = np.array([[0,  0],
                        [0, 950],
                        [650, 950]
                        ])
    data = read_odt_pts(fname)
    transform = bg.transform.CoordTransform(f3_corners_ix, f3_corners_xy)
    ix = [transform.reverse(r) for r in data[:, :2]]
    t = (data[:, 2][:, None] / dt).astype(int)
    ixt = np.hstack([ix, t])
    return ixt

print("Loading seismic")
f3 = segyio.tools.cube("./data/F3_entire.segy")
print("Seismic loaded")

class Singlet(Sequence):
    def __init__(self, batch_size, directory, steps_per_epoch, shape=(3,48,48)):
        self.batch_size = batch_size
        self.directory = directory
        self.steps_per_epoch = steps_per_epoch
        self.classes = os.listdir(directory)
        self.coos = []
        for label in self.classes:
            print(label)
            label_coos = pts_to_ixt(os.path.join(self.directory, label))
            self.coos.append(label_coos)
        self._shape = shape
        self.n_classes = len(self.classes)

    def __len__(self):
        return self.steps_per_epoch

    def get_image(self, label_id, coo_id):
        (i, x, t) = self.coos[label_id][coo_id]
        (di, dx, dt) = self._shape

        (mx_i, mx_x, mx_t) = f3.shape
        i = min(i, mx_i-di)
        x = min(x, mx_x-dx)
        t = min(t, mx_t-dt)
        im = f3[i:i+di, x:x+dx, t:t+dt]
        return im

    def __getitem__(self, idx):
        images = np.ones((self.batch_size, *self._shape))
        labels = []
        for blank_img in images:
            label_id = random.randint(0, len(self.classes)-1)
            coo_id = random.randint(0, len(self.coos[label_id])-1)
            labels.append(label_id)
            blank_img[:,:,:] = self.get_image(label_id, coo_id)
        return (np.asarray(images), np.asarray(labels))

class Triplet(Singlet):
    def __getitem__(self, idx):
        a_img = np.ones((self.batch_size, *self._shape))
        p_img = np.ones((self.batch_size, *self._shape))
        n_img = np.ones((self.batch_size, *self._shape))
        labels = []
        for j in range(self.batch_size):
            pos_class = random.randint(0, len(self.classes)-1)
            neg_class = random.randint(0, len(self.classes)-2)
            if neg_class >= pos_class:
                neg_class = neg_class + 1

            a_random_choice = random.randint(0, len(self.coos[pos_class])-1)
            p_random_choice = random.randint(0, len(self.coos[pos_class])-1)
            n_random_choice = random.randint(0, len(self.coos[neg_class])-1)

            a_img[j,:,:,:] = self.get_image(pos_class, a_random_choice)
            p_img[j,:,:,:] = self.get_image(pos_class, p_random_choice)
            n_img[j,:,:,:] = self.get_image(neg_class, n_random_choice)
            labels.append((pos_class, neg_class))

        return([a_img, p_img, n_img], np.asarray(labels))

# Testing:
if __name__ == "__main__":
    import matplotlib.pyplot as plt
    base_batch_size = 4
    train_dir = "./data/pointDatasets/"
    shape = (32,32, 32)
    steps_per_epoch = 16
    print("### Testing Singlet generator class ###")
    train_generator = Singlet(
        batch_size=base_batch_size, directory=train_dir, steps_per_epoch=steps_per_epoch, shape = shape)
    for i in range(1):
        image, label = train_generator[i]
        for j in image:
            plt.imshow(np.rot90(j[0, :, :]), cmap="seismic")
            plt.show()

    print("### Testing Triplet generator class ###")
    train_generator = Triplet(
        batch_size=base_batch_size, directory=train_dir, steps_per_epoch=steps_per_epoch, shape = shape)
    for i in range(1):
        [a_imgs, p_imgs, n_imgs], y = train_generator[i]
        for j in a_imgs:
            plt.imshow(np.rot90(j[0, :, :]), cmap="seismic")
            plt.show()


import subprocess
from threading import Thread
import time
#subprocess.run(['cd', 'python3 Documents/JarrydSteele/PythonScripts/pythonscripts/First/hello.py'])
print("Hello, World!")
#subprocess.run(['python3', 'hello.py'])
#print ("Hello, World!!")

stop_threads = False

def wait_10_seconds():
    #print ("Sleep for 10 seconds...")
    subprocess.run(['python3', 'hello.py'])
    #print ("Finished 10 Seconds")

def wait_15_seconds():
    print ("Sleep for 15 seconds...")
    time.sleep(15)
    print ("Finished 15 Seconds")

def telem_forward_1():
    print("Starting Telem Forwarding...")
    subprocess.run(['mavproxy.py', '--master=/dev/pixhawk4.1', '--out=/dev/radio2'])
    if stop_threads:
        exit()

def just_print_hi():
    while True:
        print("Hi")
        time.sleep(1)
        if stop_threads:
            break
    print("just_print_hi has been killed")

test_thread_1 = Thread(target=wait_10_seconds, args=())
test_thread_1.daemon = True
test_thread_1.start()

test_thread_2 = Thread(target=wait_15_seconds, args=())
test_thread_2.daemon = True
test_thread_2.start()

test_thread_3 = Thread(target=just_print_hi,args=())
test_thread_3.daemon = True
test_thread_3.start()

test_thread_1.join()
test_thread_2.join()

stop_threads = True
test_thread_3.join()


import logging

from threading import Thread

class BasicComponent(Thread):
    """
    Basic class, more elaborated components will herit from this class.
    """
    def __init__(self, ID, dest_endpoint, mode, queue):
        #Assert validity of the parameters received
        endpoint_above, endpoint_below = dest_endpoint

        if not (mode == "server" or mode == "client"):
            raise Exception("Malformed input")

        if not isinstance(ID, int) or \
                not isinstance(endpoint_below, int) or \
                not isinstance(endpoint_above, int):
            raise Exception("Malformed input")

        self.queue = queue
        self.dest_above = endpoint_above
        self.dest_below = endpoint_below
        self.ID = ID
        self.mode = mode
        self.incomming_events = {}
        self.condition = queue.condition

        #Init the parent class
        Thread.__init__(self)

    def create_payload(self, content):
        payload = {}
        payload['event_ID'] = 1
        payload['stream_ID'] = 1
        payload['timestamp'] = 1.0
        payload['valid_for'] = 1
        payload['content'] = content

        return payload

    #Method to create an event
    def create_event(self, event_type, endpoint, payload = "payload"):
        if not (endpoint == self.dest_above or endpoint == self.dest_below):
            raise Exception("Malformed input")
        try:
            event = self.queue.create_event(self.ID, endpoint, event_type)
            event.set_payload(payload)
        except Exception as e:
            logging.error(str(e))

        return event

    #Method to send an event to the queue
    def send_event(self, event):
        self.condition.acquire()
        rsp = self.queue.add(event)
        self.condition.notify_all()
        self.condition.release()
        return rsp

    #Method to process an event retrieved from the queue,
    #Must me implemented in child class
    def process_events(self):
        pass

    #Method to get events, depends on what this component do (peek, get or ...)
    def get_events(self):
        empty = True
        prev = self.queue.preview()
        for key, value in prev.items():
            if value.dest_ID == self.ID:
                self.incomming_events[key] = self.queue.get(self.ID, key)
                empty = False
        return empty

    #Method used to create the thread for a component
    def run(self):
        while True:
            self.condition.acquire()
            #Loop until it get events related to its component ID
            while self.get_events():
                #Wait to receive a notification for a change in the queue
                self.condition.wait()
            #Events received, processing
            try:
                self.process_events()
            except Exception as e:
                logging.warning(str(e))
            #Release the underlying lock
            self.condition.release()

if __name__ == '__main__':
    pass


#!/usr/bin/env python

# mRPG
# https://github.com/mozor/mRPG
#
# This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
# To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ or send a letter to
# Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.

import socket
import sys
import time
import ConfigParser

config = ConfigParser.RawConfigParser()
config.read('mrpg.cfg')

server = config.get('IRC', 'server')
port = config.getint('IRC', 'port')
channel = config.get('IRC', 'channel')
botnick = config.get('IRC', 'nickname')
host = config.get('Network', 'local_ip')

def ping():
  ircsock.send("PONG :Pong\n")

def joinchan(chan):
  ircsock.send("JOIN "+ chan +"\n")

ircsock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
ircsock.bind((host, 0))
ircsock.connect((server, port))
ircsock.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :Mega Python Master\n")
ircsock.send("NICK "+ botnick +"\n")
time.sleep(5)

joinchan(channel)

while 1:
  ircmsg = ircsock.recv(2048)
  ircmsg = ircmsg.strip('\n\r')
  print(ircmsg)

  if ircmsg.find("PING :") != -1:
    ping()


"""
    refresh_tokens.py
"""
from __future__ import print_function
import getpass
import json
import requests
import sys
import time
from os import path
from .exceptions import AgaveTokenError
from ..utils import handle_bad_response_status_code

def refresh_token(api_key, api_secret, refresh_token, tenant_url):
    """ Retrieve a new Oauth bearer token

    PARAMETERS
    ----------
    api_key: str
    api_secret: str
    refresh_token: str
    tenant_url : str

    RETURNS
    -------
    token_data: dict
        access_token: str
        refresh_token: str
        expires_in: str
        created_at: str
        expires_at: str
    """
    # Set request endpoint.
    endpoint = "{0}{1}".format(tenant_url, "/token")

    # Make request.
    try:
        headers = {"Content-Type": "application/x-www-form-urlencoded"}
        data = {
            "grant_type": "refresh_token",
            "refresh_token": refresh_token,
            "scope": "PRODUCTION"
        }

        resp = requests.post(endpoint, headers=headers, data=data,
                auth=(api_key, api_secret))
    except requests.exceptions.MissingSchema as err:
        raise AgaveTokenError(err)

    # Handle bad status code.
    handle_bad_response_status_code(resp)

    # Return pertinent value.
    response = resp.json()

    now = int(time.time())
    expires_at = now + int(response["expires_in"])

    token_data = {
        "access_token": response["access_token"],
        "refresh_token": response["refresh_token"],
        "expires_in": response["expires_in"],
        "created_at": str(now),
        "expires_at": time.strftime("%a %b %-d %H:%M:%S %Z %Y", time.localtime(expires_at))
    }

    return token_data


import sys
import json

asmFilename = sys.argv[1]
with open(asmFilename, 'r') as file:
    lines = file.readlines()

pyFile = open("pythonDict.py", 'r')
addrDict = json.loads(pyFile.readline())

if addrDict:
    print("\nChanging labels...")
    for index, line in enumerate(lines):
        words = line.split()
        if words:
            if words[0][:-1] in addrDict:
                print(lines[index][:-1] + ' -> ', end='')
                line = line.replace(words[2], addrDict[words[0][:-1]])
                lines[index] = line
                print(lines[index][:-1])

    with open(asmFilename, 'w') as file:
        file.writelines(lines)

    print("Labels changed.\n")

else: print("No labels to change\n")


import pygame
from robot import Robot
from automated_robot import AutomatedRobot
from numpy import random
import numpy as np

class SmartMoveRobot(AutomatedRobot):

    def decide_upgrade(self):
        if self.projectile_initial_speed <= self.self_speed:
            self.upgrade_stat("projectile_initial_speed")
        if self.self_speed < self.max_self_speed:
            self.upgrade_stat("self_speed")
        up_choice = random.choice(self.stat_keys, size=4)
        for stat_up in up_choice:
            self.upgrade_stat(stat_up)

    def decide_cast_attack(self, other_robot_properties):
        if other_robot_properties["living"]:
            cast = random.random()
            if cast < 0.75:
                pos = other_robot_properties["pos"] + np.array([other_robot_properties["width"]/2, other_robot_properties["height"]/2])
                if pos[0] < self.rect.x - 50 or pos[0] > self.rect.x + self.rect.width + 50:
                    return self.cast_basic_attack(pos)
            else:
                return None
        else:
            return None

    def move_to_coin(self, **kwargs):
        coins = kwargs["coins"]
        distance = 100 * self.width
        nearest_coin = None
        # for coin in coins:
        #     dist = self.distance(coin)
        #     if dist < distance:
        #         distance = dist
        #         nearest_coin = coin

        if len(coins) > 0:
            center_of_mas = np.average(np.array([coin.pos for coin in coins]),
                                       weights=np.array([1/(1+self.distance(coin))**2 for coin in coins]), axis=0)
            for coin in coins:
             dist = np.linalg.norm(coin.pos - center_of_mas)
             if dist < distance:
                 distance = dist
                 nearest_coin = coin

        if nearest_coin is not None:
            dx, dy = 10 * (nearest_coin.pos - self.pos - np.array([self.width / 2, self.height / 2]))
        else:
            dx, dy = (0, 0)
        self.set_velocity(dx, -dy)
        return nearest_coin

    def dodge(self, **kwargs):
        projectiles = kwargs["projectiles"]
        near = 350
        distance = 100 * self.width
        danger_projectile = None
        for projectile in projectiles:
            dist = np.linalg.norm(projectile.pos - self.pos)
            dist2 = np.linalg.norm(projectile.pos + projectile.velocity - self.pos - self.velocity)
            if dist2 < near and dist2 < dist and dist2 < distance:
                distance = dist2
                danger_projectile = projectile

        if danger_projectile is not None:
            dx, dy = 10 * projectile.velocity

            if self.pos[1] < self.height:
                if dx > 0:
                    self.set_velocity(-dy, dx)
                else:
                    self.set_velocity(dy, -dx)
            else:
                if dx > 0:
                    self.set_velocity(dy, -dx)
                else:
                    self.set_velocity(-dy, dx)

    def decide(self, other_robot_properties, coins, projectiles):
        """"Returns a projectile object or None."""

        # Randomly decide what to upgrade
        self.decide_upgrade()

        # Move towards the nearest coin
        nearest_coin = self.move_to_coin(coins=coins)

        # Move away if a projectile is too near and moving towards me
        # Only if the robot has low health
        if self.health < 5 * other_robot_properties["damage"] or nearest_coin is None:
            self.dodge(projectiles=projectiles)

        # Decide to cast a basic attack
        return self.decide_cast_attack(other_robot_properties)


from flask import Blueprint, render_template, request, redirect, url_for, session, flash
from app.core.db import db
from .forms import InputID
from .models import User, Question, User_answer

vote_views = Blueprint('vote', __name__, template_folder='../templates', static_folder='../static')

#Index route
@vote_views.route('/', methods=['GET', 'POST'])
def inputID():
    if 'user_id' in session:
        return redirect(url_for('.question'))
    form = InputID()
    #handle POST method
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if not user:
            user = User(form.full_name.data, form.email.data, form.birthday.data)
            db.session.add(user)
            db.session.commit()
            session['user_id'] = user.id
            return redirect(url_for('.question'))
        form.email.errors.append("Email has been registered")
    #handle GET method
    return render_template('inputID.html', form=form)

#vote route
@vote_views.route('/question/', methods=['POST', 'GET'])
def question():
    #check session
    if "user_id" not in session:
        flash("You're not registered, Enter your date if you wanto register")
        return redirect(url_for('.inputID'))

    ####Handle question view####
    for x in Question.query.all():
        if not User_answer.query.filter_by(user_id=session['user_id'], question_id=x.id).first():
            question = Question.query.get(x.id)
            break
    else:
        return redirect(url_for('.thanks'))

    #handle post method
    if request.method == "POST":
        if request.form["answer"] == "YES": answer = 1
        else: answer = 0
        db.session.add(User_answer(session["user_id"], question.id, answer))
        db.session.commit()
        return redirect(url_for('.question'))

    ### HANDLE GET METHOD ###
    return render_template('question.html', question=question)

@vote_views.route('/thanks/')
def thanks():
    #check session
    if 'user_id' in session:
        #check count the number of questions answered
        if Question.query.count() is not User_answer.query.filter_by(user_id=session['user_id']).count():
            flash("You must answer all question!")
            return redirect(url_for('.question'))
        #remove all session
        session.clear()
    else:
        flash("You must register to Answer question")
        return redirect(url_for('.inputID'))
    return render_template('thanks.html')


# def solution(n):
#     global board
#     board = [[0 for _ in range(n)] for _ in range(n)]
#     answer = backTracking(0, n)
#     return answer

# def backTracking(cnt, n):
#     if cnt == n:
#         return 1
#     else:
#         result = 0
#         for i in range(n):
#             if checking(cnt, i, n):
#                 board[cnt][i] = 1
#                 result += backTracking(cnt+1, n)
#                 board[cnt][i] = 0

#         return result

# def checking(row, col, n):
#     # 가로 체크
#     for i in range(n):
#         if 1 in board[row]:
#             return False

#     # 세로 체크
#     for i in range(n):
#         if board[i][col]:
#             return False

#     # 대각선 체크 우상향
#     x = row
#     y = col
#     while x >= 0 and y < n:
#         if board[x][y]:
#             return False
#         x -= 1
#         y += 1

#     # 대각선 체크 우하향
#     x = row
#     y = col
#     while x < n and y < n:
#         if board[x][y]:
#             return False
#         x += 1
#         y += 1

#     x = row
#     y = col
#     # 대각선 체크 좌하향
#     while x < n and y >= 0:
#         if board[x][y]:
#             return False
#         x += 1
#         y -= 1

#     # 대각선 체크 좌상향
#     x = row
#     y = col
#     while x >= 0 and y >= 0:
#         if board[x][y]:
#             return False
#         x -= 1
#         y -= 1

#     return True

# def solution(n):
#     answer = 0
#     global board
#     board = [-1]*n
#     answer = backTracking(0, n)
#     return answer

# def checkBoard(x, y):
#     for i in range(y):
#         if abs(x-board[i]) == 0 or abs(x-board[i]) == abs(y-i):
#             return False
#     return True

# def backTracking(idx, n):
#     if idx == n:
#         return 1
#     else:
#         result = 0
#         if not idx:
#             for value in range(n):
#                 board[idx] = value
#                 result += backTracking(idx+1,n)
#         else:
#             for value in range(n):
#                 if checkBoard(value, idx):
#                     board[idx] = value
#                     result += backTracking(idx+1,n)

#         return result
# print(solution(4))

def solution(n):
    answer = 0
    global board
    board = [-1]*n
    for i in range(n):
        board[0] = i
        answer += nqueen(1,n)
    return answer

def nqueen(x,n):
    if x == n:
        return 1
    else:
        result = 0
        for y in range(n):
            check = True
            for x2 in range(x):
                if y == board[x2] or abs(y-board[x2]) == abs(x-x2):
                    check = False
                    break
            if check:
                board[x] = y
                result += nqueen(x+1,n)

        return result
print(solution(4))


class Solution:
    def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:
        g = defaultdict(list)

        for v1,v2 in adjacentPairs:
            g[v1].append(v2)
            g[v2].append(v1)

        ans = []
        cur = [num for num in g if len(g[num]) == 1][0]
        seen = set()

        while True:
            ans.append(cur)
            seen.add(cur)
            if g[cur][0] not in seen: cur = g[cur][0]
            elif len(g[cur]) == 2 and g[cur][1] not in seen: cur = g[cur][1]
            else: break

        return ans

1701 - 1800/1743 Restore the Array From Adjacent Pairs.py


# coding: utf-8
import ui, io
def pil_to_ui(image):
	with io.BytesIO() as b:
		image.save(b, 'PNG')
		return ui.Image.from_data(b.getvalue())

class ShadowView(ui.View):
	'''A class for a ui.View that has a shadow behind it.

	This is accomplished by:
	1. Draw the background
	2. Redraw with a shadow, but set clipping so only the edge of the shadow
	shows. This prevents the part of the shadow that's under the background
	from showing.

	'''
	def draw(self):

		'1'
		#Setup path of window shape
		path = ui.Path.rect(0, 0, self.width-10, self.height-10)

		#Draw background
		ui.set_color((0.95,0.95,0.95,0.5))
		path.fill()

		'2'
		#Setup mask by creating image
		from PIL import ImageDraw, Image
		i = Image.new('RGBA',(520,290), (255,255,255,0))
		draw = ImageDraw.Draw(i)
		draw.rectangle((self.width-10, 0, self.width, self.height),fill=(0,0,0,255))
		draw.rectangle((0, self.height-10, self.width, self.height),fill=(0,0,0,255))

		#Convert to UI, apply the mask, and draw shadow!
		i = pil_to_ui(i)
		i.clip_to_mask()
		ui.set_color((1,1,1,1))
		ui.set_shadow("black",-2,-2,10)
		path.fill()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings
import django.core.validators

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('services', '0018_auto_20150716_1024'),
    ]

    operations = [
        migrations.CreateModel(
            name='UserRating',
            fields=[
                ('id', models.AutoField(serialize=False, primary_key=True)),
                ('punctuation', models.DecimalField(max_digits=4, decimal_places=1, validators=[django.core.validators.MinValueValidator(0.0), django.core.validators.MaxValueValidator(5.0)])),
                ('voted_user', models.ForeignKey(related_name='voted_user', verbose_name=b'User voted', to=settings.AUTH_USER_MODEL)),
                ('voting_user', models.ForeignKey(related_name='voting_user', verbose_name=b'User voting', to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.RemoveField(
            model_name='userratings',
            name='voted_user',
        ),
        migrations.RemoveField(
            model_name='userratings',
            name='voting_user',
        ),
        migrations.DeleteModel(
            name='UserRatings',
        ),
    ]


# -*- coding:utf-8 -*-
# Author Hsinhan Chiang
from django.shortcuts import render_to_response
import os
def greplog(request):
    logfile_dict_list = []
    grepTarget = request.POST.get('grepTarget').strip()
    servername = request.POST.get('server')
    log_date = request.POST.get('log_date')
    if servername == '' or log_date == '':
        return render_to_response("resultGreplog.html", {"grep_result": logfile_dict_list, 'error_msg': '填入信息不完整'})
    elif len(grepTarget) < 2:
        return render_to_response("resultGreplog.html", {"grep_result": logfile_dict_list, 'error_msg': '关键字长度不能小于2'})
    do_fab = 'fab --roles=%s define:value=%s definedate:log_date=%s defineGrepTarget:grepTarget=%s doGreplog -f fabfile.py' % (
        servername, servername, log_date, grepTarget)
    do_dellog = os.popen(do_fab.decode('utf-8').encode('gb18030'))
    greplog_row_string = do_dellog.read().decode('gb18030').encode('utf-8')
    greplog_list = greplog_row_string.split('out:')
    del greplog_list[0:1], greplog_list[-1]
    if len(greplog_list[0].split()) < 7:
        return render_to_response("resultGreplog.html", {"grep_result": logfile_dict_list, 'error_msg': '查无此关键字'})
    elif len(greplog_list) > 10000:
        return render_to_response("resultGreplog.html", {"grep_result": logfile_dict_list, 'error_msg': '大于一万条，放弃'})
    for row in greplog_list:
        logfile = row.split()
        try:
            dict_logfile = {logfile[7]: logfile[8], }
        except IndexError as e:
            return render_to_response("resultGreplog.html", {"grep_result": logfile_dict_list, 'error_msg': str(e)+'，可能是该日日志已被清空'})
        logfile_dict_list.append(dict_logfile)
    response = render_to_response("resultGreplog.html", {"grep_result": logfile_dict_list})
    response.set_cookie('Log_servername', servername)
    response.set_cookie('log_date', log_date)
    return response

def catlog(request):
    cat_list = []
    logname = request.GET.get('logname')
    servername = request.COOKIES.get('Log_servername', '')
    log_date = request.COOKIES.get('log_date', '')
    do_fab = 'fab --roles=%s define:value=%s definedate:log_date=%s defineGrepTarget:grepTarget=%s doCatlog -f fabfile.py' % (
        servername, servername, log_date, logname)
    do_catlog = os.popen(do_fab)
    result_catlog = do_catlog.read().decode('gb18030').encode('utf-8')
    catlog_list = result_catlog.split('out:')
    del catlog_list[0], catlog_list[-1]
    for row in catlog_list:
        row_list = row.split('[')
        del row_list[-1]
        cat_list.append(row_list)
    return render_to_response("resultCatlog.html",
                              {"grep_result": cat_list, "log_name": servername + ' : ' + log_date + '日 : ' + logname})


class Solution:
    def maximumGain(self, s: str, x: int, y: int) -> int:
        if x > y:
            s, res = self.remove(s, 'ab', x)
            res += self.remove(s, 'ba', y)[1]
        else:
            s, res = self.remove(s, 'ba', y)
            res += self.remove(s, 'ab', x)[1]
        return res

    # return new_s, res
    def remove(self, s, pattern, point):
        stack, res = [], 0
        for i in range(len(s)):
            stack.append(s[i])
            while len(stack) >= 2 and stack[-2] + stack[-1] == pattern:
                res += point
                stack.pop()
                stack.pop()
        new_s = ''.join(stack)
        return new_s, res

    def maximumGain_own_TLE(self, s: str, x: int, y: int) -> int:
        return self.dfs(s, x, y, {})

    def dfs(self, s, x, y, memo):
        if s in memo:
            return memo[s]
        res = 0
        for i in range(len(s)-1):
            sub = s[i:i+2]
            if sub == 'ab':
                res = max(res, x + self.dfs(s[:i] + s[i+2:], x, y, memo))
            elif sub == 'ba':
                res = max(res, y + self.dfs(s[:i] + s[i+2:], x, y, memo))
        memo[s] = res
        return res

    def test(self):
        test_cases = [
            ["cdbcbbaaabab", 4, 5],
            ["aabbaaxybbaabb", 5, 4],
        ]
        for s, x, y in test_cases:
            res1 = self.maximumGain(s, x, y)
            res2 = self.maximumGain_own_TLE(s, x, y)
            print('res1: %s' % res1)
            print('res2: %s' % res2)
            print('-='*30 + '-')

if __name__ == '__main__':
    Solution().test()


import socket
import tkinter as tk
import useraddress
import clientside

# Prompt the user to specify where the server is running
# Retrieves Ip address, Port and Username from User
prompt = tk.Tk()
prompt_user = useraddress.PromptUser(prompt)
prompt.mainloop()

HOST = prompt_user.get_info()[0]
PORT = int(prompt_user.get_info()[1])
username = prompt_user.get_info()[2]

# Open socket using address given by user
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect_ex((HOST, PORT))

# Load main window for chatroom, closes socket after window is closed
frame = tk.Tk()
client_frame = clientside.ClientFrame(frame, sock, username)
frame.mainloop()
sock.shutdown(socket.SHUT_RDWR)
sock.close()


import logging
from typing import Any, Dict

from lightgbm import LGBMRegressor

from freqtrade.freqai.base_models.BaseRegressionModel import BaseRegressionModel
from freqtrade.freqai.data_kitchen import FreqaiDataKitchen

logger = logging.getLogger(__name__)

class LightGBMRegressor(BaseRegressionModel):
    """
    User created prediction model. The class needs to override three necessary
    functions, predict(), train(), fit(). The class inherits ModelHandler which
    has its own DataHandler where data is held, saved, loaded, and managed.
    """

    def fit(self, data_dictionary: Dict, dk: FreqaiDataKitchen, **kwargs) -> Any:
        """
        Most regressors use the same function names and arguments e.g. user
        can drop in LGBMRegressor in place of CatBoostRegressor and all data
        management will be properly handled by Freqai.
        :param data_dictionary: the dictionary constructed by DataHandler to hold
                                all the training and test data/labels.
        """

        if self.freqai_info.get('data_split_parameters', {}).get('test_size', 0.1) == 0:
            eval_set = None
            eval_weights = None
        else:
            eval_set = (data_dictionary["test_features"], data_dictionary["test_labels"])
            eval_weights = data_dictionary["test_weights"]
        X = data_dictionary["train_features"]
        y = data_dictionary["train_labels"]
        train_weights = data_dictionary["train_weights"]

        init_model = self.get_init_model(dk.pair)

        model = LGBMRegressor(**self.model_training_parameters)

        model.fit(X=X, y=y, eval_set=eval_set, sample_weight=train_weights,
                  eval_sample_weight=[eval_weights], init_model=init_model)

        return model


from django.urls import path
import hknweb.events.views as views

app_name = "events"
urlpatterns = [
    path("<int:id>", views.show_details, name="detail"),
    path("<int:id>/rsvp", views.rsvp, name="rsvp"),
    path("<int:id>/unrsvp", views.unrsvp, name="unrsvp"),
    path(
        "<int:id>/confirm_rsvp/<int:operation>", views.confirm_rsvp, name="confirm_rsvp"
    ),
    path("new", views.add_event, name="new"),
    path("<int:pk>/edit", views.EventUpdateView.as_view(), name="edit"),
    path("<int:pk>/delete", views.EventDeleteView.as_view(), name="delete"),
    path("rsvps", views.AllRsvpsView.as_view(), name="rsvps"),
    path("leaderboard", views.get_leaderboard, name="leaderboard"),
    path("", views.index, name="index"),
    path(
        "attendance/<int:event_id>/<int:attendance_form_id>/<int:rsvp_id>",
        views.submit_attendance,
        name="submit_attendance",
    ),
    path(
        "<int:event_id>/attendance/manage",
        views.manage_attendance,
        name="manage_attendance",
    ),
]


import os
import glob
place = r"C:\Users\gille\OneDrive\Documenten\gilles mapppeke\Machine Learning\data\hypercubes\hypercube_cut"
filenames = glob.glob(place + r'/*h5')

to_displace = "labeled"

for i, fn in enumerate(filenames):
    if fn.find(to_displace)!=-1:
        fn = fn.replace("_"+ to_displace + "_hypercube", "_hypercube")
        print(fn)
        print(filenames[i])
        os.rename(filenames[i], fn)


# USAGE
# python regularization.py --dataset ../datasets/animals
from sklearn.linear_model import SGDClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from pyimagesearch.preprocessing import SimplePreprocessor
from pyimagesearch.datasets import SimpleDatasetLoader
from imutils import paths
import argparse

ap = argparse.ArgumentParser()
ap.add_argument('-d', '--dataset', required=True, help='path to input dataset')
args = vars(ap.parse_args())

print('[INFO] loading images...')
img_paths = list(paths.list_images(args['dataset']))
sp = SimplePreprocessor(32, 32)
sdl = SimpleDatasetLoader([sp])
data, labels = sdl.load(img_paths, verbose=500)
data = data.reshape((len(data), -1))

# Encode the labels as integer
le = LabelEncoder()
labels = le.fit_transform(labels)

# Split to train and test set
trainX, testX, trainY, testY = train_test_split(data, labels, test_size=0.25, random_state=42)

# Training on multiple types of regularization
for r in [None, 'l1', 'l2']:
    # train a SGD classifier using a softmax loss function and the
    # specified regularization function for 10 epochs
    print(f'[INFO] training model with {r} penalty')
    model = SGDClassifier(loss='log', penalty=r, max_iter=10, learning_rate='constant', eta0=0.1, random_state=42)
    model.fit(trainX, trainY)

    acc = model.score(testX, testY)
    print(f'[INFO] {r} penalty accuracy: {acc*100:.2f}%')


s = "a man, a plan, a canal: Panama"

def palindrome(apal):
    box = []
    delthis = ''
    for char in apal.lower():
        if char.isalpha():
            box.append(char)
    if delthis.join(reversed(box)) == delthis.join(box):
        return True, f'{delthis.join(box)} is a palindrome!'
    else:
        return False, f'{delthis.join(box)}is not a palindrome :('

print(palindrome(s))

# Well, this probably runs like a mack truck, but I won't lie im lowkey proud of myself for doing this one with
# no help from outside sources in a short amount of time. Feels good.
#I'm gunna guess since it went through a for loop and it being reversed, that would put it in O(n^2) territory.


""" a class that inherits from the list class the init method which creates a list of integers given the length and the step"""
class BinarySearch(list):

    def __init__(self, length, step):
        super(BinarySearch, self).__init__()

        for index in range(1, length + 1):
            self.append(index * step)
        self.length = len(self)

    def search(self, value_to_find):
        """a search method using the binary search algorithm to find a value passed in"""
        first_index = 0
        last_index = len(self) - 1
        value_to_find_index = 0
        is_found = False
        # initialize counter to 0
        counter = 0
        # check if value_to_find is the first or last element. if True, don't carry out the binary search
        if value_to_find == self[first_index]:
            value_to_find_index = first_index
            is_found = True
        elif value_to_find == self[last_index]:
            value_to_find_index = last_index
            is_found = True

        # check if value_to_find is not present in the list. if True, no need to search
        if value_to_find not in self:
            is_found = True
            value_to_find_index = -1

        # carry out the binary search algorithm using a while loop if value is not yet found
        while first_index <= last_index and not is_found:
            counter += 1  # increase counter when an iteration occurs
            middle_point = (first_index + last_index) // 2
            if self[middle_point] == value_to_find:
                is_found = True
                value_to_find_index = middle_point
            else:
                if value_to_find < self[middle_point]:
                    last_index = middle_point - 1
                else:
                    first_index = middle_point + 1
        return {'count': counter, 'index': value_to_find_index}


import os
import numpy as np

class InvertedIndex:
    def __init__(self, index_name):
        index_dir = os.path.join(index_name)
        self.docs = np.memmap(index_name + ".docs", dtype=np.uint32,
              mode='r')
        self.freqs = np.memmap(index_name + ".freqs", dtype=np.uint32,
              mode='r')

    def __iter__(self):
        i = 2
        while i < len(self.docs):
            size = self.docs[i]
            yield (self.docs[i+1:size+i+1], self.freqs[i-1:size+i-1])
            i += size+1

    def __next__(self):
        return self

for i, (docs, freqs) in enumerate(InvertedIndex("/home/josh/output/output.url.inv")):
    print(i, docs, freqs)


import ui
from PIL import Image as ImageP
import io
import random

mainWindow = ui.View()
mainWindow.name = 'Image Conversion'
mainWindow.background_color = 'white'
mainWindow.width = 700 #ui.get_screen_size().width
mainWindow.height = 700 #ui.get_screen_size().height

def pil2ui(pil_img):
	with io.BytesIO() as buffer:
		pil_img.save(buffer, format='PNG')
		return ui.Image.from_data(buffer.getvalue())

path = "../Images/"
quarter = pil2ui(ImageP.open(path + "quarter.png").resize((70,70), ImageP.ANTIALIAS))
dime = pil2ui(ImageP.open(path + "dime.png").resize((50,50), ImageP.ANTIALIAS))
nickel = pil2ui(ImageP.open(path + "nickel.png").resize((60,60), ImageP.ANTIALIAS))
penny = pil2ui(ImageP.open(path + "penny.png").resize((55,55), ImageP.ANTIALIAS))

picture1 = ui.ImageView()
picture1.width = 70
picture1.height = 70
picture1.image = quarter

mainWindow.add_subview(picture1)

#mainWindow.present('fullscreen')
mainWindow.present('sheet')


import os

import numpy as np
from sklearn.metrics import confusion_matrix

import pandas as pd

import matplotlib.pyplot as plt
import seaborn as sns

from tqdm import tqdm

from glob import glob

import ffmpeg

import warnings
warnings.filterwarnings('ignore')

classes = {'простой': 0,
        'вынужденная': 1,
        'сварка': 2}

df_nine_left = pd.read_csv('nine_hour_left.csv')
df_nine_right = pd.read_csv('nine_hour_right.csv')

df_five_left = pd.read_csv('five_hour_left.csv')
df_five_right = pd.read_csv('five_hour_right.csv')

ann_train = []
ann_test = []

for _, r in tqdm(df_nine_left.iterrows()):
    file_result = f'train_5s/{r["fname"]}'
    line = file_result + ' ' + str(classes[r['label']]) + '\n'
    if r['time'] > 7200:
        ann_train.append(line)
    else:
        ann_test.append(line)

for _, r in tqdm(df_nine_right.iterrows()):
    file_result = f'train_5s/{r["fname"]}'
    line = file_result + ' ' + str(classes[r['label']]) + '\n'
    if r['time'] > 7200:
        ann_train.append(line)
    else:
        ann_test.append(line)

for _, r in tqdm(df_five_left.iterrows()):
    file_result = f'train_5s/{r["fname"]}'
    line = file_result + ' ' + str(classes[r['label']]) + '\n'
    if r['time'] < 13845:
        ann_train.append(line)
    else:
        ann_test.append(line)

for _, r in tqdm(df_five_right.iterrows()):
    file_result = f'train_5s/{r["fname"]}'
    line = file_result + ' ' + str(classes[r['label']]) + '\n'
    if r['time'] < 13845:
        ann_train.append(line)
    else:
        ann_test.append(line)

with open('ann_train.txt', 'w') as train_file, open('ann_test.txt', 'w') as test_file:
    train_file.writelines(ann_train)
    test_file.writelines(ann_test)


import argparse
import dataclasses
import subprocess
import sys
from datetime import datetime
from typing import List

from testcase import get_cli_base_cmd
from testcase import Result

base_cmd = get_cli_base_cmd()

@dataclasses.dataclass
class CleanupItem:
    name: str
    list_cmd: str
    del_cmd: str
    items: List = dataclasses.field(default_factory=list)

def parse_args(*args) -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Cleanup the CloudTruth environment")
    parser.add_argument(
        dest="needles",
        nargs="*",
        default=["Windows", "Linux", "macOS", "ci-cli", "testcli"],
        help="Search strings to look for",
    )
    parser.add_argument(
        "-q",
        "--quiet",
        dest="quiet",
        action="store_true",
        help="Do not show what the script is doing",
    )
    parser.add_argument("-v", "--verbose", dest="verbose", action="store_true", help="Detailed output")
    parser.add_argument("--confirm", "--yes", dest="confirm", action="store_true", help="Skip confirmation prompt")
    return parser.parse_args(*args)

def cli(cmd: str) -> Result:
    updated = base_cmd + cmd.replace("'", '"')  # allows this to work on Windows
    start = datetime.now()
    process = subprocess.run(updated, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    delta = datetime.now() - start
    return Result(
        return_value=process.returncode,
        stdout=process.stdout.decode("us-ascii", errors="ignore").replace("\r", "").split("\n"),
        stderr=process.stderr.decode("us-ascii", errors="ignore").replace("\r", "").split("\n"),
        timediff=delta,
        command=updated,
    )

def yes_or_no(question: str) -> bool:
    reply = str(input(question + " (y/n): ")).lower().strip()
    if reply[0] == "y":
        return True
    if reply[0] == "n":
        return False
    else:
        return yes_or_no("Please enter ")

def cloudtruth_cleanup(*args):
    args = parse_args(*args)
    if not args.needles:
        print("No search strings provided")
        return -1
    # reset verbosity flags if they conflict with each other
    if args.quiet and args.verbose:
        args.quiet = False
        args.verbose = False

    result = cli("config curr -x")
    print(result.command)
    print(result.out())

    # define a set of elements to cleanup
    elements = [
        CleanupItem(name="projects", list_cmd="proj tree", del_cmd="proj del -y"),
        CleanupItem(name="environments", list_cmd="env tree", del_cmd="env del -y"),
        CleanupItem(name="users", list_cmd="user ls", del_cmd="user del -y"),
        CleanupItem(name="groups", list_cmd="group ls", del_cmd="group del -y"),
        CleanupItem(name="invitations", list_cmd="user invite ls", del_cmd="user invite del -y"),
        CleanupItem(name="types", list_cmd="types tree", del_cmd="types del -y"),
        CleanupItem(name="pushes", list_cmd="action push ls", del_cmd="action push del -y"),
        CleanupItem(name="imports", list_cmd="action import ls", del_cmd="action import del -y"),
    ]

    for elem in elements:
        if not args.quiet:
            print(f"Looking for matching {elem.name}...")
        result = cli(elem.list_cmd)

        # use reverse order to accommodate the ordering `tree` commands
        for line in reversed(result.stdout):
            item = line.strip()
            if any([needle for needle in args.needles if needle in item]):
                elem.items.append(line.strip())

    if not (any([x for x in elements if x.items])):
        types = [x.name for x in elements]
        type_list = ", ".join(types[:-1])
        type_list += f", or {types[-1]}"
        search_list = ", ".join(args.needles)
        print(f"No {type_list} items found matching: {search_list}")
        return 0

    if not (args.confirm and args.quiet):
        print("\n\nFound matches: ")
        for elem in elements:
            if not elem.items:
                print(f"  {elem.name}: None")
            else:
                print(f"  {elem.name}:")
                for item in elem.items:
                    print(f"    {item}")
        print("")

    if not args.confirm and not yes_or_no("Delete the above items"):
        print("No items deleted")
        return 0

    all_deleted = True
    for elem in elements:
        if not elem.items:
            continue
        for item in elem.items:
            result = cli(elem.del_cmd + f" '{item}'")
            if args.verbose:
                print(result.command)
            if result.return_value != 0:
                all_deleted = False
                print(f"Failed to delete {elem.name} {item}")
                if args.verbose:
                    print(result.err())

    if all_deleted:
        print("Deleted all items")
    return 0

if __name__ == "__main__":
    sys.exit(cloudtruth_cleanup(sys.argv[1:]))


import pandas as pd
from openpyxl.styles import PatternFill

def rgb_to_hex(rgb):
    return '%02x%02x%02x' % rgb

def darken(hex_code, shade):
    shade = shade/10
    #add something to convert shade number ie 9 actually equals 10% darker
    RGB = tuple(int(hex_code[i:i + 2], 16) for i in (0, 2, 4))
    r = RGB[0]
    g = RGB[1]
    b = RGB[2]

    # darken by 10%
    darken_R = int(round(r * shade))
    darken_G = int(round(g * shade))
    darken_B = int(round(b * shade))

    rgbTuple = (darken_R, darken_G, darken_B) #tuple of RGB values to convert to Hex

    return rgb_to_hex(rgbTuple)

def lighten(hex_code, shade):
    shade = shade/10
    RGB = tuple(int(hex_code[i:i + 2], 16) for i in (0, 2, 4))
    r = RGB[0]
    g = RGB[1]
    b = RGB[2]

    # lighten by 10%
    lighten_R = int(round(r + ((255 - r) * shade), 0))
    lighten_G = int(round(g + ((255 - g) * shade), 0))
    lighten_B = int(round(b + ((255 - b) * shade), 0))

    rgbTuple = (lighten_R, lighten_G, lighten_B) #tuple of RGB values to convert to Hex

    return rgb_to_hex(rgbTuple)

def create_lighten_df(colorList):
    empty_df_list = []
    df = pd.DataFrame(columns=['Original Color Hex', 'Change %', 'Color Hex', 'Direction', 'Color'])
    for item in colorList:
        for num in range(11):
            original_color = "#" + item
            change_percent = str(num) + '0%'
            color_hex = "#" + lighten(hex_code=item, shade=num)
            direction = 'Lighter'
            df = pd.concat([df,
                            pd.DataFrame.from_dict({'Original Color Hex': [original_color],
                                                    'Change %': [change_percent],
                                                    'Color Hex': [color_hex],
                                                    'Direction': [direction],
                                                     'Color' : ""})],
                           ignore_index=True)
    return df

def create_darken_df(colorList):
    empty_df_list = []
    df = pd.DataFrame(columns=['Original Color Hex', 'Change %', 'Color Hex', 'Direction', 'Color'])
    for item in colorList:
        for num in range(11):
            original_color = "#" + item
            change_percent = str(num) + '0%'
            color_hex = "#" + darken(hex_code=item, shade=num)
            direction = 'Darken'
            df = pd.concat([df,
                            pd.DataFrame.from_dict({'Original Color Hex': [original_color],
                                                    'Change %': [change_percent],
                                                    'Color Hex': [color_hex],
                                                    'Direction': [direction],
                                                     'Color' : ""})],
                           ignore_index=True)
        print(df)

    percDict = {
        '100%': "00%",
        '90%': "10%",
        '80%': "20%",
        '70%': "30%",
        '60%': "40%",
        '50%': "50%",
        '40%': "60%",
        '30%': "70%",
        '20%': "80%",
        '10%': "90%",
        '00%': "100%"
    }
    df['Change %'] = df['Change %'].apply(lambda x: percDict[x])
    df['Original Color Hex'] = df['Original Color Hex'].astype('category')
    df = df.sort_index(ascending=False).reset_index(drop=True)
    df['Sorting'] = df.index
    sorter = ['#' + str(x) for x in colorList]
    df['Original Color Hex'] = df['Original Color Hex'].cat.set_categories(sorter)
    df = df.sort_values(by=['Original Color Hex', 'Sorting']).drop(columns='Sorting')

    return df

###############start of work###################

# colorList is the list of hex codes that will be used to generate the report

colorList = ['CC0000', #red
             '000000', #black
             '4d4d4f', #dark gray
             '969697', #medium gray
             'dddddd', # light gray
             'f3f3f3', # ultra light gray
             'f58025', # ada compliant orange
             'fdb913', # ada compliant yellow
             '97ca3e', # ada compliant green
             '479cd6', # ada compliant blue
             '1d3c6d', # ada compliant navy
             '751c59' # ada compliant purple
             ]

lighten_df = create_lighten_df(colorList) #create a dataframe of lightened colors
darken_df = create_darken_df(colorList) # create a dataframe of darkened colors

with pd.ExcelWriter("ColorShadeReferenceWorkbook.xlsx", engine="openpyxl") as writer:
    # create the "Lighten" worksheet
    sheet_name = "Lighten"
    # Export DataFrame content
    lighten_df.to_excel(writer, sheet_name=sheet_name, index=False)
    # Set column width dimensions
    sheet = writer.sheets[sheet_name]# open sheet
    sheet.column_dimensions['A'].width = 18
    sheet.column_dimensions['B'].width = 10
    sheet.column_dimensions['C'].width = 10
    sheet.column_dimensions['D'].width = 10
    sheet.column_dimensions['E'].width = 9
    # Set background colors depending on cell values
    for cell, in sheet[f'E2:E{len(lighten_df) + 1}']: # Skip header row, process as many rows as there are DataFrames
        value = lighten_df["Color Hex"].iloc[cell.row - 2] #set color value to row['Color Hex'] value
        value = value.strip("#")
        cell.fill = PatternFill(start_color=value, end_color=value, fill_type='solid')

    #create the "Darken" worksheet
    sheet_name = "Darken"
    # Export DataFrame content
    darken_df.to_excel(writer, sheet_name=sheet_name, index=False)
    sheet = writer.sheets[sheet_name]
    # Set column width dimensions
    sheet.column_dimensions['A'].width = 18
    sheet.column_dimensions['B'].width = 10
    sheet.column_dimensions['C'].width = 10
    sheet.column_dimensions['D'].width = 10
    sheet.column_dimensions['E'].width = 9
    # Set background colors depending on cell values
    for cell, in sheet[f'E2:E{len(darken_df) + 1}']: # Skip header row, process as many rows as there are DataFrames
        value = darken_df["Color Hex"].iloc[cell.row - 2] #set color value to row['Color Hex'] value
        value = value.strip("#") #strip #
        cell.fill = PatternFill(start_color=value, end_color=value, fill_type='solid') #fill cell colid color


from os import system
system('clear')

lista_membros = list()
familia = dict()
# familia = [{'nome': 'Joemar',     'idade': 60, 'cor dos olhos': 'Castanhos'},
#            {'nome': 'Alessandra', 'idade': 50, 'cor dos olhos': 'Pretos'},
#            {'nome': 'Jean',       'idade': 26, 'cor dos olhos': 'Pretos'},
#            {'nome': 'Lara',       'idade': 22, 'cor dos olhos': 'Castanhos'},
#            {'nome': 'Thalles',    'idade': 19, 'cor dos olhos': 'Castanhos'}]

for i in range(1, 6):
    print('\033[1;34mMembros e características da família\033[m')
    familia.clear()
    familia['nome'] = input(f'\033[1;34mPessoa {i}: \033[m')
    familia['idade'] = int(input(f'\033[1;34mIdade do(a) {familia["nome"]}: \033[m'))
    familia['cor dos olhos'] = input(f'\033[1;34mCor dos olhos do(a) {familia["nome"]}: \033[m')
    lista_membros.append(familia)
    familia = familia.copy()
    system('clear')

print(f'\n\033[1;34mOs membros da família são: \033[m\033[31m{lista_membros}\033[m')

1º Bimestre/Capítulo 01 - Fundamentos da Linguagem/Exercício 1.29.py


import os
import statistics
import sys

import httpx
from dotenv import load_dotenv

load_dotenv(sys.argv[1])

url = os.environ['url']
attempts = int(os.environ.get('attempts', 100))
payload = os.environ.get('payload')
auth_header = os.environ.get('auth_header', 'X-Racetrack-Auth')
auth_token = os.environ.get('auth_token', '')
reuse_connection: bool = os.environ.get('reuse_connection', 'true').lower() in {'true', '1'}

print(f'Testing URL {url}')
print(f'attempts: {attempts}, reuse_connection (connection pool): {reuse_connection}, payload: {payload}')

durations = []
headers = {
    'User-Agent': 'curl/7.81.0',
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    auth_header: auth_token,
}
client = httpx.Client()
try:
    for i in range(attempts):

        if reuse_connection:
            response = client.post(url, timeout=30, headers=headers, content=payload)

        else:
            response = httpx.post(url, timeout=30, headers=headers, content=payload)

        duration = response.elapsed.total_seconds()

        try:
            response.raise_for_status()
        except httpx.HTTPStatusError:
            print(f'Response error: {response.content}')
            raise
        durations.append(duration)
        print(f'Attempt #{i+1} - request duration: {duration*1000:.2f} ms')
except KeyboardInterrupt:
    pass
finally:
    client.close()

average = sum(durations) / len(durations)
min_duration = min(durations)
max_duration = max(durations)
median = statistics.median(durations)
print(f'----------')
print(f'Requests: {len(durations)}')
print(f'Median: {median*1000:.2f} ms')
print(f'Average: {average*1000:.2f} ms')
print(f'Min: {min_duration*1000:.2f} ms')
print(f'Max: {max_duration*1000:.2f} ms')


#from threading import Thread
from bs4 import BeautifulSoup
import pandas as pd
#import os
#import sys
from selenium import webdriver
#from selenium.webdriver.common.proxy import *
from time import gmtime, strftime, sleep
#import sqlite3
#from queue import Queue
#import re
import requests

cities_frame = pd.read_html('https://en.wikipedia.org/wiki/List_of_United_States_cities_by_population')
cities = cities_frame[4]
print(cities)
abbrs = { 'Alaska':	'AK', 'Alabama': 'AL', 'Arkansas': 'AR', 'Arizona': 'AZ', 'California': 'CA',
			'Colorado': 'CO', 'Connecticut': 'CT', 'District of Columbia': 'DC', 'Delaware': 'DE',
			'Florida': 'FL', 'Georgia': 'GA', 'Iowa': 'IA', 'Idaho':	'ID',
			'Illinois': 'IL', 'Indiana': 'IN', 'Kansas': 'KS', 'Kentucky': 'KY',
			'Louisiana': 'LA', 'Massachusetts': 'MA', 'Maryland':	'MD', 'Maine': 'ME',
			'Michigan': 'MI', 'Minnesota': 'MN', 'Missouri': 'MO', 'Mississippi': 'MS',
			'Montana': 'MT', 'North Carolina': 'NC', 'North Dakota': 'ND', 'Nebraska': 'NE',
			'New Hampshire': 'NH', 'New Jersey': 'NJ', 'New Mexico': 'NM', 'Nevada': 'NV',
			'New York': 'NY', 'Ohio': 'OH', 'Oklahoma': 'OK', 'Oregon': 'OR',
			'Pennsylvania': 'PA', 'Rhode Island': 'RI', 'South Carolina': 'SC', 'South Dakota': 'SD',
			'Tennessee': 'TN', 'Texas': 'TX', 'Utah': 'UT', 'Virginia': 'VA',
			'Vermont': 'VT', 'Washington': 'WA', 'Wisconsin': 'WI', 'West Virginia': 'WV',
			'Wyoming': 'WY'}

states = pd.read_csv('/home/val/coding/USA-states-cities.csv')
#print(cities)
cities_list = pd.DataFrame()

def crawling(search_url, file_name):

	options = webdriver.ChromeOptions()
	options.add_argument('headless')
	driver = webdriver.Chrome(executable_path = './chromedriver', options = options)
	links = open(file_name, 'a')
	driver.get(search_url)
	print(search_url)
	for i in range(20):
		soup = BeautifulSoup(driver.page_source, 'lxml')
		for each in soup.find_all(class_='iUh30 bc'):
			try:
				print(each.text.split(' ')[0])
				links.write(each.text.split(' ')[0]+'\n')
			except Exception:
				print(each.text)
				links.write(each.text+'\n')
		try:
			driver.find_element_by_class_name('pn').click()
		except Exception:
			return
		print('--------')
		i += 1
		sleep(3)

	links.close()

#print(cities_list)

websites_frame = pd.DataFrame(columns=['state', 'city', 'link'])
#states = states.drop_duplicates(zip('City', 'Abbreviation'))

for i in range(len(cities)):
#	print(states.loc[i]['City'])
#	print(states.loc[i]['City'])
	try:
		city = cities.loc[i]['City'].split('[')[0]
	except Exception:
		city = cities.loc[i]['City']
	try:
		state = abbrs[str(cities.loc[i]['State[c]'])]
	except Exception:
		continue
	search_url = f'https://www.google.com/search?q=File+a+complaint+{state}+{city}'
	#print('-----', search_url, '-----')
	try:
		state = str(cities.loc[i]['State[c]']).strip()
	except Exception:
		continue
	crawling(search_url, 'file_companies_sites.csv')
	search_url = f'https://www.google.com/search?q=File+a+complaint+{state}+{city}+attorney+general'
	crawling(search_url, 'file_companies_sites.csv')
	search_url = f'https://www.google.com/search?q=local+state+agencies+{state}+{city}'
	crawling(search_url, 'local_agencies.csv')
	search_url = f'https://www.google.com/search?q=consumer+protection+{state}+{city}'
	crawling(search_url, 'file_companies_sites.csv')


import os
import re
from glob import glob
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from IPython import get_ipython

POSSIBLE_LABELS = 'yes no up down left right on off stop go silence unknown'.split()
id2name = {i: name for i, name in enumerate(POSSIBLE_LABELS)}
name2id = {name: i for i, name in id2name.items()}
len(id2name)

def load_data(data_dir):
    """ Return 2 lists of tuples:
    [(class_id, user_id, path), ...] for train
    [(class_id, user_id, path), ...] for validation
    """
    # Just a simple regexp for paths with three groups:
    # prefix, label, user_id
    pattern = re.compile("(.+\/)?(\w+)\/([^_]+)_.+wav")
    all_files = glob(os.path.join(data_dir, 'train/audio/*/*wav'))

    with open(os.path.join(data_dir, 'train/validation_list.txt'), 'r') as fin:
        validation_files = fin.readlines()
    valset = set()
    for entry in validation_files:
        r = re.match(pattern, entry)
        if r:
            valset.add(r.group(3))

    possible = set(POSSIBLE_LABELS)
    train, val = [], []
    for entry in all_files:
        r = re.match(pattern, entry)
        if r:
            label, uid = r.group(2), r.group(3)
            if label == '_background_noise_':
                label = 'silence'
            if label not in possible:
                label = 'unknown'

            label_id = name2id[label]

            sample = (label, label_id, uid, entry)
            if uid in valset:
                val.append(sample)
            else:
                train.append(sample)

    print('There are {} train and {} val samples'.format(len(train), len(val)))

    columns_list = ['label', 'label_id', 'user_id', 'wav_file']

    train_df = pd.DataFrame(train, columns = columns_list)
    valid_df = pd.DataFrame(val, columns = columns_list)

    return train_df, valid_df

def process_wav_file(fname):
    wav = read_wav_file(fname)

    L = 16000  # 1 sec

    if len(wav) > L:
        i = np.random.randint(0, len(wav) - L)
        wav = wav[i:(i+L)]
    elif len(wav) < L:
        rem_len = L - len(wav)
        i = np.random.randint(0, len(silence_data) - rem_len)
        silence_part = silence_data[i:(i+L)]
        j = np.random.randint(0, rem_len)
        silence_part_left  = silence_part[0:j]
        silence_part_right = silence_part[j:rem_len]
        wav = np.concatenate([silence_part_left, wav, silence_part_right])

    specgram = stft(wav, 16000, nperseg = 400, noverlap = 240, nfft = 512, padded = False, boundary = None)
    phase = np.angle(specgram[2]) / np.pi
    amp = np.log1p(np.abs(specgram[2]))

    return np.stack([phase, amp], axis = 2)

train_df, valid_df = load_data('./train/')
train_df.head()
train_df.label.value_counts()

silence_files = train_df[train_df.label == 'silence']
train_df      = train_df[train_df.label != 'silence']

from scipy.io import wavfile
from scipy.signal import stft

def read_wav_file(fname):
    _, wav = wavfile.read(fname)
    wav = wav.astype(np.float32) / np.iinfo(np.int16).max
    return wav

silence_data = np.concatenate([read_wav_file(x) for x in silence_files.wav_file.values])

# last batch will contain padding, so remove duplicates
submission = dict()
for i in range(0, 10500):
    fname, label = os.path.basename(test_paths[i]), id2name[classes[i]]
    submission[fname] = label

with open('106368019_submission.csv', 'w') as fout:
    fout.write('fname,label\n')
    for fname, label in submission.items():
        fout.write('{},{}\n'.format(fname, label))


"""
Demo of custom tick-labels with user-defined rotation.
"""
import math
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
from matplotlib.widgets import Slider, Button, RadioButtons

z = int(input("how long you wanna go? "))
n1 = 2
n2 = int(input("another number "))
xcor = []
ycor =[]
lcor=[]
x = 0
i = 0

for j in range(0,z):
	lcor.append(j*(math.log(2,math.e)/math.log(3,math.e)))

def pycode(x):
    n = math.ceil(x*(math.log(n2,math.e)/math.log(n1,math.e))-1)#a1
    return n
while x <= z:
    x += 1
    ycor.append((n2**x/n1**pycode(x)))
    ycor.append((n1**(pycode(x)+1)/n2**x))
while i <= z*2+1: #math done to allign x and y coordinates
    i+=1
    xcor.append(i)
labels = []

#plt.subplot(111,polar=True)

plt.plot(xcor[0:z:2], ycor[0:z:2], 'co')
plt.plot(xcor[1:z:2], ycor[1:z:2], 'ro')

plt.plot((n2**x/n1**pycode(x)),'k')

#plt.plot(xcor,ycor,'k')
# You can specify a rotation for the tick labels in degrees or with keywords.
#plt.xticks(lor, labels, rotation='vertical')
plt.xticks(xcor, labels, rotation='vertical')
# Pad margins so that markers don't get clipped by the axes
plt.margins(0.2)
# Tweak spacing to prevent clipping of tick-labels
plt.subplots_adjust(bottom=0.15)
plt.show()