import time
import traceback

import aiohttp
import feedparser
import requests

from app.models.rss_post_model import RSSPostModel
from app.schemas.rss_post_schema import RSSPostCreate
from app.schemas.rss_source_schema import RSSSource

class Parser:
    def __init__(self) -> None:
        pass

    def _strip_feed(self, source: RSSSource, feed) -> list[RSSPostCreate]:
        stripped_feed = []

        for item in feed:
            stripped_feed.append(
                RSSPostCreate(
                    source_id=source.id,
                    title=(item.title if hasattr(item, "title") else None),
                    description=(
                        item.description if hasattr(item, "description") else None
                    ),
                    image_url=(
                        item.enclosures[0].href
                        if item.enclosures[0].href.endswith((".png", ".jpg", ".jpg"))
                        else None
                    )
                    if len(item.enclosures) > 0
                    else None,
                    post_url=(item.link if hasattr(item, "link") else None),
                    categories=(item.category if hasattr(item, "category") else None),
                    publish_date=(
                        int(time.mktime(item.published_parsed))
                        # item.published
                        if hasattr(item, "published_parsed")
                        else None
                    ),
                    blacklisted=False,
                )
            )

        return stripped_feed

    def _checkFeed(self, feed):
        check_results = {
            "total_posts": 0,
            "titles": 0,
            "descriptions": 0,
            "image_urls": 0,
            "post_urls": 0,
            "categories": 0,
            "publish_dates": 0,
        }

        for item in feed:
            check_results["total_posts"] += 1
            if hasattr(item, "title"):
                check_results["titles"] += 1
            if hasattr(item, "description"):
                check_results["descriptions"] += 1
            if hasattr(item, "image_url"):
                check_results["image_urls"] += 1
            if hasattr(item, "post_url"):
                check_results["post_urls"] += 1
            if hasattr(item, "category"):
                check_results["categories"] += 1
            if hasattr(item, "publish_date"):
                check_results["publish_dates"] += 1

        return check_results

    async def parse(self, sources: list[RSSSource]) -> list[RSSPostCreate]:
        posts: RSSPostCreate = []

        for source in sources:
            try:
                async with aiohttp.ClientSession() as session:
                    async with session.get(source.rss_url) as response:
                        print(f"Fetching {source.title} feed...")
                        feed = feedparser.parse(await response.text())
                        stripped_feed = self._strip_feed(source, feed.entries)

                        posts += stripped_feed
            except Exception:
                print(f"An error occured while parsing the next feed: {source.title}")
                print(traceback.format_exc())

        return posts

    def parseSync(self, sources: list[RSSSource]) -> list[RSSPostCreate]:
        posts: RSSPostCreate = []

        for source in sources:
            try:
                print(f"Fetching {source.title} feed...")
                response = requests.get(source.rss_url)
                feed = feedparser.parse(response.text)
                stripped_feed = self._strip_feed(source, feed.entries)

                posts += stripped_feed
            except Exception:
                print(f"An error occured while parsing the next feed: {source.title}")
                print(traceback.format_exc())

        return posts

    async def checkFeed(self, source_url: str):
        try:
            async with aiohttp.ClientSession() as session:
                async with session.get(source_url) as response:
                    feed = feedparser.parse(await response.text())
                    check_results = self._checkFeed(feed.entries)

                return check_results
        except:
            return False


import controller
import time
import datetime

start_time = time.time()

####define com ports for controller and baudrate (keep at 115200)
port = "COM5"
baud_rate = 115200

setup = controller.Setup(port, baud_rate)
setup.connect()

#################### Fluidics parameters ###########################
wait = 10
move = controller.Motor()
power = controller.MainPower()

# Parameters related to peristaltic pumps
p1_new = [
    13.712609063042798,
    0.977763871750637,
    4.104248850640944e-05,
    -4.143399187088928e-08,
]
p1_default = [
    19.801938114061617,
    0.964367848880719,
    1.167139063529185e-05,
    -2.873709837738213e-09,
]
p2_default = [
    11.765533598083050,
    0.994151183002726,
    -2.200584843815698e-05,
    5.268389857671134e-09,
]
p_linear = [0, 1, 0, 0]

########### start of script! #################################################

# Main Power ON
print("\n----MAIN POWER ON----")
power.state("ON")
time.sleep(5)

# Homming
print("\n----NOZZLES HOMING----")
message_home2 = bytes("<homeDisp,0,0>", "UTF-8")
move.send(message_home2)
time.sleep(wait + 10)

print("\n----GANTRY HOMING----")
message_home1 = bytes("<homeGantry,0,0>", "UTF-8")
move.send(message_home1)
time.sleep(wait + 5)

# Move to the dummy cell
print("\n----Moving to cell 4 (dummy)----")
pos = controller.Position_in_cell(4)
pos.run()
time.sleep(wait + 5)

######## Filling a flushing tube ######################################
print("\n----Flushing tube filling ----")
message_f4 = bytes(
    "<PUMP4,1000,25000>", "UTF-8"
)  # change the value if needed (SPEEDS, STEPS)
move.send(message_f4)
time.sleep(60)

######## Filling tube in dispenser 1 and 2 ######################################
print("\n----Disp. nozzle 1 & 2 initialization ----")

dispense_fill_1 = controller.Dispense(
    nozzle=1,
    volume=3300,
    speed=8000,
    wait_time=[70, 3, 0, 3, 0],
    motor_values=[-9000, 20, -2755, 20, 9000],
    p=p_linear,
)
dispense_fill_1.run()

dispense_fill_2 = controller.Dispense(
    nozzle=2,
    volume=3300,
    speed=8000,
    wait_time=[70, 3, 0, 3, 0],
    motor_values=[-9000, 20, -2755, 20, 9000],
    p=p_linear,
)
dispense_fill_2.run()

# Dummy cell suction
suction_only = controller.Rinse_dummy(loop=1, wait_time=[16, 12, 0, 0, 16])
suction_only.run()
time.sleep(5)

### Main Power OFF #################################################################
print("\n----MAIN POWER OFF----")
power.state("OFF")
time.sleep(5)

print("Finished")
setup.disconnect()

print("\n----\033[31m Print the total time duration \033[0m----")
end_time = time.time()
total_time = end_time - start_time
total_time_list = str(datetime.timedelta(seconds=total_time)).split(".")
print(total_time_list[0])  # Hrs:Mins:Secs format


"""
2419. Longest Subarray With Maximum Bitwise AND
You are given an integer array nums of size n.
Consider a non-empty subarray from nums that has the maximum possible bitwise AND.
- In other words, let k be the maximum value of the bitwise AND of any subarray of nums. Then, only subarrays with a bitwise AND equal to k should be considered.

Return the length of the longest such subarray.

The bitwise AND of an array is the bitwise AND of all the numbers in it.
A subarray is a consiguous sequence of elements within an array.

Example1:
Input: nums = [1,2,3,3,2,2]
Output: 2
Explanation:
The maximum possible bitwise AND of a subarray is 3.
The longest subarray with that value is [3,3], so we return 2.

Example2:
Input: nums = [1,2,3,4]
Output: 1
Explanation:
The maximum possible bitwise AND of a subarray is 4.
The longest subarray with that value is [4], so we return 1.

Constraints:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^6
"""

"""
Note:
1. Sliding Window: O(n) time | O(1) space - where n is the length of array nums
"""

from typing import List
import unittest
class Solution:
    def longestSubarray(self, nums: List[int]) -> int:
        maxBitwiseAnd = max(nums)
        prev = -1
        count = maxCount = 0
        for num in nums:
            if num == prev:
                count += 1
            else:
                count = 1
                prev = num
            if num == maxBitwiseAnd:
                maxCount = max(maxCount, count)
        return maxCount

# Unit Tests
funcs = [Solution().longestSubarray]

class TestLongestSubarray(unittest.TestCase):
    def testLongestSubarray1(self):
        for func in funcs:
            nums = [1, 2, 3, 3, 2, 2]
            self.assertEqual(func(nums=nums), 2)

    def testLongestSubarray2(self):
        for func in funcs:
            nums = [1, 2, 3, 4]
            self.assertEqual(func(nums=nums), 1)

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


"""
todas las tablas del 1 al 10
"""

for multiplicando in range (1,11):
    multiplicador=1
    print(f"\n\n\n------------TABLA DEL {multiplicando}------------\n")
    while multiplicador<=10:
        producto=multiplicando*multiplicador
        print(f"{multiplicando} * {multiplicador} = {producto}")
        multiplicador+=1

else:
    print("\nesas son todas las tablas del 1 al 10\n")


import subprocess

import pytest

def git_is_not_installed():
    try:
        subprocess.check_output(['which', 'git'])

        return False

    except Exception:
        return True

pytestmark = pytest.mark.skipif(
    git_is_not_installed(),
    reason='git is not installed',
)

def test_git(flamingo_env, run):
    version = run('git describe --always')[1].strip()

    flamingo_env.settings.PLUGINS = [
        'flamingo.plugins.Git',
    ]

    flamingo_env.settings.GIT_VERSION_CMD = 'git describe --always'

    flamingo_env.write('/content/article.rst', """

    Article
    =======

    {{ GIT_VERSION }}

    """)

    flamingo_env.build()

    assert version in flamingo_env.read('/output/article.html')
    assert flamingo_env.settings.EXTRA_CONTEXT['GIT_VERSION'] == version

def test_invalid_command(flamingo_env, run, caplog):
    import logging

    version = run('git describe --always')[1].strip()

    flamingo_env.settings.PLUGINS = [
        'flamingo.plugins.Git',
    ]

    flamingo_env.settings.GIT_VERSION_CMD = 'echo foo'

    flamingo_env.write('/content/article.rst', """

    Article
    =======

    {{ GIT_VERSION }}

    """)

    flamingo_env.build()

    assert version not in flamingo_env.read('/output/article.html')
    assert 'GIT_VERSION' not in flamingo_env.settings.EXTRA_CONTEXT

    assert (
        'flamingo.plugins.Git',
        logging.ERROR,
        'settings.GIT_VERSION_CMD has to start with "git"',
    ) in caplog.record_tuples

def test_invalid_return_code(flamingo_env, run, caplog):
    version = run('git describe --always')[1].strip()

    flamingo_env.settings.PLUGINS = [
        'flamingo.plugins.Git',
    ]

    flamingo_env.settings.GIT_VERSION_CMD = 'git foo'

    flamingo_env.write('/content/article.rst', """

    Article
    =======

    {{ GIT_VERSION }}

    """)

    flamingo_env.build()

    assert version not in flamingo_env.read('/output/article.html')
    assert 'GIT_VERSION' not in flamingo_env.settings.EXTRA_CONTEXT

    assert any(
        [x[2].startswith('git foo returned 1:') for x in caplog.record_tuples]
    )


#!/usr/bin/env python3

import math
from tkinter import *
from tkinter import ttk
import matplotlib.pyplot as plt
import numpy as np

