# -*- coding: utf-8 -*-
# file: pdfrog/taglistwidget.py
from PySide.QtGui import *
from PySide.QtCore import *
import pdfrog
from .datamodel import Tag
import sqlalchemy as sa

class TagList(QTableView):
    def __init__(self, *args):
        QTableView.__init__(self, *args)
        mdl = TagListModel()
        self.setModel(mdl)
        self.horizontalHeader().setMovable(True)
        self.horizontalHeader().setHighlightSections(False)
        self.installEventFilter(self)
        self.verticalHeader().setVisible(False)
        self.setSortingEnabled(True)
        self.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.query = None
        self.refreshData()

    def createMenu(self, tag_menu):
        tag_remove_action = QAction(QIcon.fromTheme("edit-delete"), "Remove", self)
        tag_remove_action.triggered.connect(self.removeSelectedTags)

        tag_rename_action = QAction(QIcon.fromTheme("document-edit"), "Rename", self)
        tag_rename_action.triggered.connect(self.renameSelectedTag)

        tag_discharge_action = QAction(QIcon.fromTheme("document-decrypt"), "Discharge", self)
        tag_discharge_action.triggered.connect(self.dischargeSelectedTags)

        tag_refresh_list_action = QAction(QIcon.fromTheme("view-refresh"), "Refresh list", self)
        tag_refresh_list_action.triggered.connect(self.refreshData)

        self.context_menu = tag_menu
        tag_menu.addAction(tag_refresh_list_action)
        tag_menu.addAction(tag_remove_action)
        tag_menu.addAction(tag_rename_action)
        tag_menu.addAction(tag_discharge_action)

    def refreshData(self, query=None):
        if query is None:
            query = self.query or pdfrog.session.query(Tag).limit(300)
        self.query = query
        self.model().clearData()
        item_count = 0
        for tag in query:
            self.model().appendTag(tag)
            item_count += 1
        return item_count

    def removeSelectedTags(self):
        idxs = self.selectionModel().selectedRows()
        if all([self.item(idx.row()).getUsageCount()==0 for idx in idxs]):
            # all selected tags have zero usage count
            tag_names_list = [self.item(idx.row()).name for idx in idxs]

            res = QMessageBox.question(self, "Remove tags", \
                "Do you want to remove tags: \n{} ?".format(", ".join(tag_names_list)), \
                buttons = QMessageBox.Ok | QMessageBox.Cancel)

            for idx in idxs:
                tag = self.item(idx.row())
                pdfrog.session.delete(tag)

            self.refreshData()
        else:
            QMessageBox.warning(self, "Remove tags",
                "Can't remove tags with non-zero usage. " + \
                "You must manually discharge them first. Sorry.")

    def renameSelectedTag(self):
        """renames first selected tag. Asks user for new name"""
        idxs = self.selectionModel().selectedRows()
        if len(idxs) > 0:
            tag = self.item(idxs[0].row())
            (new_tag_name, ok_pressed) = QInputDialog.getText(self, "Rename tag", "New name:", text=tag.name)
            if ok_pressed and new_tag_name != "":
                tag.name = new_tag_name
                self.refreshData()

    def dischargeSelectedTags(self):
        """removes any use of the selected tags"""
        idxs = self.selectionModel().selectedRows()
        if len(idxs) == 0: return

        tag_names_list = [self.item(idx.row()).name for idx in idxs]

        res = QMessageBox.question(self, "Discharge tags",
            "Do you want to discharge tags:\n" + \
            ", ".join(tag_names_list), \
            buttons = QMessageBox.Ok | QMessageBox.Cancel)

        if res == QMessageBox.Ok:
            for idx in self.selectionModel().selectedRows():
                tag = self.item(idx.row())
                tag.discharge()

            self.refreshData()

    def eventFilter(self, obj, event):
        if event.type() == QEvent.ContextMenu:
            self.context_menu.exec_(QCursor.pos())
            return True
        else:
            return QTableView.eventFilter(self, obj, event)

    def item(self, row):
        return self.model().item(row)

