from django.urls import path
from .import views
# from google import views as view

urlpatterns = [
    path('register/', views.register, name='register'),
    path('base/', views.base, name='base'),
    path('farmer_register/', views.farmer_register, name='farmer_register'),
    path('customer_register/', views.customer_register, name='customer_register'),
    path('login/', views.loginpage, name='loginpage'),
    path('logout/', views.logoutUser, name='logoutUser'),
    path('home/', views.home, name='home'),
    path('farmerhome/', views.farmerhome, name='farmerhome'),
    path('product/', views.product, name='product'),
    path('update/<int:id>/', views.updatepage, name='updatepage'),
    path('products/delete/<product_id>', views.deleteProduct, name = 'delete_product'),
    path('delete/<int:id>', views.deletepage),
    path('farmer/<int:id>/', views.farmer, name='farmer'),
    path('farmer/add_connection/<int:id>/', views.connect, name='connect'),
    path('connection/', views.connectionpage, name='connection'),
    path('post/', views.post, name='post'),
    path('farmerpost/', views.postpage, name='postpage'),
    path('updatepost/<int:id>/', views.updatepost, name='updatepost'),
    path('deletePost/<int:post_id>/', views.deletePost, name='deletepost'),
    path('map/customer/', views.maps_viewcustomer, name="maps_customer"),
    path('map/farmer/', views.maps_viewfarmer, name="maps_farmer"),
    path('profile/<int:id>/', views.profile, name='profile'),
    path('cluster/', views.cluster, name="cluster"),
    path('all_farmers/', views.all_farmers, name='all_farmers'),

]


import pandas as pd
import subprocess
import iphost
import plotly.express as px
import re

import sys
if sys.version_info[0] < 3:
    from StringIO import StringIO
else:
    from io import StringIO

def parseShellCall(username):
    output = subprocess.check_output(
        ["ssh", "-o", "StrictHostKeyChecking=no",
         "%s@%s" % (username, iphost.get()), "df"]
    ).decode("utf-8")
    lines = output.split("\n")
    disks = []
    for i in range(len(lines)):
        line = lines[i].split(" ")
        line = [j for j in line if j]
        reg = re.match("\/dev\/sd*", lines[i]) or re.match("merger", lines[i])
        if reg or i == 0:
            disks.append(line)
    return [i for i in disks if i]

def generateDataFrame(shell_output):
    df = pd.DataFrame(shell_output[1:], columns=shell_output[0][:-1])
    df["1K-blocks"] = df["1K-blocks"].astype(int)
    df["Used"] = df["Used"].astype(int)
    df["Available"] = df["Available"].astype(int)
    df = df.drop(columns=["Use%"])
    df["Fraction"] = df.Used/df["1K-blocks"]
    return df

def main():
    output = parseShellCall(sys.argv[1])
    df = generateDataFrame(output)
    print(df)
    fig = px.bar(df, x="Mounted", y="Fraction")
    fig.update_yaxes(range=[0, 1])
    fig.write_html('/plots/usage.html')

if __name__ == '__main__':
    main()


def run():
    #ask user what type of adventure they want
    print("Enter the type of adventure you'd like.")
    adventure = str(input())
    if (adventure == "scary") or (adventure == "short"):
        print("Entering the dark forest")
    elif (adventure == "safe") or (adventure == "long"):
        print("Taking the safe route")
    else:
        print("Not sure which route to take")
if __name__ == "__main__":
    run()


import re

from aiogram import Router
from aiogram.filters import Command, CommandStart, Text
from aiogram.types import Message, CallbackQuery
from sqlalchemy import select, delete
from sqlalchemy.sql.expression import and_
from keyboards.bookmarks import create_bookmarks_keyboard, create_edit_keyboard
from keyboards.books import create_books_keyboard
from keyboards.pagination import create_pagination_keyboard, create_contents_keyboard
from lexicon.lexicon_en import LEXICON
from models.methods import get_user
from models.models import User, Bookmark, Book
from services.book_handing import prepare_book
from filters.filters import DelCallbackFactory, IsDigitCallbackData, BookCallbackFactory

router = Router()

#
@router.message(CommandStart())
async def process_start_command(message: Message, **kwargs):
    user_id = message.from_user.id
    session = kwargs['session_maker']
    user = await get_user(user_id, session)
    if not user:
        user = User(user_id=user_id)
        async with session() as session:
            session.add(user)
            await session.commit()
        await message.answer('You have been successfully registered')
    await message.answer(LEXICON['/start'])

@router.message(Command(commands=['help']))
async def process_help_command(message: Message):
    await message.answer(LEXICON['/help'])

@router.message(Command(commands=['books']))
@router.callback_query(Text(text=['books']))
async def process_books_command(response: Message | CallbackQuery, **kwargs):
    session = kwargs['session_maker']
    async with session() as session:
        books = await session.execute(select(Book))
        books = books.scalars().all()
    if isinstance(response, Message):
        await response.answer(text=LEXICON['/books'], reply_markup=create_books_keyboard(books))
    else:
        await response.message.edit_text(text=LEXICON['/books'], reply_markup=create_books_keyboard(books))

@router.callback_query(lambda cb: cb.data.startswith('book_'))
async def get_necessary_book(callback: CallbackQuery, **kwargs):
    title = re.sub(r'book_', '', callback.data)
    session = kwargs['session_maker']
    async with session() as session:
        book_dict = await prepare_book(title, session)
        total_pages = list(book_dict.keys())[-1]
        user = await session.get(User, callback.from_user.id)
        user.contents_page = 0
        if user.active_book == '' or user.active_book != title:
            user.page = 1
            user.active_book = title
            current_page = user.page
            session.add(user)
            text = book_dict[current_page]
        else:
            current_page = user.page
            text = book_dict[current_page]
        await session.commit()
    await callback.message.edit_text(text=text,
                                     reply_markup=create_pagination_keyboard('backward',
                                                                             f'{current_page} / {total_pages}',
                                                                             'forward'))

@router.callback_query(Text(text=['forward']))
async def process_backward_command(callback: CallbackQuery, **kwargs):
    session = kwargs['session_maker']
    async with session() as session:
        user = await session.get(User, callback.from_user.id)
        book_dict = await prepare_book(user.active_book, session)
        total_pages = list(book_dict.keys())[-1]
        if user.page < int(total_pages):
            user.page += 1
            current_page = user.page
            text = book_dict[current_page]
            session.add(user)
            await session.commit()
            await callback.message.edit_text(text=text,
                                             reply_markup=create_pagination_keyboard('backward',
                                                                                f'{current_page} / {total_pages}',
                                                                                'forward'))
        else:
            await callback.answer(text=LEXICON['max_page'])

@router.callback_query(Text(text=['backward']))
async def process_backward_command(callback: CallbackQuery, **kwargs):
    session = kwargs['session_maker']
    async with session() as session:
        user = await session.get(User, callback.from_user.id)
        book_dict = await prepare_book(user.active_book, session)
        total_pages = list(book_dict.keys())[-1]
        if user.page > 1:
            user.page -= 1
            current_page = user.page
            text = book_dict[current_page]
            session.add(user)
            await session.commit()
            await callback.message.edit_text(text=text,
                                             reply_markup=create_pagination_keyboard('backward',
                                                                                f'{current_page} / {total_pages}',
                                                                                'forward'))
        else:
            await callback.answer(text=LEXICON['min_page'])

@router.callback_query(Text(text=['contents']))
async def show_contents(callback: CallbackQuery, **kwargs):
    session = kwargs['session_maker']
    async with session() as session:
        user = await session.get(User, callback.from_user.id)
        book_dict = await prepare_book(user.active_book, session)
        await callback.message.edit_text(text=LEXICON['contents'],
                                         reply_markup=create_contents_keyboard(user.active_book, user.contents_page,
                                                                               book_dict))

@router.callback_query(IsDigitCallbackData())
async def get_necessary_page(callback: CallbackQuery, **kwargs):
    session = kwargs['session_maker']
    async with session() as session:
        user = await session.get(User, callback.from_user.id)
        user.page = current_page = int(callback.data)
        book_dict = await prepare_book(user.active_book, session)
        session.add(user)
        await session.commit()
        total_pages = list(book_dict.keys())[-1]
        text = book_dict[current_page]
    await callback.message.edit_text(text=text,
                                     reply_markup=create_pagination_keyboard('backward',
                                                                             f'{current_page} / {total_pages}',
                                                                             'forward'))

@router.callback_query(Text(text=['backward_contents']))
async def process_backward_contents(callback: CallbackQuery, **kwargs):
    session = kwargs['session_maker']
    async with session() as session:
        user = await session.get(User, callback.from_user.id)
        book_dict = await prepare_book(user.active_book, session)
        if user.contents_page >= 15:
            user.contents_page -= 15
            session.add(user)
            await callback.message.edit_text(text=LEXICON['contents'],
                                             reply_markup=create_contents_keyboard(user.active_book,
                                                                                user.contents_page, book_dict))
            await session.commit()
        else:
            await callback.answer(text=LEXICON['min_page'])

@router.callback_query(Text(text=['forward_contents']))
async def process_forward_contents(callback: CallbackQuery, **kwargs):
    session = kwargs['session_maker']
    async with session() as session:
        user = await session.get(User, callback.from_user.id)
        book_dict = await prepare_book(user.active_book, session)
        if user.contents_page <= list(book_dict.keys())[-1] - 15:
            user.contents_page += 15
            session.add(user)
            await callback.message.edit_text(text=LEXICON['contents'],
                                             reply_markup=create_contents_keyboard(user.active_book,
                                                                                user.contents_page, book_dict))
            await session.commit()
        else:
            await callback.answer(text=LEXICON['max_page'])

@router.message(Command(commands=['beginning']))
async def process_beginning_command(message: Message, **kwargs):
    session = kwargs['session_maker']
    async with session() as session:
        user = await session.get(User, message.from_user.id)
        if user.active_book:
            book_dict = await prepare_book(user.active_book, session)
            total_pages = list(book_dict.keys())[-1]
            user.page = 1
            session.add(user)
            await message.answer(text=book_dict[1],
                                 reply_markup=create_pagination_keyboard('backward',
                                                                         f'{user.page} / {total_pages}',
                                                                         'forward'))
            await session.commit()
        else:
            await message.answer(LEXICON['None_page'])

@router.message(Command(commands=['continue']))
@router.callback_query(Text(text='continue'))
async def process_continue_command(response: Message | CallbackQuery, **kwargs):
    session = kwargs['session_maker']
    async with session() as session:
        user = await session.get(User, response.from_user.id)
        if user.active_book:
            book_dict = await prepare_book(user.active_book, session)
            total_pages = list(book_dict.keys())[-1]
            if isinstance(response, Message):
                await response.answer(text=book_dict[1],
                                      reply_markup=create_pagination_keyboard('backward',
                                                                              f'{user.page} / {total_pages}',
                                                                              'forward'))
            else:
                await response.message.edit_text(text=book_dict[1],
                                                 reply_markup=create_pagination_keyboard('backward',
                                                                                f'{user.page} / {total_pages}',
                                                                                'forward'))
        else:
            if isinstance(response, Message):
                await response.answer(LEXICON['None_page'])
            else:
                await response.answer()
                await response.message.answer(LEXICON['None_page'])