#Things that happen when you press the button
#Do math, show results, draw figure
def plot_figure(*args):
	#Simulation deltas pulled from nowhere
	#1/100 of a seconds
	delta = 8 #0.08*100

	#Check if cycle time is given. If it is t hen cycle accurate simulation is used.
	try:
		cycle = float(input_cycle.get())
		#Convert to 1/100 second. Round to integer.
		cycle = int( round(cycle,2)*100 )
		cycle_simulate = True
	except ValueError:
		#no cycle time. Cycle on every delta
		cycle_simulate = False
		cycle = delta

	try:
		max_hp = int(input_max_hp.get())
		recharge_time = int(input_recharge_time.get())
		resist = int(input_resist.get())/100
		dps = int(input_dps.get())

		#Do the math and then plot the figure
		eff_dps = dps*(1-resist)
		regen_term = 10*max_hp/recharge_time

		cycle = cycle - cycle%delta
		volley = eff_dps*(cycle/100)

		stop = False
		hp = []
		time_list = []
		current_hp = max_hp
		stability_check_counter = 0
		iteration_count = 0

		while stop == False:
			#1. apply damage
			#2. check if died
			#3. if not dead apply regeneration
			old_hp = current_hp

			current_time = iteration_count * delta/100

			#cycle accurate damage
			if (iteration_count*delta)%cycle == 0:
				current_hp = current_hp - volley

			#Check if died
			if current_hp <= 0:
				#you died
				current_hp = 0
				stop = True
				stable = False
			else:
				current_hp = min(current_hp + (delta/100) * regen_term *( math.sqrt(current_hp / max_hp) - (current_hp / max_hp) ), max_hp)

			old_percentage = round(old_hp/max_hp, 2)
			new_percentage = round(current_hp/max_hp, 2)
			#Save the situation if:
			#hp percentage has changed
			#or if on next cycle is damage (only if user gave cycle)
			if old_percentage != new_percentage or (((iteration_count+1)*delta)%cycle == 0 and cycle_simulate):
				time_list.append(current_time)
				hp.append(current_hp)

				#Check if shields have stabilized. Checked every 80 second (or cycle time + 2).
				#If current shield level less than 2 less than the max shield level in past 80 seconds then assume shields stable
				#In practice stability checker doesn't work if cycle time over 80 seconds.
				if stability_check_counter > max(1000, int(100*cycle/delta)):
					if math.ceil(current_hp) >= math.floor(max(hp[-1000:]))-2:
						stop = True
						stable = True

			#Timeout after 24 hours. Literally impossible to tank for lnger than that.
			if current_time>86400:
				print('Timeup')
				stop = True
				stable = True
			stability_check_counter = stability_check_counter+1
			iteration_count = iteration_count+1

		shield_percentage = 100*np.array(hp)/max_hp

		#Show results
		peak_regen.set( str(round(2.5*max_hp/(recharge_time*(1-resist))))+' EHP/s ('+ str(round(2.5*max_hp/recharge_time)) + ' HP/s)')

		print(len(hp))
		if stable == False:
			minutes = math.floor(time_list[-1]/60)
			seconds = math.floor(time_list[-1]-60*minutes)
			tank_time.set(  str(minutes) +' min ' + str(seconds) + ' s')
			damage_tanked.set( round(time_list[-1]*dps) )
		else:
			tank_time.set('Stable at '+str(round(shield_percentage[-1], 1))+'%')
			damage_tanked.set('Infinite')

		plt.plot(time_list, shield_percentage)
		plt.ylabel('Shield HP (%)')
		plt.xlabel('Time (s)')
		plt.grid(True)
		axes = plt.gca()
		axes.set_ylim([0,100])
		axes.set_xlim([0,max(axes.get_xlim()[1], time_list[-1])])
		plt.show()

	except ValueError:
		print('Something went wrong. Probably invalid input.')
		pass

#Clear all things
def clear_all(*args):
	peak_regen.set( '' )
	tank_time.set( '' )
	damage_tanked.set( '' )
	plt.clf()
	plt.show()

#The input window code:
root = Tk()
root.title("Shield regen calc")

window = ttk.Frame(root, padding="3 3 12 12")
window.grid(column=0, row=0, sticky=(N, W, E, S))

#Inputs
input_max_hp = StringVar()
input_recharge_time = StringVar()
input_resist = StringVar()
input_dps = StringVar()
input_cycle = StringVar()

#Outputs
peak_regen = StringVar()
tank_time = StringVar()
damage_tanked = StringVar()

#Input field labels
ttk.Label(window, text="Shield max HP: ").grid(column=1, row=1, sticky=E)
ttk.Label(window, text="Shield recharge time:").grid(column=1, row=2, sticky=E)
ttk.Label(window, text="Shield resist (%):").grid(column=1, row=3, sticky=E)
ttk.Label(window, text="Incoming DPS:").grid(column=1, row=4, sticky=E)
ttk.Label(window, text="Cycle duration:").grid(column=1, row=5, sticky=E)
ttk.Label(window, text="(optional)").grid(column=3, row=5, sticky=W)

#input fields
max_hp_entry = ttk.Entry(window, width=7, textvariable=input_max_hp)
recharge_time_entry = ttk.Entry(window, width=7, textvariable=input_recharge_time)
resist_entry = ttk.Entry(window, width=7, textvariable=input_resist)
dps_entry = ttk.Entry(window, width=7, textvariable=input_dps)
cycle_entry = ttk.Entry(window, width=7, textvariable=input_cycle)

#Input field positions
max_hp_entry.grid(column=2, row=1, sticky=(W, E))
recharge_time_entry.grid(column=2, row=2, sticky=(W, E))
resist_entry.grid(column=2, row=3, sticky=(W, E))
dps_entry.grid(column=2, row=4, sticky=(W, E))
cycle_entry.grid(column=2, row=5, sticky=(W, E))

#Output field labels
ttk.Label(window, text="Peak regen:").grid(column=1, row=7, sticky=E)
ttk.Label(window, text="Tank time:").grid(column=1, row=8, sticky=E)
ttk.Label(window, text="Damage received:").grid(column=1, row=9, sticky=E)

#Output fields
ttk.Label(window, textvariable=peak_regen).grid(column=2, row=7, sticky=(W, E))
ttk.Label(window, textvariable=tank_time).grid(column=2, row=8, sticky=(W, E))
ttk.Label(window, textvariable=damage_tanked).grid(column=2, row=9, sticky=(W, E))

#Buttons
ttk.Button(window, text="Plot", command=plot_figure).grid(column=2, row=6, sticky=W)
ttk.Button(window, text="Clear", command=clear_all).grid(column=3, row=6, sticky=W)

for child in window.winfo_children(): child.grid_configure(padx=5, pady=5)

max_hp_entry.focus()
root.bind('<Return>', plot_figure)

root.mainloop()


#!/usr/local/bin/python3
import psycopg2
import argparse
import time
import csv
from subprocess import call
from yaml import load, load_all

try:
    from yaml import CLoader as Loader
except ImportError:
    from yaml import Loader

# Returns the timestamp,usercount pair which is closest to the specified timestamp
def find_closest_timestamp( input_dict, seek_timestamp ):
    a = []
    for item in input_dict:
        a.append( item['timestamp'] )
    return input_dict[ min(range(len(a)), key=lambda i: abs(a[i]-seek_timestamp)) ]

# Get the current count of non-deleted users from the database
def getCount( dbFile ):
    usercount = 0
    localposts = 0
    localcomments = 0

    usercountQuery = 'select count(id) from users where email not like \'deleted_%\';'
    # adapted from presenters/node_info_presenter.rb
    localpostQuery = """select count(posts.guid) from posts join people on posts.author_id =
         people.id where posts.type = \'StatusMessage\' AND people.owner_id IS NOT null;"""
    # adapted from presenters/node_info_presenter.rb
    localCommentQuery = """select count(comments.guid) from comments join people on comments.author_id =
         people.id where people.owner_id IS NOT null;"""

    conn = None
    dbData = load(dbFile, Loader=Loader)
    params = {}

    params['host']     = dbData['postgresql']['host']
    params['dbname']   = dbData['production']['database']
    params['user']     = dbData['postgresql']['username']
    params['port']     = dbData['postgresql']['port']
    params['password'] = dbData['postgresql']['password']

    conn = psycopg2.connect(**params)

    # create a cursor
    cur = conn.cursor()

    try:
        # get non-deleted users
        cur.execute(usercountQuery)
        usercount = cur.fetchone()[0]
        # print( "User count: {}".format(usercount) )
        cur.execute(localpostQuery)
        localposts = cur.fetchone()[0]
        # print( "Post count: {}".format(localposts) )
        cur.execute(localCommentQuery)
        localcomments = cur.fetchone()[0]
        cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()
    return(usercount, localposts, localcomments)

if __name__ == '__main__':
        # Handle command line
    parser = argparse.ArgumentParser(
        description="Generate daily diaspora user stats off postgres."
    )
    parser.add_argument('-c', '--csv', type=argparse.FileType('a'),
         default='./diasporastats.csv', required=False,
         help='Name of the CSV file. "./diasporastats.csv" by default')
    parser.add_argument('-d', '--database', type=argparse.FileType('r'),
        default='./secrets/database.yml', required=False,
        help='Database YAML configuration file from diaspora. Default: "./secrets/database.yml"')

    args = parser.parse_args()
    currentCount, numPosts, numComments = getCount( args.database )
    # Get current timestamp
    ts = int(time.time())
    # Append to CSV file
    line = "{},{},{},{}\n".format(str(ts), str(currentCount), str(numPosts), str(numComments))
    args.csv.write(line)

    # rewind to the beginning of the file
    args.csv = open(args.csv.name)
    # Load CSV file
    with args.csv as f:
        usercount_dict = [{k: int(v) for k, v in row.items()}
            for row in csv.DictReader(f, skipinitialspace=True)]

    # Calculate difference in times
    hourly_change_string = ""
    daily_change_string  = ""
    weekly_change_string = ""

    one_hour = 60 * 60
    one_day  = one_hour * 24
    one_week = one_hour * 168

    # Hourly change
    if len(usercount_dict) > 2:
        one_hour_ago_ts = ts - one_hour
        one_hour_ago_val = find_closest_timestamp( usercount_dict, one_hour_ago_ts )
        hourly_change = currentCount - one_hour_ago_val['usercount']
        print ("Hourly change %s"%hourly_change)
        if hourly_change > 0:
            hourly_change_string = "+" + format(hourly_change, ",d") + " in the last hour\n"

    # Daily change
    if len(usercount_dict) > 24:
        one_day_ago_ts = ts - one_day
        one_day_ago_val = find_closest_timestamp( usercount_dict, one_day_ago_ts )
        daily_change = currentCount - one_day_ago_val['usercount']
        print ("Daily change %s"%daily_change)
        if daily_change > 0:
            daily_change_string = "+" + format(daily_change, ",d") + " in the last day\n"

    # Weekly change
    if len(usercount_dict) > 168:
        one_week_ago_ts = ts - one_week
        one_week_ago_val = find_closest_timestamp( usercount_dict, one_week_ago_ts )
        weekly_change = currentCount - one_week_ago_val['usercount']
        print ("Weekly change %s"%weekly_change)
        if weekly_change > 0:
            weekly_change_string = "+" + format(weekly_change, ",d") + " in the last week\n"

    # Generate chart
    call(["gnuplot", "generate.gnuplot"])


import pandas as pd

def data_merge(p=True):
    account = pd.read_csv("ficheiros_competicao_dev/account.csv")
    cards = pd.read_csv("ficheiros_competicao_dev/card_dev.csv")
    clients = pd.read_csv("ficheiros_competicao_dev/client.csv")
    disps = pd.read_csv("ficheiros_competicao_dev/disp.csv")
    districts = pd.read_csv("ficheiros_competicao_dev/district.csv")
    loans = pd.read_csv("ficheiros_competicao_dev/loan_dev.csv")
    trans = pd.read_csv("ficheiros_competicao_dev/trans_dev.csv")

    dataset = account.rename({'frequency' : 'frequency_account', 'date' : 'date_of_creation'}, axis=1)

    dataset = dataset.merge(loans, how='outer')
    dataset.drop('loan_id', inplace=True, axis=1)
    dataset = dataset.rename({'date' : 'date_of_loan', 'duration' : 'duration_loan', 'payments' : 'payments_loan', 'status' : 'status_loan'}, axis=1)

    dataset = dataset.merge(pd.DataFrame(trans.groupby('account_id').size(), columns=['n.of trans']), left_on='account_id', right_index=True, how="outer")
    dataset = dataset.merge(pd.DataFrame(trans[trans['operation']=='credit in cash'].groupby('account_id').size(), columns=['op credit cash']), right_index=True, left_on='account_id', how="outer")
    dataset = dataset.merge(pd.DataFrame(trans[trans['operation']=='credit card withdrawal'].groupby('account_id').size(), columns=['op cc withdrawal']), right_index=True, left_on='account_id', how="outer")
    dataset = dataset.merge(pd.DataFrame(trans[trans['operation']=='withdrawal in cash'].groupby('account_id').size(), columns=['op withdrawal cash']), right_index=True, left_on='account_id', how="outer")
    dataset = dataset.merge(pd.DataFrame(trans[trans['operation']=='collection from another bank'].groupby('account_id').size(), columns=['op collection bank']), right_index=True, left_on='account_id', how="outer")
    dataset = dataset.merge(pd.DataFrame(trans[trans['operation']=='remittance to another bank'].groupby('account_id').size(), columns=['op remittance bank']), right_index=True, left_on='account_id', how="outer")
    # dataset = dataset.rename({'amount_x' : 'amount_loan', 'amount_y' : 'amount_trans', 'date' : 'date_trans', 'account' : 'account partner'}, axis=1)
    dataset = dataset.merge(pd.DataFrame(trans.groupby('account_id').amount.mean()).rename(columns={'amount':'avg trans amount'}), right_index=True, left_on='account_id', how="outer")
    dataset = dataset.merge(pd.DataFrame(trans.groupby('account_id').balance.mean()).rename(columns={'balance':'avg trans balance'}), right_index=True, left_on='account_id', how="outer")

    dataset = dataset.merge(disps,  how='outer')
    dataset = dataset.rename({'type' : 'disp_type'}, axis=1)

    dataset = dataset.merge(cards, how='outer')
    dataset = dataset.rename({'type' : 'card_type'}, axis=1)
    dataset.drop('disp_id', inplace=True, axis=1)

    dataset = dataset.merge(clients, left_on="client_id", right_on="client_id", how='outer')
    dataset = dataset.rename({'district_id_x' : 'district_id_account', 'district_id_y' : 'district_id_client'}, axis=1)
    dataset = dataset.merge(districts, left_on = "district_id_client", right_on="district_id", how='outer' )
    dataset.drop("district_id", inplace=True, axis=1)

    if(p):
        print(dataset.columns.tolist())
        print(len(dataset))
        print(dataset.head())

    data_trans(districts,'no. of commited crimes \'95', 'int64')

    #aggregate loans by dispositions(client + account\)
    #aggregate dispositions by clients

    # print(df.groups)
    # print(df.first())

    return dataset