class TagListModel(QAbstractTableModel):
    def __init__(self, parent=None, *args):
        QAbstractTableModel.__init__(self, parent, *args)
        self.view = parent
        self.datastore = []

    COLUMN_TAG = 0
    COLUMN_TIMES_USED = 1

    def rowCount(self, parent=None):
        return len(self.datastore)

    def columnCount(self, parent=None):
        return 2

    def data(self, index, role = Qt.DisplayRole):
        if not index.isValid():
            return None
        elif role == Qt.DisplayRole:
            if index.column() == self.COLUMN_TAG:
                return self.datastore[index.row()].name
            if index.column() == self.COLUMN_TIMES_USED:
                return self.datastore[index.row()].getUsageCount()
            else:
                return "Unknown"
        else:
            return None

    def headerData(self, column, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            if column == self.COLUMN_TAG:
                return "Tag"
            elif column == self.COLUMN_TIMES_USED:
                return "Times used"
            else:
                return "Unknown"
        else:
            return None

    def clearData(self):
        self.modelReset.emit()
        self.datastore = []

    def appendTag(self, tag, update=True):
        if type(tag) != Tag:
            raise Exception("tag is not Tag")
        if update: self.beginInsertRows(QModelIndex(), len(self.datastore), len(self.datastore))
        self.datastore.append(tag)
        if update: self.endInsertRows()

    def sort(self, column, order):
        reverse = (order == Qt.DescendingOrder)
        self.layoutAboutToBeChanged.emit()

        if column == self.COLUMN_TAG:
            self.datastore = sorted(self.datastore, key=lambda obj: obj.name, reverse=reverse)
        elif column == self.COLUMN_TIMES_USED:
            self.datastore = sorted(self.datastore, key=lambda obj: obj.getUsageCount(), reverse=reverse)

        self.layoutChanged.emit()

    def item(self, row):
        return self.datastore[row]


"""

"""
import sys

def comb(nums, idx, n, memo):
    if idx >= n:
        return 0
    if memo[idx]:
        return memo[idx]

    max_val = max(
        comb(nums, idx + 1, n, memo),  # 현재 값을 안 더했을 때,
        comb(nums, idx + 2, n, memo) + nums[idx]  # 현재 값을 더했을 때,
    )

    memo[idx] = max_val
    return max_val

def solution():
    sys_input = sys.stdin.readline

    n = int(sys_input())
    nums = list(map(int, sys_input().split()))
    print(comb(nums, 0, n, [0] * n))

solution()

01. 이코테/Chapter 08 다이나믹 프로그래밍/실전_02_개미 전사.py


import requests
from bs4 import BeautifulSoup
import pandas as pd

url = "https://webscraper.io/test-sites/e-commerce/allinone/computers/laptops"
htmlDoc = requests.get(url)
# print(htmlDoc.text)

# Parser

soup = BeautifulSoup(htmlDoc.text, "lxml")
# print(soup.prettify)

# Access h1 tag
# print(soup.h1)

# Access header tag
# print(soup.header)

# Access div tag
# print(soup.div)

# Access string from nested tags
# print(soup.header.p)
# print(soup.header.p.string)

# Access a tag in header
# check1 = soup.header.a
# check1.attrs
# print(check1.attrs["data-target"])

# check1["new-target"] = "This is the new attribute"
# print(check1.attrs)

# Searching specific attribute

# price = soup.find("h4", class_="pull-right price")
# price = soup.find_all("h4", class_="pull-right price")[2:5]

# price = soup.find_all(["h4","a","p"])
# price =soup.find_all(["header", "div"])
# price =soup.find_all(id=True)
# print(price)

# Data Collection

name = soup.find_all("a", class_="title")
price = soup.find_all("h4", class_="pull-right price")
reviews = soup.find_all("p", class_="pull-right")
description = soup.find_all("p", class_="description")

# price = soup.find("h4", class_="pull-right price")
# print(price.text)

# Creating loop to make string from find_all list
productNameList = []
for i in name:
    name = i.text
    productNameList.append(name)

productPriceList = []
for i in price:
    price = i.text
    productPriceList.append(price)

productReviewsList = []
for i in reviews:
    reviews = i.text
    productReviewsList.append(reviews)

productDescriptionList = []
for i in description:
    description = i.text
    productDescriptionList.append(description)

# Creating data frame
table = pd.DataFrame({"Product Name": productNameList, "Product Price": productPriceList, "Product Reviews": productReviewsList, "Product Description": productDescriptionList})

# Exporting to csv
# table.to_csv("Price.csv", index=False)

# Read CSV
tabel2 = pd.read_csv("Price.csv")
print(tabel2)


import tensorflow as tf
from tensorflow import keras
from abc import ABC, abstractmethod
from utils.Builders.model_builder import (build_discrete_actor, build_continuous_stochastic_actor,
    build_state_value_critic, CheckpointedModel)
from utils.model_util_functions import *
from utils.util_functions import append_folder_name_to_path

class A2CModel(ABC):

    def create_models(self, state_space, action_space, learning_rate, gradient_clipping, save_path):
        self.actor = self._create_actor(state_space, action_space, learning_rate, gradient_clipping,
            append_folder_name_to_path(save_path, 'actor'))
        self.critic = build_state_value_critic(state_space, learning_rate, gradient_clipping,
            append_folder_name_to_path(save_path, 'critic'))

    def load_models(self, checkpoint_path, gradient_clipping):
        self.actor = CheckpointedModel(append_folder_name_to_path(checkpoint_path, 'actor'), gradient_clipping)
        self.critic = CheckpointedModel(append_folder_name_to_path(checkpoint_path, 'critic'), gradient_clipping)

    @abstractmethod
    def _create_actor(self, state_space, action_space, learning_rate, gradient_clipping, save_path):
        pass

    @abstractmethod
    def forward(self, states):
        pass

    @abstractmethod
    def _compute_actor_loss(tape, states, actions, advantages):
        pass

    def update_actor(self, states, actions, advantages):
        tape = tf.GradientTape()
        loss = self._compute_actor_loss(tape, states, actions, advantages)
        trainable_variables = self.actor.get_trainable_variables()
        gradients = tape.gradient(loss, trainable_variables)
        self.actor.update_model(gradients)
        return loss

    def update_critic(self, states, returns):
        with tf.GradientTape() as tape:
            state_values = self.critic(states)
            state_values = tf.squeeze(state_values, axis = -1)
            loss = keras.losses.MSE(returns, state_values)

        trainable_variables = self.critic.get_trainable_variables()
        gradients = tape.gradient(loss, trainable_variables)
        self.critic.update_model(gradients)
        return loss

    def save_models(self):
        self.actor.save_model()
        self.critic.save_model()

class A2CModelDiscrete(A2CModel):

    def _create_actor(self, state_space, action_space, learning_rate, gradient_clipping, save_path):
        return build_discrete_actor(state_space, action_space, learning_rate, gradient_clipping, save_path)

    def forward(self, states):
        values = tf.squeeze(self.critic(states), axis = -1)
        prob_dists = self.actor(states)
        actions = sample_from_categoricals(prob_dists)
        return values.numpy(), actions.numpy()

    def _compute_actor_loss(self, tape, states, actions, advantages):
        with tape:
            prob_dists = self.actor(states)
            log_probs_dists = compute_log_of_tensor(prob_dists)
            log_probs_actions = select_values_of_2D_tensor(log_probs_dists, actions)
            loss = -tf.reduce_mean(log_probs_actions*advantages)
        return loss

class A2CModelContinuous(A2CModel):

    def __init__(self, action_space):
        self.min_action = action_space.get_min_action()
        self.max_action = action_space.get_max_action()

    def _create_actor(self, state_space, action_space, learning_rate, gradient_clipping, save_path):
        return build_continuous_stochastic_actor(state_space, action_space, learning_rate, gradient_clipping, save_path)

    def forward(self, states):
        values = tf.squeeze(self.critic(states), axis = -1)
        mus, log_sigmas = self.actor(states)
        actions = tf.clip_by_value(sample_from_gaussians(mus, log_sigmas), self.min_action, self.max_action)
        return values.numpy(), actions.numpy()

    def _compute_actor_loss(self, tape, states, actions, advantages):
        with tape:
            mus, log_sigmas = self.actor(states)
            probs_actions = compute_pdf_of_gaussian_samples(mus, log_sigmas, actions)
            log_probs_actions = compute_log_of_tensor(probs_actions)
            loss = -tf.reduce_mean(log_probs_actions*advantages)
        return loss


"""
module:1
description:to convert snake case to pascle case
"""
from string import capwords
try:
    string=input("Enter the string: ")
    if string.isnumeric():
        print("please enter string")
        exit()
        print("Snake case: ",string)
    Pascal_Case= capwords(string.replace('_',' '))
    PascaCase= Pascal_Case.replace(' ','')
    print("Pascal case: ",Pascal_Case)
except Exception as e:
    print("Enter the valid input")


from app import create_app
from flask import jsonify, request
import sqlalchemy
from sqlalchemy.sql import text
import os
import data_analysis as da

#ENV variable
localhost=False
fields = ['team_name','points','yards','pass_yards','rush_yards']

conn = sqlalchemy.create_engine('sqlite:///football_stats.db')
app = create_app("development")

if(not localhost):
    import logging
    logging.basicConfig(filename='logging.log',level=logging.DEBUG)

def map_keys_to_values(keys, values):
    return {key : value for key, value in zip(keys, values)}

@app.route('/')
def index():
    return 'To query the API, put team names as parameters. For example: "/team_a=DEN&team_b=DET" '

@app.route('/to_sql')
def sqlify():
    if(localhost):
        da.to_sql()
        return "Done!"
    else:
        return "This can only be done locally!"

@app.route('/team_a=<a>&team_b=<b>')
def get_stats(a,b):
    return jsonify(da.stats(a,b))

@app.route('/max_difference/<stat>')
def get_max_difference(stat):
    if stat not in fields:
        return {"error":"Couldn't query database - invalid stat."}

    max_offense = conn.execute(text("select max("+stat+") from offense")).fetchone()[0]
    min_offense = conn.execute(text("select min("+stat+") from offense")).fetchone()[0]

    max_defense = conn.execute(text("select max("+stat+") from defense")).fetchone()[0]
    min_defense = conn.execute(text("select min("+stat+") from defense")).fetchone()[0]

    output = {}
    output["offense"] = max_offense-min_offense
    output["defense"] = max_defense-min_defense
    return jsonify(output)

@app.route('/stats/<team>')
def get_team_stats(team):
    output = {}
    query = text("select "+','.join(fields)+" from defense where team_name = :t")
    defense_stats = conn.execute(query,t=team).fetchone()
    output['defense'] = map_keys_to_values(fields,defense_stats)

    query = text("select "+','.join(fields)+" from offense where team_name = :t")
    offense_stats = conn.execute(query,t=team).fetchone()
    output['offense'] = map_keys_to_values(fields,offense_stats)

    return jsonify(output)

@app.route('/log')
def read_log():
    f  = open('logging.log', "r")
    return f.read()

@app.route('/status')
def status():
    return 'Ok!'

@app.after_request
def after_request(response):
  response.headers.add('Access-Control-Allow-Origin', '*')
  response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
  response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
  return response

if __name__ == '__main__':
    if(localhost):
        app.run()
    else:
        port = int(os.environ.get("PORT", 8886))
        app.run(host='0.0.0.0', port=port)


from tkinter import Tk, filedialog
import os
import re

# Open file selector dialog
root = Tk()
root.withdraw()
file_path = filedialog.askopenfilename()

# Get file extension
file_name, file_extension = os.path.splitext(file_path)

# Define comment patterns for different file types
comment_patterns = {
    '.py': r'#.*?(?<!\\)\n|\'\'\'.*?(?<!\\)\'\'\'|\"\"\".*?(?<!\\)\"\"\"',  # Python (single-line and multi-line comments)
    '.sql': r'--.*?(?<!\\)\n|\/\*.*?(?<!\\)\*\/',                        # SQL (single-line and multi-line comments)
    '.go': r'\/\/.*?(?<!\\)\n|\/\*.*?(?<!\\)\*\/',                       # Go (single-line and multi-line comments)
    '.cs': r'\/\/.*?(?<!\\)\n|\/\*.*?(?<!\\)\*\/',                        # C# (single-line and multi-line comments)
    # Add more file extensions and comment patterns as needed
}

# Process file and remove lines with comments
lines = []
with open(file_path, 'r') as file:
    content = file.read()
    pattern = comment_patterns.get(file_extension, '')
    cleaned_content = re.sub(pattern, '', content, flags=re.MULTILINE | re.DOTALL)
    lines = cleaned_content.splitlines(keepends=True)

# Save modified content to a new file
new_file_path = file_name + '_comments_removed' + file_extension
with open(new_file_path, 'w') as new_file:
    new_file.writelines(lines)

print(f"Lines with comments removed. Saved as: {new_file_path}")


import sys
import inspect
import logging
import numpy as np
import tensorflow as tf
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from model.models import resolve_model
from model.rewards import resolve_reward
from environments.env import test_cases, resolve_env

class NES():
	"""
	Implementation of NES algorithm by OpenAI: https://arxiv.org/pdf/1703.03864.pdf
	"""

	def __init__(self, training_directory, config):
		self.config = config
		self.training_directory = training_directory
		self.env = resolve_env(self.config['environment'])(test_cases[self.config['environment']][self.config['environment_index']], self.training_directory, self.config)
		self.env.pre_processing()
		self.model = resolve_model(self.config['model'])(self.config)
		self.reward = resolve_reward(self.config['reward'])
		self.master_params = self.model.init_master_params()
		self.learning_rate = self.config['learning_rate']
		self.noise_std_dev = self.config['noise_std_dev']
		logging.info("\nReward:")
		logging.info(inspect.getsource(self.reward) + "\n")

	def run_simulation(self, sample_params, model, population, master=False):
		"""
		Black box interaction with environment using model as the action decider given environmental inputs.
		Args:
		    sample_params (tensor): Master parameters jittered with gaussian noise
		    model (tensor): The output layer for a tensorflow model
		Returns:
			reward (float): Fitness function evaluated on the completed trajectory
		"""
		with tf.Session() as sess:
			reward = 0
			valid = False
			for t in range(self.config['n_timesteps_per_trajectory']):
				inputs = np.array(self.env.inputs(t)).reshape((1, self.config['input_size']))
				net_output = sess.run(model, self.model.feed_dict(inputs, sample_params))
				action = net_output
				if self.env.discrete:
					action = np.argmax(net_output)
				valid = self.env.act(action, population, sample_params, master)
			reward += self.reward(self.env.reward_params(valid))
			success = self.env.reached_target()
			self.env.reset()
			return reward, success

	def update(self, noise_samples, rewards, n_individual_target_reached):
		"""
		Update function for the master parameters (weights and biases for neural network)
		Args:
		    noise_samples (float array): List of the noise samples for each individual in the population
		    rewards (float array): List of rewards for each individual in the population
		"""
		normalized_rewards = (rewards - np.mean(rewards))
		if np.std(rewards) != 0.0:
			normalized_rewards = (rewards - np.mean(rewards)) / np.std(rewards)

		learning_decay_rate = 1.0 - (float(n_individual_target_reached)/float(self.config['n_individuals']))
		noise_decay_rate = 1.0 - np.sqrt((float(n_individual_target_reached)/float(self.config['n_individuals'])))
		self.learning_rate *= learning_decay_rate
		self.noise_std_dev *= noise_decay_rate
		logging.info("Learning Rate: {}".format(self.learning_rate))
		logging.info("Noise Std Dev: {}".format(self.noise_std_dev))

		self.master_params += (self.learning_rate / (self.config['n_individuals'] * self.noise_std_dev)) * np.dot(noise_samples.T, normalized_rewards)

	def run(self):
		"""
		Run NES algorithm given parameters from config.
		"""
		model = self.model.model()
		n_reached_target = []
		population_rewards = []
		for p in range(self.config['n_populations']):
			logging.info("Population: {}\n{}".format(p+1, "="*30))
			noise_samples = np.random.randn(self.config['n_individuals'], len(self.master_params))
			rewards = np.zeros(self.config['n_individuals'])
			n_individual_target_reached = 0
			self.run_simulation(self.master_params, model, p, master=True) # Run master params for progress check, not used for training
			for i in range(self.config['n_individuals']):
				logging.info("Individual: {}".format(i+1))
				sample_params = self.master_params + noise_samples[i]
				rewards[i], success = self.run_simulation(sample_params, model, p)
				n_individual_target_reached += success
				logging.info("Individual {} Reward: {}\n".format(i+1, rewards[i]))
			self.update(noise_samples, rewards, n_individual_target_reached)
			n_reached_target.append(n_individual_target_reached)
			population_rewards.append(sum(rewards)/len(rewards))
			self.plot_graphs([range(p+1), range(p+1)], [population_rewards, n_reached_target], ["Average Reward per population", "Number of times target reached per Population"], ["reward.png", "success.png"], ["line", "scatter"])
		self.env.post_processing()
		logging.info("Reached Target {} Total Times".format(sum(n_reached_target)))

	def plot_graphs(self, x_axes, y_axes, titles, filenames, types):
		for i in range(len(x_axes)):
			plt.title(titles[i])
			if types[i] == "line":
				plt.plot(x_axes[i], y_axes[i])
			if types[i] == "scatter":
				plt.scatter(x_axes[i], y_axes[i])
				plt.plot(np.unique(x_axes[i]), np.poly1d(np.polyfit(x_axes[i], y_axes[i], 1))(np.unique(x_axes[i])), 'r--')
			plt.savefig(self.training_directory + filenames[i])
			plt.clf()


import weakref
import numpy as np
import pygame as p

class Object:
    objects = weakref.WeakSet()
    def __init__(self, typeX, vel, xsize, ysize):

        self.type = typeX
        self.damage = 10

        if self.type == 0:
            self.damage = 10
            self.sprite = p.image.load("vfx/sprites/misil1.png")

        self.vel = vel
        self.size = (40, 70)
        self.pos = (np.random.randint(20, xsize-20), ysize-40)

        self.cann = p.transform.scale(self.sprite, self.size)
        self.hitbox = (self.pos[0]-self.size[0]/2, self.pos[1]-self.size[1]/2, \
            self.size[0]-15, self.size[1]-2)
        self.sprite_rect = None

        self.__class__.objects.add(self)

    def UpdatePos(self):
        self.hitbox = (self.pos[0]-self.size[0]/2, self.pos[1]-self.size[1]/2, \
            self.size[0]-10, self.size[1]-10)

        self.pos = (self.pos[0], self.pos[1]-self.vel)

    def Draw(self, win, hitbox=False):
        self.sprite = p.transform.rotate(self.cann, 0)
        self.sprite_rect = self.sprite.get_rect()

        self.sprite_rect.center = self.pos
        win.blit(self.sprite, self.sprite_rect)
        if hitbox:
            p.draw.rect(win, (255, 0, 0), (self.pos[0]+self.hitbox[2]/2, \
                self.pos[1]-self.hitbox[3]/2, 3, self.hitbox[3]))

            p.draw.rect(win, (255, 255, 0), (self.pos[0]-self.hitbox[2]/2, \
                self.pos[1]-self.hitbox[3]/2, 3, self.hitbox[3]))

            p.draw.rect(win, (255, 255, 255), (self.pos[0]-self.hitbox[2]/2, \
                self.pos[1]+self.hitbox[3]/2, self.hitbox[2], 3))

            p.draw.rect(win, (255, 0, 255), (self.pos[0]-self.hitbox[2]/2, \
                self.pos[1]-self.hitbox[3]/2, self.hitbox[2], 3))

    @classmethod
    def getObjects(cls):
        return cls.objects


#John Brent David
#CS 2-1
#Function for Fibonacci
from pickle import APPEND
from tracemalloc import start
import random

next_num =1
prev_num =0
total_num =0
def Fibonacci(num1):
    global next_num #use global variable to overwrite a global variable inside a function
    global prev_num #only works when using python
    global total_num
    if(num1 >0):
        total_num = (prev_num + next_num)
        prev_num = next_num
        next_num = total_num
        print(total_num," ",end="")
        Fibonacci(num1-1)
#function for factorial
def getFactorial(num1):
    if num1 ==1:
        return 1
    else:
        num2 = num1 -1
        return(num1 *getFactorial(num2))
#function to reverse the number
def reverseNum(num):
    if num<10:
        print(num)
        return
    else:
        print(num%10,end="") #use end = "" when printing to prevent newline when printing
        reverseNum(int(num/10))
#function to reverse a word
def reverseWord(word):
    if len(word)==0:
        return word
    else:
        return reverseWord(word[1:])+word[0]
#function for tower of hanoi
def printRods(start_rod,aux_rod,des_rod):
    print("Start Rod :",end=" ")
    for i in range (0,len(start_rod)):
        print(start_rod[i],end=" ")
    print("\nAux Rod : ",end=" ")
    for i in range (0,len(aux_rod)):
        print(aux_rod[i],end=" ")
    print("\nDes Rod : ",end=" ")
    for i in range (0,len(des_rod)):
        print(des_rod[i],end=" ")
    print("\n------------------")
#main function of tof
def towerofHanoi(num,start,aux,des,source,destination,auxiliary):
    if num == 1:
        des.append(start.pop(len(start)-1))
        print ("Move disk 1 from",source,"to",destination)
        return
    towerofHanoi(num-1,start,des,aux,source, auxiliary, destination)
    des.append(start.pop(len(start)-1))#transfer the top most element of start array
    print ("Move disk",num,"from",source,"to",destination)
    towerofHanoi(num-1,aux,start,des,source, auxiliary, destination)
#Recursion calling function
# I have created a simple game in which you will choose which has more in an array Odd or Even?
def is_even(n):
    if n == 0:
        return True
    else:
        return not_even(n-1)

def not_even(n):
    if n == 0:
        return False
    else:
        return is_even(n-1)

#START
repeat = True
while repeat:
    app = int(input("What application would you like to use?\n[1]Fibonacci\t\t[2]Factorial\n[3]Reverse a number\t[4]Reverse a Word\n[5]Tower of Hanoi\t[6]Odd or Even Game\n[0]EXIT\nDecision : "))
    if app == 1:
        num1 = int(input("How many # to display on fibonacci series: "))
        Fibonacci(num1)
    elif app == 2:
        num1 = int(input("Enter a base value to factorial: "))
        print("The factorial of",num1,"is",getFactorial(num1))
    elif app == 3:
        num1 = int(input("Enter a value to be reversed: "))
        reverseNum(num1)
    elif app == 4:
        word = str(input("Enter a value to be reversed: "))
        print("The reverse of the word is :",reverseWord(word))
    elif app == 5:
        num = int(input("Enter the number of rings: "))
        value=num #value as placeholder to init start array
        start_rod=[]
        aux_rod=[]
        des_rod=[]
        for i in range (0,num):
            if i==num:
                break
            else:
                start_rod.append(value)
                value-=1
        print("------------------\n   START Position\n------------------")
        printRods(start_rod,aux_rod,des_rod)#Prints Before
        towerofHanoi(num,start_rod,aux_rod,des_rod,"Start","Des","Aux")
        print("------------------\n   END Position\n------------------")
        printRods(start_rod,aux_rod,des_rod)#Prints After
    elif app== 6:
        numEven =0
        numOdd = 0
        arr=[]
        #this gives the random value to the array
        for i in range (0,49):
            arr.append(random.randint(1,100))
            print(arr[i], end=" ")
            is_it_even=is_even(arr[i])
            #if statement to know if the element at ith index is even or odd then add 1 to the correct category
            if is_it_even:
                numEven +=1
            else:
                numOdd +=1
        choice = int(input("\nWhat do you think has more on the list?\n[1]Odd\t[2]Even\nDecision: "))
        if choice ==1:
            if numEven < numOdd:
                print("Congrats!You guessed it correctly")
            else:
                print("Unfortunately!You guessed it wrong")
        elif choice == 2:
            if numOdd < numEven:
                print("Congrats!You guessed it correctly")
            else:
                print("Unfortunately!You guessed it wrong")
        else:
            print("Wrong input!")
    elif app == 0:
        print("You are now exiting the Program!\nThanks for trying it")
        repeat = False
    else:
        print("Wrong Input! Try Again")
    print("\n=============================")


from flask import Flask, jsonify, request
from pymongo import MongoClient
from bson import json_util
from datetime import datetime
import sys
import uuid
import json
from flask_cors import CORS
import timedelta
import itertools
from datetime import datetime, timedelta
import openai
from flask_sslify import SSLify

openai.api_key = ""

def generate_quote(event):

    if event["progress"] == 1: #doing
        prompt = f"Generate a creative motivational quote within 13 words for completing the ongoing task '{event['title']}' with the description '{event['description']}'"
        response = openai.Completion.create(
            engine="text-davinci-003" ,
            prompt=prompt,
            max_tokens=1024,
            n=1,
            stop=None,
            temperature=0.8,
            )
        return response.choices[0].text.strip()

    if event["progress"] == 0: #done
        prompt = f"Generate a creative appreciation quote within 13 words for finishing the task '{event['title']}' with the description '{event['description']}'"
        response = openai.Completion.create(
            engine="text-davinci-003" ,
            prompt=prompt,
            max_tokens=1024,
            n=1,
            stop=None,
            temperature=0.5,
            )

        return response.choices[0].text.strip()

    if event["progress"] == 2: #overdue
        prompt = f"Generate a creative motivating quote within 13 words for the overdue task '{event['title']}' with the description '{event['description']}'"
        response = openai.Completion.create(
            engine="text-davinci-003" ,
            prompt=prompt,
            max_tokens=1024,
            n=1,
            stop=None,
            temperature=0.8,
            )
        quote = response.choices[0].text.strip()
        return quote

    if event["progress"] == 3: #upcoming
        prompt = f"Generate a creative motivating quote within 13 words for the upcoming task with title as '{event['title']}' and the description '{event['description']}'"
        response = openai.Completion.create(
            engine="text-davinci-003" ,
            prompt=prompt,
            max_tokens=1024,
            n=1,
            stop=None,
            temperature=0.8,
            )
        quote = response.choices[0].text.strip()
        return quote

def printf(x):
    print(x, file=sys.stderr)
    #app.logger.info(x)
printf("Running!")
def parse_json(data):
    return json.loads(json_util.dumps(data))

app = Flask(__name__)
CORS(app)
sslify = SSLify(app)

client = MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["mycollection"]

# with collection.watch() as stream:
#     for change in stream:
#         printf(change)

collection.delete_many({})

unique_id = str(uuid.uuid4())
one = {
        "id": unique_id,
        'title' :  'Gym',
        'description' : 'Hit the Gym',
        'date' : "2023-04-01",
        'duration' : '2',
        'deadline' : "2023-04-01",
        'type' : 'Personal',
        "progress": 0,

}

unique_id = str(uuid.uuid4())
quote1 = generate_quote({'title' :  'Machine Learning Project',
        'description' : 'Implementing exchange rate prediction using different regression models and choosing the best from them',
        "progress": 1})
two = {
        "id": unique_id,
        'title' :  'Machine Learning Project',
        'description' : 'Implementing exchange rate prediction using different regression models and choosing the best from them',
        'date' : "2023-04-01",
        'duration' : '8',
        'deadline' : "2023-04-10",
        'type' : 'Personal',
        "progress": 1,
        "quote": quote1
}

quote2 = generate_quote({        'title' :  'Deep Learning',
        'description' : 'Implementing exchange rate prediction using different regression models and choosing the best from them',
        "progress": 2})
two = {
        "id": unique_id,
        'title' :  'Deep Learning',
        'description' : 'Implementing exchange rate prediction using different regression models and choosing the best from them',
        'date' : "2023-04-01",
        'duration' : '8',
        'deadline' : "2023-04-10",
        'type' : 'Personal',
        "progress": 2,
        "quote": quote2
}
collection.insert_one(one)
collection.insert_one(two)

printf(collection)

def fetch():
    data = []
    printf(collection.find())
    blocks = collection.find()

    data = []
    for block in blocks:
        data.append(block)
    printf(data)
    json_data = parse_json(data)

    # Print the JSON string
    print(json_data)
    return {"data":json_data}

@app.route("/")
def route():
    return "Hello World!"

@app.route("/api/clearall")
def clear():
    collection.delete_many({})
    return "Cleared all"

@app.route("/api/create", methods=["POST", "GET"])
def create():
    data = request.json
    unique_id = str(uuid.uuid4())
    #deadline = datetime.strptime(data["deadline"], "%Y-%m-%d")
    try:
        my_data = {
                        "id": unique_id,
                        "title": data.get('title'),
                        "description": data.get('description'),
                        "duration": data.get('duration'),
                        "date": str("2023-04-01"),
                        "deadline": data.get('deadline'),
                        "type": data.get('type'),
                        "progress": 0
                    }
        quote = generate_quote(my_data)
        my_data = {
                        "id": unique_id,
                        "title": data.get('title'),
                        "description": data.get('description'),
                        "duration": data.get('duration'),
                        #"date": str(datetime.today().replace(microsecond=0)),
                        "date": str("2023-04-01"),
                        "deadline": data.get('deadline'),
                        "type": data.get('type'),
                        "progress": 0,
                        "quote": quote
                    }

        collection.insert_one(my_data)
        x = parse_json({"data": my_data})

        return x

    except Exception as e:
        printf(e)
        return ({"Exception": "ERRROROROROROROROOR" + e})

@app.route("/api/read", methods=["POST", "GET"])
def read():
    data = []
    printf(collection.find())
    blocks = collection.find()

    data = []
    for block in blocks:
        data.append(block)
    printf(data)
    json_data = parse_json(data)

    # Print the JSON string
    print(json_data)
    return {"data":json_data}

@app.route("/api/update", methods=["POST", "GET"])
def update():
    data = request.json
    blocks = collection.find()

    old_data = []
    quote = ""
    for block in blocks:
        old_data.append(block)
    if old_data["progress"] != data["progress"]:
        quote = generate_quote(data)

    my_query = {
        "id": data["id"]}

    new_values = {"$set": {
        "title": data.get('title'),
        "description": data.get("description"),
        "duration": data.get("duration"),
        "date": data.get("date"),
        "deadline": data.get("deadline"),
        "type": data.get("type"),
        "progress": data.get("progress"),
        "quote": quote
    }}
    collection.update_one(my_query, new_values)
    return {"data": new_values}

@app.route("/api/delete", methods=["POST", "GET"])
def delete():
    data = request.json
    my_query = {"id": data["id"]}
    collection.delete_one(my_query)
    return "Data deleted successfully!"

@app.route("/api/optimize")
def optimize():
    d = fetch()
    data = fetch()["data"]
    #printf(type(data))
    events = [
        {"id": 1, "title": "Event A", "duration": 2, "deadline": "2023-04-10"},
        {"id": 2, "title": "Event B", "duration": 3, "deadline": "2023-04-05"},
        {"id": 3, "title": "Event C", "duration": 1, "deadline": "2023-04-07"},
        {"id": 4, "title": "Event D", "duration": 2, "deadline": "2023-04-12"},
        {"id": 5, "title": "Event E", "duration": 1, "deadline": "2023-04-09"}
    ]
    events = []

    for i in data:
        #printf(data)
        events.append(data)
    printf("FUCKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK\n")
    printf(events)
    # Step 1: Sort the events by deadline
    events_list = list(itertools.chain.from_iterable(events))
    printf(events_list)
    events = sorted(events_list, key=lambda x: x["deadline"])

    # Step 2: Assign priority scores to each event based on deadline
    for i, event in enumerate(events):
        event["priority"] = i

    # Step 3: Initialize the scheduling queue with all events
    scheduling_queue = events.copy()

    # Step 4: Schedule events based on priority score
    current_time = datetime.strptime("2023-04-01", "%Y-%m-%d")  # Set initial time as a datetime object
    while scheduling_queue:
        # Select the event with the highest priority score
        next_event = max(scheduling_queue, key=lambda x: x["priority"])
        # Convert the deadline string to a datetime object
        deadline = datetime.strptime(next_event["deadline"], "%Y-%m-%d")
        # Check if there is enough time to complete the event before the deadline
        if current_time + timedelta(days=int(next_event["duration"])) <= deadline:
            # Assign the event to the current time slot
            next_event["start_time"] = current_time
            current_time += timedelta(days=int(next_event["duration"]))
            # Remove the event from the scheduling queue
            scheduling_queue.remove(next_event)
        else:
            # Remove the event from the scheduling queue if there isn't enough time
            scheduling_queue.remove(next_event)

    # Print the scheduled events
    for event in events:
        print(event)
    return {"sorted data": events}
    return d

if __name__ == "__main__":
    app.run(host="localhost", port=5000, debug=True)


import time
import sys

class CodeTimer:
    def __init__(self):
        self.start = None

    def __enter__(self):
        self.start = time.time()  # засекли наше время (точка старта)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        t = time.time() - self.start  # остановили таймер (точка стопа)
        print(f'Код работал {t} сек.')
        return True

timer = CodeTimer()

with timer as t:
    # # l = [x for x in range(100_000_000)]
    # l = [1, 2, 3]
    # l[5]
    print(t)
    print(1)

# class ThreadRedirect:
#     def __init__(self):
#         self.stdout = sys.stdout
#
#     def __enter__(self):
#         sys.stdout = open('file.txt', 'w', encoding='utf-8')
#
#     def __exit__(self, exc_type, exc_val, exc_tb):
#         sys.stdout = self.stdout
#
#
# with ThreadRedirect():
#     print("Hello, world!")
#
# print("Hello, world!")


import streamlit as st
from PIL import Image
import cv2
import numpy as np
from tensorflow.keras.models import load_model

def prepare_image(img):
    img_size = 64
    image = img.resize((img_size, img_size))
    image = np.array(image).reshape(1, 64, 64, 3)
    return image

@st.cache
def load_image(image_file):
    img = Image.open(image_file)
    return img

def main():
    st.write('''

    Clasificación de Números realizados con la Mano

''', unsafe_allow_html=True)

    menu = ["Sobre la App", "Cargar Imagen", "Cámara"]
    st.sidebar.write('''

Bienvenido

''', unsafe_allow_html=True)
    choice = st.sidebar.selectbox("Selecciona una opción", menu)

    col1, col2 = st.beta_columns(2)

    if choice == "Cargar Imagen":
        col1.write('''

Aquí se muestra la Imagen

''', unsafe_allow_html=True)

        #st.sidebar.title('Cargar Imagen')
        image_file = st.sidebar.file_uploader("", type=['jpg', 'jpeg'])

        if image_file is not None:
            #st.write(type(image_file))
            # st.write(dir(image_file))
            file_details = {"filename":image_file.name, "filetype":image_file.type, "filesize":image_file.size}
            #st.write(file_details)

            img = load_image(image_file)
            col1.image(img, width=250)

            data = prepare_image(img)

            col2.write('''

''', unsafe_allow_html=True)

            if col2.button('Clasificar', key="1"):
                prediction = model.predict([data])
                #print(prediction)
                col2.write("El número en la imagen corresponde a {}".format((prediction[0].tolist()).index(max(prediction[0].tolist()))))
    elif choice == "Cámara":
        st.sidebar.write("")
        col1.write('''

Cámara Activa

''', unsafe_allow_html=True)
        FRAME_WINDOW = col1.image([])
        camera = cv2.VideoCapture(0) # 0 corresponde al índice de la cámara

        col2.write('''

''', unsafe_allow_html=True)
        capture = col2.button('Tomar Foto', key="2")
        col2.write("")

        while choice == 'Cámara':
            _, frame = camera.read()
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            FRAME_WINDOW.image(frame)
            if capture:
                image = cv2.resize(frame, (64, 64))
                data = image.reshape(1, 64, 64, 3)
                prediction = model.predict([data])
                #print(prediction)
                col2.write("El número en la imagen corresponde a {}".format((prediction[0].tolist()).index(max(prediction[0].tolist()))))
                capture = False
    else:
        col1.write('''

Sobre la App

                        Esta es una aplicación de Computer Vision que tiene como objetivo la clasificación de
                        imágenes de números realizados con la mano, desde cero (0) hasta cinco (5).

''',unsafe_allow_html=True)
        col2.write('''

Cargar Imagen

                        En esta opción, se carga la imagen que se desea clasificar; luego, se presiona
                        el botón de clasificar y la aplicación imprime el resultado.

Cámara

                        En esta opción, se toma la captura de la imagen que se desea clasificar
                        y la aplicación imprime el resultado.

''', unsafe_allow_html=True)
if __name__ == '__main__':
    model = load_model('Network.model')
    main()


import numpy as np

class SquaredLoss:
    def forward(self, Yhat: np.array, Y: np.array) -> np.ndarray:
        """
        Yhat, Y: shape should be n x N
        return L: the sfloat
        """

        assert (
            Yhat.shape[0] == Y.shape[0] and Yhat.shape[1] == Y.shape[1]
        ), "forward: Yhat, Y shape mismatch"

        # reduction : sum
        # Loss = np.linalg.norm(Yhat - Y, axis=0) ** 2
        # reduction : mean
        Loss = np.square(Yhat - Y)

        Loss = np.mean(Loss)

        return Loss

    def backward(self, Yhat: np.array, Y: np.array) -> np.ndarray:
        """
        Yhat, Y: shape should be n x N
        return dLdY: n x N
        """

        assert (
            Yhat.shape[0] == Y.shape[0] and Yhat.shape[1] == Y.shape[1]
        ), "forward: Yhat, Y shape mismatch"

        dLdY = Yhat - Y

        return dLdY


#!/usr/bin/python3
"""
Schools AIP action
"""
from app.models import storage
from app.api.v1.views import app_views
from app.models.certificate import Certificate
from app.models.certificate_request_verification import VerifyCertificate
from flask import abort, jsonify, make_response, request

@app_views.route('/certificate', methods=['GET'], strict_slashes=False)
def get_certificate():
    """
    Retrieves the list of all certificate objects
    or a specific certificate
    """
    all_certificates = storage.all(Certificate).values()
    list_certificates = []
    for certificate in all_certificates:
        list_certificates.append(certificate.to_dict())
    return jsonify(list_certificates)

@app_views.route('/users/<user_id>/certificate', methods=['GET'], strict_slashes=False)
def get_user_certificate(user_id):
    """
    Retrieves the list of all certificate objects
    for a specific user
    """
    all_certificates = storage.get_user_certificates(Certificate, user_id)
    if not all_certificates:
        abort(404, "No certificate was found")
    list_certificates = []
    for certificate in all_certificates:
        certificate_verification_status = storage.get_certificates_status(VerifyCertificate, certificate.id)
        certificate_data = certificate.to_dict()
        certificate_data["certificate_status"] = certificate_verification_status.certificate_status
        list_certificates.append(certificate_data)
    return jsonify(list_certificates)

@app_views.route('certificate/<certificate_id>',
                 methods=['GET'], strict_slashes=False)
def get_Certificate(certificate_id):
    """ Retrieves an Certificate """
    certificate = storage.get(Certificate, certificate_id)
    if not certificate:
        abort(404)
    return jsonify(certificate.to_dict())

@app_views.route('/users/<user_id>/certificates/<certificate_id>', methods=['DELETE'],
                 strict_slashes=False)
def delete_Certificate(certificate_id):
    """
    Deletes a certificate Object
    """

    certificate = storage.get(Certificate, certificate_id)

    if not certificate:
        abort(404)

    storage.delete(certificate)
    storage.save()

    return make_response(jsonify({}), 200)

@app_views.route('/users/<user_id>/certificates', methods=['POST'], strict_slashes=False)
def post_certificate(user_id):
    """
    Creates a certificate
    """
    data = request.get_json()
    if not data:
        abort(400, description="Not a JSON")
    if 'student_name' not in data:
        abort(400, description="student_name")
    if 'student_email' not in data:
        abort(400, description="Missing student email")
    if "school_id" not in data:
        abort(400, 'Missing school id')
    if "school_name" not in data:
        abort(400, 'Missing school name')
    if "school_major" not in data:
        abort(400, 'Missing school major')
    if "school_department" not in data:
        abort(400, "Missing school department")
    if "school_location" not in data:
        abort(400, "MIssing school location")

    data['user_id'] = user_id
    instance = Certificate(**data)
    certificate_status = {
        "user_id": user_id,
        "school_id": instance.school_id,
        "certificate_id": instance.id
    }
    status = VerifyCertificate(**certificate_status)
    instance.save()
    status.save()
    certificate = instance.to_dict()
    certificate["certificate_status"] = status.certificate_status
    return make_response(jsonify(certificate), 201)

@app_views.route('/users/<user_id>/certificates/<certificate_id>',
                 methods=['PUT'], strict_slashes=False)
def put_certificate(user_id, certificate_id):
    """
    Updates a certificate
    """
    certificate = storage.get(Certificate, certificate_id)

    if not certificate:
        abort(404)

    if not request.get_json():
        abort(400, description="Not a JSON")

    ignore = ['id', 'email', 'created_at', 'updated_at']

    data = request.get_json()
    for key, value in data.items():
        if key not in ignore:
            setattr(certificate, key, value)
    storage.save()
    return make_response(jsonify(certificate.to_dict()), 200)


import unittest
from unittest.mock import MagicMock
from src.customer import functions

class TestFunctions(unittest.TestCase):
	def setUp(self) -> None:
		self.start_date = "2019-09-20"
		self.end_date = "2019-10-01"

	def test_determine_active_services(self):
		service_1 = MagicMock()
		service_2 = MagicMock()
		service_1.start_date = self.start_date
		service_2.start_date = None
		self.assertEqual([service_1], functions.determine_active_services([service_1, service_2]))
		self.assertEqual([],functions.determine_active_services([service_2, service_2, service_2]))

	def test_calculate_days_difference(self):
		self.assertEqual(11, functions.calculate_days_difference(self.start_date, self.end_date, businessdays=False))
		self.assertNotEqual(12, functions.calculate_days_difference(self.start_date, self.end_date, businessdays=False))
		self.assertEqual(7, functions.calculate_days_difference(self.start_date, self.end_date, businessdays=True))
		self.assertNotEqual(8, functions.calculate_days_difference(self.start_date, self.end_date, businessdays=True))

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


import requests
import json

class StatioN_Status:

    bikes = []
    docks = []

    def getData(self):
        try:
            print("Divvya Bikes Stations ...")
            url = "https://gbfs.divvybikes.com/gbfs/en/station_status.json"
            headers = { 'Accept':'application/json','Content-Type': 'application/x-www-form-urlencoded' }
            response = requests.get(url, headers=headers, timeout=15)

            serialization = response.json()
            print('Response_Code :',response.status_code)

            jsondata = json.dumps(serialization)

            dictdata = json.loads(jsondata)
        except Exception as e:
            self.Log.error("Error get payload")

        return dictdata

    def stationsData(self):
        jsondata = self.getData()
        mainstation = jsondata.get("data")

        stations = mainstation.get("stations")

        print('Stations :',len(stations))

        return stations
    def activeStationsData(self):
        satations = self.stationsData()
        activestationcount = 0
        for i in satations:
            if i.get('station_status') == 'active':
                activestationcount += 1
            self.docks.append(i.get('num_docks_available'))

            self.bikes.append(i.get('num_bikes_available'))
        return activestationcount

    def docksQty(self):
        #print(self.docks)
        return self.docks

    def bikesQty(self):
        #print(self.bikes)
        return self.bikes

s = StatioN_Status()
a = s.activeStationsData()
d = s.docksQty()
print(sum(d))
print(sum(s.bikesQty()))


import sys
import os
#add in auto add to sys path

#print(os.path.isdir("/home/pi/programs/p4/lib/python3.9/site-packages"))
#sys.path.append("/home/pi/programs/p4/lib/python3.9/site-packages")

print(os.listdir("/dev/serial/by-id")[0])
arduino_id="/dev/serial/by-id/"+os.listdir("/dev/serial/by-id")[0]
print(os.path.exists(arduino_id))
working_dir=os.getcwd()
packages_path=working_dir+"/lib/python3.9/site-packages"
sys.path.append(packages_path)
sys.path.append("/usr/lib/python3/dist-packages")
import socket
import select
import cv2
import time
import multiprocessing
from multiprocessing import Process, Value
from multiprocessing.sharedctypes import (
	Synchronized,
)
import numpy as np
import serial
import pygame
from pygame import mixer
import subprocess as sp
import RPi.GPIO as GPIO

def sound_handler(channel_num, volume,sound_effect):
	global sound_names
	if channel_num>2: #channels 0-2
		channel_num=0
	else:
		channel_num+=1

	if sound_effect==sound_names["reload"]:
		channel_num=2
	if (sound_effect==sound_names["kill"]) or (sound_effect==sound_names["dead"]):
		channel_num=3

	mixer.Channel(channel_num).set_volume(volume)
	mixer.Channel(channel_num).play(mixer.Sound(sound_effect))
	print(channel_num, sound_effect)
	return(channel_num)

def serial_process(serial_arr: Synchronized) :#serial function
		#arduino_file=open("arduino_id.txt",'r')
		#arduino_id=arduino_file.readline().split('\n')[0]

		serial_obj=serial.Serial(arduino_id,115200)

		print("starting serial")
		prev_av=0
		changed_from=0
		prev_state=False

		#serial arr[0] is for trigger serial arr[1] is for health serial arr[2] is for reload
		while True:
			s_bytes=serial_obj.readline()
			if (serial_arr[1]!=prev_av):
				changed_from=prev_av
				prev_av=serial_arr[1]
				print("health change:" ,serial_arr[1],prev_av)
			elif(changed_from!=serial_arr[1]):
				encoded_v=str(serial_arr[1]).encode("utf-8")
				serial_obj.write(encoded_v)
			if len(s_bytes)>2:
				if s_bytes[3]==49: #trigger logic
					serial_arr[0]=1
					if not prev_state:
						print("SHOOTING-----")
					prev_state=True
				else:
					serial_arr[0]=0
					prev_state=False

				if s_bytes[2]==49: #reload logic
					print("RELOADING")
					serial_arr[2]=1
				else:
					serial_arr[2]=0

def trigger_handler(switch_state,firing_mode, fire_rate):
	a=time.time()
	global prev_switch_state
	global shot_counter
	global last_shot_time
	return_v=False
	if (1/fire_rate)<=(time.time()-last_shot_time):#fire rate handler
		if firing_mode=='a':#full auto
			if switch_state:
				return_v=True
			else:
				return_v=False
		elif firing_mode=='s':#single fire
			if not prev_switch_state and switch_state:
				return_v=True
			else:
				return_v=False
		elif firing_mode=='b':#burst
			if (not prev_switch_state and switch_state):
				shot_counter=0
			if shot_counter<3:
				shot_counter+=1
				return_v=True
			else:
				return_v=False
		return(return_v)
	return(False) #if nothing return false

def update_crop(camera_index,zoom,x,y):#handles zoom and gets offset from file
	ts=time.time()
	offsetX=0
	offsetY=0
	with open ("campos.txt",'r') as posfile:
		data=posfile.readline().split()
		data+=posfile.readline().split()

		if camera_index==0:
			offsetX=int(data[0])
			offsetY=int(data[1])
		else:
			offsetX=int(data[2])
			offsetY=int(data[3])
	X_MIN=int(x*(1-1/zoom)/2)+offsetX
	Y_MIN=int(y*(1-1/zoom)/2)+offsetY
	X_MAX=X_MIN+int(x/zoom)
	Y_MAX=Y_MIN+int(y/zoom)
	return(X_MIN,X_MAX,Y_MIN,Y_MAX)

def capture_frames(camera_index, window_name,shared_frame):	#opencv image capture method
	cap=cv2.VideoCapture(camera_index)#,cv2.CAP_DSHOW)
	cap.set(cv2.CAP_PROP_BUFFERSIZE,1)
	cap.set(cv2.CAP_PROP_FPS,30)
	X_DIM=640
	Y_DIM=480
	ZOOM_M=2.0
	if camera_index==2:
		ZOOM_M=2.0
		X_DIM=int(640)
		Y_DIM=int(480)
		cap.set(cv2.CAP_PROP_FRAME_WIDTH,X_DIM)
		cap.set(cv2.CAP_PROP_FRAME_HEIGHT,Y_DIM)
	#if camera_index==0:
	#	ZOOM_M=10.0
	#	X_DIM=int(640)
	#	Y_DIM=int(480)
	#	cap.set(cv2.CAP_PROP_FRAME_WIDTH,X_DIM)
	#	cap.set(cv2.CAP_PROP_FRAME_HEIGHT,Y_DIM)
	offsetX=0
	offsetY=0
	with open ("campos.txt",'r') as posfile:
		data=posfile.readline().split()
		data+=posfile.readline().split()
		if camera_index==0:
			offsetX=int(data[0])
			offsetY=int(data[1])
		else:
			offsetX=int(data[2])
			offsetY=int(data[3])
	X_MIN=int(X_DIM*(1-1/ZOOM_M)/2)+offsetX
	Y_MIN=int(Y_DIM*(1-1/ZOOM_M)/2)+offsetY
	X_MAX=X_MIN+int(X_DIM/ZOOM_M)
	Y_MAX=Y_MIN+int(Y_DIM/ZOOM_M)
	X_MIN=160
	X_MAX=480
	Y_MIN=120
	Y_MAX=360
	t1s=time.time()
	X_MIN,X_MAX,Y_MIN,Y_MAX=update_crop(camera_index,ZOOM_M,X_DIM,Y_DIM)
	X_MIN2,X_MAX2,Y_MIN2,Y_MAX2=update_crop(camera_index,10,X_DIM,Y_DIM)
	t_l=time.time()
	while True:
		if (time.time()-t1s)>1:
			t1s=time.time()
			X_MIN,X_MAX,Y_MIN,Y_MAX=update_crop(camera_index,ZOOM_M,X_DIM,Y_DIM)
			X_MIN2,X_MAX2,Y_MIN2,Y_MAX2=update_crop(camera_index,10,X_DIM,Y_DIM)
		t1=time.time()
		ret= cap.grab()
		ret, frame = cap.retrieve()
		if ret:
			dim_frame=frame.shape
			frame_r=frame
			frame=frame[Y_MIN:Y_MAX,X_MIN:X_MAX]
			frame2=frame_r[Y_MIN2:Y_MAX2,X_MIN2:X_MAX2]
			#if camera_index==2:
			frame=cv2.resize(frame,(320,240))
			frame2=cv2.resize(frame2,(320,240))
			shared_frame["im2"]=frame2
			#if camera_index==0:
			#	frame=cv2.resize(frame,(320,240))
			#	shared_frame["im2"]=frame2
			shared_frame["im"]=frame
		#time.sleep(0.01)
		if (time.time()-t_l)>2:
			print(camera_index, ": ",1/(time.time()-t1))
			t_l=time.time()
	cap.release()

def ffmpeg_capture(camera_index, window_name,shared_frame):
	command = [# Start the ffmpeg process
			'ffmpeg',
			# Input device
			'-loglevel','error',
			'-input_format','mjpeg',
			'-video_size','640x480',
			'-i', f'/dev/video{camera_index}',
			'-vf', 'fps=30', #'30',  # Filter for 1 frame per second
			'-pix_fmt', 'bgr24',  # Pixel format for OpenCV
			'-f','rawvideo','-',
			#'-vcodec', 'rawvideo', '-an', '-',  # Output encoding and destination
	]

	size=[480,640]#set paramters for crop
	X_DIM=size[1]
	Y_DIM=size[0]
	ZOOM_M=2.0

	time_update_crop=time.time()
	print_time=time.time()
	t_loop=time.time()

	X_MIN,X_MAX,Y_MIN,Y_MAX=update_crop(camera_index,ZOOM_M,X_DIM,Y_DIM)#set crop
	global using_double
	if using_double:
		ZOOM_M2=10.0
		X_MIN2,X_MAX2,Y_MIN2,Y_MAX2=update_crop(camera_index,ZOOM_M2,X_DIM,Y_DIM)

	with sp.Popen(command, stdout=sp.PIPE, bufsize=10**5) as pipe:
		while True:
			if (time.time()-time_update_crop)>1:#update crop values each second
				X_MIN,X_MAX,Y_MIN,Y_MAX=update_crop(camera_index,ZOOM_M,X_DIM,Y_DIM)
				if using_double:
					X_MIN2,X_MAX2,Y_MIN2,Y_MAX2=update_crop(camera_index,ZOOM_M2,X_DIM,Y_DIM)
				time_update_crop=time.time()

			raw_image = pipe.stdout.read(size[0]*size[1]*3)# Read one frame's worth of data\
			pipe.stdout.flush()# Clear the buffer to prevent overflow

			frame =  np.frombuffer(raw_image, dtype='uint8')#turn image from bytes to array
			frame_o = frame.reshape((size[0],size[1], 3))	#reshape image

			frame=frame_o[Y_MIN:Y_MAX,X_MIN:X_MAX]	#crop the image
			shared_frame["im"]=cv2.resize(frame,(320,240))
			if using_double:
				frame2=frame_o[Y_MIN2:Y_MAX2,X_MIN2:X_MAX2]
				shared_frame["im2"]=cv2.resize(frame2,(320,240))

			if (time.time()-print_time)>2:#print frame rate
				print(camera_index, ": ",1/(time.time()-t_loop))
				print_time=time.time()
			t_loop=time.time()

if __name__=="__main__":
	sound_select=0
	sound_names={}
	sound_names["shoot"]="sounds/shoot/"+str(os.listdir("sounds/shoot")[sound_select])
	sound_names["hit"]="sounds/hit/"+str(os.listdir("sounds/hit")[sound_select])
	sound_names["reload"]="sounds/reload/"+str(os.listdir("sounds/reload")[sound_select])
	sound_names["kill"]="sounds/kill/"+str(os.listdir("sounds/kill")[sound_select])
	sound_names["dead"]="sounds/dead/"+str(os.listdir("sounds/dead")[sound_select])
	print(sound_names["kill"],"\n")
	pygame.init()#setup sound
	mixer.init()
	mixer.Channel(3).set_volume(1.0)
	mixer.Channel(3).play(mixer.Sound(sound_names["dead"]))
	chan_num=0 #keeps track of what channel is being used on mixer
	time.sleep(1)
	GPIO.setmode(GPIO.BOARD)
	GPIO.setup(38,GPIO.IN,pull_up_down=GPIO.PUD_UP)

	run_arduino=True#arduino thread
	if run_arduino:
		serial_arr=multiprocessing.Array("i",5)
		cam_arr=multiprocessing.Array("i",5)
		switch_on=False
		prev_switch_state=switch_on
		a_p=Process(target=serial_process, args=(serial_arr,))
		a_p.start()

	a=time.time()	#pre while
	run_main_loop=True
	print_time_m=time.time()
	send_time=time.time()

	failed_conn=False	#start socket
	s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	print("attempting connection to .23")
	s.connect(("192.168.1.3",2345))
	print("connected to",s)

	health=100	#initialize player stats
	prev_health=health
	dead=False
	dead_time=time.time()
	mag_size=10 #shots = + 1
	fire_rate=11
	firing_mode='a' #define firing mode
	mag_count=mag_size
	shot_counter=3	#to initialize burst
	reload_dur=3.7
	reload_time=time.time()
	reload_playing=False
	reload_sound_playing=False
	last_shot_time=time.time()
	shoot_override=False

	manager=multiprocessing.Manager()	#make sharing dicts for iamges
	shared_1=manager.dict()
	shared_2=manager.dict()
	shared_1["im"]=[]
	shared_1["im2"]=[]
	shared_2["im"]=[]
	shared_2["im2"]=[]

	cam_setttings_file_name="camsettings.txt"
	cam_setttings_file=open(cam_setttings_file_name,"r")
	cam_settings=cam_setttings_file.readline()
	print("CAM SETTINGS: ",cam_settings)
	cam_setttings_file.close()
	cam2_on=True
	cam1_on=True
	using_double=False
	if cam_settings[0]=='f':
		using_double=True
		cam2_on=False
		pass
	elif cam_settings[0]=='c':
		pass
	elif cam_settings[0]=='b':
		pass
	cam2_thread=multiprocessing.Process(target=capture_frames, args=(2,"cam2",shared_2,))
    #cam1_thread=multiprocessing.Process(target=capture_frames, args=(0,"cam1",shared_1,))
	cam1_ffthread=multiprocessing.Process(target=ffmpeg_capture,args=(0,"cam1",shared_1,))

	if cam2_on:
		cam2_thread.start()	#start cameras
		print("cam_thread2 started")
		time.sleep(2)
	if cam1_on:
		cam1_ffthread.start()
		print("cam_thread1 started")
		time.sleep(1)

	print("starting main")
	while (run_main_loop):
		if (time.time()-print_time_m)>1:#print out player info
			print("health: ",health,"loop: ",time.time()-a,"send: ",send_time) #" image capture time: ",t3-t2,t4-t2)	#time printing
			try:
				print("T: ",t_bottom_while_loop-t_before_player_logic,t_before_recieve-t_before_player_logic,t_before_send-t_before_recieve,t_bottom_while_loop-t_before_send)
			except:
				pass
			print_time_m=time.time()

		t_before_player_logic=time.time()
		if health<=0:#check if dead
			dead=True
			mag_count=mag_size
		else:
			dead=False
		prev_switch_state=switch_on
		if (not (GPIO.input(38)))or(serial_arr[0]==1):	#switch on or off
			switch_on=True
		else:
			switch_on=False
		t2=time.time()
		if not dead:
			shoot_or_no=(trigger_handler(switch_on,firing_mode,fire_rate))	#transfer block and firing mode handler
			if shoot_or_no:
				if mag_count>0:
					last_shot_time=time.time()
					sound_handler(chan_num,1.5,sound_names["shoot"])

			if shoot_override:	#if remote shooting
				shoot_or_no=True
				shoot_override=False
			if mag_count>0:#check if mag empty
				if shoot_or_no:
					mag_count-=1
			else: #blanks
				reload_playing=True
				shoot_or_no=0

			if serial_arr[2]:	#if reload start reloading
				reload_playing=True
				serial_arr[2]=0

			if not reload_playing:	#reload control logic
				reload_time=time.time()
			else:
				if not reload_sound_playing and (time.time()-reload_time)>0.4:
					sound_handler(7,1.3,sound_names["reload"])
					reload_sound_playing=True
				shoot_or_no=False
				if((time.time()-reload_time)>reload_dur):
					mag_count=mag_size
					reload_playing=False
					reload_sound_playing=False
		else:#if dead dont shoot
			shoot_or_no=False

		t_before_recieve=time.time()
		ready=select.select([s],[],[],0.005)	#recieve data start
		if ready[0]:
			in_data=s.recv(1024).decode("utf-8")	#get data
			index_s=0
			string_arr=in_data.split(',')	#turn data to array
			try:
				if string_arr[0]=='1':#got a hit
					sound_handler(chan_num+3,1,sound_names["hit"])
				if string_arr[0]=='2':#got a kill
					sound_handler(chan_num+3,1,sound_names["hit"])
					sound_handler(8,1,sound_names["kill"])
				if string_arr[0]=='3':#remote shoot
					shoot_override=True
				if len(string_arr)>1:
					health=int(string_arr[1])#update health
					if health>101:
						health=100
					serial_arr[1]=health#send health to arduino
					if (health<=0) and not dead:
						sound_handler(8,1,sound_names["dead"])#play sound if dead
				if len(string_arr)>2:
					fire_rate=int(string_arr[2])#get fire rate paramter
				if len(string_arr)>3:
					mag_size=int(string_arr[3])#get mag size
					if mag_count>mag_size:
						mag_count=mag_size
				if len(string_arr)>4:
					firing_mode=string_arr[4]#get firing mode
			except:
				pass

		t_before_send=time.time()
		if shoot_or_no:	#send shot logic
			if cam_settings[0]=='f':
				frame=np.concatenate((shared_1["im"],shared_1["im2"]),axis=0)
			else:
				frame=np.concatenate((shared_1["im"],shared_2["im"]),axis=0)	#concatinate frames
			cv2.imwrite("dimg.jpg",frame)
			im_file=open("dimg.jpg",'rb')
			data=im_file.read(1024*5)#read in first packet to be sent
			print("sending data")
			try:
				send_time=time.time()
				while data:#send data for length of image file
					s.send(data)
					data=im_file.read(1024*5)
				im_file.close()
				s.send(b"next")#send b'next' as cutoff term when all data has been sent
				send_time=time.time()-send_time

			except:#if sending fails then try to restart connection
				failed_conn=True
				while failed_conn:
					try:
						s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
						s.connect(("192.168.1.3",2345))
						print("connected to",s)
						failed_conn=False
					except:
						time.sleep(0.5)
						print("conn failed retrying")
						failed_conn=True
				try:
					im_file.close()
				except:
					print("error closing file")
		t_bottom_while_loop=time.time()

	a_p.join()#join arduino after while is finished


def seat_number_type(number):
    """
    Функция определения типа места в плацкартном вагоне

    :param number: Номер места в вагоне
    :type number: int
    :return: Тип места в вагоне
    :rtype: str
    """
    if number < 38:
        if number % 2 == 0:
            return "Купе, нижнее"
        else:
            return "Купе, верхнее"
    elif number <= 54:
        if number % 2 == 0:
            return "Боковое, нижнее"
        else:
            return "Боковое, верхнее"
    return "Место не найдено"

if __name__ == '__main__':
    print(seat_number_type(int(input("Введите номер места в вагоне\n"))))


import streamlit as st
import yfinance as yf
import plotly.graph_objects as go

# Título do App
st.title('Stock History App')
st.sidebar.title('Selecione o stock')

ticker_symbol=st.sidebar.text_input('stock','AAPL',max_chars=10)

# Baixando os dados
data=yf.download(ticker_symbol,start='2020-01-01',end='2023-06-26')

# Exibindo os dados
st.subheader('HIstorico')
st.dataframe(data)

# Plot o grafico
fig=go.Figure()
fig.add_trace(go.Scatter(x=data.index,y= data['Close'],name= 'Fechamento'))
fig.update_layout(title=f"{ticker_symbol}",xaxis_title = "Date", yaxis_title = "Preço")
st.plotly_chart(fig)


#! /usr/bin/python3

# Daniel Quiroga
# March 11, 2019

# Project 4: type.py
""" semantics.py implements a dynamically typed version of a subset of Gee.
This subset makes sure that all variables are first defined with a specific
type and then makes sure that only operations valid for that type are performed"""

import re, sys, string

debug = False

dict = { }

tokens = [ ]

math = ["+", "-", "*", "/"]

bools = ['>','<','<=','>=','==','!=','and','or']

# Class of StatementList: maintain a list of Statement objects

class StatementList( object ):

	def __init__(self):

		self.statementList = [ ]

	def addStatement(self, statement):

		self.statementList.append(statement)

	def __str__(self):

		printStr = ''

		for statement in self.statementList:

			printStr += str(statement)

		return printStr

	def meaning(self, state):

		for section in self.statementList:

			section.meaning(state)

		return state

	def tipe(self, tm):

		for section in self.statementList:

			section.tipe(tm)

		#return tm #used for debugging

# Statement class and subclasses

class Statement( object ):

	def __str__(self):

		return ""

class Assignment( Statement ):

	def __init__(self, identifier, expression):

		self.identifier = identifier

		self.expression = expression

	def __str__(self):

		return "= " + str(self.identifier) + " " + str(self.expression) + "\n"

	def meaning(self, state):

		state[self.identifier] = self.expression.meaning(state)

		return state

	def tipe(self, tm):
		tipe_return = self.expression.tipe(tm)
#make sure something is returned this will also be caught later on as well -- wrote it when i started the project
		if tipe_return == "":

			error("Type Error: variable is never defined!")
# this will make sure that the current variable has not be defined yet and will now have a type associated to it
		if self.identifier not in tm:

			tm[self.identifier] = tipe_return

			type_print(self.identifier, tipe_return) #the actual printing mechanism
		else:

			if tm[self.identifier] != tipe_return: #check to see if it matches the tipes if not return an error

				error("Type Error: " + str(tm[self.identifier]) + " = " + str(tipe_return) + "!")

class WhileStatement( Statement ):

	def __init__(self, expression, block):

		self.expression = expression

		self.block = block

	def __str__(self):

		return "while " + str(self.expression) + "\n" + str(self.block) + "endwhile\n"

	def meaning(self, state):

        #checks if the value of the expression exists, then obtains the value of the block
		while self.expression.meaning(state) == True:

			self.block.meaning(state)

		return state

	def tipe(self, tm):

		tipe_return = self.expression.tipe(tm)
		#in while loops we need the expression to contain a boolean or else the while statement will never enter
		if tipe_return != "boolean":

			error("Type Error: While statement does not contain a boolean expression.")

		#then i just take the block and run it through the type checker to make sure everything is defined and performed properly
		self.block.tipe(tm)

		#return tm

class IfStatement( Statement ):

	def __init__(self, expression, ifBlock, elseBlock):

		self.expression = expression

		self.ifBlock = ifBlock

		self.elseBlock = elseBlock

	def __str__(self):

		return "if " + str(self.expression) + "\n" + str(self.ifBlock) + "else\n" + str(self.elseBlock) + "endif\n"

	def meaning(self, state):

        #checks if the value of the expression exists, then obtains the value of the ifBlock
		if self.expression.meaning(state) == True:

			self.ifBlock.meaning(state)

			return state

        #else: checks if the next block is not empty, then obtains the value of the elseBlock
		elif self.elseBlock is not '':

			self.elseBlock.meaning(state)

			return state

		return state

	def tipe(self, tm):
		tipe_return = self.expression.tipe(tm)

#in for loops we need the expression to contain a boolean or else the while statement will never enter
		if tipe_return != "boolean":

			error("Type Error: If statement does not contain a boolean expression.")

#then i just take the block and run it through the type checker to make sure everything is defined and performed properly
		self.ifBlock.tipe(tm)
#this just checks to see that the elseblock is not empty
		if not(self.elseBlock == ""):

			self.elseBlock.tipe(tm)
		#return tm

# Expression class and subclasses

class Expression( object ):

	def __str__(self):

		return ""

class BinaryExpr( Expression ):

	def __init__(self, op, left, right):

		self.op = op

		self.left = left

		self.right = right

	def __str__(self):

		return str(self.op) + " " + str(self.left) + " " + str(self.right)

	def meaning(self,state):

        #obtains left and right expressions
		left = self.left.meaning(state)

		right = self.right.meaning(state)

        #returns operations on left and right
		if self.op == '+':

			return left + right
		elif self.op == '-':

			return left - right

		elif self.op == '*':

			return left * right

		elif self.op == '/':

			return left / right

        #evaulates relationals for left and right expressions
		elif re.match(Lexer.relational, self.op):

			switcher = {

			">": left > right,

			"<": left < right,

			">=": left >= right,

			"<=:": left <= right,

			"==": left == right,

			"!=": left != right,

			}

			return switcher.get(self.op, "invalid relation")

        #evaluates and & or for left and right expressions
		elif self.op in ["and", "or"]:

			switcher = {

			"and": left and right,

			"or": left or right

			}

			return switcher.get(self.op, "invalid relation")

	def tipe(self, tm):
# this gets the types of both sides of the operation occuring (either boolean operator or math operator)
		right = self.right.tipe(tm)

		left = self.left.tipe(tm)
#if they do not match then this is an error
		if left != right:

			error("Type Error: Operation not possible between two different types.")
#then we just return if the expression is a number or a boolean
		if self.op in bools:#if self.op in bools and left == "boolean" and right == "boolean":

			return "boolean"

		elif self.op in math and left == "number" and right == "number": #elif self.op in math:

			return "number"

class Number( Expression ):

	def __init__(self, value):

		self.number = int(value)

	def __str__(self):

		return str(self.number)

	def meaning(self, state):

        #gets integer value of a number
        #incase its written as a string
		return int(self.number)
#return that the variable is a number type
	def tipe(self, tm):

		return "number"

class VarRef( Expression ):

	def __init__(self, value):

		self.relation = value

	def __str__(self):

		return str(self.relation)

	def meaning(self, state):

        #returns relation as a key in state dictionary
		return state[self.relation]

	def tipe(self, tm):
		#bring up an error if the variable is never defined
		if self.relation not in tm: #not ( self. val in tm):

			error("Type Error: " + str(self.relation) + " is referenced before being defined!")
#this will just return the type of the variable
		return tm[self.relation]

# we do not need to worry about String in type checker
class String( Expression ):

	def __init__(self, value):

		self.string = value

	def __str__(self):

		return str(self.string)

	def meaning(self):

        #returns the string
		return self.string

# Lexer, a private class that represents lists of tokens from a Gee

class Lexer :

	special = r"\(|\)|\[|\]|,|:|;|@|~|;|\$"

	relational = "<=?|>=?|==?|!="

	arithmetic = "\+|\-|\*|/"

	#char = r"'."

	string = r"'[^']*'" + "|" + r'"[^"]*"'

	number = r"\-?\d+(?:\.\d+)?"

	literal = string + "|" + number

	#idStart = r"a-zA-Z"

	#idChar = idStart + r"0-9"

	#identifier = "[" + idStart + "][" + idChar + "]*"

	identifier = "[a-zA-Z]\w*"

	lexRules = literal + "|" + special + "|" + relational + "|" + arithmetic + "|" + identifier

	def __init__( self, text ) :

		self.tokens = re.findall( Lexer.lexRules, text )

		self.position = 0

		self.indent = [ 0 ]

	def peek( self ) :

		if self.position < len(self.tokens) :

			return self.tokens[ self.position ]

		else :

			return None

	def next( self ) :

		self.position = self.position + 1

		return self.peek( )

	def __str__( self ) :

		return "<Lexer at " + str(self.position) + " in " + str(self.tokens) + ">"

def parse( text ) :

	global tokens

	tokens = Lexer( text )

	stmtlist = parseStmtList( )

	return stmtlist

def state(stateList):
    """state function creates a dictionary for the state
    and calls meaning() and semantic_format() on it"""

    statedict = {} #state dictionary
    state_dict = stateList.meaning(statedict) #calls meaning on dictionary
    semantics_final = semantic_format(state_dict) #calls on semantic to format output
    print(semantics_final) #prints output
    return

def semantic_format(statedict):

    """semantic format function creates {<ident, state>} format for output"""

    final = "" #empty string
    for k, v in statedict.items(): #for each key and its value in state dictionary
        final += ", <" +str(k) + ", " + str(v) + ">" #add ", <key, value>" to string
    final = final[2:] #omits first space and comma
    return "{" + final +"}" #returns string with brackets

def types(stateList):

	typedict = {}
	stateList.tipe(typedict)
	# type_dict = stateList.tipe(typedict)
	# dictionary = types_dictionary(type_dict)
	# print(dictionary)

def types_dictionary(typedict):
	final = "" #empty string
	for k, v in typedict.items(): #for each key and its value in state dictionary
		final += ", <" +str(k) + ", " + str(v) + ">" #add ", <key, value>" to string
	final = final[2:] #omits first space and comma
	print("{" + final + "}")
	return "{" + final +"}" #returns string with brackets

def type_print(ident, tipe):
	if (ident is not "" and ident is not None) and (tipe is not "" and tipe is not None):
		print(ident, tipe)
	else:
		error("Type Error: variable is never defined!")

def parseStmtList(  ):

	""" stmtList =  {  statement  } """

	tok = tokens.peek( )

	statementList = StatementList()

	while tok not in [None ,"~"]: #have to account for undent that signals an end of block

		statement = parseStatement()

		statementList.addStatement(statement)

		tok = tokens.peek()

	return statementList

def parseStatement():

	"""statement = ifStatement |  whileStatement  |  assignment"""

	tok = tokens.peek()

	if debug: print ("Statement: ", tok)

	if tok == "if":

		return parseIfStmt()

	elif tok == "while":

		return parseWhileStmt()

	elif re.match(Lexer.identifier, tok):

		return parseAssignment()

	error("error msg: statement")

	return

def parseAssignment():

	"""assign = ident "=" expression  eoln"""

	identifier = tokens.peek()

	if debug: print ("Assign statement: ", left)

	if tokens.next() != "=":

		error("error msg: assignment")

	tokens.next()

	exp = expression()

	tok = tokens.peek()

	if tok != ";":

		error("error msg: assignment")

	tokens.next()

	return Assignment(identifier, exp)

def parseIfStmt():

	"""ifStatement = "if" expression block   [ "else" block ] """

	tok = tokens.next()

	if debug: print ("If statement: ", tok)

	expr = expression()

	ifBlock = parseBlock()

	elseBlock = ''

	if tokens.peek() == "else":

		tok = tokens.next()

		if debug: print ("Else statement: ", tok)

		elseBlock = parseBlock()

	return IfStatement(expr, ifBlock, elseBlock)

def parseWhileStmt():

	"""whileStatement = "while"  expression  block"""

	tok = tokens.next()

	if debug: print ("While statement: ", tok)

	expr = expression()

	block = parseBlock()

	return WhileStatement(expr, block)

def parseBlock():

	"""block = ":" eoln indent stmtList undent"""

	tok = tokens.peek()

	if debug: print ("Block: ", tok)

	# Check to make sure each of the appropriate terminal tokens exist and are in the right place

	if tok != ":":

		error("error msg: block")

	tok = tokens.next()

	if tok != ";":

		error("error msg: block")

	tok = tokens.next()

	if tok != "@":

		error("error msg: block")

	tok = tokens.next()

	stmtList = parseStmtList()

	if tokens.peek() != "~":

		error("error msg: block")

	tokens.next()

	return stmtList

def expression():

	"""expression = andExpr { "or" andExpr }"""

	tok = tokens.peek( )

	if debug: print ("expression: ", tok)

	left = andExpr( )

	tok = tokens.peek( )

	while tok == "or":

		tokens.next()

		right = andExpr( )

		left = BinaryExpr(tok, left, right)

		tok = tokens.peek( )

	return left

def andExpr():

	"""andExpr    = relationalExpr { "and" relationalExpr }"""

	tok = tokens.peek( )

	if debug: print ("andExpr: ", tok)

	left = relationalExpr( )

	tok = tokens.peek( )

	while tok == "and":

		tokens.next()

		right = relationalExpr( )

		left = BinaryExpr(tok, left, right)

		tok = tokens.peek( )

	return left

def relationalExpr():

	"""relationalExpr = addExpr [ relation addExpr ]"""

	tok = tokens.peek( )

	if debug: print ("relationalExpr: ", tok)

	left = addExpr( )

	tok = tokens.peek( )

	while re.match(Lexer.relational, tok):

		tokens.next()

		right = addExpr( )

		left = BinaryExpr(tok, left, right)

		tok = tokens.peek( )

	return left

def addExpr( ):

	""" addExpr    = term { ('+' | '-') term } """

	tok = tokens.peek( )

	if debug: print ("addExpr: ", tok)

	left = term( )

	tok = tokens.peek( )

	while tok == "+" or tok == "-":

		tokens.next()

		right = term( )

		left = BinaryExpr(tok, left, right)

		tok = tokens.peek( )

	return left

def term( ):

	""" term    = factor { ('*' | '/') factor } """

	tok = tokens.peek( )

	if debug: print ("Term: ", tok)

	left = factor( )

	tok = tokens.peek( )

	while tok == "*" or tok == "/":

		tokens.next()

		right = factor( )

		left = BinaryExpr(tok, left, right)

		tok = tokens.peek( )

	return left

def factor( ):

	"""factor  = number | string | ident |  "(" expression ")" """

	tok = tokens.peek( )

	if debug: print ("Factor: ", tok)

	if re.match(Lexer.number, tok):

		expr = Number(tok)
		tokens.next( )

		return expr

	elif re.match(Lexer.string, tok):

		expr = String(tok)

		tokens.next()

		return expr

	elif re.match(Lexer.identifier, tok):

		expr = VarRef(tok)

		tokens.next()

		return expr

	if tok == "(":

		tokens.next( )  # or match( tok )

		expr = expression( )

		tokens.peek( )

		tok = match(")")

		return expr

	error("error msg: factor()")

	return

def match(matchtok):

	tok = tokens.peek( )

	if (tok != matchtok): error("error msg: match()")

	tokens.next( )

	return tok

def error( msg ):

	sys.exit(msg)

def mklines(filename):

	inn = open(filename, "r")

	lines = [ ]

	pos = [0]

	ct = 0

	file = ""

	for line in inn:

		file += line

		ct += 1

		line = line.rstrip( )+";"

		line = delComment(line)

		if len(line) == 0 or line == ";": continue

		indent = chkIndent(line)
		line = line.lstrip( )

		if indent > pos[-1]:

			pos.append(indent)

			line = '@' + line

		elif indent < pos[-1]:

			while indent < pos[-1]:
				del(pos[-1])

				line = '~' + line

		#print (ct, "\t", line)

		lines.append(line)

	# print len(pos)
	undent = ""

	#print(file)

	for i in pos[1:]:

		undent += "~"

	lines.append(undent)

	inn.close()

	return lines

def chkIndent(line):

	ct = 0
	for ch in line:

		if ch != " ": return ct

		ct += 1

	return ct

def delComment(line):

	pos = line.find("#")

	if pos > -1:

		line = line[0:pos]

		line = line.rstrip()

	return line

def main():
	global debug

	ct = 0

	for opt in sys.argv[1:]:

		if opt[0] != "-": break

		ct = ct + 1

		if opt == "-d": debug = True

	if len(sys.argv) < 2+ct:

		print ("Usage:  %s filename" % sys.argv[0])

		return

	original = parse("".join(mklines(sys.argv[1+ct])))

	#state(original)
	types(original)
 #calls state on parsed grammar
	return

main()


from wordcloud import WordCloud, STOPWORDS
import numpy as npy
import random as random
from PIL import Image

def randomize(str):
    str = str.split(' ')
    random.shuffle(str)
    str = ' '.join(str)
    return str

dataset = open("alt.txt", "r").read()
dataset = randomize(dataset)
maskArray = npy.array(Image.open("india.jpg"))
customstopwords = {'in', 'on', 'as', 'from', 'video', 'viral', 'shared', 'claim', 'fake', 'image', 'old', 'new', 'false', 'falsely'}
customstopwords |= STOPWORDS
cloud = WordCloud(background_color = "white", width = 800, height = 400, mask = maskArray, max_words = 200, stopwords = set(customstopwords))
cloud.generate(dataset)
cloud.to_file("wordcloud-india.png")


import datetime
import random
from typing import List, NamedTuple

from dim_mafii.domain.config import DATE_FORMAT
from dim_mafii.domain.model import Player, House, Game
from dim_mafii.domain.types import ClassicRole, GameResult, AdvancedGameResult
from dim_mafii.adapters.orm import SqlAlchemyUnitOfWork
from dim_mafii.tests.fakes import FakeUnitOfWorkManager
from dim_mafii.domain import model

TEST_VALUE_FOR_DATE = '01_01_1999'

def get_int_or_zero_from_str(value: str) -> int:
    result = 0
    try:
        result = int(value)
    except ValueError:
        ...
    finally:
        return result

# This is default players to test some basic logic
DEFAULT_PLAYERS = [
    Player(
        nickname="Zlo",
        name="Irka",
        club="ZloMafiaClub"
    ),
    Player(
        nickname="Nicolleta",
        name="Nicolleta",
        club="ZloMafiaClub"
    ),
    Player(
        nickname="Ништяк",
        name="Stas",
        club="ZloMafiaClub"
    ),
    Player(
        nickname="Червона",
        name="Червона",
        club="ZloMafiaClub"
    ),
    Player(
        nickname="Британка",
        name="Nastya",
        club="ZloMafiaClub"
    ),
    Player(
        nickname="Дюймовочка",
        name="Dima",
        club="ZloMafiaClub"
    ),
    Player(
        nickname="Mana",
        name="Marina",
        club="ZloMafiaClub"
    ),
    Player(
        nickname="BurryBuster",
        name="Lubomur",
        club="ZloMafiaClub"
    ),
    Player(
        nickname="Джентльмен",
        name="Den",
        club="ZloMafiaClub"
    ),
    Player(
        nickname="De Marko",
        name="Ostap",
        club="ZloMafiaClub"
    )
]

def generate_ten_slots_for_game(game_id, randomize_roles=False) -> List[House]:
    """
    Use default players to generate slots for game
    """
    houses: List[House] = []
    for i, player in enumerate(DEFAULT_PLAYERS, start=1):
        houses.append(
            House(
                player_id=player.player_id,
                role=ClassicRole.citizen.value,
                game_id=game_id,
                slot=i,
                house_id=f'{i}_house_id_test',
                fouls=0,
                bonus_mark=0.0
            )
        )
    # first number will be sheriff
    # second -> don
    # third and fourth will be mafia
    # This 4 roles will be updated on slots based on number
    if randomize_roles:
        roles = random.sample(range(1, 11), k=4)
        houses[roles[0]].role = ClassicRole.sheriff.value
        houses[roles[1]].role = ClassicRole.don.value
        houses[roles[2]].role = ClassicRole.mafia.value
        houses[roles[3]].role = ClassicRole.mafia.value
    else:
        houses[0].role = ClassicRole.sheriff.value
        houses[1].role = ClassicRole.don.value
        houses[2].role = ClassicRole.mafia.value
        houses[3].role = ClassicRole.mafia.value

    return houses

def prepare_game(
    uow: FakeUnitOfWorkManager,
    date=None,
    heading_player=None,
    game_id=None,
    table=0,
    club="ZloMafiaClub",
    result=GameResult.unfinished
) -> Game:

    if heading_player is None:
        heading_player = Player(nickname="Nata", name="Katya", club="ZloMafiaClub")
        uow.sess.players.add(heading_player)

    game = Game(
        date=date if date else datetime.datetime.utcnow(),
        game_id=game_id if game_id is not None else 'test_game_id_0',
        heading=heading_player.player_id,
        club=club,
        result=result.value,
        table=table,
        tournament=None,
        advance_result=AdvancedGameResult.guessing_game.value
    )

    uow.sess.games.add(game)
    return game

def get_house_mapper(game_id, tx: SqlAlchemyUnitOfWork):
    houses = tx.houses.get_by_game_id(game_id)
    return {house.slot: house.house_id for house in houses}

def get_result_game(matrix):
    if matrix[1][9]:
        result = 2
    elif matrix[0][9]:
        result = 1
    else:
        result = 0

    advance_result = 0
    if result == 2:
        if matrix[4][7]:
            advance_result = 1
        elif matrix[4][8]:
            advance_result = 2
        else:
            advance_result = 3
    elif result == 1:
        if matrix[4][10]:
            advance_result = 4
        else:
            advance_result = 5

    return result, advance_result

def get_excepted_models(matrix, tx: SqlAlchemyUnitOfWork):

    game_id = matrix[6][2]

    # Game model
    res, advance_res = get_result_game(matrix)
    heading = tx.players.get_by_nickname(matrix[1][2].lower().strip())
    game = model.Game(
        game_id=game_id,
        date=datetime.datetime.strptime(TEST_VALUE_FOR_DATE, DATE_FORMAT),
        result=res,
        club=matrix[3][2],
        table=get_int_or_zero_from_str(matrix[4][5]),
        tournament=matrix[4][2] or None,
        heading=heading.player_id,
        advance_result=advance_res
    )

    # House models
    players = [tx.players.get_by_nickname(row[2].strip().lower()) for row in matrix[10:20]]
    players_mapper = {player.nickname.lower().strip(): player.player_id for player in players}
    role_mapper = {'': 0, 'М': 1, 'Ш': 2, 'Д': 3}
    houses = [
        model.House(
            game_id=game_id,
            house_id='',
            player_id=players_mapper.get(row[2].strip().lower()),
            role=ClassicRole(role_mapper.get(row[0])).value,
            slot=index,
            bonus_mark=float(row[7]) if row[7] else 0.0,
            fouls=len(row[3] + row[4] + row[5] + row[6])
        )
        for index, row in enumerate(matrix[10:20], start=1)
    ]

    # House mapper
    houses_from_db = tx.houses.get_by_game_id(game_id)
    house_mapper = {house.slot: house.house_id for house in houses_from_db}

    # Kills models
    kills = [
        model.Kills(
            game_id=game_id,
            kill_id='',
            killed_house_id=house_mapper.get(get_int_or_zero_from_str(slot)),
            circle_number=day
        )
        for day, slot in enumerate(matrix[33][2:11], start=1)
        if slot.isdigit()
    ]

    # Voted models
    votes = [
        model.Voted(
            game_id=game_id,
            voted_id='',
            house_id=house_mapper.get(get_int_or_zero_from_str(slot)),
            day=day
        )
        for day, slot in enumerate(matrix[44][2:11], start=1)
        if slot.isdigit()
    ]

    # Misses models
    misses = [
        model.Misses(
            game_id=game_id,
            miss_id='',
            house_id=house_mapper.get(get_int_or_zero_from_str(slot)),
            circle_number=day
        )
        for day, slot in enumerate(matrix[34][2:11], start=1)
        if slot.isdigit()
    ]

    best_move = model.BestMove(
        game_id=game_id,
        best_move_id='',
        best_1=house_mapper.get(get_int_or_zero_from_str(matrix[22][2])),
        best_2=house_mapper.get(get_int_or_zero_from_str(matrix[22][3])),
        best_3=house_mapper.get(get_int_or_zero_from_str(matrix[22][4])),
        killed_house=house_mapper.get(get_int_or_zero_from_str(matrix[22][1])),
    )

    don_checks = [
        model.DonChecks(
            game_id=game_id,
            don_check_id='',
            circle_number=day,
            checked_house_id=house_mapper.get(get_int_or_zero_from_str(slot))
        )
        for day, slot in enumerate(matrix[40][2:11], start=1)
        if slot.isdigit()
    ]

    hand_of_mafia = model.HandOfMafia(
        game_id=game_id,
        hand_of_mafia_id='',
        house_hand_id=house_mapper.get(get_int_or_zero_from_str(matrix[6][8])),
        victim_id=house_mapper.get(get_int_or_zero_from_str(matrix[6][9]))
    )

    disqualifieds = [
        model.Disqualified(
            game_id=game_id,
            disqualified_id='',
            house=house_mapper.get(get_int_or_zero_from_str(slot))
        )
        for slot in matrix[21][7:]
        if slot.isdigit()
    ]

    sheriff_checks = [
        model.SheriffChecks(
            game_id=game_id,
            sheriff_check_id='',
            checked_house_id=house_mapper.get(get_int_or_zero_from_str(slot)),
            circle_number=day
        )
        for day, slot in enumerate(matrix[37][2:], start=1)
        if slot.isdigit()
    ]

    sheriff_versions = [
        model.SheriffVersion(
            game_id=game_id,
            sheriff_version_id='',
            house=house_mapper.get(get_int_or_zero_from_str(slot))
        )
        for slot in matrix[22][7:]
        if slot.isdigit()
    ]

    nominated_for_best = [
        model.NominatedForBest(
            game_id=game_id,
            nominated_for_best_id='',
            house=house_mapper.get(get_int_or_zero_from_str(slot))
        )
        for slot in matrix[24][2:]
        if slot.isdigit()
    ]

    bonus_from_players = [
        model.BonusFromPlayers(
            game_id=game_id,
            bonus_id='',
            bonus_from=house_mapper.get(slot),
            bonus_to=house_mapper.get(get_int_or_zero_from_str(row[8]))
        )
        for slot, row in enumerate(matrix[10:20], start=1)
        if row[8].isdigit()
    ]

    bonus_tolerant_from_players = [
        model.BonusTolerantFromPlayers(
            game_id=game_id,
            bonus_id='',
            house_from_id=house_mapper.get(slot),
            house_to_id=house_mapper.get(get_int_or_zero_from_str(row[9]))
        )
        for slot, row in enumerate(matrix[10:20], start=1)
        if row[9].isdigit()
    ]

    class ExceptedModels(NamedTuple):
        game: model.Game
        houses: List[model.House]
        kills: List[model.Kills]
        votes: List[model.Voted]
        misses: List[model.Misses]
        best_move: model.BestMove
        don_checks: List[model.DonChecks]
        hand_of_mafia: model.HandOfMafia
        disqualifieds: List[model.Disqualified]
        sheriff_checks: List[model.SheriffChecks]
        sheriff_versions: List[model.SheriffVersion]
        nominated_for_best: List[model.NominatedForBest]
        bonus_from_players: List[model.BonusFromPlayers]
        bonus_tolerant_from_players: List[model.BonusTolerantFromPlayers]

    return ExceptedModels(
        game,
        houses,
        kills,
        votes,
        misses,
        best_move,
        don_checks,
        hand_of_mafia,
        disqualifieds,
        sheriff_checks,
        sheriff_versions,
        nominated_for_best,
        bonus_from_players,
        bonus_tolerant_from_players
    )


from math import floor, log

for T in range(1, int(input()) + 1):
    B, M = map(int, input().strip().split())
    if 2 ** (B - 2) < M:
        print('Case #{}: IMPOSSIBLE'.format(T))
    else:
        print('Case #{}: POSSIBLE'.format(T))
        A = [[0] * B for _ in range(B)]
        for i in range(B):
            for j in range(i+1, B):
                A[i][j] = 1
        N = 2 ** (B - 2) - M
        while N:
            x = floor(log(N, 2))
            A[0][B - (x + 1)] = 0
            N -= 2 ** x
        # d = floor(log(M, 2))
        # A = [[0] * B for _ in range(B)]
        # dp = d + 2
        # for i in range(dp):
        #     for j in range(i+1, dp):
        #         A[i][j] = 1
        # M -= 2 ** d
        # i = dp
        # while M:
        #     print('M', M)
        #     print('i', i)
        #     x = floor(log(M, 2))
        #     A[0][i] = 1
        #     A[i][d - x] = 1
        #     M -= 2 ** x
        #     i += 1
        # for i in range(B):
        #     A[i][B-1], A[i][dp - 1] = A[i][dp - 1], A[i][B-1]
        print('\n'.join(' '.join(map(str, x)) for x in A))


from pathlib import Path

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

scoresheet = pd.read_csv(Path(__file__).parent / "all_subjects_results.txt", sep="\t")
df = (
    scoresheet.groupby("question_idx")[
        ["gpt4_correct", "gpt4cot_correct", "smartgpt_correct"]
    ]
    .mean()
    .melt()
)
df["value"] *= 100

# Make the plot larger
plt.figure(figsize=(5, 3.5))

# Plotting all the values as dots
sns.stripplot(x="variable", y="value", data=df, jitter=True, color="black")

# Plotting the mean values with error bars
sns.barplot(
    x="variable", y="value", data=df, ci="sd", capsize=0.2, palette="hls", errwidth=1
)

# Add labels
plt.title("Mean scores for 57-subject testing\n(1 question per subject)")
plt.ylabel("Score (% correct)")
plt.xlabel("Model")
plt.xticks(np.arange(3), ["GPT-4", "GPT-4 CoT", "SmartGPT"])

plt.ylim(df.value.min() - 1, df.value.max() + 1)

plt.tight_layout()
plt.savefig(Path(__file__).parent.parent / "assets/all_subjects.png")


from datetime import datetime, timedelta

from django.core.mail import send_mail
from celery import shared_task

from config import settings
from users.models import User

@shared_task
def send_notification_task(course_title, recipient_list):
    """
    Рассылает письма пользователям об обновлении материалов курса при активной подписке.
    """
    send_mail(
        subject=f'Обновления в курсе {course_title}!',
        message=f'В курсе {course_title} произошли обновления, посетите наш сайт.',
        from_email=settings.EMAIL_HOST_USER,
        recipient_list=recipient_list
    )

@shared_task
def check_user_last_login_task():
    """
    Периодическая задача. Проверяет пользователей по дате последнего входа по паролю
    и если пользователь не заходил более месяца, блокирует его.
    """
    for user in User.objects.all():
        if user.last_login:
            delta = datetime.now() - user.last_login.replace(tzinfo=None)
            if delta > timedelta(days=30):
                user.is_active = False
                user.save()


from network import LoRa
import socket
import time
from machine import SD
from L76GNSS import L76GNSS
from pytrack import Pytrack
import time
import pycom
from machine import Pin

# receive packet from Lopy card, write current GPS coords and LoRa stats in a file, send back a packet containing GPS coords to Lopy card and switch RGB Led color
def lora_cb(lora) :
	global fileOpen
	global toggle
	if (fileOpen) :
		recept = s.recv(64)
		stat = lora.stats()
		coord = l76.coordinates()

		f.write("{} ; {} ; {}\n".format(coord, stat.rssi, stat.snr))
		print("{} - {} - {}".format(coord, stat.rssi, stat.snr))

		# Convert GPS coords from tuple to string then send it by socket
		coordStr = str(coord)
		s.send(coordStr)

		if toggle:
			pycom.rgbled(0x007f00)
			toggle = False
		else:
			pycom.rgbled(0x7f0000)
			toggle = True

# Close file
def pin_handler(arg):
	global fileOpen
	if (fileOpen) :
		f.close()
		print('File closed')
		fileOpen = False

# Init LoRa and socket
lora = LoRa(mode=LoRa.LORA, tx_power = 2, sf = 7, bandwidth=LoRa.BW_500KHZ, coding_rate=LoRa.CODING_4_8, preamble=8, frequency=868000000)
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setblocking(False)

# Init Pytrack card and GPS receiver
time.sleep(2)
py = Pytrack()
l76 = L76GNSS(py, timeout=3)

# Mount SD card and open a file on it
sd = SD()
os.mount(sd, '/sd')
f = open('/sd/gps-record.txt', 'w')
f.write('LoRa test with: tx_power = 2, sf = 7, bandwidth=LoRa.BW_500KHZ, coding_rate=LoRa.CODING_4_8, preamble=8, frequency=868000000\n')

# Send first packet to init comm on the other side
s.send('Pong')
print('Send Pong')

# Init RGB Led and global variables
pycom.heartbeat(False)
pycom.rgbled(0x7f0000)
toggle = True
fileOpen = True

# Init button for closing file purpose
p_in = Pin('P14', mode=Pin.IN, pull = Pin.PULL_UP)

# Call lora_cb function when a packet is received
lora.callback(trigger = LoRa.RX_PACKET_EVENT,  handler = lora_cb)

# Call pin_handler function when button is pressed
p_in.callback(Pin.IRQ_FALLING, pin_handler)


# 틀린 내 답
from collections import deque

def solution(cap, n, deliveries, pickups):
    dist = 0
    dlist, plist = deque(deliveries[::-1]), deque(pickups[::-1])

    while dlist:

        d = 0
        dcnt = 0
        for i in range(len(dlist)):
            d += dlist[i]
            dlist[i] = 0
            dcnt += 1
            if d > cap:
                dlist[i] += d - cap
                d = cap
                dcnt -= 1
                break

        p = 0
        pcnt = 0
        for i in range(len(plist)):
            p += plist[i]
            plist[i] = 0
            pcnt += 1
            if p > cap:
                plist[i] += p - cap
                p = cap
                pcnt -= 1
                break

        dist += len(dlist) * 2

        for _ in range(min(dcnt, pcnt)):
            dlist.popleft()
            plist.popleft()

    return dist

############################
# 정답 풀이 - 그리디
# 그리디로 풀 때 잉여회수량, 잉여배달량이라는 개념으로 생각하여 가감 후 회복할 때까지 cap을 더한다는 아이디어를 배움
#
# dist에 i+1을 곱하는 이유는 인덱스가 거리보다 1 작아서
def solution(cap, n, deliveries, pickups):
    dist = 0
    d, p = 0, 0
    for i in range(n - 1, -1, -1):

        d -= deliveries[i]
        p -= pickups[i]

        cnt = 0
        while d < 0 or p < 0:
            d += cap
            p += cap
            cnt += 1

        dist += (i + 1) * 2 * cnt

    return dist

택배-배달과-수거하기.py