@router.callback_query(Text(text=['add_to_bookmarks']))
async def add_to_bookmarks(callback: CallbackQuery, **kwargs):
    session = kwargs['session_maker']
    async with session() as session:
        user = await session.get(User, callback.from_user.id)
        bookmark = await session.execute(
            select(Bookmark).filter(
                Bookmark.book == user.active_book,
                Bookmark.page == user.page,
                Bookmark.user_id == user.user_id
            )
        )
        bookmark = bookmark.one_or_none()
        if not bookmark:
            bookmark = Bookmark(user_id=user.user_id,
                                user=user,
                                book=user.active_book,
                                page=user.page)
            session.add(bookmark)
            await session.commit()
            await callback.answer('The bookmark was created successfully')
        else:
            await callback.answer('The bookmark was created earlier')

@router.message(Command(commands=['bookmarks']))
@router.callback_query(Text(text='bookmarks'))
async def get_bookmarks_list(response: Message | CallbackQuery, **kwargs):
    session = kwargs['session_maker']
    async with session() as session:
        bookmarks = await session.execute(select(Bookmark).where(Bookmark.user_id == response.from_user.id))
        bookmarks = bookmarks.scalars().all()
        if bookmarks:
            if isinstance(response, Message):
                await response.answer(text=LEXICON['/bookmarks'],
                                      reply_markup=create_bookmarks_keyboard(bookmarks))
            else:
                await response.message.edit_text(text=LEXICON['/bookmarks'],
                                                 reply_markup=create_bookmarks_keyboard(bookmarks))
        else:
            if isinstance(response, Message):
                await response.answer(LEXICON['no_bookmarks'])
            else:
                await response.message.edit_text(LEXICON['no_bookmarks'])

@router.callback_query(Text(text='edit_bookmarks'))
async def process_edit_press(callback: CallbackQuery, **kwargs):
    session = kwargs['session_maker']
    async with session() as session:
        bookmarks = await session.execute(select(Bookmark).where(Bookmark.user_id == callback.from_user.id))
        bookmarks = bookmarks.scalars().all()
        await callback.message.edit_text(text=LEXICON['edit_bookmarks'],
                                         reply_markup=create_edit_keyboard(bookmarks))

@router.callback_query(DelCallbackFactory.filter())
async def process_del_bookmark(callback: CallbackQuery, callback_data: DelCallbackFactory, **kwargs):
    session = kwargs['session_maker']
    async with session() as session:
        await session.execute(delete(Bookmark).where(
            and_(
                Bookmark.book == callback_data.book,
                Bookmark.page == int(callback_data.page)
            )
        ))
        bookmarks = await session.execute(select(Bookmark).where(Bookmark.user_id == callback.from_user.id))
        bookmarks = bookmarks.scalars().all()
        await callback.message.edit_text(text=LEXICON['edit_bookmarks'],
                                         reply_markup=create_edit_keyboard(bookmarks))
        await session.commit()

@router.callback_query(BookCallbackFactory.filter())
async def view_necessary_bookmark(callback: CallbackQuery, callback_data: DelCallbackFactory, **kwargs):
    session = kwargs['session_maker']
    async with session() as session:
        user = await session.get(User, callback.from_user.id)
        user.page = callback_data.page
        user.active_book = callback_data.book
        book_dict = await prepare_book(user.active_book, session)
        total_pages = list(book_dict.keys())[-1]
        session.add(user)
        await callback.message.edit_text(text=book_dict[callback_data.page],
                                         reply_markup=create_pagination_keyboard('backward',
                                                                                f'{user.page} / {total_pages}',
                                                                                'forward'))
        await session.commit()


import pickle
import tensorflow as tf
import argparse
import os
import numpy as np

def make_model(i, l1, l2):
    inputs = tf.keras.Input(shape=(i,))
    x = tf.keras.layers.Dense(l1, activation=tf.nn.relu)(inputs)
    x = tf.keras.layers.Dense(l2)(x)
    model = tf.keras.Model(inputs=inputs, outputs=x)
    return model

def train_dagger(defined_model, data_dict, batch, epochs):
    model = defined_model
    print(model.summary())

    data = data_dict
    x_train = np.squeeze(data['observations'], axis=1)
    y_train = np.squeeze(data['actions'], axis=1)
    history = model.fit(
        x_train, y_train,
        batch_size=batch,
        epochs=epochs)

    return history

def train(ckpt, pkl_file, epochs, lr, decay, momentum, no_nesterov, batch):
    model = make_model(111, 64, 8)
    model.compile(
        optimizer=tf.keras.optimizers.SGD(lr=lr, decay=decay,
                                          momentum=momentum,
                                          nesterov=not no_nesterov),
        loss='mean_squared_error',
        metrics=['mse'])
    print(model.summary())

    data = pickle.load(open(pkl_file, 'rb'))
    x_train = data['observations'][:int(0.8*len(data['observations']))]
    y_train = np.squeeze(data['actions'][:int(0.8*len(data['actions']))], axis=1)
    x_val = data['observations'][int(-0.2*len(data['observations'])):]
    y_val = np.squeeze(data['actions'][int(-0.2*len(data['actions'])):], axis=1)

    os.makedirs(ckpt, exist_ok=True)
    cp_callback = tf.keras.callbacks.ModelCheckpoint(
        os.path.join(ckpt, 'weights.{epoch}-{val_loss:.4f}.hdf5'),
        save_weights_only=True,
        verbose=1)

    history = model.fit(
        x_train, y_train,
        batch_size=batch,
        epochs=epochs,
        validation_data=(x_val, y_val),
        callbacks=[cp_callback])

    return history

if __name__=='__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('ckpt', type=str)
    parser.add_argument('--pkl_file', type=str, default='')
    parser.add_argument('--data_dict', type=str)
    parser.add_argument('--epochs', type=int, default=35)
    parser.add_argument('--lr', type=float, default=1e-4)
    parser.add_argument('--decay', type=float, default=1e-6)
    parser.add_argument('--momentum', type=float, default=0.9)
    parser.add_argument('--no-nesterov', action='store_true', default=False)
    parser.add_argument('--batch', type=int, default=1)
    args = parser.parse_args()
    print(args)
    train(args.ckpt, args.pkl_file, args.epochs, args.lr, args.decay, args.momentum, args.no_nesterov, args.batch)


import sys
import re
from pyhelpers import Parser, Grid, Coord
from pprint import pp

def make_data(input_file):
    sensors = []
    beacons = []
    width = 0
    height = 0
    with open(input_file, "r") as f:
        for line in f:
            sx, sy, bx, by = re.findall(r"(-?\d+)", line)
            sensors.append(Coord(int(sx)+2, int(sy)))
            beacons.append(Coord(int(bx)+2, int(by)))
            width = max(width, int(sx), int(bx))
            height = max(height, int(sy), int(by))
    return sensors, beacons, width+2, height

if len(sys.argv) > 1:
    print("INPUT\n")
    sensors, beacons, width, height = make_data("input")
else:
    print("EXAMPLE\n")
    sensors, beacons, width, height = make_data("example")

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

def manhattan(a, b):
    return abs(a.x-b.x) + abs(a.y-b.y)

grid = Grid(".", width+1, height+1)

for sensor in sensors:
    print(sensor)
    grid[sensor] = "S"

for beacon in beacons:
    grid[beacon] = "B"

# for sensor, beacon in zip(sensors, beacons):
#     dist = manhattan(sensor, beacon)

pp(sensors)
pp(beacons)

print(grid)


'''
Created on October 28, 2013
@author: yniknafs
'''
import os
import sys
import argparse
import logging
import numpy as np
import csv