def nulls(dataset, jcolumns):
    for col in jcolumns:
        if(col in dataset.columns.tolist()):
            for row in range(0,len(dataset)):
                if dataset.iloc[row][col] is None:
                    dataset.drop(row, axis=0, inplace=True)
        else:
            print('Error: column ' + col + ' does not exist in dataset')
    dataset.fillna(0)
    return dataset

def outliers(dataset):
    print()

def data_trans(dataset, attribute, type):
    dataset[attribute] = pd.to_numeric(dataset[attribute], errors='coerce').fillna(0).astype(type)

def add_features(dataset):
    print()

def ds_clean(dataset):
    dataset = nulls(dataset, ['account_id','client_id', 'card_id', 'name '])
    return dataset


from math import *
from collections import *
from sys import *
from os import *

class LinkedListNode:
    def __init__(self,data):
        self.data = data
        self.next = None
        self.random = None

def cloneRandomList(head):
    if not head:
        return None
    new = head

    d = defaultdict(LinkedListNode)

    while new:
        d[new] = LinkedListNode(new.data)
        new = new.next

    k = d[head]
    new1 = head
    ans = d[head]

    while new1:
        if new1.next:
            k.next = d[new1.next]
        else:
            k.next = None

        if new1.random:
            k.random = d[new1.random]
        else:
            k.random = None

        k = k.next
        new1 = new1.next
    return ans


from collections import deque
from bisect import bisect_left

x = int(input())

num = set(range(1, 100))
d = deque()
for i in range(10, 100):
    d.append(i)

while d:
    y = d.popleft()

    if y <= 10**18:
        diff = y//10%10 - y%10
        if 0 <= y%10 + diff <= 9:
            ny = y*10 + (y%10 + diff)
            if diff == ny//10%10 - ny%10:
                if ny not in num:
                    d.append(ny)
                    num.add(ny)
        if 0 <= y%10 - diff <= 9:
            ny = y*10 + (y%10 - diff)
            if diff == ny//10%10 - ny%10:
                if ny not in num:
                    d.append(ny)
                    num.add(ny)
num = sorted(num)
b = bisect_left(num, x)
print(num[b])


#salario.py
# 8. Faça um Programa que pergunte quanto você ganha por hora e o número
#de horas trabalhadas no mês. Calcule e mostre o total do seu salário no
#referido mês.

gph = input(
    'Digite quando você ganha por hora: '
)

htm = input(
    'Digite o número de horas trabalhadas no mês: '
)

salario = float(gph) * float(htm)

print(
    'No referido mês você ganhou: ',
    round(salario, 2),
    'reais'
)


from pyDolarVenezuela import network
from bs4 import BeautifulSoup

def _get_price_and_symbol_in_simple(strong_tag: BeautifulSoup):
    price = str(strong_tag.find_next('strong').text).split('Bs.')[-1][:-1].strip()
    symbol = str(strong_tag.find_next('strong').text).split('Bs.')[-1][-1]

    return price, symbol

def _get_values_monitors(url: str):
    response = network.get(url)
    soup = BeautifulSoup(response, "html.parser")

    section_information_dollar = soup.find('div', 'td-post-content')
    monitors_simple = section_information_dollar.find('p', style='font-size:16px')
    image_monitors = section_information_dollar.find_all('div', 'wp-block-image')

    information  = _extract_simple_data(monitors_simple)
    image = _extract_image_data(image_monitors)
    result = {}

    for key, value in information.items():
        result[key] = value
        if key in image:
            result[key]['image'] = image[key]

    return result

def _extract_simple_data(monitors_simple):
    result = {}
    for strong_tag in monitors_simple.find_all('strong'):
        title_map = {
            'Dólar Oficial BCV': 'BCV',
            'Monitor': 'EnParaleloVzla',
            'Dolartoday': 'DolarToday'
        }
        for key, value in title_map.items():
            if key in strong_tag.text:
                price, symbol = _get_price_and_symbol_in_simple(strong_tag)
                result[value.lower()] = {'title': value, 'price': price.replace(',', '.'), 'symbol': symbol}
    return result

def _extract_image_data(image_monitors):
    result = {}
    for image in image_monitors:
        title_map = {
            'Tasa': 'bcv',
            'Monitor': 'enparalelovzla',
            'Dolartoday': 'dolartoday'
        }
        alt_text = str(image.find('img')['alt']).split(' ')[0]
        for key, value in title_map.items():
            if key in alt_text:
                if value not in result:
                    result[value] = [image.find('img')['src']]
                else:
                    result[value].append(image.find('img')['src'])
    return result

class iVenezuela:
    def __init__(self, url: str) -> None:
        response  = network.get(url + 'precio-dolar-venezuela-dolartoday-monitor-oficial-bcv-hoy-tipo-de-cambio/')
        self.soup = BeautifulSoup(response, "html.parser")

    def _load(self):
        section_information_dollar = self.soup.find('div', 'td-post-content')

        for page in section_information_dollar.find_all('p', 'has-text-align-center'):
            if page.find('a'):
                self.data = _get_values_monitors(page.find('strong').find('a')['href'])
                self.data['date'] = ' '.join(page.find('a').text.split('hoy  ')[1::])

    def get_values(self, monitor_code: str = None, name_property: str = None, prettify: bool = False):
        self._load()

        if not monitor_code:
            return self.data

        try:
            monitor_data = self.data[monitor_code.lower()]
            if name_property:
                value = monitor_data[name_property]
                return f'Bs. {value}' if prettify and name_property == 'price' else value
            return monitor_data
        except KeyError:
            raise KeyError("Does not match any of the properties that were provided in the dictionary. Most information: https://github.com/fcoagz/pyDolarVenezuela")


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

"""
You are given two non-empty linked lists representing two non-negative integers.
The digits are stored in reverse order and each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
"""

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        # l1_val = l1.val
        # p = l2.val
        res_l = []
        carry = 0
        p = l1
        q = l2
        while p is not None or q is not None or carry != 0:
            p_val = p.val if p is not None else 0
            q_val = q.val if q is not None else 0
            tmp = p_val + q_val + carry

            if tmp >= 10:
                res_l.append(tmp - 10)
                carry = 1
            else:
                res_l.append(tmp)
                carry = 0

            if p is None and q is None:
                break

            p = p.next if p else None
            q = q.next if q else None

        res = self.convert_to_list_node(res_l)
        return res

    @staticmethod
    def convert_to_list_node(l):
        if len(l) == 1:
            return ListNode(l[0])
        res = None
        pointer = None
        for i in range(len(l) - 1):
            new_node = ListNode(l[i + 1])
            if res is None:
                res = ListNode(l[i])
                pointer = res

                pointer.next = new_node
                pointer = pointer.next
            else:
                pointer.next = new_node
                pointer = pointer.next
        return res

if __name__ == "__main__":
    l_a = ListNode(2)
    l_a.next = ListNode(4)
    l_a.next.next = ListNode(3)

    l_b = ListNode(5)
    l_b.next = ListNode(6)
    l_b.next.next = ListNode(9)

    # for i in (2, 4, 3):
    #     if l_a is None:
    #         l_a = ListNode(i)
    #         l_a.next =
    l_a = ListNode(0)
    l_b = ListNode(0)

    s = Solution()
    s.addTwoNumbers(l_a, l_b)


from fractions import Fraction
from math import ceil
from typing import Any, Dict

from pytorchvideo.data.clip_sampling import ClipInfo, ClipSampler

class MinimumFullCoverageClipSampler(ClipSampler):
    """Find the minmimum number of clips to cover the full video.

    Args:
        clip_duration: Duration of a clip.
        augs_per_clip: Number of augmentations to be applied on each clip.
    """

    def __init__(self, clip_duration: float, augs_per_clip: int = 1) -> None:
        super().__init__(clip_duration)
        self._augs_per_clip = augs_per_clip

    def __call__(
        self, last_clip_time: float, video_duration: float, annotation: Dict[str, Any]
    ) -> ClipInfo:
        """
        Args:
            last_clip_time: Not used.
            video_duration:: The duration (in seconds) for the video that's
                being sampled.
            annotation: Not used by this sampler.
        Returns:
            includes the clip information of (clip_start_time,
                clip_end_time, clip_index, aug_index, is_last_clip). The times are in seconds.
                ``is_last_clip`` is ``True`` after the end of the video is reached.

        """
        max_possible_clip_start = Fraction(max(video_duration - self._clip_duration, 0))
        clips_per_video = ceil(Fraction(video_duration / self._clip_duration))

        uniform_clip = Fraction(max_possible_clip_start, max(clips_per_video - 1, 1))

        clip_start_sec = uniform_clip * self._current_clip_index
        clip_index = self._current_clip_index
        aug_index = self._current_aug_index

        self._current_aug_index += 1
        if self._current_aug_index >= self._augs_per_clip:
            self._current_clip_index += 1
            self._current_aug_index = 0

        # Last clip is True if sampled self._clips_per_video or if end of video is reached.
        is_last_clip = False
        if (
            self._current_clip_index >= clips_per_video
            or uniform_clip * self._current_clip_index > max_possible_clip_start
        ):
            self._current_clip_index = 0
            is_last_clip = True

        if is_last_clip:
            self.reset()

        return ClipInfo(
            clip_start_sec,
            clip_start_sec + self._clip_duration,
            clip_index,
            aug_index,
            is_last_clip,
        )

    def reset(self):
        self._current_clip_index = 0
        self._current_aug_index = 0


import config
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from routes.questionares import router as QRouter
from routes.records import router as RRouter

app = FastAPI()

origins = [
    config.Settings().GATE
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(QRouter, tags=["Questionare"], prefix="/questionare")
app.include_router(RRouter, tags=["Records"], prefix="/records")

@app.get("/", tags=["Root"])
async def read_root():
    return {"message": "Questionare Service API"}


import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

def get_days(assigned_days, n_people):

    days = np.zeros(assigned_days.max(), int)

    for i, r in enumerate(assigned_days):

        days[r-1] += n_people[i]

    return days

def dataset_plot(dataset):

    desired = dataset.values[:,1:11]

    n_people = dataset.values[:,11]

    n_days = desired.max()

    plt.rcParams['figure.figsize'] = [20, 5]

    for i in range(10):

        plt.plot(np.arange(n_days), get_days(desired[:,i], n_people), alpha=0.9, label=f'choice {i}')

    days = np.zeros(desired.max(), int)

    for i, r in enumerate(desired):

        for j in range(10):

            days[r[j]-1] += n_people[i]

    plt.bar(np.arange(n_days), days/10, label='mean choices')

    plt.ylim(0, 1100)

    plt.legend()

    plt.show()
def example_ortools(desired, n_people, has_accounting=True):

    from ortools.linear_solver import pywraplp

    def accounting_penalty(day, next_day):

        return (day-125)*(day**(0.5 + abs(day-next_day)/50.0))/400

    NUM_THREADS = 4

    NUM_SECONDS = 3600

    FAMILY_COST = np.asarray([0,50,50,100,200,200,300,300,400,500])

    MEMBER_COST = np.asarray([0, 0, 9,  9,  9, 18, 18, 36, 36,235])

    num_days = desired.max()

    num_families = desired.shape[0]

    solver = pywraplp.Solver('Santa2019', pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)

#     solver.set_time_limit(NUM_SECONDS*NUM_THREADS*1000)

    solver.SetNumThreads(NUM_THREADS)

    C, B, I = {}, {}, {}

    for fid, choices in enumerate(desired):

        for cid in range(10):

            B[fid, choices[cid]-1] = solver.BoolVar('')

            C[fid, choices[cid]-1] = FAMILY_COST[cid] + n_people[fid] * MEMBER_COST[cid]

    for day in range(num_days):

        I[day] = solver.IntVar(125, 300, f'I{day}')

        solver.Add(solver.Sum(n_people[fid]*B[fid, day] for fid in range(num_families) if (fid,day) in B) == I[day])

    for fid in range(num_families):

        solver.Add(solver.Sum(B[fid, day] for day in range(num_days) if (fid,day) in B) == 1)

    objective = solver.Sum(C[fid, day]*B[fid, day] for fid, day in B)

    if has_accounting:

        Y = {}

        for day in range(num_days):

            next_day = np.clip(day+1, 0, num_days-1)

            gen = [(u,v) for v in range(176) for u in range(176)]

            for u,v in gen:

                Y[day,u,v] = solver.BoolVar('')

            solver.Add(solver.Sum(Y[day,u,v]*u for u,v in gen) == I[day]-125)

            solver.Add(solver.Sum(Y[day,u,v]*v for u,v in gen) == I[next_day]-125)

            solver.Add(solver.Sum(Y[day,u,v]   for u,v in gen) == 1)

        accounting_penalties = solver.Sum(accounting_penalty(u+125,v+125) * Y[day,u,v] for day,u,v in Y)

        objective += accounting_penalties

    solver.Minimize(objective)

    sol = solver.Solve()

    status = ['OPTIMAL', 'FEASIBLE', 'INFEASIBLE', 'UNBOUNDED', 'ABNORMAL', 'MODEL_INVALID', 'NOT_SOLVED']

    if status[sol] == 'OPTIMAL':

        print("Result: ", objective.solution_value())

        assigned_days = np.zeros(num_families, int)

        for fid, day in B:

            if B[fid, day].solution_value() > 0.5:

                assigned_days[fid] = day + 1

        return assigned_days
def example_cplex(desired, n_people, has_accounting=True): # can't run on kaggle notebooks

    def accounting_penalty(day, next_day):

        return (day-125)*(day**(0.5 + abs(day-next_day)/50.0))/400

    from docplex.mp.model import Model

    FAMILY_COST = np.asarray([0,50,50,100,200,200,300,300,400,500])

    MEMBER_COST = np.asarray([0, 0, 9,  9,  9, 18, 18, 36, 36,235])

    num_days = desired.max()

    num_families = desired.shape[0]

    solver = Model(name='Santa2019')

    solver.parameters.mip.tolerances.mipgap = 0.00

    solver.parameters.mip.tolerances.absmipgap = 0.00

    C = {}

    for fid, choices in enumerate(desired):

        for cid in range(10):

            C[fid, choices[cid]-1] = FAMILY_COST[cid] + n_people[fid] * MEMBER_COST[cid]

    B = solver.binary_var_dict(C, name='B')

    I = solver.integer_var_list(num_days, lb=125, ub=300, name='I')

    for day in range(num_days):

        solver.add(solver.sum(n_people[fid]*B[fid, day] for fid in range(num_families) if (fid,day) in B) == I[day])

    for fid in range(num_families):

        solver.add(solver.sum(B[fid, day] for day in range(num_days) if (fid,day) in B) == 1)

    preference_cost = solver.sum(C[fid, day]*B[fid, day] for fid, day in B)

    if has_accounting:

        Y = solver.binary_var_cube(num_days, 176, 176, name='Y')

        for day in range(num_days):

            next_day = np.clip(day+1, 0, num_days-1)

            gen = [(u,v) for v in range(176) for u in range(176)]

            solver.add(solver.sum(Y[day,u,v]*u for u,v in gen) == I[day]-125)

            solver.add(solver.sum(Y[day,u,v]*v for u,v in gen) == I[next_day]-125)

            solver.add(solver.sum(Y[day,u,v]   for u,v in gen) == 1)

        gen = [(day,u,v) for day in range(num_days) for v in range(176) for u in range(176)]

        accounting_penalties = solver.sum(accounting_penalty(u+125,v+125) * Y[day,u,v] for day,u,v in gen)

        solver.minimize(accounting_penalties+preference_cost)

    else:

        solver.minimize(preference_cost)

    solver.print_information()

    sol = solver.solve(log_output=True)

    if sol:

        print(sol.objective_value)

        assigned_days = np.zeros(num_families, int)

        for fid, day in C:

            if sol[B[fid, day]] > 0:

                assigned_days[fid] = day + 1

        return assigned_days
for n_days in [10,20,40,80]:

    dataset_plot(pd.read_csv(f'/kaggle/input/santa-2019-{n_days}-uniform-days/family_data.csv'))

    dataset_plot(pd.read_csv(f'/kaggle/input/santa-2019-{n_days}-days/family_data.csv'))

#     dataset_plot(pd.read_csv(f'/kaggle/input/santa-revenge-of-the-accountants-{n_days}-uniform-days/family_data.csv'))

#     dataset_plot(pd.read_csv(f'/kaggle/input/santa-2019-revenge-of-the-accountants-{n_days}-days/family_data.csv'))
for n_days in [10,20,40,80]:

    ds = pd.read_csv(f'/kaggle/input/santa-2019-{n_days}-uniform-days/family_data.csv')

columns = ['competition', 'distribution', 'number days', 'optimum', 'Cplex(seconds)', 'OR-Tools(seconds)']

pd.DataFrame([

    ['Santa 2019', 'uniform', 10,   0, 0, 0],

    ['Santa 2019', 'uniform', 20,   0, 0, 1],

    ['Santa 2019', 'uniform', 40, 150, 2, 3],

    ['Santa 2019', 'uniform', 80,   0, 3, 4],

    ['Santa 2019', '', 10,  5148,  2,    1],

    ['Santa 2019', '', 20,  8481,  2, 1317],

    ['Santa 2019', '', 40, 12090,  3, 'Too long'],

    ['Santa 2019', '', 80, 32806, 15, 'Too long'],

    ['Santa Revenge', 'uniform', 10,   0, 0, 0],

    ['Santa Revenge', 'uniform', 20, 100, 1, 3],

    ['Santa Revenge', 'uniform', 40, 150, 3, 3],

    ['Santa Revenge', 'uniform', 80, 850, 5, 'Too long'],

    ['Santa Revenge', '', 10,  9206,  0, 'Too long'],

    ['Santa Revenge', '', 20, 14627,  3, 'Too long'],

    ['Santa Revenge', '', 40, 22565, 26, 'Too long'],

    ['Santa Revenge', '', 80, 55212, 44, 'Too long'],

], columns=columns)
pd.DataFrame([

    ['Santa 2019', 'uniform', 10, 251.5312,  86, 'Too long'],

    ['Santa 2019', 'uniform', 20, 992.2934, 761, 'Too long'],

    ['Santa 2019', 'uniform', 40, None, 'Too long', 'Too long'],

    ['Santa 2019', 'uniform', 80, None, 'Too long', 'Too long'],

    ['Santa 2019', '', 10,  7902.8137, 1960, 'Too long'],

    ['Santa 2019', '', 20, 12794.1957, 4504, 'Too long'],

    ['Santa 2019', '', 40, None, 'Too long', 'Too long'],

    ['Santa 2019', '', 80, None, 'Too long', 'Too long'],

], columns=columns)


# -*- coding: utf-8 -*-
"""
Created on Tue Mar 29 09:46:42 2022

@author: Natalia
"""
import math
import numpy as np
import statistics as stt
class Transformacje:
    def __init__(self, model: str = "wgs84"):
        #https://en.wikipedia.org/wiki/World_Geodetic_System#WGS84
        if model == "wgs84":
            self.a = 6378137.0 # semimajor_axis
            self.b = 6356752.31424518 # semiminor_axis
        elif model == "grs80":
            self.a = 6378137.0
            self.b = 6356752.31414036
        else:
            raise NotImplementedError(f"{model} model not implemented")
        self.flattening = (self.a - self.b) / self.a
        self.ecc2 = 2 * self.flattening - self.flattening ** 2

        def hirvonen(self,x, y, z, a, e2):
            eps1=0.000001 #sekundy
            eps=eps1/3600*math.pi/180 #rad

            r=math.sqrt(x**2 + y**2)

            fi=math.atan(z/(r*(1-e2))) #radiany
            fi2=2*fi
            while np.abs(fi2-fi)>eps:
                fi=fi2

                N=self.a/math.sqrt(1-self.ecc2*math.sin(fi2)**2)

                h=(r/np.cos(fi) - N)

                fi2=math.atan(z/(r*(1-self.ecc2* (N/(N+h))))) #radiany

            N=self.a/np.sqrt(1-self.ecc2*np.sin(fi2)**2)
            h=r/math.cos(fi) - N
            lam = math.atan(y/x)
            return fi2, lam, h , N

        def blh2xyz(self, fi, lam, h):
                N = self.a / math.sqrt(1 - self.ecc2 * (math.sin(fi)) ** 2)
                X = (N + h) * math.cos(fi) * math.cos(lam)
                Y = (N + h) * math.cos(fi)*math.sin(lam)
                Z = (N * (1 - self.ecc2) + h) * math.sin(fi)
                return X, Y, Z

        def s_A_z2neu(s, A, z):
            A = np.deg2rad(A)
            z = np.deg2rad(z)
            n = s*np.sin(z)*np.cos(A)
            e = s*np.sin(z)*np.sin(A)
            u = s*np.cos(z)
            return n, e, u

        def neu2dXYZ(n, e, u, F1, L1):

             R = np.array([[-np.sin(F1) * np.cos(L1), -np.sin(L1), np.cos(F1)*np.cos(L1)],
                  [-np.sin(F1)*np.sin(L1), np.cos(L1), np.cos(F1)*np.sin(L1)],
                  [np.cos(F1), 0, np.sin(F1)]])
             dx = np.linalg.inv(R.transpose()) @ np.array([n, e, u])
             return dx

        dx = neu2dXYZ(n, e, u, fi, lam)

        e_2 = self.ecc2 / (1-self.ecc2)

        def u1992(self,fi, lam, a, e2, m_0):
            N = self.a/(math.sqrt(1-self.ecc2 * np.sin(fi)**2))
            t = np.tan(fi)
            n2 = e_2 * np.cos(lam)**2
            lam_0 = math.radians(19) #poczatek ukladu w punkcie przeciecia poludnika L0 = 19st z obrazem równika
            l = lam - lam_0

            A_0 = 1 - (self.ecc/4) - (3*(self.ecc2**2))/64 - (5*(self.ecc2**3))/256
            A_2 = 3/8 * (self.ecc2 + ((self.ecc2**2)/4) + ((15*self.ecc2**3)/128))
            A_4 = 15/256 * (self.ecc2**2 + (3*(self.ecc2**3))/4)
            A_6 = (35*(self.ecc2**3))/3072

            sigma = self.a* ((A_0*fi) - (A_2*np.sin(2*fi)) + (A_4*np.sin(4*fi)) - (A_6*np.sin(6*fi)))

            x = sigma + ((l**2)/2) * (N*np.sin(fi)*np.cos(fi)) * (1 + ((l**2)/12) * ((np.cos(fi))**2) * (5 - t**2 + 9*n2 + (4*n2**2)) + ((l**4)/360) * ((np.cos(fi))**4) * (61 - (58*(t**2)) + (t**4) + (270*n2) - (330 * n2 *(t**2))))
            y = l * (N*np.cos(fi)) * (1 + ((((l**2)/6) * (np.cos(fi))**2) * (1-(t**2) + n2)) +  (((l**4)/(120)) * (np.cos(fi)**4)) * (5 - (18 * (t**2)) + (t**4) + (14*n2) - (58*n2*(t**2))))

            x92 = round(x * m_0 - 5300000, 3)
            y92 = round(y * m_0 + 500000, 3)

            return x92, y92

        def u2000(self,fi, lam, a, e2, m_0):
            N = self.a/(math.sqrt(1-self.ecc2 * np.sin(fi)**2))
            t = np.tan(fi)
            n2 = self.ecc2 * np.cos(lam)**2
            lam = math.degrees(lam)

            if lam > 13.5 and lam < 16.5:
                s = 5
                lam_0 = 15
            elif lam > 16.5 and lam < 19.5:
                s = 6
                lam_0 = 18
            elif lam > 19.5 and lam < 22.5:
                s = 7
                lam_0 = 21
            elif lam > 22.5 and lam < 25.5:
                s = 8
                lam_0 = 24

            lam = math.radians(lam)
            lam_0 = math.radians(lam_0)
            l = lam - lam_0

            A_0 = 1 - (self.ecc2/4) - (3*(self.ecc2**2))/64 - (5*(self.ecc2**3))/256
            A_2 = 3/8 * (self.ecc2 + ((self.ecc2**2)/4) + ((15*self.ecc2**3)/128))
            A_4 = 15/256 * (self.ecc2**2 + (3*(self.ecc2**3))/4)
            A_6 = (35*(self.ecc2**3))/3072

            sigma = self.a* ((A_0*fi) - (A_2*np.sin(2*fi)) + (A_4*np.sin(4*fi)) - (A_6*np.sin(6*fi)))

            x = sigma + ((l**2)/2) * (N*np.sin(fi)*np.cos(fi)) * (1 + ((l**2)/12) * ((np.cos(fi))**2) * (5 - t**2 + 9*n2 + (4*n2**2)) + ((l**4)/360) * ((np.cos(fi))**4) * (61 - (58*(t**2)) + (t**4) + (270*n2) - (330 * n2 *(t**2))))
            y = l * (N*np.cos(fi)) * (1 + ((((l**2)/6) * (np.cos(fi))**2) * (1-(t**2) + n2)) +  (((l**4)/(120)) * (np.cos(fi)**4)) * (5 - (18 * (t**2)) + (t**4) + (14*n2) - (58*n2*(t**2))))

            x00 = round(x * m_0, 3)
            y00 = round(y * m_0 + (s*1000000) + 500000, 3)

            return x00, y00


import logging
import logging.config
import time

from pyspark.sql import SparkSession

from lightautoml.spark.utils import logging_config, VERBOSE_LOGGING_FORMAT
from .utils import DummyTabularAutoML
from .. import spark as spark_sess

spark = spark_sess

logging.config.dictConfig(logging_config(level=logging.DEBUG, log_filename='/tmp/lama.log'))
logging.basicConfig(level=logging.DEBUG, format=VERBOSE_LOGGING_FORMAT)
logger = logging.getLogger(__name__)

def test_automl_preset(spark: SparkSession):
    n_classes = 10

    train_data = spark.createDataFrame([
        {"a": i, "b": 100 + i, "c": 100 * i, "TARGET": i % n_classes} for i in range(120)
    ])

    test_data = spark.createDataFrame([
        {"a": i, "b": 100 + i, "c": 100 * i, "TARGET": i % n_classes} for i in range(120, 140)
    ])

    automl = DummyTabularAutoML(n_classes=n_classes)

    # 1. check for output result, features, roles (required columns in data, including return_all_predictions)
    # 2. checking for layer-to-layer data transfer (internal in DummyTabularAutoML):
    #   - all predictions of the first level are available in all pipes of the second level
    #   - all inputs data are presented in all pipes of the first level
    #   - all inputs data are presented in all pipes of the second level (if skip_conn)
    # 3. blending and return_all_predictions works correctly
    oof_ds = automl.fit_predict(train_data, roles={"target": "TARGET"})
    pred_ds = automl.predict(test_data)

    oof_df = oof_ds.data.cache()
    oof_df.write.mode('overwrite').format('noop').save()

    pred_df = pred_ds.data.cache()
    pred_df.write.mode('overwrite').format('noop').save()

    logger.info("Finished")


from matplotlib import colors, pyplot as plt

plt.style.use("fivethirtyeight")

slice = [120,80,30,20]
labels = ['forty','sixty','extra1','extra2']
colors=['blue','red','yello','green']
explode= [0,0.1,0.2,0]
plt.pie(slice, labels = labels, explode = explode, startangle=90,autopct='%1.1f%%', shadow = True, wedgeprops = { 'edgecolor' : 'black' } )

plt.title("my awsome pychart")

plt.tight_layout()

plt.show()


"""
Type of moves taken by each player e.g. Checktile, Removetile, Placetile, Checkwin
Move will recieve data from board to get moves from player and pass it to tile for changing value. then move
will recieve data from tile to change board before returning board value to the currentboard class.
"""
import string
alphabets = list(string.ascii_uppercase)
turncount = 0
#Obtain board from CurrentBoard, after player selects tile, tile data is sent to tile class. tile data recieved from tile. board is updated. Board data sent from removetile to currentboard.
#Tile is selected by player.
def picktile():
	choosetile = input("Please pick a tile to remove. E.g. A1,A2,B1,B2... etc >")
	return choosetile
#Tile is checked by computer to see if valid move, need to check if the tile are at the borders...
def checktile(choosetile,playernumber,board):
	#need to find the corresponding tile with the position of tile given by the player.
	#allow if tile = 0 or correct tile number. return true
	#if not return false
	tileposition = list(choosetile)
	#print(tileposition)
	horizontalvalue = alphabets.index(tileposition[0]) + 1
	verticalvalue = int(tileposition[1])
	#print (horizontalvalue)
	#print (verticalvalue)
	tilevalue = board[verticalvalue][horizontalvalue]
	#print(tilevalue)
	#need to check which player it is 1 or 2
	#i.e. if tilevalue == '0' or str(playernumber):
	#     	return True, verticalvalue, horizontalvalue
	#     else:
	#     	return False
	if playernumber%2 == 1:
		playtile = "1"
	elif playernumber%2 == 0:
		playtile = "2"
	if (tilevalue == "0") or (tilevalue == playtile):
		#for the tiles in the middle validtile = False
		validtile = True
		for hor in range(2,len(board[1])-1):
			#print(hor)
			for vert in range(2,len(board[1])-1):
				#print(vert)
				if (vert == verticalvalue) and (hor == horizontalvalue):
					#print(vert,hor,verticalvalue,horizontalvalue)
					validtile = False
					#print(validtile)
	else:
		validtile = False
	return verticalvalue,horizontalvalue,validtile,playtile
#Tile is removed if checktile returns true
def removetile(validtile,vertical,horizontal,board):
	#need to remove tile --> number to '-' and interact with board object and update board.
	#after Move.removetile() then Board.updateboard()?
	if validtile == True:
		#replace tile with '-'
		board[vertical][horizontal] = '-'
		#update board after this** - call the board function?
	elif validtile == False:
		print ("You cannot remove this tile")
	currentboard = board
	return currentboard
#Obtain board from CurrentBoard, after player places tile, board is updated. Board data sent from placetile to currentboard
#def placetile():
	#need to select direction to put in the tile from
	#check if can put tile in that position if not reject
#def checkwin():
	#check for tiles in a row.
	#if win then end the game and show who is the winner.
def checkturn(nameofplayers,turncount):
	#check for number of turns
	turncount += 1
	#check whose turn
	playernumber = turncount%len(nameofplayers)
	playerturn = nameofplayers[playernumber - 1]
	return turncount,playerturn,playernumber
def checkdirection(verticalvalue,horizontalvalue,board):
	#get input from player to see which direction player wants to input from
	#check if direction is valid.
	#by looking at the tile before '-'
	placecheck = False
	while placecheck == False:
		insertdirection = int(input("Which direction would you like to insert this tile from? 1)Left,2)Right,3)Up or 4)Below?>"))
		try:
			if insertdirection == 1: #if left, check left of '-'
				if (board[verticalvalue][horizontalvalue-1] == "0") or (board[verticalvalue][horizontalvalue-1] == "1") or (board[verticalvalue][horizontalvalue-1] == "2") or (board[verticalvalue][horizontalvalue-1] == "-"):
					placecheck = True
				else:
					placecheck = False
			elif insertdirection == 2: #if right, check right of '-'
				if (board[verticalvalue][horizontalvalue+1] == "0") or (board[verticalvalue][horizontalvalue+1] == "1") or (board[verticalvalue][horizontalvalue+1] == "2") or (board[verticalvalue][horizontalvalue+1] == "-"):
					placecheck = True
				else:
					placecheck = False
			elif insertdirection == 3: #if up, check up of '-'
				if (board[verticalvalue-1][horizontalvalue] == "0") or (board[verticalvalue-1][horizontalvalue] == "1") or (board[verticalvalue-1][horizontalvalue] == "2") or (board[verticalvalue-1][horizontalvalue] == "-"):
					placecheck = True
				else:
					placecheck = False
			elif insertdirection == 4: #if down, check down of '-'
				if (board[verticalvalue+1][horizontalvalue] == "0") or (board[verticalvalue+1][horizontalvalue] == "1") or (board[verticalvalue+1][horizontalvalue] == "2") or (board[verticalvalue+1][horizontalvalue] == "-"):
					placecheck = True
				else:
					placecheck = False
		except IndexError:
			placecheck = False
	print(placecheck)
	return insertdirection
def placetile(verticalvalue,horizontalvalue,board,insertdirection,playernumber,playtile):
	verticalvalue = int(verticalvalue)
	horizontalvalue = int(horizontalvalue)
	endboard = len(board[1]) - 1
	#if it is the four corner tiles aka (1,1),(1,n),(n,1)(n,n), only can insert from two directions
	#if it is the other border tiles, can insert only from three directions.
	if insertdirection == 1: #Left means must keep the verticalvalue, horizontal value decreases as it iterates
		newhorizontal = 1
		#get the position of '-' in the board
		#shift from before the position of '-' towards '-',meaning '-' will take value of previous
		while int(horizontalvalue) > 1:
			board[verticalvalue][horizontalvalue] = board[verticalvalue][horizontalvalue-1]
			horizontalvalue -= 1
		board[verticalvalue][newhorizontal] = playtile
		#tile. And afterwards new tile will be inserted into '-'
		#need to push the remaining tiles
		#need to put tile in that position
	elif insertdirection == 2: #Right means must keep the verticalvalue, horizontal value increases as it iterates
		newhorizontal = endboard
		while int(horizontalvalue) < endboard:
			board[verticalvalue][horizontalvalue] = board[verticalvalue][horizontalvalue+1]
			horizontalvalue += 1
		board[verticalvalue][newhorizontal] = playtile

	elif insertdirection == 3: #Up means must keep the horizontalvalue, vertical value decreases as it iterates
		newvertical = 1
		while verticalvalue > 1:
			board[verticalvalue][horizontalvalue] = board[verticalvalue-1][horizontalvalue]
			verticalvalue -= 1
		board[newvertical][horizontalvalue] = playtile

	elif insertdirection == 4: #Down means must keep the horizontalvalue , vertical value increases as it iterates
		newvertical = endboard
		while verticalvalue < endboard:
			board[verticalvalue][horizontalvalue] = board[verticalvalue+1][horizontalvalue]
			verticalvalue += 1
	#	board[1][3] = board[2][3]
	#	board[2][3] = board[3][3]
		board[newvertical][horizontalvalue] = playtile
	return board
def checkwin(board):
	boardsize = len(board[1]) - 1
	win = False
	#checking horizontal
	for rows in board:
		count1 = 0
		count2 = 0
		for values in rows:
			if values == "1":
				count1 += 1
			if values == "2":
				count2 += 1
			else:
				pass
		#print (count1,count2,boardsize)
		if count1 == boardsize:
			print("Player 1 wins!")
			win = True
		elif count2 == boardsize:
			print("Player 2 wins!")
			win = True
	#checking vertical
	for horizontalnum in range(1,boardsize +1):
		#print (horizontalnum)
		count1 = 0
		count2 = 0
		for verticalnum in range(1,boardsize +1):
			#print(verticalnum,board[verticalnum][horizontalnum])
			if board[verticalnum][horizontalnum] == "1":
				count1 += 1
			elif board[verticalnum][horizontalnum] == "2":
				count2 += 1
			else:
				pass
		#print (count1,count2)
		if count1 == boardsize:
			print("Player 1 wins!")
			win = True
		elif count2 == boardsize:
			print("Player 2 wins!")
			win = True
	#checking diagonal increment
	countone = 0
	counttwo = 0
	for num in range(1,boardsize +1):
		if board[num][num] == "1":
			countone += 1
		elif board[num][num] == "2":
			counttwo += 1
		else:
			pass
	#print (countone,counttwo)
	if countone == boardsize:
		print("Player 1 wins!")
		win = True
	elif counttwo == boardsize:
		print("Player 2 wins!")
		win = True
	#checking diagonal one decreases
	count3 = 0
	count4 = 0
	horlist = [0]
	for i in range(boardsize,0,-1):
		horlist.append(i)
	#print (horlist)
	for vert in range(1,boardsize +1):
		#print(vert)
		if board[vert][horlist[vert]] == "1":
			count3 += 1
		if board[vert][horlist[vert]] == "2":
			count4 += 1
		else:
			pass
	#print (count3, count4)
	if count3 == boardsize:
		print("Player 1 wins!")
		win = True
	elif count4 == boardsize:
		print("Player 2 wins!")
		win = True
	return win


import re

TextList = 'Hat,mat,pat,sat'

findText = re.findall('[m-p]at',TextList)
for i in findText:
    print(i)

print("----------Second Part ---------")
# If I say, not between this range(m-p) I use the ^ character

findText2 = re.findall('[^m-p]at',TextList)
for i in findText2:
    print(i)


#User function Template for python3

from typing import List

class Solution:
    def numberOfEnclaves(self, grid: List[List[int]]) -> int:
        if not grid:
            return 0

        def dfs(row, col):
            stack = [(row, col)]
            count = 0

            while stack:
                r, c = stack.pop()
                if (
                    r < 0
                    or r >= len(grid)
                    or c < 0
                    or c >= len(grid[0])
                    or grid[r][c] == 0
                ):
                    continue

                grid[r][c] = 0  # Mark the cell as visited
                count += 1

                # Add adjacent cells to the stack
                stack.append((r - 1, c))
                stack.append((r + 1, c))
                stack.append((r, c - 1))
                stack.append((r, c + 1))

            return count

        # Start DFS from the boundary land cells
        for row in range(len(grid)):
            if grid[row][0] == 1:
                dfs(row, 0)
            if grid[row][len(grid[0]) - 1] == 1:
                dfs(row, len(grid[0]) - 1)

        for col in range(len(grid[0])):
            if grid[0][col] == 1:
                dfs(0, col)
            if grid[len(grid) - 1][col] == 1:
                dfs(len(grid) - 1, col)

        # Count the remaining land cells (those not connected to the boundary)
        enclave_count = sum(row.count(1) for row in grid)

        return enclave_count

#{
 # Driver Code Starts
#Initial Template for Python 3

if __name__ == "__main__":
    for _ in range(int(input())):
        n, m = map(int,input().strip().split())
        grid = []
        for i in range(n):
            grid.append([int(i) for i in input().strip().split()])

        obj=Solution()
        print(obj.numberOfEnclaves(grid))
# } Driver Code Ends

GFG/Problem of the day/Number Of Enclaves.py


from django.urls import path
from . import views
from .views import MapView

urlpatterns = [
    path('', views.home, name = "HOME"),
    #path('newPage/', views.users, name = "USER"),
    #path('editPage/<int:user_id>/', views.edit, name = "EDIT"),
    #path('delete/<int:user_id>/', views.delete_user, name='DELETE'),
    path('mysignup/', views.myregister, name = "REGISTER"),
    path('mylogin/', views.mylogin, name = "LOGIN"),
    path('userhome/<int:user_id>/', views.UserHomePage, name = "UserHomePage"),
    path('adminhome/<int:user_id>/', views.AdminHomePage, name = "AdminHomePage"),
    path('arrest/<int:admin_id>/', views.ArrestPage, name = "ArrestPage"),
    path('applyCIS/', views.applyCISLoader, name = "applyCISLoad"),
    path('criminalpage/<int:admin_id>', views.allCriminalPage, name = "CriminalPage"),
    path('p1complain/<int:user_id>/<int:FIR_id>', views.complain1, name = "UseComplainPage1"),
    path('p2complain/<int:user_id>/<int:FIR_id>', views.complain2, name = "UseComplainPage2"),
    path('p3complain/<int:user_id>/<int:FIR_id>', views.complain3, name = "UseComplainPage3"),
    path('p4complain/<int:user_id>/<int:FIR_id>', views.complain4, name = "UseComplainPage4"),
    path('saveContents/<int:user_id>/', views.saveComplain_1, name = "SAVE1"),
    path('search_req_user/<int:user_id>/', views.goto_search_page, name = "Search_Page"),
    path('activate/<uidb64>/<token>',views.activatefunction, name="ACTIVATE"),
    path('fetch_user_data/',views.fetch_user_data, name="fetch_user_data"),
    path('fetch_victim_data/',views.fetch_victim_data, name="fetch_victim_data"),
    path('Upload_Victim_Record/',views.upload_victim_record, name="upload_victim_record"),
    path('Upload_WITHNESS_Record/',views.upload_witeness_record, name="upload_witeness_record"),
    path('Upload_Offender_Record/',views.upload_offender_record, name="upload_offender_record"),
    path('your_complaint_view/',views.pdf_view, name="pdf_view"),
    #path('map/', MapView.as_view(), name='map-view'),

    path('map/', views.context_date, name='map-view'),
    path('get-station/', views.near_stations),
]


import json
import uuid
import urllib
from uuid import getnode as getmac

from pyportify import gpsoauth

SJ_DOMAIN = "mclients.googleapis.com"
SJ_URL = "/sj/v2.5"

FULL_SJ_URL = "https://{0}{1}".format(SJ_DOMAIN, SJ_URL)

def encode(values):
    return urllib.parse.urlencode(values)

class Mobileclient(object):

    def __init__(self, session, token=None):
        self.token = token
        self.session = session

    async def login(self, username, password):
        android_id = _get_android_id()
        res = gpsoauth.perform_master_login(username, password, android_id)

        if "Token" not in res:
            return None

        self._master_token = res['Token']
        res = gpsoauth.perform_oauth(
            username, self._master_token, android_id,
            service='sj', app='com.google.android.music',
            client_sig='38918a453d07199354f8b19af05ec6562ced5788')
        if 'Auth' not in res:
            return None
        self.token = res["Auth"]
        return self.token

    async def search_all_access(self, search_query, max_results=30):
        data = await self._http_get("/query", {"q": search_query,
                                               "max-results": max_results,
                                               "ct": "1,2,3,4,6,7,8,9"})
        return data

    async def find_best_tracks(self, search_query):
        tracks = []
        for i in range(0, 2):
            data = await self.search_all_access(search_query)
            if 'suggestedQuery' in data:
                data = await self.search_all_access(
                    data['suggestedQuery'])
            if "entries" not in data:
                continue
            for entry in data["entries"]:
                if entry["type"] == "1":
                    tracks.append(entry["track"])
            if tracks:
                break
        return tracks

    async def fetch_playlists(self):
        data = await self._http_post("/playlistfeed", {})
        # TODO: paging
        return data

    async def create_playlist(self, name, public=False):
        mutations = build_create_playlist(name, public)
        data = await self._http_post("/playlistbatch",
                                     {"mutations": mutations})
        res = data["mutate_response"]
        playlist_id = res[0]["id"]
        return playlist_id

    async def add_songs_to_playlist(self, playlist_id, track_ids):
        data = {"mutations": build_add_tracks(playlist_id, track_ids)}
        res = await self._http_post('/plentriesbatch', data)
        added_ids = [e['id'] for e in res['mutate_response']]
        return added_ids

    async def _http_get(self, url, params):
        headers = {"Authorization": "GoogleLogin auth={0}".format(self.token),
                   "Content-type": "application/json"}

        merged_params = params.copy()
        merged_params.update({'tier': 'aa',
                              'hl': 'en_US',
                              'dv': 0})

        res = await self.session.request('GET',
                                         FULL_SJ_URL + url,
                                         headers=headers,
                                         params=merged_params)
        data = await res.json()
        return data

    async def _http_post(self, url, data):
        data = json.dumps(data)
        headers = {"Authorization": "GoogleLogin auth={0}".format(self.token),
                   "Content-type": "application/json"}
        res = await self.session.request(
            'POST',
            FULL_SJ_URL + url,
            data=data,
            headers=headers,
            params={'tier': 'aa',
                    'hl': 'en_US',
                    'dv': 0,
                    'alt': 'json'})
        ret = await res.json()
        return ret

def build_add_tracks(playlist_id, track_ids):
    mutations = []
    prev_id = ""
    cur_id = str(uuid.uuid1())
    next_id = str(uuid.uuid1())

    for i, track_id in enumerate(track_ids):
        details = {"create": {"clientId": cur_id,
                              "creationTimestamp": "-1",
                              "deleted": False,
                              "lastModifiedTimestamp": "0",
                              "playlistId": playlist_id,
                              "source": 1,
                              "trackId": track_id}}

        if track_id.startswith("T"):
            details["create"]["source"] = 2  # AA track

        if i > 0:
            details["create"]["precedingEntryId"] = prev_id

        if i < len(track_ids) - 1:
            details["create"]["followingEntryId"] = next_id

        mutations.append(details)

        prev_id = cur_id
        cur_id = next_id
        next_id = str(uuid.uuid1())
    return mutations

def build_create_playlist(name, public):
    return [{
        "create": {"creationTimestamp": "-1",
                   "deleted": False,
                   "lastModifiedTimestamp": 0,
                   "name": name,
                   "description": "",
                   "type": "USER_GENERATED",
                   "shareState": "PUBLIC" if public else "PRIVATE"}}]

def parse_auth_response(s):
    # SID=DQAAAGgA...7Zg8CTN
    # LSID=DQAAAGsA...lk8BBbG
    # Auth=DQAAAGgA...dk3fA5N
    res = {}
    for line in s.split("\n"):
        if not line:
            continue
        k, v = line.split("=", 1)
        res[k] = v
    return res

def _get_android_id():
    mac_int = getmac()
    if (mac_int >> 40) % 2:
        raise OSError("a valid MAC could not be determined."
                      " Provide an android_id (and be"
                      " sure to provide the same one on future runs).")

    android_id = _create_mac_string(mac_int)
    android_id = android_id.replace(':', '')
    return android_id

def _create_mac_string(num, splitter=':'):
    mac = hex(num)[2:]
    if mac[-1] == 'L':
        mac = mac[:-1]
    pad = max(12 - len(mac), 0)
    mac = '0' * pad + mac
    mac = splitter.join([mac[x:x + 2] for x in range(0, 12, 2)])
    mac = mac.upper()
    return mac


from unicodedata import category
from django.shortcuts import get_object_or_404, render
from django.views.decorators.clickjacking import xframe_options_exempt

from .models import Content, Category

@xframe_options_exempt
def index(request):
    categories = Category.objects.all()
    context = {
        'categories': categories,
    }
    return render(request, 'j34main/index.html', context)

def blog(request, blog_id):
    article = get_object_or_404(Content, pk=blog_id)
    context = {
        'article': article,
    }
    return render(request, 'j34main/blog.html', context)

def blogs(request):
    articles = Content.objects.all().order_by('-pub_date')
    context = {
        'articles': articles,
    }
    return render(request, 'j34main/blogs.html', context)

def category_blogs(request, cat_pk):
    articles = Content.objects.filter(categories=cat_pk).order_by('-pub_date')[:4]
    row_one = articles[0:2]
    row_two = articles[2:4]
    context = {
        'row_one': row_one,
        'row_two': row_two,
    }
    return render(request, 'j34main/partials/category_blogs.html', context)


import matplotlib.pyplot as plt

try:
    from csc_486b_assignments.solution.assignment1 import utils
except ModuleNotFoundError:
    import utils

if __name__ == "__main__":

    img = utils.read_image("input.jpg")
    img_inv = utils.invert_image(img)
    utils.save_image_to_h5(img_inv, "output.h5")

    plt.figure()
    plt.imshow(img)
    plt.figure()
    plt.imshow(img_inv)
    plt.show()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# https://github.com/shenwei356/bio_scripts
from __future__ import print_function

import argparse
import gzip
import logging
import os
import re
import sys

from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.SeqUtils import MeltingTemp as mt

def parse_args():
    parser = argparse.ArgumentParser(description="Compute DNA MeltingTemp")
    group = parser.add_mutually_exclusive_group()
    group.add_argument("--stdin", action="store_true",
                       help='read from stdin, one sequence per line')
    group.add_argument('-i', '--infile', type=str,
                       help='file name should like this: infile.[fasta|fa|fastq|fq][.gz]')
    parser.add_argument('-f', '--format', type=str, # default='fasta',
                        help='seqence format: fasta |fastq  [fasta]')

    args = parser.parse_args()
    if not (args.stdin or args.infile):
        sys.stderr.write("option --stdin or -i should be given\n")
        sys.exit(1)
    if args.format and not args.format in ['fasta', 'fastq']:
        sys.stderr.write("option -f | --format should be 'fasta' or 'fastq'\n")
        sys.exit(1)
    if args.stdin and not args.format:
        sys.stderr.write("option -f | --format should be given when --stdin is set.\n")
        sys.exit(1)

    return args

if __name__ == '__main__':
    args = parse_args()

    file, seq_format, fh = args.infile, args.format,  None,
    if file:
        if not seq_format:
            found = re.search(r'(?i)(fasta|fa|fastq|fq)(.gz)?$', file)
            if not found:
                print("invalid file name suffix.\nfile name should like this: infile.[fasfa|fa|fastq|fq][.gz]",
                      file=sys.stderr)
                sys.exit(1)
            seq_format, is_gz = found.groups()
            if seq_format == 'fa':
                seq_format = 'fasta'
            if seq_format == 'fq':
                seq_format = 'fastq'

        fh = gzip.open(file, 'rt') if file.endswith('.gz') else open(file, 'r')
    else:
        fh = sys.stdin
        seq_format = args.format

    sys.stdout.write('{}\t{}\t{}\t{}\n'.format('seq_id', 'Tm_Wallace', 'Tm_GC', 'Tm_NN'))
    for seq in SeqIO.parse(fh, seq_format):
        sys.stdout.write('{}\t{:0.2f}\t{:0.2f}\t{:0.2f}\n'.format(seq.id, mt.Tm_Wallace(seq.seq), mt.Tm_GC(seq.seq), mt.Tm_NN(seq.seq)))
    fh.close()


import pygame
import time
import random

pygame.init()

white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0, 155, 0)