def CNV_pts(headers, line, last_pheno_col, amp_thresh, del_thresh):

    logging.basicConfig(level=logging.DEBUG,
                      format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    #logging.info('Identifying CNV samples')

    cnv_pts = []
    null_pts = []

    peak_type = line[0].split('Peak')[0]

    if peak_type == "Amplification":
        thresh = float(amp_thresh)
        multiplier = 1
    elif peak_type == "Deletion":
        thresh = float(del_thresh)
        multiplier = -1
    else:
        logging.debug("Not a valid peak type in CNV_sample identification")
        sys.exit()

    #categorize the samples based on whether or not they are amplified
    for x in xrange(last_pheno_col, len(line)):
        #use this product so that you don't have to have multiple if statements for directionality
        product = float(line[x])*multiplier
        #print product
        if product > thresh:
            if headers[x] != []:
                cnv_pts.append(headers[x])
        else:
            if headers[x] != []:
                null_pts.append(headers[x])
    return cnv_pts, null_pts

    return 0

if __name__ == '__main__':
    sys.exit(main())


# -*- coding:utf-8 -*-
from cx_Oracle import connect
from datetime import datetime
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from pandas.core.frame import DataFrame

fontFile = "C:\\windows\\Fonts\\malgun.ttf"
fontName = fm.FontProperties(fname = fontFile, size = 50).get_name()
plt.rc("font",family=fontName)

con = connect("sdedu/1@121.160.41.151:1521/xe")
sql = "select * from project_corona_2"
cur = con.cursor()
cur.execute(sql)
day, name, count = [], [], []
for _, day1, name1, count1 in cur:
    day1 = datetime.strftime(day1, "%Y-%m")
    # print(day1, name1, count1)
    day.append(day1)
    name.append(name1)
    count.append(count1)

con.close()
df = DataFrame()
df['찐날짜'] = day
df['시.도'] = name
df['추가 확진'] = count

print(df)
print(df['찐날짜'].unique())
print(df['시.도'].unique())
print(df.groupby("시.도").sum())
df2 = df.groupby("시.도").sum()
# plt.plot(df2)
# plt.show()

df2 = df2.sort_values(by = "추가 확진", ascending=False)
print(df2)
# df2.to_csv("C:/wodnd_file/soso.csv",header=False) # 보내고 나서 다음페이지에 해야겠지만 그냥 이번페이지에

df3 = pd.read_csv("C:/wodnd_file/soso.csv",names=['시.도',"추가 확진"])
print(df3)
df3 = df3.sort_values(by="추가 확진", ascending=True)
# plt.bar(df3['시.도'],df3['추가 확진'])
# plt.show()

d = {'width':0.7, 'edgecolor':'black','linewidth':1}
plt.pie(df3['추가 확진'], labels = df3['시.도'], startangle=90, autopct="%.f%%",wedgeprops=d)
plt.title("전국 코로나 누적 확진자%")

plt.show()


# Problems
# 1.	Reverse a string
# a.	Write code that takes a string as input and returns the string reversed
# b.	i.e. “Hello” will be returned as “olleH”
def reverse(word):
    backwards_word = ""
    for letter in range(len(word)-1, -1, -1):
        backwards_word += word[letter]
    return backwards_word
print(f"Your reversed word is: {reverse('Hello')}")

print("")
# 2.	Capitalize letter
# a.	Write code that takes a string as input and capitalize the first letter of each word. Words will be separated by only one space. i.e. “hello world” should be outputted as “Hello World”
string = "this string will capitalize the first letter in each word!"
capitalized_string = string.title()

user_input = input("Type anything you'd like: ")
capitalize_user_input = user_input.title()

print(capitalized_string)
print(capitalize_user_input)

print("")
# 3.	Compress a string of characters
# a.	For example, an input of "aaabbbbbccccaacccbbbaaabbbaaa" would compress to "3a5b4c2a3c3b3a3b3a"
def compress(string):
    index = 0
    compressed = ""
    string_length = len(string)
    while index != string_length:
        count = 1
        while (index < string_length-1) and (string[index] == string[index+1]):
            count = count + 1
            index = index + 1
        if count == 1:
            compressed += str(string[index])
        else:
            compressed += str(string[index]) + str(count)
        index = index + 1
    return compressed
string = "bookkeeping"
print(compress(string))

print("")
# 4.	BONUS CHALLENGE: Palindrome
# a.	A word, phrase, or sequence that reads the same backward as forward i.e. madam
# b.	Write code that takes a user input and checks to see if it is a Palindrome and reports the result
def palindrome(string):
    if string == string[::-1]:
        print(True)
    else:
         print(False)
palindrome("spacecaps")
palindrome("Wednesday")


import math
import os.path
import subprocess
import sys

def get_track_duration(fn):
    """
    Get the duration in seconds of the given media file.
    """

    # Simple "ffprobe -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 $fn" does not work well
    # for media files with Variable Bit Rate.
    # So we are reading the timestamp and duration of the last packet.
    args = ['ffprobe', '-v', 'error', '-select_streams', 'a', '-show_entries', 'packet=pts_time:packet=duration_time',
            '-of', 'default=noprint_wrappers=1:nokey=1', fn]
    p = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if p.returncode != 0:
        print(f'{fn}: ffprobe failed!', file=sys.stderr)
        print('STDOUT:\n', p.stdout.decode(), file=sys.stderr)
        print('STDERR:\n', p.stderr.decode(), file=sys.stderr)
        return None

    # Decode the output, and calculate the stream duration
    try:
        lines = p.stdout.decode().splitlines()[-2:]  # PTS and duration of the last packet (in seconds)
        return round(float(lines[0]) + float(lines[1]), 3)
    except BaseException:
        print(f'{fn}: invalid output of ffprobe!', file=sys.stderr)
        print('STDOUT:\n', p.stdout.decode(), file=sys.stderr)
        return None

def get_track_id_from_file_name(fn):
    """
    Get the track ID (the base file name without known extensions) from the file name.
    """
    known_exts = {'.aac', '.flac', '.m4a', '.mp3', '.ogg', '.opus', '.vorbis', '.wav', '.wma',  # audio
                  '.avi', '.flv', '.mkv', '.mov', '.mp4', '.mpg', '.wmv',  # video
                  '.csv', '.json', '.msgpack', '.txt'}  # data

    track_id = os.path.basename(fn)
    while True:
        root, ext = os.path.splitext(track_id)
        if ext in known_exts:
            track_id = root
        else:
            break

    return track_id

def pitch_scale_to_cents(scale):
    """
    Convert pitch scale to cents (100 cents = 1 semitone, 12 semitones = 1 octave).
    """
    return 1200 * math.log(scale) / math.log(2)

def tempo_scale_to_per_cent(scale):
    """
    Convert tempo scale to per cent.
    """
    return 100 * scale


"""
Setup file for {{ cookiecutter.module_name }}
"""

import os
from setuptools import setup

def read(filename):
    """Read a filename as a string"""
    return open(os.path.join(os.path.dirname(__file__), filename)).read()

setup(
    name="{{ cookiecutter.module_name }}",
    version="{{ cookiecutter.version }}",
    author="{{ cookiecutter.full_name }}",
    author_email="{{ cookiecutter.email }}",
    description="{{ cookiecutter.description }}",
    url="{{ cookiecutter.project_home }}",
    packages=["{{ cookiecutter.module_name }}"],
    long_description=read('README.md'),
)


def armazena_tabela_relacionamento(tabela_um, tabela_dois, tabela_relacionamento):
    output = open(f'{tabela_relacionamento}/output.sql', "w")
    for chave, valor_tb in tabela_um.items():
        for key, value in tabela_dois.items():
            if (value[1] == valor_tb[1] and value[2] == valor_tb[2]):
                valores = [str(chave), str(key)]
                valores_formatados = []
                for valor in valores:
                    if isinstance(valor, str):
                        valores_formatados.append(str(valor))
                    else:
                        valores_formatados.append(f"'{valor}'")
                valores_string = ', '.join(valores_formatados)
                result = f"INSERT INTO {tabela_relacionamento} values ({valores_string});\n"
                output.write(result)


from django.shortcuts import redirect
from django.utils import timezone
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin

from backend.developments.models import (
    Development,
    Media,
    Link
)
from backend.users.models import User
from .forms import (
    ProfileUpdateForm,
    DevelopmentCreateForm,
    DevelopmentUpdateForm,
    MediaCreateForm,
    LinkCreateForm
)

class MypageHomeView(LoginRequiredMixin, generic.TemplateView):
    template_name = 'mypage/index.html'
    model = User

    def get(self, *args, **kwargs):
        context = {
            'developments': Development.objects.filter(developer_id=self.kwargs['pk'])
        }
        return self.render_to_response(context)

class ProfileUpdateView(LoginRequiredMixin, generic.TemplateView):
    template_name = 'mypage/profile/update.html'

    def get(self, request, *args, **kwargs):
        form = ProfileUpdateForm(
            initial={
                'associations': request.user.get_associations()
            }
        )

        user = self.request.user
        form.fields['generation'].widget.attrs['value'] = user.generation
        form.fields['description'].initial = user.description

        context = dict(form=form)
        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
        if request.method == 'POST':
            form = ProfileUpdateForm(request.POST, request.FILES)
            if form.is_valid():
                user = self.request.user
                cleaned_data = form.cleaned_data
                user.generation = cleaned_data['generation']
                user.associations = ','.join(cleaned_data['associations'])
                user.description = cleaned_data['description']
                if cleaned_data['image']:
                    user.image = cleaned_data['image']
                user.save()

                return redirect('mypage:home', request.user.pk)
        else:
            form = ProfileUpdateForm()

        return redirect('mypage:profile_update')

class DevelopmentNewView(LoginRequiredMixin, generic.TemplateView):
    template_name = 'mypage/developments/new.html'

    def get(self, *args, **kwargs):
        development_form = DevelopmentCreateForm()
        media_form = MediaCreateForm()
        link_form = LinkCreateForm()
        development_form.fields['co_developers'].queryset = (
            User.objects.filter(is_superuser=False)
                .exclude(pk=self.request.user.pk)
        )

        context = {
            'development_form': development_form,
            'media_form': media_form,
            'link_form': link_form
        }
        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
        if request.method == 'POST':
            development_form = DevelopmentCreateForm(request.POST, request.FILES)
            media_form = MediaCreateForm(request.POST, request.FILES)
            link_form = LinkCreateForm(request.POST)

            media_flag = False
            if media_form.is_valid():
                cleaned_data = media_form.cleaned_data
                if cleaned_data['media_type'] and cleaned_data['file']:
                    media_flag = True
                    media = Media()
                    media.type = cleaned_data['media_type']
                    media.file = cleaned_data['file']
                    media.save()

            link_flag = False
            if link_form.is_valid():
                cleaned_data = link_form.cleaned_data
                if cleaned_data['link_type'] and cleaned_data['link']:
                    link_flag = True
                    link = Link()
                    link.type = cleaned_data['link_type']
                    link.link = cleaned_data['link']
                    link.save()

            if development_form.is_valid():
                cleaned_data = development_form.cleaned_data
                development = Development()
                development.title = cleaned_data['title']
                development.description = cleaned_data['description']
                development.developer = request.user
                if cleaned_data['top_image']:
                    development.top_image = cleaned_data['top_image']
                development.associations = ','.join(cleaned_data['associations'])
                development.is_private = cleaned_data['is_private']
                development.save()

                for co_developer in development_form.cleaned_data['co_developers']:
                    development.co_developers.add(co_developer)

                if media_flag:
                    development.medias.add(media)
                if link_flag:
                    development.links.add(link)

                development.submitted_at = timezone.now()
                development.updated_at = timezone.now()
                development.save()

                return redirect('mypage:home', request.user.pk)
        else:
            form = DevelopmentCreateForm

        return redirect('mypage:devlopments_new')

class DevelopmentUpdateView(LoginRequiredMixin, generic.TemplateView):
    template_name = 'mypage/developments/update.html'

    def get(self, *args, **kwargs):
        development = Development.objects.get(pk=self.kwargs['pk'])
        media = development.medias.first()
        media_flag = bool(media)
        link = development.links.first()
        link_flag = bool(link)
        development_form_initial = {
            'title': development.title,
            'description': development.description,
            'associations': development.get_associations(),
            'is_private': development.is_private,
            'top_image': [development.top_image if development.top_image else None]
        }
        if media_flag:
            media_form_initial = {
                'media_type': media.type,
                'file': media.file
            }
        else:
            media_form_initial = {}

        if link_flag:
            link_form_initial = {
                'link_type': link.type,
                'link': link.link
            }
        else:
            link_form_initial = {}

        development_form = DevelopmentCreateForm(initial=development_form_initial)
        media_form = MediaCreateForm(initial=media_form_initial)
        link_form = LinkCreateForm(initial=link_form_initial)
        development_form.fields['co_developers'].queryset = (
            User.objects.filter(is_superuser=False)
                .exclude(pk=self.request.user.pk)
        )
        development_form.fields['co_developers'].initial = (
            [co_developer.pk for co_developer in development.co_developers.all()]
        )

        context = {
            'development': development,
            'development_form': development_form,
            'media_form': media_form,
            'link_form': link_form
        }

        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
        development = Development.objects.get(pk=self.kwargs['pk'])
        media_exists = False
        if development.medias.exists():
            media_exists = True
            media = development.medias.first()
        link_exists = False
        if development.links.exists():
            link = development.links.first()

        if request.method == 'POST':
            development_form = DevelopmentCreateForm(request.POST, request.FILES)
            media_form = MediaCreateForm(request.POST, request.FILES)
            link_form = LinkCreateForm(request.POST)

            media_flag = False
            if media_form.is_valid():
                cleaned_data = media_form.cleaned_data
                if str(cleaned_data['file']) == 'False':
                    media.delete()
                elif cleaned_data['media_type'] and cleaned_data['file']:
                    if not media_exists:
                        media = Media()
                    media_flag = True
                    media.type = cleaned_data['media_type']
                    media.file = cleaned_data['file']
                    media.save()

            link_flag = False
            if link_form.is_valid():
                cleaned_data = link_form.cleaned_data
                if cleaned_data['link_type'] and cleaned_data['link']:
                    if not link_exists:
                        link = Link()
                    link_flag = True
                    link.type = cleaned_data['link_type']
                    link.link = cleaned_data['link']
                    link.save()

            if development_form.is_valid():
                cleaned_data = development_form.cleaned_data
                development.title = cleaned_data['title']
                development.description = cleaned_data['description']
                if str(cleaned_data['top_image']) == 'False':
                    development.top_image.delete()
                elif cleaned_data['top_image']:
                    development.top_image = cleaned_data['top_image']
                development.associations = ','.join(cleaned_data['associations'])
                development.is_private = cleaned_data['is_private']
                development.save()

                development.co_developers.clear()
                for co_developer in development_form.cleaned_data['co_developers']:
                    development.co_developers.add(co_developer)

                if media_flag:
                    development.medias.add(media)
                if link_flag:
                    development.links.add(link)

                development.updated_at = timezone.now()
                development.save()

                return redirect('mypage:home', request.user.pk)
        else:
            form = DevelopmentUpdateForm()

        return redirect('mypage:devlopments_update', development.pk)

class DevelopmentDeleteView(LoginRequiredMixin, generic.TemplateView):
    template_name = 'mypage/developments/delete.html'

    def get(self, *args, **kwargs):
        context = {
            'development': Development.objects.get(pk=self.kwargs['pk'])
        }

        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
        development = Development.objects.get(pk=self.kwargs['pk'])

        if request.method == 'POST':
            development.delete()
            return redirect('mypage:home', request.user.pk)

        return redirect('mypage:developments_update', development.pk)

class DevelopmentDetailView(LoginRequiredMixin, generic.TemplateView):
    template_name = 'mypage/developments/detail.html'

    def get(self, *args, **kwargs):
        context = {
            'development': Development.objects.get(pk=self.kwargs['pk'])
        }

        return self.render_to_response(context)


# This is a puzzle game.
print("Welcome to my puzzle game!")
print("Intro: N-puzzle Game is a sliding puzzle game having 8 (or 15) square tiles placed on a board, with digits 1 - n \n\
       numbered in a frame that is 3 (or 4) tiles high and 3 (or 4) tiles wide, leaving one unoccupied tile position. \n\
       Tiles in the same row or column of the open position can be moved by sliding them horizontally or vertically. \n\
       The goal of the puzzle is to place the tiles in numerical order.")
while True:
    con = input('Enter "c" to continue, "q" to quit: ')
    if con == "q": break
    if con == "c": pass
    else: print("Invalid input. Please try again.")

## Step 1: User Input
    raw_num = 0
    while True:
        raw_num = input('Enter "1" for 8-puzzle, "2" for 15-puzzle: ')
        if raw_num == "1":
            num = 3
            break
        if raw_num == "2":
            num = 4
            break
        else: print("Invalid input. Please try again.")
### num indicates the length of side.

    while True:
        try:
            raw_direct = input("Enter the four letters used for left, right, up and down move: ")

            left = raw_direct[0]
            right = raw_direct[2]
            up = raw_direct[4]
            down = raw_direct[6]

            direct_list = []
            direct_list.append(left)
            direct_list.append(right)
            direct_list.append(up)
            direct_list.append(down)
            if (left.isalpha()) and (right.isalpha()) and (up.isalpha()) and (down.isalpha())\
                and sorted(direct_list) == sorted(list(set(direct_list)))\
                and len(direct_list) == 4:
                break
            else: print("Invalid input. Please try again.")
        except: print("Invalid input. Please try again.")
#### Ensure the symbol is a letter, no repetition and in adequate numbers.
### Determine the direction symbol.

## Step 2: Data Initialization
    import random
    raw = []
    for i in range(num**2):
        raw.append(str(i))
### Initialize a ordered value in raw list.
    while True:
        for i in range(num**2):
            tmp = raw[i]
            pos = random.randint(0,num**2-1)
            raw[i] = raw[pos]
            raw[pos] = tmp
        rev_num = 0
        for j in raw:
            for k in raw[0:raw.index(j)-1]:
                if k > j:
                    rev_num += 1
        if num == 3:
            if rev_num % 2 == 0: break
        if num == 4:
            if rev_num % 2 == 1: break
### Generate a random list by swapping one element in raw list with another one.
### Also guarantee the puzzle is solvable.

## Step 3: Interface Presentation
    def pre():
        for i in range(num**2):
            if raw[i] == "0":
                print("".ljust(4),end="")
            else: print(raw[i].ljust(4),end="")
            if i % num == num - 1: print("\n")
    ### Generate and adjust for an artificial board.

## Step 4: Find Blank
    def findBlank():
        for i in range(num**2):
            if raw[i] == "0":
                return i
### Find blank space and return its index.

## Step 5: User Movement
    def movement():
        opt_list = []
        if (findBlank() + 1) < num**2 and (findBlank() + 1) % num != 0:
            opt_list.append("left-%s" % left)
### The spaces on the right must be within, and must be an artificial neighbour of it.
        if (findBlank() - 1) >= 0 and findBlank() % num != 0:
            opt_list.append("right-%s" % right)
### The spaces on the left must be within, and must be an artificial neighbour of it.
        if (findBlank() + num) < num**2:
            opt_list.append("up-%s" % up)
### The spaces on the top must be within, and must be an artificial neighbour of it.
        if (findBlank() - num) >= 0:
            opt_list.append("down-%s" % down)
### The spaces on the bottom must be within, and must be an artificial neighbour of it.
        opt_str = ""
        for temp in opt_list:
            opt_str += temp + ", "
        opt_str = opt_str[: -2]
        option = input("Enter your move! " + "(" + opt_str + ") ")
### Display possible operations.
        if option == left:
            pos = findBlank()
            tmp = raw[pos]
            raw[pos] = raw[pos+1]
            raw[pos+1] = tmp
        elif option == right:
            pos = findBlank()
            tmp = raw[pos]
            raw[pos] = raw[pos-1]
            raw[pos-1] = tmp
        elif option == up:
            pos = findBlank()
            tmp = raw[pos]
            raw[pos] = raw[pos + num]
            raw[pos + num] = tmp
        elif option == down:
            pos = findBlank()
            tmp = raw[pos]
            raw[pos] = raw[pos - num]
            raw[pos - num] = tmp

## Step 6: Game Start
    def win():
        for i in range(num**2 - 1):
            if raw[i] != str(i+1):
                return False
        else: return True
 ### Determine if it is in accordance with a win.

## Main:
    pre()
    i = 0
    while (win() != True):
        movement()
        pre()
        i += 1
    print("Congratulations! You solved the puzzle in " + str(i) + " moves!")


import nmslib
import torch
from flask import Flask, render_template, request, url_for
from sentence_transformers import SentenceTransformer
import pandas as pd
import re

import autoencoder

app = Flask(__name__)

valid_dataframe = pd.read_csv('../generated_resources/valid_data.csv')
albert_model = SentenceTransformer('bert-base-nli-mean-tokens').to('cuda')
autoencoder_model = autoencoder.AutoEncoder(768, 256).to('cuda')
autoencoder_model.load_state_dict(torch.load('../generated_resources/autoencoder_0.pt'))
autoencoder_model.eval()
search_index = nmslib.init(method='hnsw', space='cosinesimil')
search_index.loadIndex('../generated_resources/final.nmslib')

def search(query):
    embedding = albert_model.encode(query)
    with torch.no_grad():
        output = autoencoder_model(torch.tensor(embedding).to('cuda'))
    # Search five nearest neighbours, their index value and cosine distances are returned
    idxs, dists = search_index.knnQuery(output.cpu(), k=5)

    # Function details for the index value returned are extracted and printed
    all_funcs = []
    list_of_dist = []
    list_of_git = []
    for idx, dist in zip(idxs, dists):
        code = valid_dataframe['code'][idx]
        list_of_git.append(valid_dataframe['url'][idx])
        list_of_dist.append(dist)
        code = re.sub(r'"""(.*)?"""\s\n', r' ', code, flags=re.DOTALL)
        all_funcs.append(code)
    return all_funcs, list_of_dist, list_of_git

@app.route('/')
def main_page():
    return render_template("main_page.html")

@app.route('/results', methods=['GET'])
def results_page():
    query = request.args.get('query')
    funcs, dists, gits = search(query)
    print(funcs)
    values = len(funcs)
    return render_template("result_page.html", data=query, result=values, codes=funcs, dist=dists, git=gits)

if __name__ == "__main__":
    app.run()


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

dataset = pd.read_csv("C:/Users/user/Downloads/P14-Apriori-Python/Apriori_Python/Market_Basket_Optimisation.csv" , header= None)
transactions = []
for i in range(0, 7501):
    transactions.append([str(dataset.values[i,j]) for j in range(0, 20)])

# Training Apriori on the dataset
from apyori import apriori
rules = apriori(transactions, min_support = 0.003, min_confidence = 0.2, min_lift = 3, min_length = 2)

# Visualising the results
results = list(rules)

soll=[]
for k in results:
    soll.append(list(k[0]))
ask=input("Product name")

for n in soll:
    if ask in n:
        #print("hi")
        n.remove(ask)
        for o in n:
            print(o)
        break
    else:
        #print("no")
        continue


#!/usr/bin/env python
import os
from setuptools import setup, find_packages
import torch
from torch.utils.cpp_extension import (BuildExtension, CppExtension,
                                       CUDAExtension)

def make_cuda_ext(name, module, sources, sources_cuda):

    define_macros = list()
    extra_compile_args = {'cxx': []}

    if torch.cuda.is_available() or os.getenv('FORCE_CUDA', '0') == '1':
        define_macros += [('WITH_CUDA', None)]
        extension = CUDAExtension
        extra_compile_args['nvcc'] = [
            '-D__CUDA_NO_HALF_OPERATORS__',
            '-D__CUDA_NO_HALF_CONVERSIONS__',
            '-D__CUDA_NO_HALF2_OPERATORS__',
        ]
        sources += sources_cuda
    else:
        print(f'Compiling {name} without CUDA')
        extension = CppExtension
        # raise EnvironmentError('CUDA is required to compile MMDetection!')

    return extension(
        name=f'{module}.{name}',
        sources=[os.path.join(*module.split('.'), p) for p in sources],
        define_macros=define_macros,
        extra_compile_args=extra_compile_args)

if __name__ == '__main__':
    setup(
        name='cvtools',
        packages=find_packages(),
        # package_data={'cvtools.ops': ['*/*.so']},
        ext_modules=[
            make_cuda_ext(
                name='compiling_info',
                module='cvtools.ops.utils',
                sources=['src/compiling_info.cpp'],
                sources_cuda=[]),
            make_cuda_ext(
                name='nms_ext',
                module='cvtools.ops.nms',
                sources=['src/nms_ext.cpp', 'src/cpu/nms_cpu.cpp'],
                sources_cuda=[
                    'src/cuda/nms_cuda.cpp', 'src/cuda/nms_kernel.cu'
                ]),
            make_cuda_ext(
                name='roi_align_ext',
                module='cvtools.ops.roi_align',
                sources=[
                    'src/roi_align_ext.cpp',
                    'src/cpu/roi_align_v2.cpp',
                ],
                sources_cuda=[
                    'src/cuda/roi_align_kernel.cu',
                    'src/cuda/roi_align_kernel_v2.cu'
                ]),
            make_cuda_ext(
                name='roi_pool_ext',
                module='cvtools.ops.roi_pool',
                sources=['src/roi_pool_ext.cpp'],
                sources_cuda=['src/cuda/roi_pool_kernel.cu']),
            make_cuda_ext(
                name='deform_conv_ext',
                module='cvtools.ops.dcn',
                sources=['src/deform_conv_ext.cpp'],
                sources_cuda=[
                    'src/cuda/deform_conv_cuda.cpp',
                    'src/cuda/deform_conv_cuda_kernel.cu'
                ]),
            make_cuda_ext(
                name='deform_pool_ext',
                module='cvtools.ops.dcn',
                sources=['src/deform_pool_ext.cpp'],
                sources_cuda=[
                    'src/cuda/deform_pool_cuda.cpp',
                    'src/cuda/deform_pool_cuda_kernel.cu'
                ]),
            make_cuda_ext(
                name='sigmoid_focal_loss_ext',
                module='cvtools.ops.sigmoid_focal_loss',
                sources=['src/sigmoid_focal_loss_ext.cpp'],
                sources_cuda=['src/cuda/sigmoid_focal_loss_cuda.cu']),
            make_cuda_ext(
                name='masked_conv2d_ext',
                module='cvtools.ops.masked_conv',
                sources=['src/masked_conv2d_ext.cpp'],
                sources_cuda=[
                    'src/cuda/masked_conv2d_cuda.cpp',
                    'src/cuda/masked_conv2d_kernel.cu'
                ]),
            make_cuda_ext(
                name='carafe_ext',
                module='cvtools.ops.carafe',
                sources=['src/carafe_ext.cpp'],
                sources_cuda=[
                    'src/cuda/carafe_cuda.cpp',
                    'src/cuda/carafe_cuda_kernel.cu'
                ]),
            make_cuda_ext(
                name='carafe_naive_ext',
                module='cvtools.ops.carafe',
                sources=['src/carafe_naive_ext.cpp'],
                sources_cuda=[
                    'src/cuda/carafe_naive_cuda.cpp',
                    'src/cuda/carafe_naive_cuda_kernel.cu'
                ]),
            make_cuda_ext(
                name='corner_pool_ext',
                module='cvtools.ops.corner_pool',
                sources=['src/corner_pool.cpp'],
                sources_cuda=[]),
        ],
        cmdclass={'build_ext': BuildExtension},
        zip_safe=False)


import traceback
from os import path
from random import sample, randint
import sys
from winsound import PlaySound, SND_NODEFAULT, SND_FILENAME, SND_NOSTOP

arti = ["mano destra", "mano sinistra", "piede destro", "piede sinistro"]
colori = ["verde", "giallo", "blu", "rosso"]
base = path.join(path.abspath(path.dirname(__file__)), "wavs")

def play(name):
    PlaySound(path.join(base, f"{name}.wav"), SND_FILENAME | SND_NODEFAULT | SND_NOSTOP)

def main():
    print(base)
    print("Premi enter per sentire la mia bella voce.")
    for _ in sys.stdin:
        arto, colore, numero = (sample(arti, 1)[0], sample(colori, 1)[0], randint(1, 6))
        print(f"{arto},\t{colore},\t{numero}", end='', flush=True)
        play(arto)
        play(colore)
        play(numero)

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        pass
    except Exception:
        print()
        print("senti, l'ho fatto di fretta")
        traceback.print_exc()
        input()


import sys
from collections import deque

input = sys.stdin.readline

test = int(input())

for _ in range(test):
    stock = int(input())
    q = deque()
    ans = 0
    arr = list(map(int, input().split()))
    arr.reverse()
    max_value = arr[0]
    for i in range(1, stock):
        if arr[i] >= max_value:
            max_value = arr[i]
        else:
            ans += max_value - arr[i]
    print(ans)

    # 이 코드는 87프로에서 시간초과 뜬다.
    # 주식이 다음날 주식이 오르면 사고, 내리면 판다.
    # for i in arr:
    #     q.append(i)
    #     if i >= max_value:
    #         max_value = i
    # while q:
    #     day_stock = q[0]
    #     q.popleft()
    #     if day_stock == max_value:
    #         if q:
    #             max_value = max(q)
    #     else:
    #         ans += max_value - day_stock
    # print(ans)
    #
    #
# 1 2 1 5 2 3


file = open("frequenze.txt")
"""
frequenza = 0
for riga in file:
    n = int(riga)
    frequenza += n
print(frequenza)
"""
freq = [0]
frequenza = 0
for riga in file:
    n = int(riga)
    if n >= 0:
        for f in range(frequenza + 1, frequenza + n + 1):
            freq.append(f)
    else:
        for f in range(frequenza - 1, frequenza + n - 1, -1):
            freq.append(f)

for c in freq:
    if freq.count(c) > 1:
        print(c)
        break


# https://leetcode.com/problems/partition-labels/
class PartitionLabels:
    def Solution(self, s: str) -> List[int]:
        result = []
        map = {}

        for i in range(len(s)):
            map[s[i]] = i

        right = 0
        length = 0

        for left in range(len(s)):
            length += 1

            if map[s[left]] > right:
                right = map[s[left]]

            if left == right:
                result.append(length)
                length = 0

        return result

PartitionLabels().Solution("ababcbacadefegdehijhklij")


import random

def display_board(board):
    print(board[7] + " | " + board[8] + " | " + board[9])
    print("---------")
    print(board[4] + " | " + board[5] + " | " + board[6])
    print("---------")
    print(board[1] + " | " + board[2] + " | " + board[3])

def player_input():
    marker = ""
    while not (marker == "X" or marker == "O"):
        marker = input("Pradėkite pasirinkdami 'X' ar 'O': ").upper()

    if marker == "X":
        return 'X', 'O'
    else:
        return 'O', 'X'

def place_marker(board, marker, position):
    board[position] = marker

def win_check(board, mark):
    return ((board[7] == board[8] == board[9] == mark) or
            (board[4] == board[5] == board[6] == mark) or
            (board[1] == board[2] == board[3] == mark) or

            (board[1] == board[4] == board[7] == mark) or
            (board[2] == board[5] == board[8] == mark) or
            (board[3] == board[6] == board[9] == mark) or

            (board[1] == board[5] == board[9] == mark) or
            (board[3] == board[5] == board[7] == mark))

def choose_first():
    if random.randint(0, 1) == 0:
        return "Žaidėjas 2"
    else:
        return "Žaidėjas 1"

def space_check(board, position):
    return board[position] == " "

def full_board_check(board):
    for i in range(1, 10):
        if space_check(board, i):
            return False
    return True

def player_choice(board):
    position = 0
    while position not in [1, 2, 3, 4, 5, 6, 7, 8, 9] or not space_check(board, position):
        position = int(input("Pasirinkite langelį nuo 1 iki 9: "))
    return position

def replay():
    choice = input("Dar kartą?: Taip arba Ne: ")
    return choice == 'Taip'

def main():
    print("Pažaiskime 'Kryžiukus - nuliukus!'")

    while True:

        the_board = [" "] * 10
        player1_marker, player2_marker = player_input()

        turn = choose_first()
        print(turn + " pradės pirmas")

        game_on = True
        while game_on:
            if turn == "Žaidėjas 1":
                print(turn + " jūsų eilė")

                display_board(the_board)
                position = player_choice(the_board)
                place_marker(the_board, player1_marker, position)

                if win_check(the_board, player1_marker):
                    display_board(the_board)
                    print("Laimėjo Žaidėjas1!")
                    game_on = False

                else:
                    if full_board_check(the_board):
                        display_board(the_board)
                        print("Lygiosios")
                        break

                    else:
                        turn = "Žaidėjas 2"

            else:

                print(turn + " jūsų eilė")
                display_board(the_board)
                position = player_choice(the_board)
                place_marker(the_board, player2_marker, position)

                if win_check(the_board, player2_marker):
                    display_board(the_board)
                    print("Laimėjo Žaidėjas2!")
                    game_on = False
                else:
                    if full_board_check(the_board):
                        display_board(the_board)
                        print("Lygiosios!")
                        break
                    else:
                        turn = "Žaidėjas 1"

        if not replay():
            print("Geros kloties!!!!")
            break

main()


import PCF8591 as ADC
import time

js_msg = ['home','up','down','left','right','pressed']  # 状态

def detect_js():
    state=0
    if ADC.read(0) <= 30 and 30<ADC.read(1)<225:  state = 1	# up方向
    if ADC.read(0) >= 225 and 30<ADC.read(1)<225: state = 2	# down方向
    if ADC.read(1) <= 30 and 30<ADC.read(0)<225:  state = 4	# right方向
    if ADC.read(1) >= 205 and 30<ADC.read(0)<225: state = 3	# left方向
    if ADC.read(2) == 0:   state = 5	# Button按下
    if ADC.read(0)<140 and ADC.read(0)>110 and ADC.read(1) <140\
	   and ADC.read(1)>110 and ADC.read(2) <1: state = 0	#复位
    return state   # 返回状态

def loop():
    state=last_state=0
    while True:
        state = detect_js()   	 # 调用状态监测函数
        if state != last_state:  # 判断状态是否发生改变
            print(js_msg[state]) # 打印
            print(ADC.read(0))
            last_state = state   # 保存以防止同一状态多次打印
        time.sleep(0.01)		 # sleep函数可以带小数参数

def destroy(): # 异常处理函数
    pass

if __name__ == '__main__':
	ADC.setup(0x48)  # 设置PCF8591模块地址
	try:
		loop() # 调用循环函数
	except KeyboardInterrupt:  	# 当按下Ctrl+C时
		destroy()   # 调用析构函数


# JTMS-14
# a3 p5.py
# Abdullah Rafique
# arafique@jacobs-university.de

# character to be assigned
char = input("character: ")

# if else statement condition is set
if char >= 'A' and char <= 'Z':
    print("Character is Captial letter")
# if not captial this will be print
else:
    print("Character is Smol letter")


class Ics:
    year=2022
    company=""

    def __init__(self,name,age,place):
        self.name=name
        self.age=age
        self.place=place
    date="19/2/2022"
    def add_age(self):
        self.age=self.age+1
    def add_place(self,place):
        self.place=place
    def display(self):
        print("name:",self.name)
        print("age:",self.age)
        print("place:",self.place)
        print("year is:",Ics.year)
        print("date is:",Ics.date)
        print("company is:",Ics.company)

    @classmethod
    def add_year(cls):
        cls.year=cls.year+1
    @classmethod
    def add_company(cls,company):
        cls.company=company

x=Ics("Anu",20,"MKD")
y=Ics("Raju",34,"PKD")
x.add_age()
x.add_place("PRNMA")
Ics.add_year()
company=input("enter a company")
Ics.add_company(company)
x.display()


#!/usr/bin/env python
# coding: utf-8

# In[109]:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import random
import os
from scipy import stats
import pickle
import xml.etree.ElementTree as ET
import json

# # Update these 2 variables

# In[93]:

# ID of mouse (example: G25)
mouse_id = "test_000"

# cellfinder_output_path = 'path/to/root/directory/of/cellfinder/output/data/'
cellfinder_output_path = "/Users/grant/Desktop/mock_df/cellfinder_output/"

# ### Create new folder in your cellfinder output folder
#

# In[105]:

# Create new folder in your cellfinder output folder
new_folder_path = cellfinder_output_path + str(mouse_id) + "_Completed_Analysis" # create the path for the new folder

if not os.path.exists(new_folder_path):
    os.makedirs(new_folder_path)
    print('folder has been created.')
    print(f'{new_folder_path}')
else:
    print('path already exists, skipping...')
    print(f'{new_folder_path}')

# ### Read in tdTomato & GFP output data from cellfinder

# In[106]:

# import cellfinder summary csv, containing cell counts and more
gfp_df = pd.read_csv(cellfinder_output_path + 'analysis/' + 'gfp_summary.csv')
tdTomato_df = pd.read_csv(cellfinder_output_path + 'analysis/' + 'tdTomato_summary.csv')

# output path for created csv
output_path_csv = new_folder_path + '/' + mouse_id + '_labled_cells.csv'

gfp_df

# # GFP Data

# In[108]:

# make list of each brain region with labeled cells
all_gfp_brain_regions = gfp_df['structure_name'].to_list()
print("All Brain Regions: " + str(len(all_gfp_brain_regions)))

# make a list of total cell count for each brain region labeled with GFP
all_gfp_brain_regions_cell_count = gfp_df['total_cells'].to_list()
print("total cells: " + str(sum(all_gfp_brain_regions_cell_count)))

# make dict of brain_regions & cell_count
all_gfp_dictionary = dict(zip(all_gfp_brain_regions, all_gfp_brain_regions_cell_count))
all_gfp_df = pd.DataFrame.from_dict(all_gfp_dictionary,orient='index')

# In[97]:

# Find all brain regions with labeled gfp cells, make gfp_df
gfp_cells_df = gfp_df[gfp_df['total_cells'] >= 1]

# make list of each brain region with labeled cells
gfp_brain_regions = gfp_cells_df['structure_name'].to_list()
gfp_brain_regions_sum = len(gfp_brain_regions)
print("GFP Brain Regions With labeled Cells: " + str(gfp_brain_regions_sum))

# make a list of total cell count for each brain region labeled with GFP
gfp_brain_regions_cell_count = gfp_cells_df['total_cells'].to_list()
gfp_labled_cells_sum = sum(gfp_brain_regions_cell_count)
print("total labeled GFP cells: " + str(gfp_labled_cells_sum ))

# make dict of brain_regions & cell_count
gfp_dictionary = dict(zip(gfp_brain_regions, gfp_brain_regions_cell_count))
gfp_df_01 = pd.DataFrame.from_dict(gfp_dictionary,orient='index')

# In[120]:

# File path to the desktop
file_path =  new_folder_path + '/gfp_brainregions_list.json'
print(file_path)

# Open a file
with open(file_path, 'w') as f:
    # Save the list to the file
    json.dump(gfp_brain_regions, f)

# In[121]:

# File path to the desktop
count_file_path =  new_folder_path + '/gfp_brainregions_count.json'
print(count_file_path)

# Open a file
with open(count_file_path, 'w') as f:
    # Save the list to the file
    json.dump(gfp_brain_regions_cell_count, f)

# # tdTomato Data

# In[98]:

# make list of each brain region with labeled cells
all_tdTomato_brain_regions = tdTomato_df['structure_name'].to_list()
print("All Brain Regions: " + str(len(all_tdTomato_brain_regions)))

# make a list of total cell count for each brain region labeled with GFP
all_tdTomato_brain_regions_cell_count = tdTomato_df['total_cells'].to_list()
print("total cells: " + str(sum(all_tdTomato_brain_regions_cell_count)))

# make dict of brain_regions & cell_count
all_tdTomato_dictionary = dict(zip(all_tdTomato_brain_regions, all_tdTomato_brain_regions_cell_count))
all_tdTomato_df = pd.DataFrame.from_dict(all_tdTomato_dictionary,orient='index')

# In[99]:

# create a dictonary of only the
# Find all brain regions with labeled gfp cells, make gfp_df
tdTomato_cells_df = tdTomato_df[tdTomato_df['total_cells'] >= 1]

# make list of each brain region with labeled cells
tdTomato_brain_regions = tdTomato_cells_df['structure_name'].to_list()
tdTomato_brain_regions_sum = len(tdTomato_brain_regions)
print("tdTomato Brain Regions With labeled Cells: " + str(tdTomato_brain_regions_sum))

# make a list of total cell count for each brain region labeled with GFP
tdTomato_brain_regions_cell_count = tdTomato_cells_df['total_cells'].to_list()
tdTomato_labled_cells_sum = sum(tdTomato_brain_regions_cell_count)
print("total labeled tdTomato cells: " + str(tdTomato_labled_cells_sum))

# make dict of brain_regions & cell_count
tdTomato_dictionary = dict(zip(tdTomato_brain_regions, tdTomato_brain_regions_cell_count))
tdTomato_df_01 = pd.DataFrame.from_dict(tdTomato_dictionary,orient='index')

# ## Create csv file with summary of gfp and tdTomato Cellcount and Brain Regions

# In[100]:

data = {'total whole-brain cell count': [gfp_labled_cells_sum, tdTomato_labled_cells_sum],
        'total brain regions': [gfp_brain_regions_sum,tdTomato_brain_regions_sum],
        'brain regions list': [gfp_brain_regions,all_tdTomato_brain_regions]}

summary_df = pd.DataFrame(data)
summary_df.rename(index={0: 'GFP'}, inplace=True)
summary_df.rename(index={1: 'tdTomato'}, inplace=True)

# Save out summary df
summary_df.to_csv(new_folder_path + '/' + mouse_id + '_summary_df.csv')

summary_df

# In[101]:

# making a df with percent of gfp cells labled compared to tdTomato
percent_labled = []
i = 0
for count in all_tdTomato_brain_regions_cell_count:
    percent_labled.append(all_gfp_brain_regions_cell_count[i] / count *100)
    i += 1

# ## df for percentage of labled gfp cells vs tdTomato cells

# In[102]:

# create df with gfp and tdTomato cell counts, and percent labled
all_gfp_df['tdTomato cell count'] = all_tdTomato_brain_regions_cell_count
all_gfp_df['percent labled gfp/tdTomato'] = percent_labled

# Add the header 'New Column Name' to column at index 0
all_gfp_df.rename(columns={gfp_df_01.columns[0]: 'gfp cell count'}, inplace=True)

# In[103]:

# Find all brain regions with labeled gfp cells, make gfp_df
labled_cells_df = all_gfp_df[all_gfp_df['gfp cell count'] >= 1]
labled_cells_df

labled_cells_df.to_csv(output_path_csv)

# In[117]:

labled_cells_df[0:20]

# # There are several ways to statistically compare the values at each index location of two lists in Python. Here are a few options:
#
# ### 1. Using the scipy library's stats.ttest_ind() function, you can perform a t-test to compare the means of the two lists at each index location. For example:

# In[614]:

t, p = stats.ttest_ind(gfp_brain_regions_cell_count, mock_tdTomato_cellcount)
print("t-statistic: ", t)
print("p-value: ", p)

# ### 2. Using the numpy library's corrcoef() function, you can calculate the correlation coefficient between the two lists at each index location. For example:

# In[615]:

corr = np.corrcoef(gfp_brain_regions_cell_count, mock_tdTomato_cellcount)[0, 1]
print("correlation coefficient: ", corr)

# ### 3.  Using the pandas library, you can create a dataframe from the two lists and use the corr() function to calculate the correlation between the two lists:

# In[616]:

df = pd.DataFrame({'list1': gfp_brain_regions_cell_count, 'list2': mock_tdTomato_cellcount})
corr = df['list1'].corr(df['list2'])
print("correlation coefficient: ", corr)

# # load voxel locations of cells

# In[81]:

data = np.load("/Users/grant/Desktop/mock_df/points.npy")

# In[84]:

print(len(data))

# # Load cell_classification data

# In[87]:

tree = ET.parse("/Users/grant/Desktop/mock_df/cell_classification.xml")
root = tree.getroot()

# In[91]:

# Iterate over child elements
for child in root:
    print(child.tag, child.attrib)

# # load all point

# In[94]:

all_points = pd.read_csv("/Users/grant/Desktop/mock_df/all_points.csv")

# In[95]:

all_points

# # load volumes

# In[97]:

volumes = pd.read_csv("/Users/grant/Desktop/mock_df/volumes.csv")

# In[98]:

volumes

# In[ ]:


import discord
from discord.ext import commands
import asyncio
import requests, bs4
from itertools import cycle
import os
import time
import youtube_dl
from discord import opus

client = commands.Bot(command_prefix=("x"))
client.remove_command("help")
status = ["xhelp", "testing the bot"]

async def change_status():
	await client.wait_until_ready()
	msgs = cycle(status)

	while not client.is_closed:
		current_status = next(msgs)
		await client.change_presence(game=discord.Game(name=current_status))
		await asyncio.sleep(4)

players = {}

@client.event
async def on_ready():
	print('Logged in as')
	print("User name:", client.user.name)
	print("User id:", client.user.id)
	print('---------------')

@client.event
async def on_message(message):
  if message.content == 'xstop':
      serverid = message.server.id
      players[serverid].stop()
      await client.send_message(message.channel, "Player stopped")
  if message.content == 'xpause':
      serverid = message.server.id
      players[serverid].pause()
      await client.send_message(message.channel, "Player paused")
  if message.content == 'xresume':
      serverid = message.server.id
      players[serverid].resume()
      await client.send_message(message.channel, "Player resumed")
  if message.content.startswith('xplay '):
      author = message.author
      name = message.content.replace("xplay ", '')
      fullcontent = ('http://www.youtube.com/results?search_query=' + name)
      text = requests.get(fullcontent).text
      soup = bs4.BeautifulSoup(text, 'html.parser')
      img = soup.find_all('img')
      div = [ d for d in soup.find_all('div') if d.has_attr('class') and 'yt-lockup-dismissable' in d['class']]
      a = [ x for x in div[0].find_all('a') if x.has_attr('title') ]
      title = (a[0]['title'])
      a0 = [ x for x in div[0].find_all('a') if x.has_attr('title') ][0]
      url = ('http://www.youtube.com'+a0['href'])
      delmsg = await client.send_message(message.channel, 'Now Playing ** >> ' + title + '**')
      server = message.server
      voice_client = client.voice_client_in(server)
      player = await voice_client.create_ytdl_player(url)
      players[server.id] = player
      print("User: {} From Server: {} is playing {}".format(author, server, title))
      player.start()
  await client.process_commands(message)

@client.command(pass_context=True, no_pm=True)
async def ping(ctx):
    pingtime = time.time()
    pingms = await client.say("Pinging...")
    ping = (time.time() - pingtime) * 1000
    await client.edit_message(pingms, "Pong! :ping_pong: ping time is `%dms`" % ping)

@client.command(pass_context=True, no_pm=True)
async def join(ctx):
    channel = ctx.message.author.voice.voice_channel
    await client.join_voice_channel(channel)
    await client.say('Connected to voice channel: **[' + str(channel) + ']**')

@client.command(pass_context=True, no_pm=True)
async def leave(ctx):
    server = ctx.message.server
    channel = ctx.message.author.voice.voice_channel
    voice_client = client.voice_client_in(server)
    await voice_client.disconnect()
    await client.say("Successfully disconnected from ***[{}]***".format(channel))

@client.command(pass_context=True, no_pm=True)
async def help(ctx):
	embed = discord.Embed(title="Help Section", description=" ", color=0xFFFF)
	embed.add_field(name="xjoin", value="make the bot join voice channel")
	embed.add_field(name="xleave", value="make the bot leave the voice channel")
	embed.add_field(name="xplay", value="please be careful when using this command it will break if theres music playing.")
	embed.add_field(name="xstop", value="to stop the music from playing")
	embed.add_field(name="xping", value="get bot's ping time")
	await client.say(embed=embed)

client.loop.create_task(change_status())
client.run(os.environ['BOT_TOKEN'])


from math import sqrt

ls = [1,2,3,4,5]
print(ls)
ls.pop()
print(ls)
ls.pop(2)
print(ls)

# x= (-b+-sqrt(b^2-4ac))/2a

# a = 5
# b = 2
# c = -10
a = float(input("Enter a:"))
b = float(input("Enter b"))
c = float(input("Enter c: "))

x1 = (-b+sqrt(b**2-4*a*c))/(2*a)
x2 = (-b-sqrt(b**2-4*a*c))/(2*a)
print(x1,x2)
print("Value error.")

km = 100
m = km*100
print(km,"km is = ",m,"meter")


# Run this script with something like
#    python loop.py N > N.log
# where N is an integer from 1 to the number of models.
#
# ModLoop does this for N from 1 to 300 (it runs the tasks in parallel on a
# compute cluster), then returns the single model with the best (lowest)
# value of the Modeller objective function.

from modeller import *
from modeller.automodel import *
import sys

# to get different starting models for each task
taskid = int(sys.argv[1])
env = environ(rand_seed=-1000-taskid)

class MyLoop(loopmodel):
    def select_loop_atoms(self):
        rngs = (
           self.residue_range('195:A', '214:A'),
        )
        for rng in rngs:
            if len(rng) > 30:
                raise ModellerError("loop too long")
        s = selection(rngs)
        if len(s.only_no_topology()) > 0:
            raise ModellerError("some selected residues have no topology")
        return s

m = MyLoop(env, inimodel='input.pdb',
           sequence='loop')
m.loop.md_level = refine.slow
m.loop.starting_model = m.loop.ending_model = taskid

m.make()


#!/usr/bin/env python
from pymongo import Connection
try:
    import urllib.request as urllib2
except ImportError:
    import urllib2
import json
import collections
import types
import time
import datetime
import sys
from pprint import pprint

# ----------------------
# Functions
# ----------------------
# Read threads
def readThreads(subreddit):
	for t in subreddit:

		# Get the thread info
		threadId = t['data']['id']
		title = t['data']['title']
		text = t['data']['selftext']
		permalink = t['data']['permalink']
		score = t['data']['score']
		created = t['data']['created_utc']

		redditThread = {'text':title, 'desc':text,'permalink':permalink,'created':created}
		# Save it to the database. Duplicate threads will be ignored due to the UNIQUE KEY constraint
		try:
			collection.save(redditThread)
		except Exception as e:
			print ("Thread not saved")
		print("Thread saved")
		jsonData = requestJson(baseUrl + urllib2.quote(permalink.encode('utf8')) + ".json", delay)
		postData = jsonData[0]['data']['children']
		readComments(postData, threadId, permalink)
		data = jsonData[1]['data']['children']
		readComments(postData, threadId, permalink)

# Recursive function to read comments
def readComments(obj, threadId, threadUrl):

	for i in obj:

		# Basic info, present both in Title and Comment
		commentId = i['data']['id']
		content = ""
		url = ""
		score = 0
		created = 0
		if 'created_utc' in i['data']:
			created = i['data']['created_utc']
		else:
			print ("Error")

		# Is it a comment?
		if 'body' in i['data']:

			url = threadUrl + commentId
			content = i['data']['body']
			ups = int(i['data']['ups'])
			downs = int(i['data']['downs'])
			score = ups - downs

		# Or is it the title post?
		elif 'selftext' in i['data']:

			url = i['data']['url']
			content = i['data']['selftext']
			score = i['data']['score']

		redditThread = {'text':content,'desc':"", 'permalink':"",'created':created}
		try:
			collection.save(redditThread)
		except Exception as e:
			print ("Thread not saved")
		print("Thread saved")
		if 'replies' in i['data'] and len(i['data']['replies']) > 0:
			readComments(i['data']['replies']['data']['children'], threadId, threadUrl)

def requestJson(url, delay):
	while True:
		try:
			# Reddit API Rules: "Make no more than thirty requests per minute"
			time.sleep(delay)

			req = urllib2.Request(url, headers=hdr)
			response = urllib2.urlopen(req)
			jsonFile = response.read()
			return json.loads(jsonFile.decode('utf-8'))
		except Exception as e:
			print (e)

# ----------------------
# Script begins here
# ----------------------

# Setup ------------------------------------------

connection = Connection('localhost', 27017)
db = connection.RedditStream
collection = db.reddit
delay = 5
# Url, header and request delay
# If we don't set an unique User Agent, Reddit will limit our requests per hour and eventually block them
userAgent = "Python crypto crawler v1.0 (by /u/ledzepp106)"
if userAgent == "":
	print ("Error: you need to set an User Agent inside this script")
	sys.exit()

hdr = {'User-Agent' : userAgent}
baseUrl = "http://www.reddit.com"

subreddit = "/r/bitcoin"
subredditUrl = baseUrl + subreddit + "/new/.json"

print ("Starting crawler")
print ("Press ctrl+c to stop")

# Start! -----------------------------------------
while True:

	# Log starting time
	startingTime = datetime.datetime.now()
	# Read the Threads
	print ("Requesting new threads...")
	jsonObj = requestJson(subredditUrl, delay)

	# Save the threads
	readThreads(jsonObj['data']['children'])


# Sheila Truong 53588737
# Project 5

class GameState:

    def __init__(self, rows, columns, turn, color, win):

        self._rows = rows
        self._columns = columns
        self._turn = turn
        self._color = color
        self._win = win
        self._board = []

    def _valid_row(self, row):
        '''checks if the row is valid'''
        return 0 < row <= self._rows

    def _valid_col(self, col):
        '''checks if the columns are valid'''
        return 0 < col <= self._columns

    def build_board(self):
        '''builds the board with the given rows and columns'''
        middle_row = int(self._rows / 2) - 1
        middle_col = int(self._columns / 2 ) - 1

        for row in range(self._rows):
            game_board = []
            for numb in range(self._columns):
                game_board.append('.')
            self._board.append(game_board)

        self._board[middle_row][middle_col] = self._color
        self._board[middle_row+1][middle_col+1] = self._color

        if self._color == 'B':
            self._board[middle_row+1][middle_col] = 'W'
            self._board[middle_row][middle_col+1] = 'W'
        else:
            self._board[middle_row+1][middle_col] = 'B'
            self._board[middle_row][middle_col+1] = 'B'

        return self._board

    def pieces_to_flip(self, row, col):
        '''returns a list of the pieces to flip'''
        directions = [(1,0), (1,1), (0,1), (-1,1), (-1,0), (-1,-1), (0,-1), (1,-1)]
        flip = []
        for item in directions:
            new_x = row + item[0]
            new_y = col + item[1]
            if self._valid_row(new_x) and self._valid_col(new_y):
                surroundings = self._board[new_x-1][new_y-1]
                opposite = self._opposite_turn()
                possibly_flip = []
                while surroundings == opposite:
                    possibly_flip.append((new_x, new_y))
                    new_x += item[0]
                    new_y += item[1]
                    possibly_flip.append((new_x, new_y))
                    if self._valid_row(new_x) and self._valid_col(new_y):
                        if self._board[new_x-1][new_y-1] == self._turn:
                            flip.extend(possibly_flip[:-1])

                    else:
                        break
        return flip

    def flipped_pieces(self, row, col):
        '''goes through the list of pieces to flip and flip those pieces'''
        to_flip = self.pieces_to_flip(row, col)
        if len(to_flip) != 0:
            for self.item in to_flip:
                self._board[self.item[0]-1][self.item[1]-1] = self._turn
            return True
        else:
            return False

    def _opposite_turn(self):
        '''returns the opposite turn'''
        if self._turn == 'B':
            return 'W'
        else:
            return 'B'

    def drop(self, move):
        '''checks if the spot the user wants to drop, and if it is valid
        make the drop and do the correct flipping'''

        if self._board[int(move[0])-1][int(move[1])-1] == '.':
            if self.flipped_pieces(int(move[0]), int(move[1])):
                self._board[int(move[0])-1][int(move[1])-1] = self._turn #counting the row and col start with 0

                score = self.score()

                if self.winner():
                    return self.winner()
                else:
                    self._turn = self._opposite_turn()

                    return 'VALID'

    def score(self):
        '''returns the score of the game'''
        B_score = 0
        W_score = 0

        for element in self._board:
            for letter in element:
                if letter == 'B':
                    B_score += 1
                elif letter == 'W':
                    W_score += 1
        return [("B",B_score),("W",W_score)]

    def winner(self):
        '''checks to see who is the winner if the board is filled'''
        score_stuff = self.score()
        winning_Score = int(score_stuff[0][1]),int(score_stuff[1][1])
        empty_space = self.give_empty_spaces()
        if len(empty_space) == 0:
            if max(winning_Score) == min(winning_Score):
                return 'WINNER:', 'NONE'
            elif self._win == '>':
                score_to_return = max(winning_Score)
                if score_to_return == score_stuff[0][1]:
                    return "WINNER:",score_stuff[0][0]
                return "WINNER:",score_stuff[1][0]
            elif self._win == '<':
                score_to_return = min(winning_Score)
                if score_to_return == score_stuff[0][1]:
                    return "WINNER:",score_stuff[0][0]
                return "WINNER:",score_stuff[1][0]

    def give_empty_spaces(self):
        '''gives a list of the empty spaces'''
        empty_space = []
        for row in range(self._rows):
            for col in range(self._columns):
                if self._board[row][col] == '.':
                    empty_space.append((row+1, col+1))
        return empty_space

    def empty_cell_winners(self):
        '''if there is empty space and no valid moves can be made then
        count the pieces and return the winner'''

        score_stuff = self.score() #[("B",B_score),("W",W_score)]
        winning_Score = (int(score_stuff[0][1]),int(score_stuff[1][1]))
        opposite = self._opposite_turn()
        empty_space = self.give_empty_spaces()

        for item in empty_space:
            if len(self.pieces_to_flip(item[0], item[1])) != 0:
                return
        print("No valid moves for turn", self._turn)
        self._turn = self._opposite_turn()
        print("It is ", self._turn, "'s turn.")

        for item in empty_space:
            if len(self.pieces_to_flip(item[0], item[1]))!= 0: #checks oppo empty space valid
                return

        if max(winning_Score) == min(winning_Score):
                return 'WINNER:', "NONE"
        elif self._win == '>':
            score_to_return = max(winning_Score)
            if score_to_return == score_stuff[0][1]:
                return "WINNER:",score_stuff[0][0]
            return "WINNER:",score_stuff[1][0]
        elif self._win == '<':
            score_to_return = min(winning_Score)
            if score_to_return == score_stuff[0][1]:
                return "WINNER:",score_stuff[0][0]
            return "WINNER:",score_stuff[1][0]


# -*- coding: utf-8 -*-
"""
Created on Wed Sep  2 10:27:46 2020

@author: Asus
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
##laoding data
pca_data=pd.read_csv('PCA_practice_dataset.csv')
x=pca_data.to_numpy()
print(x.shape)
scaler = StandardScaler()
x=scaler.fit_transform(x)

##PCA
pca=PCA()

x=pca.fit_transform(x)

cum_var = np.cumsum(pca.explained_variance_ratio_)*100

thresholds = [i for i in range(90,98)]

components = [np.argmax(cum_var>threshold) for threshold in thresholds]

for component,threshold in zip(components,thresholds):
    print("component we got for threshold "+str(threshold)+"% are :",component)

##plot corresponding to principle components vs threshold
plt.ylabel("threshold")
plt.xlabel("principle component")
plt.plot(components,range(90,98),'o-')

##dimensionality reduction
M=x
for component ,threshold in zip(components,thresholds):
    pca=PCA(n_components=component)
    newX=pca.fit_transform(M)
    print("\nthreshold: ",threshold)
    print("shape after dimensionality reduction: ",newX.shape)


# -*- coding: utf-8 -*-
#!/usr/bin/env python
# Author:
#     Mateusz Kruszyński <mateusz.kruszynski@gmail.com>
#

from data_generic_write_proxy import DataGenericWriteProxy
BUF_SIZE = 1024

class DataBufferedWriteProxy(DataGenericWriteProxy):
    def __init__(self, p_file_path, p_unpack_later=False, p_append_ts=False, p_sample_type='FLOAT'):
        """Open p_file_name file in p_dir_path directory."""
        self.buffer = [0.0]*BUF_SIZE
        super(DataBufferedWriteProxy, self).__init__(p_file_path, p_unpack_later, p_append_ts, p_sample_type)

    def data_received(self, p_data):
        """ p_data must be protobuf SampleVector message, but serialized to string.
        Data is stored in temp buffer, once a while the buffer is flushed to a file."""
        ind = self._number_of_samples % BUF_SIZE
        self.buffer[ind] = p_data
        self._number_of_samples = self._number_of_samples + 1
        if (ind + 1) == BUF_SIZE:
                self._write_buffer()

    def _write_buffer(self):
        if self._unpack_later:
            self._write_file(''.join(self.buffer))
        else:
            for d in self.buffer:
                self._write_file(self._vect_to_string(d))

    def finish_saving(self):
        """Close the file, return a tuple -
        file`s name and number of samples."""
        self._write_file(''.join(self.buffer[:(self._number_of_samples % BUF_SIZE)]))
        return super(DataBufferedWriteProxy, self).finish_saving()


# def factor_counter(n):
#     ctr = 0
#     for divisor in range(1, n+1):
#         if n % divisor == 0:
#             ctr += 1

#     return ctr
num = int(input())

def factor_counter(n):
    ctr = 0
    if n < 9:
        for divisor in range(1, n + 1):
            if n % divisor == 0:
                ctr += 1
        return ctr
    else:
        end = int(n ** 0.5) + 1

        for divisor in range(1, end):
            if n % divisor == 0 and (n // divisor) != divisor:
                ctr += 2
            # second condition ensures that divisor is not added twice
            elif n % divisor == 0 and (n // divisor) == divisor:
                ctr += 1
    return ctr

print(factor_counter(num))


#!/usr/bin/env python3

# import core modules
import os
import rospy
import numpy as np
import time

# import functionalities
from attachment_pub import Attachment_Pub
from attachment_sub import Attachment_Sub

SPEED = 0.5
MIN_WALL = 0.5

class MiRoExplore(object):

    def __init__(self, mode = "parent"):

        self.mode = mode

        # initialise node for publishing and odom message
        self.miro_pub = Attachment_Pub()
        self.miro_sub = Attachment_Sub()

        # set robot init
        self.wall_distance = self.miro_sub.range
        self.explore_robot = True
        check_dir = np.random.randint(1, 3)
        if check_dir == 1:
            self.angle_turn = (np.pi/2)/3 * 8
        else:
            self.angle_turn = -(np.pi/2)/3 * 8
        self.rand_turn = 0

        # record start time of MiRo node
        self.start_time = time.time()

    """
        Check whether the robot should turn or go straight
    """
    def check_turn(self):
        time_elasped = int(time.time() - self.start_time)
        # check if robot is in the middle of turning
        if self.explore_robot == False:
            if ((time_elasped % 2) == 0):
                self.explore_robot = True
            print("turning", self.miro_sub.range)
            return True
        else:
            # check if the wall is too near
            if self.miro_sub.range < MIN_WALL:
                self.start_turn = rospy.get_rostime()
                self.explore_robot = False
                print("wall ahead", self.miro_sub.range)
                return True
            else:
                print("going straight")
                return False

    """
        Carry out exploration function
    """
    def explore_action(self):
        time_elasped = time.time() - self.start_time
        if self.check_turn() == False:
            if ((time_elasped % 2) < 0.1):
                max_angle_turn = np.pi/2 # 90 degrees max angle
                self.rand_turn = np.random.randint(-np.ceil(max_angle_turn * 10), np.ceil(max_angle_turn * 10))/10
            self.miro_pub.set_move_cmd(linear=SPEED, angular=self.rand_turn)
        else:
            check_dir = np.random.randint(1, 3)
            if ((time_elasped % 4) == 0):
                if check_dir == 1:
                    self.angle_turn = (np.pi/2)/3 * 8
                else:
                    self.angle_turn = -(np.pi/2)/3 * 8
            self.miro_pub.set_move_cmd(linear=0, angular=self.angle_turn * 2)


n=input().split()
lst=[]
for i in n:
    lst.append(len(i))
sums=sum(lst)
while(sums>0):
    s=0
    while(sums>0):
        s+=sums%10
        sums=int(sums/10)
    if len(str(s))>1:
        n=s
    else:
        break
print(s)

'''n=input()
for i in n.split():
    print(i)'''


## This is the text editor interface.
## Anything you type or change here will be seen by the other person in real time.
"""
put (1, K, "A")
put(2, K, "B")
put(3, K, "C")

get(1, K) = "A"
get(1.5, K) = "A"
get(2, K) = "B"
get(2.5, K) = "B"
get(3.5, K) = "C"
get(0, K) = NULL or NotFoundException

"""
import collections
import math

class TTHash(object):

    def __init__(self):
        self.times = {}

    def put(self, time, key, value):
        self.times[time] = {key: value}

    def get(self, time, key):
        if time  in self.times:
            hashmap = self.times[time]
            return hashmap[key]
        else:
            if int(math.floor(time)) in self.times:
                hashmap = self.times[int(math.floor(time))]
                return hashmap[key]
            else:
                return None

class Node:
    def __init__(self, key, value):
        self.key = key
        self.value = value
        self.next = None
        self.prev = None

def main():
    tth = TTHash()
    tth.put (1, 'K', "A")
    tth.put(3, 'K', "C")

    assert tth.get(1, 'K') == "A"
    assert tth.get(1.5, 'K') == "A"
    assert tth.get(2, 'K') == "A"
    assert tth.get(2.5, 'K') == "A"
    assert tth.get(3.5, 'K') == "C"
    assert tth.get(0, 'K') == None

if __name__ == '__main__':
    main()


class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def bstToDoublyList(self, root):
        if not root:
            return None

        self.prev = None
        head = None

        def inorder(node):
            nonlocal head
            if not node:
                return
            inorder(node.left)
            if self.prev:
                node.left = self.prev
                self.prev.right = node
            else:
                head = node
            self.prev = node
            inorder(node.right)

        inorder(root)
        return head

# 测试用例
# 构建 BST
#              10
#         6          12
#      4     8   11      16
root = TreeNode(10)
root.left = TreeNode(6)
root.right = TreeNode(12)
root.left.left = TreeNode(4)
root.left.right = TreeNode(8)
root.right.left = TreeNode(11)
root.right.right = TreeNode(16)

# 转换为双向链表并打印结果
solution = Solution()
head = solution.bstToDoublyList(root)
current = head
while current:
    print(current.val, end=" <-> " if current.right else "\n")
    current = current.right


from django.test import TestCase
from django.test.utils import override_settings
from datetime import date
from BeautifulSoup import BeautifulSoup

from oil_and_gas.models import FieldProduction
from .models import UkRequest, UkManager
from .tasks import update_uk

class UkRequestTest(TestCase):
    def test_get_production(self):
        """
        Tests that production is correct.
        """
        soup = BeautifulSoup('
'
                             '2009	'
                             ' 	'
                             ' 	'
                             ' 	'
                             ' 	'
                             ' 	'
                             ' 	'
                             ' 	'
                             '10,270	'
                             '798	'
                             '0	'
                             '344	'
                             '30	'
                             '11,442	'
                             '
')
        uk_request = UkRequest()
        productions = uk_request.get_production(soup, "Name")
        expected_production = FieldProduction(
            country="UK",
            name="Name",
            date=date(year=2009, month=9, day=1),
            production_oil=798,
        )
        self.assertEqual(len(productions), 12)
        production = productions[8]
        self.assertEqual(production.country, expected_production.country)
        self.assertEqual(production.date, expected_production.date)
        self.assertEqual(production.name, expected_production.name)
        self.assertEqual(production.production_oil, expected_production.production_oil)
        self.assertEqual(production.production_gas, expected_production.production_gas)
        self.assertEqual(production.production_water, expected_production.production_water)

    def test_get_soup(self):
        """
        Tests that production is correct.
        """
        uk_request = UkRequest()
        soup = uk_request.get_soup(page=0)
        table = soup.find('table', width="861", cellspacing="0")
        trs = table.findAll('tr')
        self.assertEqual(len(trs), 6)

    def test_get_production_page(self):
        """
        Tests that production is correct.
        """
        uk_request = UkRequest()
        productions = uk_request.get_production_page(0)
        self.assertEqual(len(productions), 60)
        production = productions[0]
        expected_production = FieldProduction(
            name="AFFLECK",
            country="UK",
            date=date(year=2009, month=1, day=1),
            production_oil=0,
        )
        self.assertEqual(production.name, expected_production.name)
        self.assertEqual(production.country, expected_production.country)
        self.assertEqual(production.date, expected_production.date)
        self.assertEqual(production.production_oil, expected_production.production_oil)
        self.assertEqual(production.production_gas, expected_production.production_gas)
        self.assertEqual(production.production_water, expected_production.production_water)
        production = productions[-1]
        expected_production = FieldProduction(
            name="AFFLECK",
            country="UK",
            date=date(year=2013, month=12, day=1),
            production_oil=5462,
        )
        self.assertEqual(production.name, expected_production.name)
        self.assertEqual(production.country, expected_production.country)
        self.assertEqual(production.date, expected_production.date)
        self.assertEqual(production.production_oil, expected_production.production_oil)
        self.assertEqual(production.production_gas, expected_production.production_gas)
        self.assertEqual(production.production_water, expected_production.production_water)

class UkManagerTest(TestCase):
    def test_update(self):
        """
        Tests update.
        """
        uk_manager = UkManager()
        self.assertEqual(uk_manager.get_youngest_date(0), date(year=1947, month=11, day=1))
        uk_manager.update(1)
        count = FieldProduction.objects.count()
        self.assertEqual(count, 300)
        self.assertEqual(uk_manager.get_youngest_date("AFFLECK"), date(year=2013, month=12, day=1))

    @override_settings(CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
                       CELERY_ALWAYS_EAGER=True,
                       BROKER_BACKEND='memory',)
    def test_async_update(self):
        result = update_uk.delay(2)
        self.assertEquals(result.get(), 624)
        self.assertTrue(result.successful())