display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Andrew\'s Snake Game')

pygame.display.update()

#frames per second
clock = pygame.time.Clock()

block_size = 10
FPS = 30

#font object
font = pygame.font.SysFont(None, 25)

def snake(block_size, snakeList):
    for elementXY in snakeList:

        pygame.draw.rect(gameDisplay, green, [elementXY[0],elementXY[1],block_size,block_size])

def message_to_screen(msg,color):
    screen_text = font.render(msg, True, color)
    #put the font on our game screen
    gameDisplay.blit(screen_text,[display_width/2, display_height/2])

def gameLoop():

    gameExit = False
    gameOver = False

    #first location head of the snake
    lead_x = display_width/2
    lead_y = display_height/2

    lead_x_change = 0
    lead_y_change = 0

    snakeList = []
    snakeLength = 1

    #we do not want the randomly generated apples to appear from 800-810, which will not appear on the screen
    #with '- block_size range is reduced to 0 -790, where the block will fill with 790-800
    #round function will reduce or in crease the block to a multiple of 10, needed for overlapping when snake eats an apple
    randAppleX = round(random.randrange(0, display_width - block_size)/10.0) * 10.0
    randAppleY = round(random.randrange(0, display_height - block_size)/10.0) * 10.0

    while not gameExit:

        while gameOver == True:
            gameDisplay.fill(white)
            message_to_screen("Game over, press C to play again or Q to quit", red)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        gameExit = True
                        gameOver = False
                    if event.key == pygame.K_c:
                        gameLoop()

        #event is local variable, event handling loop
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                    gameExit = True
            #event is keydown
            if event.type == pygame.KEYDOWN:
                #event is left key
                if event.key == pygame.K_LEFT:
                    lead_x_change = -block_size
                    lead_y_change = 0
                elif event.key == pygame.K_RIGHT:
                    lead_x_change = block_size
                    lead_y_change = 0
                elif event.key == pygame.K_UP:
                    lead_y_change = -block_size
                    lead_x_change = 0
                elif event.key == pygame.K_DOWN:
                    lead_y_change = 10
                    lead_x_change = 0

        #goes off screen, game over
        if lead_x >= display_width or lead_x < 0 or lead_y >= display_height or lead_y < 0:
            gameOver = True
            # if event.type == pygame.KEYUP:
            #     if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
            #         lead_x_change = 0
            #     if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
            #         lead_y_change = 0

            #print(event)
        lead_x += lead_x_change
        lead_y += lead_y_change

        gameDisplay.fill(white)

        #pygame.draw.rect('Surface', 'color', '[x,y,size(x,y)])
        #using my lead_x and lead_y variable allows me to move our rectangle
        pygame.draw.rect(gameDisplay, red, [randAppleX, randAppleY, block_size, block_size])

        snakeHead = []
        snakeHead.append(lead_x)
        snakeHead.append(lead_y)
        snakeList.append(snakeHead)
        if len(snakeList) > snakeLength:
            del snakeList[0]

        #handles collision if we run into our own snake body
        for eachSegment in snakeList [:-1]:
            if eachSegment == snakeHead:
                gameOver = True
        snake(block_size, snakeList)
        #fill with rectangle, is faster processing
        #gameDisplay.fill(red, rect=[200,200,50,50])

        pygame.display.update()
        #higher fps means more processing power is used

        if lead_x == randAppleX and lead_y == randAppleY:
            randAppleX = round(random.randrange(0, display_width - block_size)/10.0) * 10.0
            randAppleY = round(random.randrange(0, display_height - block_size)/10.0) * 10.0
            snakeLength +=1

        clock.tick(FPS)

    pygame.quit()
    quit()

gameLoop()


#! /usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import frida
import time

def on_message(message, data):
	if message['type'] == 'error':
		print('[!] ' + message['stack'])
	elif message['type'] == 'send':
		print('[i] ' + message['payload'])
	else:
		print(message)

def main(target_process, addr, size):
	session = frida.attach(target_process)
	script = session.create_script("""
		var buf = Memory.readByteArray(ptr('0x%x'), %d);
		 console.log(hexdump(buf, {
	 		offset: 0,
		 		length: %d,
		 		header: true,
		 		ansi: false
		 	}));
""" % (addr, size, size))

	script.on('message', on_message)
	script.load()
	time.sleep(2)
	session.detach()

if __name__ == '__main__':
	if len(sys.argv) < 4:
		print('Usage: {} <process name or PID> <addr> <size>'.format(__file__))
		sys.exit(1)

	if sys.argv[1].isdigit():
		target_process = int(sys.argv[1])
	else:
		target_process = sys.argv[1]

	addr, size = int(sys.argv[2], 16), int(sys.argv[3])
	main(target_process, addr, size)


#!/usr/bin/env python
import rospy
from performance_tests.msg import SuperAwesome
from std_msgs.msg import Float32

def timer_callback(event):
    global rate, update_rate
    step_size = rospy.get_param('~step_size_hz',1000)
    frequency_end = rospy.get_param('~end_frequency_hz',10000)

    update_rate = update_rate + step_size

    if (update_rate > frequency_end):
        update_rate = frequency_end

    rate = rospy.Rate(update_rate)

def performance_pub():
    global rate, update_rate
    pub = rospy.Publisher('performance_pub', SuperAwesome, queue_size=100)
    freq_pub = rospy.Publisher('/real_frequency', Float32, queue_size=100)
    rospy.init_node('performance_test', anonymous=False)

    #Get private parameters from launch file:
    step_time_sec = rospy.get_param('~step_time_sec',4)
    update_rate = rospy.get_param('~start_frequency_hz',1000)

    rate = rospy.Rate(update_rate)

    rospy.Timer(rospy.Duration(step_time_sec), timer_callback)

    while not rospy.is_shutdown():
        performance_str = "Python publish rate set to %#.2f Hz" % update_rate
        pub.publish(performance_str)
        freq_pub.publish(update_rate) #Real Rate message publication
        rate.sleep()

if __name__ == '__main__':
    try:
        performance_pub()
    except rospy.ROSInterruptException:
        pass


import os
from funcionesGrafica import *
from funcionesEstadistica import *
from models import RockSampleModel, Model
from solvers import POMCP, PBVI
from parsers import PomdpParser, GraphViz
from logger import Logger as log

class PomdpRunner:

    def __init__(self, params):
        self.params = params
        if params.logfile is not None:
            log.new(params.logfile)

    def create_model(self, env_configs):
        """
        Builder method for creating model (i,e, agent's environment) instance
        :param env_configs: the complete encapsulation of environment's dynamics
        :return: concrete model
        """
        MODELS = {
            'RockSample': RockSampleModel,
        }
        return MODELS.get(env_configs['model_name'], Model)(env_configs)

    def create_solver(self, algo, model):
        """
        Builder method for creating solver instance
        :param algo: algorithm name
        :param model: model instance, e.g, TigerModel or RockSampleModel
        :return: concrete solver
        """
        SOLVERS = {
            'pbvi': PBVI,
            'pomcp': POMCP,
        }
        return SOLVERS.get(algo)(model)

    def snapshot_tree(self, visualiser, tree, filename):
        visualiser.update(tree.root)
        visualiser.render('./dev/snapshots/{}'.format(filename))

    def run(self, numeroEjecuciones,modo, algo, T, **kwargs):
        pasos = []
        recompensas = []
        while numeroEjecuciones != 0:
            params, pomdp = self.params, None
            total_rewards, budget = 0, params.budget
            if modo != "benchmark":
                log.info('~~~ Inicializando ~~~')
            with PomdpParser(params.env_config) as ctx:
                # Crea el modelo y el solucionador
                model = self.create_model(ctx.copy_env())
                pomdp = self.create_solver(algo, model)

                # Suministrar parámetros adicionales del algoritmo
                belief = ctx.random_beliefs() if params.random_prior else ctx.generate_beliefs()

                if algo == 'pbvi':
                    belief_points = ctx.generate_belief_points(kwargs['stepsize'])
                    pomdp.add_configs(belief_points)
                elif algo == 'pomcp':
                    pomdp.add_configs(budget, belief, **kwargs)

            if modo != "benchmark":
                log.info('''
                ++++++++++++++++++++++
                    Estado inicial:  {}
                    Presupuesto inicial:  {}
                    Creencia inicial: {}
                    Horizonte temporal: {}
                    Max Play: {}
                    Modo: {}
                ++++++++++++++++++++++'''.format(model.curr_state, budget, belief, T, params.max_play, modo))

            if modo == "interactiva":
                res = input("¿Desea continuar? [S]/[N]")
                if(res.lower() == "n"):
                    return

            condicionParada = False
            i = 0
            while not condicionParada:
                # plan, take action and receive environment feedbacks
                pomdp.solve(modo, T)
                action = pomdp.get_action(belief)
                new_state, obs, reward, cost = pomdp.take_action(action)

                # update states
                belief = pomdp.update_belief(belief, action, obs)
                total_rewards += reward
                budget -= cost

                # print info
                if modo == "interactiva":
                    log.info('\n'.join([
                    'Accion tomada: {}'.format(action),
                    'Observacion: {}'.format(obs),
                    'Recompensa: {}'.format(reward),
                    'Presupuesto: {}'.format(budget),
                    'Nuevo estado: {}'.format(new_state),
                    'Nueva Creencia: {}'.format(belief),
                    'Paso numero: {}'.format(i),
                    '=' * 20
                    ]))

                if budget <= 0:
                    log.info('Presupuesto superado.')
                    break

                if params.env == "Tigre.POMDP":
                    condicionParada = action == "open-left" or action == "open-right" or i >= params.max_play
                elif params.env == "TAG.POMDP":
                    condicionParada = action == "Catch"  or i >= params.max_play
                elif params.env == "IndianaJones.POMDP":
                    condicionParada = action == "izquierda" or action == "centro" or action == "derecha"  or i >= params.max_play
                elif params.env == "AnunciosWeb.POMDP":
                    condicionParada = action == "A1" or action == "AN" or action == "A2"  or i >= params.max_play
                else:
                    condicionParada = i >= params.max_play

                i += 1

            if modo != "benchmark":
                log.info('{} pasos. Recompensa Total = {}'.format(i, total_rewards))
            else:
                log.info('{} | {} pasos. Recompensa Total = {}'.format(numeroEjecuciones, i, total_rewards))
            pasos.append(i)
            recompensas.append(total_rewards)
            numeroEjecuciones -= 1
        if modo == "benchmark":
            log.info('\n'.join([
            '#' * 20,
            'Media de los pasos: {}'.format(media(pasos)),
            'Varianza de los pasos: {}'.format(varianza(pasos)),
            'Desviacion Tipida de los pasos: {}'.format(desviacion_tipica(pasos)),
            'Grafica: {}'.format(generaGrafica(pasos)),
            '#' * 20
            ]))
            log.info('\n'.join([
            'Media de la recompensa: {}'.format(media(recompensas)),
            'Varianza de la recompensa: {}'.format(varianza(recompensas)),
            'Desviacion Tipida de la recompensa: {}'.format(desviacion_tipica(recompensas)),
            'Grafica: {}'.format(generaGrafica(recompensas)),
            '#' * 20
            ]))
        return pomdp


import random

from Data import data
import LVQ as nn
from LVQ import make_plots

"""
This script implements some experiments to test LVQ model
"""

# printing vectors
def pprint_vector(vector):
    vector = [str(round(value, 3)) for value in vector]
    if len(vector) > 6:
        vector = [*vector[:3], "...", *vector[-3:]]
    print("[" + ", ".join([f"{value:>7}" for value in vector]) + "]")

# main function for experiments
def main_algorithm(labels_mapping,
                   dataset,
                   epochs,
                   learning_rate,
                   codebooks_count,
                   folds):
    # printing all unique output classes
    print("Label mapping:")
    print(labels_mapping)

    # randomly assigned codebook vector
    sample = random.choice(dataset)

    # calculating length of codebook vector, number of features
    *features, label = sample
    features_count = len(features)
    labels_count = len(labels_mapping)

    # number of codebook vectors that will used to train LVQ model
    codebooks_count = codebooks_count

    # LVQ neural network initialization
    model = nn.LVQ(codebooks_count,
                   features_count,
                   labels_count,
                   "sample",
                   dataset)

    # assigned codebook vectors (initial values)
    print("Initialized codebook:")
    for vector in model.codebook:
        pprint_vector(vector)

    # LVQ model training
    print("Training model...")
    print("Innitial model:")
    accuracy_list, accuracy = model.train_codebook(
        train_vectors=dataset,
        base_learning_rate=learning_rate,
        learning_rate_decay=None,
        epochs=epochs,
    )

    print("Trained codebook:")
    for vector in model.codebook:
        pprint_vector(vector)

    print("Cross validating model...")
    scores, confusion_matrices, iter = nn.cross_validate(
        dataset,
        folds,
        learning_rate=0.01,
        learning_rate_decay=None,
        epochs=epochs,
        codebook_size=codebooks_count,
        features_count=features_count,
        labels_count=labels_count,
        codebook_init_method="sample",
        model=model
    )
    # EXPERIMENT 1: how learning rate affects model accuracy

    # model1 = nn.LVQ(codebooks_count,
    #                       features_count,
    #                       labels_count,
    #                       "sample",
    #                       dataset)
    # print("Learning rate experiment:")
    # learning_rate_list = [0.01, 0.05, 0.09, 0.13,
    #                       0.17, 0.21, 0.25, 0.29,
    #                       0.33, 0.37, 0.41, 0.45,
    #                       0.49, 0.53, 0.57, 0.61,
    #                       0.65, 0.69, 0.73, 0.77,
    #                       0.81, 0.85, 0.89, 0.93, 0.97]
    # results1 = []
    # parameters_learning_rate = {}
    # for i in learning_rate_list:
    #     accuracy_list, accuracy = model1.train_codebook(
    #         train_vectors=dataset,
    #         base_learning_rate=i,
    #         learning_rate_decay='linear',
    #         epochs=epochs,
    #     )
    #     parameters_learning_rate[i] = accuracy
    #     results1.append(accuracy)
    # max_accuracy = max(parameters_learning_rate.values())
    # best = [key for key, val in parameters_learning_rate.items() if val == max_accuracy]
    # best_lr = best[0]
    # print(len(learning_rate_list) == len(results1))
    #

    # EXPERIMENT 2: how number of epochs affects model accuracy
    # print("Epochs experiment:")
    # model2 = nn.LVQ(codebooks_count,
    #                       features_count,
    #                       labels_count,
    #                       "sample",
    #                       dataset)
    # epochs_range = [10, 50, 100, 150, 200,
    #                 250, 300, 350, 400,
    #                 450, 500, 550, 600,
    #                 650, 700, 750, 800,
    #                 850, 900, 950, 1000]
    # results2 = []
    # parameters_epochs = {}
    # for i in epochs_range:
    #     accuracy_list, accuracy = model2.train_codebook(
    #         train_vectors=dataset,
    #         base_learning_rate=0.01,
    #         learning_rate_decay='linear',
    #         epochs=i,
    #     )
    #     print(accuracy)
    #     parameters_epochs[i] = accuracy
    #     results2.append(accuracy)
    # max_accuracy = max(parameters_epochs.values())
    # best = [key for key, val in parameters_epochs.items() if val == max_accuracy]
    # best_epoch = best[0]

    # EXPERIMENT 3: how number of codebook vectors affects model accuracy
    # print("Codebook size experiment:")
    # codebooks_sizes = [1, 5, 10, 20, 30,
    #                    40, 50, 100, 200,
    #                    400, 600, 800, 900, 950]
    # results3 = []
    # parameters_codebooks_count = {}
    #
    # for i in codebooks_sizes:
    #     model3 = nn.LVQ(i,
    #                           features_count,
    #                           labels_count,
    #                           "sample",
    #                           dataset)
    #     accuracy_list, accuracy = model3.train_codebook(
    #         train_vectors=dataset,
    #         base_learning_rate=0.01,
    #         learning_rate_decay='linear',
    #         epochs=100,
    #     )
    #     parameters_codebooks_count[i] = accuracy
    #     results3.append(accuracy)
    # max_accuracy = max(parameters_codebooks_count.values())
    # best = [key for key, val in parameters_codebooks_count.items() if val == max_accuracy]
    # best_codebooks_count = best[0]

    # EXPERIMENT 4: trainig LVQ model with the best parameters that are found in previous experiments
    # print("Best parameters experiment:")
    # model3 = nn.LVQ(best_codebooks_count,
    #                       features_count,
    #                       labels_count,
    #                       "sample",
    #                       dataset)
    # best_accuracy_list, best_accuracy = model3.train_codebook(train_vectors=dataset,
    #                                                           base_learning_rate=best_lr,
    #                                                           learning_rate_decay='linear',
    #                                                           epochs=best_epoch, )
    # epoch = 250
    # learning_rate = 0.01
    # learning_rate = 0.13

    # give parameters you need and this function will make plots for you
    make_plots(epochs=epochs,
               iter=iter,
               scores=scores,
               confusion_matrixes=confusion_matrices,
               accuracy=accuracy_list
               )

    return accuracy, accuracy_list

# function that starts experiment
def experiments():
    print("Starting...")
    print("---------------------------------------------------------")
    # use path for your dataset
    labels_mapping, dataset = data.load_data_normalization(
        'Data/german_credit_data.csv')
    main_algorithm(labels_mapping, dataset, 100, 0.01, 30, 5)

experiments()


from typing import *
from kaia.eaglesong.core import Return, Routine, Subroutine
from kaia.eaglesong.drivers.telegram import TgCommand, TgContext
import telegram as tg
import logging
from abc import ABC, abstractmethod

logger = logging.getLogger('group_chat')

class AdminReplySkillLogic(ABC):
    @abstractmethod
    def run(self, context: TgContext, update: tg.Update):
        pass

class AdminReplySkill(Routine):
    def __init__(self,
                 owner_id: int,
                 initial_message: str,
                 wrong_owner_reply: str,
                 no_message_reply: str,
                 logic: AdminReplySkillLogic
                 ):
        self.owner_id = owner_id
        self.initial_message = initial_message
        self.wrong_owner_reply = wrong_owner_reply
        self.no_message_reply = no_message_reply
        self.logic = logic

    def run(self, context: TgContext):
        update = context.update
        if update.effective_message.text!=self.initial_message:
            yield Return()
        logger.info(f'Entered {type(self.logic)}')

        if update.effective_user.id != self.owner_id:
            yield TgCommand.mock().send_message(
                chat_id = update.effective_chat.id,
                text = self.wrong_owner_reply,
                reply_to_message_id=update.effective_message.id
            )
            return
        logger.info('Owner OK')

        if update.effective_message.reply_to_message is None:
            yield TgCommand.mock().send_message(
                chat_id=update.effective_chat.id,
                text=self.no_message_reply,
                reply_to_message_id=update.effective_message.id
            )
            return
        logger.info(f'Message OK')

        yield Subroutine(self.logic.run, update)


from django.contrib import admin
from django.urls import path
from . import views
from django.contrib.auth import views as auth_views

#define route path to redirect one to another pages

urlpatterns = [
    path('', views.Home,name="Home"),

    path('login/', views.login,name="login"),

    path('loged/', views.loged,name="loged"),

    path('blog/',views.blog, name="blog"),

    path('sendQuery/',views.sendQuery,name="sendQuery"),

    path('admin/', admin.site.urls,name="admin"),

    path('readPost/<int:id>',views.readPost,name="readPost"),

    path('About/',views.About,name="About"),

    path('Searching/',views.Searching, name="Searching"),

   ]


# 별 그리는 재귀함수
def star(n):
    global Maps

    if n == 3:
        Maps[0][:3] = Maps[2][:3] = [1] * 3
        Maps[1][:3] = [1, 0, 1]
        return

    a = n // 3
    star(n//3)
    for i in range(3):
        for j in range(3):
            if i == 1 and j == 1:
                continue
            for k in range(a):
                Maps[a*i + k][a*j:a*(j+1)] = Maps[k][:a]        # 핵심 아이디어

N = int(input())

Maps = [ [0 for i in range(N)] for i in range(N) ]              # 매트릭스 만들기
'''''
a = [[0]*3 for _ in range(3)]
print(a)
# [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
'''''

star(N)

for i in Maps:
    for j in i:
        if j:
            print('*', end= '')             # 1은 '별' 0은 '빈칸'
        else:
            print(' ', end= '')
    print()

'''''
def draw_star(n):
    mat = [ ]
    for i in range(3 * len(n)):
        if i // len(n) == 1:
            mat.append(n [i % len(n)] + " " * len(n) + n[i % len(n)])
        else:
            mat.append(n[i % len(n)] * 3)
    return list(mat)

star = ['***', '* *', '***']
N = int(input())
k = 0
while N != 3:
    N = int(N/3)
    k += 1

for i in range(k):
    star = draw_star(star)
for i in star:
    print(i)
'''''