##Television Sets | TCS MockVita 2020
##Difficulty Level : Medium
## Last Updated : 17 Sep, 2020
##Problem Description
##
##Dr. Vishnu is opening a new world-class hospital in a small town designed to be the first preference of the patients in the city. Hospital has N rooms of two types with TV and without TV, with daily rates of R1 and R2 respectively. However, from his experience Dr. Vishnu knows that the number of patients is not constant throughout the year, instead, it follows a pattern. The number of patients on any given day of the year is given by the following formula:
##
##Patients per day = (6 – M)2 + |D – 15|
##where,
##M: the number of month starting from 1 to 12
##D: the date from 1 to 31
##
##All patients prefer without TV rooms as they are cheaper, but will opt for with TV rooms only if without TV rooms are not available. Hospital has a revenue target for the first year of operation. Given this target and the values of N, R1, and R2 you need to identify the number of TVs the hospital should buy so that it meets the revenue target. Assume the Hospital opens on 1st Jan and year is a non-leap year.
##
##Examples:
##
##
##
##Input: N = 20, R1 = 1500, R2 = 1000, target = 7000000
##Output: 14
##Explanation:
##Using the formula:
##The number of patients on 1st Jan will be 39, on 2nd Jan will be 38 and so on.
##Considering there are only twenty rooms and rates of both type of rooms are 1500 and 1000 respectively.
##Therefore, 14 TV sets are needed to get the revenue of 7119500 with 13 TV sets.
##The total revenue will be less than 7000000.
##
##Input: N = 10, R1 = 1000, R2 = 1500, target = 10000000
##Output: 10
##Explanation:
##In the above example, the target will not be achieved, even by equipping all the rooms with TV.
##Hence, the answer is 10 i.e., total number of rooms in the hospital.
##
##Recommended: Please try your approach on {IDE} first, before moving on to the solution.
##Approach: The idea is to traverse through the whole year and generate revenue for each day. Find the revenue for the first year for every possible number of rooms that can have a TV. Follow the below steps to solve the problem:
##
##Suppose the total number of rooms having a TV is tvs, where 0 ≤ tvs ≤ N.
##For each number for TVs, revenue for the first year can be found by traversing through each day.
##The above formula can be used to find the number of patients per day. Suppose np is the current number of patients.
##The current number of patients np can have the value of the number of patients today or the total number of rooms whichever is minimum.
##If the number of patients is less than the number of rooms without TV, then the total revenue for today will be np*R1 because it is cheap.
##Else if the number of patients is greater than the rooms without TV, then the total revenue for today is given by:
##(N – tvs)*R2 + (np – (N – tvs))*R1
##
##Add the revenue for each day in target value and print the maximum target value generated after checking all possible combinations.

def getPatients(M,D):
    return(((6-M)*(6-M))+ abs(D-15))

def countTV(n, r1, r2, target):
    #np, tvs, current_target = 0
    days = [0,31,28,31,30,31,30,31,31,30,31,30,31]

    for tvs in range(n+1):
        current_target = 0
        for m in range(12):
            for d in range(days[m]):
                np = getPatients(m,d)
                np = min(np,n)
                if np <= (n-tvs):
                    current_target += np*r2
                else:
                    current_target += ((n-tvs)*r2 + ((np-(n-tvs))*r1))
        if current_target >= target:
            break
    return (min(tvs,n))

N = 20#10
R1 = 1500#1000
R2 = 1000#1500
Target = 7000000#10000000
print(countTV(N, R1, R2, Target))


#!/bin/python3

import math
import os
import random
import re
import sys
import heapq

"""
given a directed weighted graph
determine length of shortest path between nodes
try to be efficient

"""

"""
test cases

node only has a single way to get to it
node has 2 ways to get to it
there is a middle node with a shorter path but more nodes to traverse

"""

"""
ways to go about it

can do either depth first or breadth first traversal
can record shortest path to nodes, reuse later
use floyd warshall - the idea is to find shortest path between all verticies. store in 2d array and continuously store the next most cheapest solution
use dijkstras

"""

"""
function will need to pass in:
road from
road to
road weight
from
to

"""
def floydBlindingLight(road_from, road_to, road_weight, start, to):
    breadthFirstDiffForLoop(road_from, road_to, road_weight, start, to)

"""
shared function to create a graph

key is node from
value is dict of { to : weight }

input is:
- road from
- road to
- road weight

"""
# create a hash
def createGraph(road_from, road_to, road_weight):
    # check if input is illegal
    # they need to all be the same length

    # key is starting node
    # value is hash of node and distance
    result = {}
    for i in range(0, len(road_from)):
        #print (e)
        start = road_from[i]
        to = road_to[i]
        weight = road_weight[i]

        # check if the starting node is in result
        if start not in result:
            # initialize it
            result[start] = {}

        result[start][to] = weight

    return result

# -- go through shortest path, not efficient --

# works for easy ones, but not efficient enough for large graphs

# function for it
def greedyFindShortest(road_from, road_to, road_weight, start, to):
    # check if input is illegal

    # check case if start and to are the same
    if start == to:
        print("0")
        return

    # convert the edges into a graph hash
    h_edges = createGraph(road_from, road_to, road_weight)

    # initialize a priority queue of edge to traverse to next
    # this is ordered off of shortest distance to travel.
    # this distance is: distance to the node + next edge
    q = []

    # hold onto a visited hash
    # q: in this one, do I need this? yes it might be cyclical
    visited = {}

    # hold onto a hash which has the shortest path to each node from the starting one
    distance_to = {}

    # set the rest to infinity
    for node in h_edges:
        distance_to[node] = -1

        # use to get all nodes
        # some nodes may not have another destination
        for destination in h_edges[node]:
            distance_to[destination] = -1

    # set the starting node to 0
    distance_to[start] = 0

    # check if it is the end node
    if start not in h_edges:
        print("-1")
        return

    # put the starting node's edges into the queue
    for destination in h_edges[start]:
        heapq.heappush(q, (h_edges[start][destination], destination))

    # while the edges queue is not empty
    while len(q) > 0:
        # pull out the first edge in queue
        edge = heapq.heappop(q)

        distance = edge[0]
        next_node = edge[1]
        if distance_to[next_node] != -1:
            distance += distance_to[edge[1]]

        # if it has not been visited
        if distance_to[next_node] == -1:

            # set the shortest distance hash
            distance_to[next_node] = distance

            # need to check this in case the next node has no edges starting from it
            if next_node in h_edges:
                # for all destination node's edges
                for next_dest in h_edges[next_node]:
                    # calculate the distance + edge distance
                    next_distance = distance + h_edges[next_node][next_dest]

                    # put tuple into the priority queue
                    # first element is distance
                    # second element is destination node
                    heapq.heappush(q, (next_distance, next_dest))

        # if the destination node is the last one
        if next_node == to:
            # break
            break

    # print(h_edges)
    # print(distance_to)

    # print the result for distance to last one
    print(distance_to[to])

# -- go through shortest path, not efficient, for loop different --

# works for easy ones, but not efficient enough for large graphs

# function for it
def greedyFindShortestDiffForLoop(road_from, road_to, road_weight, start, to):
    # check if input is illegal

    # check case if start and to are the same
    if start == to:
        print("0")
        return

    # convert the edges into a graph hash
    h_edges = createGraph(road_from, road_to, road_weight)

    # initialize a priority queue of edge to traverse to next
    # this is ordered off of shortest distance to travel.
    # this distance is: distance to the node + next edge
    q = []

    # hold onto a visited hash
    # q: in this one, do I need this? yes it might be cyclical
    visited = {}

    # hold onto a hash which has the shortest path to each node from the starting one
    distance_to = {}

    # set the rest to infinity
    for node in h_edges:
        distance_to[node] = -1

        # use to get all nodes
        # some nodes may not have another destination
        for destination in h_edges[node]:
            distance_to[destination] = -1

    # set the starting node to 0
    distance_to[start] = 0

    # check if it is the end node
    if start not in h_edges:
        print("-1")
        return

    # put the starting node's edges into the queue
    for destination in h_edges[start]:
        heapq.heappush(q, (h_edges[start][destination], destination))

    # while the edges queue is not empty
    while len(q) > 0:
        # pull out the first edge in queue
        edge = heapq.heappop(q)

        distance = edge[0]
        next_node = edge[1]
        if distance_to[next_node] != -1:
            distance += distance_to[edge[1]]

        #print(distance_to)

        # if it has been visited, then can skip because there already is a shorter path to it
        if distance_to[next_node] != -1:
            continue

        # set the shortest distance hash
        distance_to[next_node] = distance

        # if the destination node is the last one
        if next_node == to:
            # break
            break

        # if the destination node has no edges starting from it, there are no edges to add
        if next_node not in h_edges:
            continue

        # at this point, the destination node is known to have edges originating from it
        # for all destination node's edges
        for next_dest in h_edges[next_node]:
            # calculate the distance + edge distance
            next_distance = distance + h_edges[next_node][next_dest]

            # put tuple into the priority queue
            # first element is distance
            # second element is destination node
            heapq.heappush(q, (next_distance, next_dest))

    # print(h_edges)
    # print(distance_to)

    # print the result for distance to last one
    print(distance_to[to])

# -- dijkstras --

# function for this
    # check if input is illegal

    # create a graph of edges

    # create a priority queue
    # the compare value is the distance
    # the attached value is destination

    # hold onto the distance to
    # key is node to
    # value is node distance

    # hold onto visited
    # key is node to
    # value is true if there
    # if node has not been traveled to, omit it

    # put in the initial one
    # the compare value is 0
    # the attached value is the starting node

    # while the queue is not empty
        # if the node has been visited
            # continue

        # set distance to the distance value

        # for each edge from the node
            #

    # print the node to

# -- floyd warshall, efficient --
"""
the goal is to find the shortest distance between every pair of verticies
"""

# store to hold
# this will be a 2d array
# row is from vertex
# column is to vertex
store = None

# function for this
# this is the correct algorithm. however, python is so slow that this still doesn't execute in the time limits
# this same algorithm in C is very fast
# lesson: be careful about using python for production grade things that need to be highly performant
def floydMarshall(road_nodes, road_from, road_to, road_weight, start, to):
    # check if inputs are illegal

    # declare store
    global store

    infin = float("inf")

    # if store has already been initialized, then the shortest path has already been calculated
    if store is not None:
        if store[start][to] == infin:
            print("-1")
            return

        print(store[start][to])
        return

    # at this point, we know that we need to initialize store

    # initialize all edges from __ to __
    store = [ [infin]*(road_nodes + 1) for i in range(road_nodes + 1)]

    # initialize each [v][v] as 0
    for i in range(0, road_nodes + 1):
        store[i][i] = int(0)

    # initialize the edge distances that exist
    for i in range(0, len(road_from)):
        store[road_from[i]][road_to[i]] = int(road_weight[i])

    # print(store)

    # for i from 0 to length of array
    for i in range(0, len(store)):
        # for j from 0 to length of array
        for j in range(0, len(store)):
            # for k from 0 to length of array
            for k in range(0, len(store)):
                # set i to k as minimum between i to k or i to j + j to k
                # basically, its the current path or the intermediate path
                store[i][k] = min(store[i][k], store[i][j] + store[j][k])

    if store[start][to] == infin:
        print("-1")
        return

    print(store[start][to])

if __name__ == '__main__':
    road_nodes, road_edges = map(int, input().rstrip().split())

    road_from = [0] * road_edges
    road_to = [0] * road_edges
    road_weight = [0] * road_edges

    for i in range(road_edges):
        road_from[i], road_to[i], road_weight[i] = map(int, input().rstrip().split())

    q = int(input().strip())

    for q_itr in range(q):
        first_multiple_input = input().rstrip().split()

        x = int(first_multiple_input[0])

        y = int(first_multiple_input[1])

        # call function here
        # floydBlindingLight(road_from, road_to, road_weight, x, y)
        floydMarshall(road_nodes, road_from, road_to, road_weight, x, y)


def f(li):
    result = []
    for i, e in enumerate(li):
        result.append(e+i)

    return result

if __name__ == '__main__':
    # simple tests
    li = [8, 4, 1, 7]
    if f(li) != [8, 5, 3, 10]:
        print('Failed')

    li = [10, 11, 12, 13]
    if f(li) != [10, 12, 14, 16]:
        print('Failed')


fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox.txt"

try:
    fhand = open(fname)
except:
    print('File does not exist.')
    exit()

counts = dict()

for line in fhand:
    if line.startswith('From: '):
        words = line.rstrip().split()
        counts[words[1]] = counts.get(words[1], 0) + 1

big_count = None
big_emailer = None

for email, count in counts.items():
    if big_count is None or count > big_count:
        big_count = count
        big_emailer = email

print(big_emailer, big_count)


#!/usr/bin/env python

""" MultiQC example plugin module """

from __future__ import print_function
from collections import OrderedDict
import logging

from multiqc import config
from multiqc.plots import table
from multiqc.modules.base_module import BaseMultiqcModule

# Initialise the main MultiQC logger
log = logging.getLogger('multiqc')

headers = OrderedDict()

headers['Percent_Methylated_All'] = {
    'suffix': '%',
    'format': '{:,.2f}'
}

headers['Percent_Methylated_CpG'] = {
    'suffix': '%',
    'format': '{:,.2f}'
}

headers['Lambda_Percent_Methylated_All'] = {
    'suffix': '%',
    'format': '{:,.2f}'}

headers['Lambda_Percent_Methylated_CpG'] = {
    'suffix': '%',
    'format': '{:,.2f}'
}

headers['Methylated_All'] = {
    'hidden': True
}

headers['Unmethylated_All'] = {
    'hidden': True
}

headers['Methylated_CpG'] = {
    'hidden': True
}

headers['Unmethylated_CpG'] = {
    'hidden': True
}

headers['Methylated_nonCpG'] = {
    'hidden': True
}

headers['Unmethylated_nonCpG'] = {
    'hidden': True
}

headers['Percent_Methylated_nonCpG'] = {
    'hidden': True,
    'suffix': '%',
    'format': '{:,.2f}'
}

headers['Lambda_Methylated_All'] = {
    'hidden': True
}

headers['Lambda_Unmethylated_All'] = {
    'hidden': True
}

headers['Lambda_Methylated_CpG'] = {
    'hidden': True
}

headers['Lambda_Unmethylated_CpG'] = {
    'hidden': True
}

headers['Lambda_Methylated_nonCpG'] = {
    'hidden': True
}

headers['Lambda_Unmethylated_nonCpG'] = {
    'hidden': True
}

headers['Lambda_Percent_Methylated_nonCpG'] = {
    'hidden': True,
    'suffix': '%',
    'format': '{:,.2f}'
}

headers['z'] = {
    'hidden': True
}

headers['Z'] = {
    'hidden': True
}

headers['x'] = {
    'hidden': True
}

headers['X'] = {
    'hidden': True
}

headers['h'] = {
    'hidden': True
}

headers['H'] = {
    'hidden': True
}

headers['u'] = {
    'hidden': True
}

headers['U'] = {
    'hidden': True
}

headers['z_lambda'] = {
    'hidden': True
}

headers['Z_lambda'] = {
    'hidden': True
}

headers['x_lambda'] = {
    'hidden': True
}

headers['X_lambda'] = {
    'hidden': True
}

headers['h_lambda'] = {
    'hidden': True
}

headers['H_lambda'] = {
    'hidden': True
}

headers['u_lambda'] = {
    'hidden': True
}

headers['U_lambda'] = {
    'hidden': True
}

class MultiqcModule(BaseMultiqcModule):

    def __init__(self):

        # Halt execution if we've disabled the plugin
        if config.kwargs.get('disable_plugin', True):
            return None

        # Initialise the parent module Class object
        super(MultiqcModule, self).__init__(
            name = 'bs_conversion_stats',
            target = "bs_conversion_stats",
            anchor = 'bs_conversion_stats',
            href = 'https://github.com/Apompetti-Cori/MQC_BS_Conversion_Stats',
            info = "module to generate stats relating to bisulfite conversion."
        )

        # Find and load any input files for this module
        self.bs_conversion_stats_data = dict()
        for f in self.find_log_files('bs_conversion_stats/reports'):
            parsed_data = self.parse_reports(f['f'])
            if parsed_data is not None:
                s_name = self.clean_s_name(f['fn'], root=None)
                if s_name in self.bs_conversion_stats_data:
                    log.debug("Duplicate sample name found! Overwriting: {}".format(f['s_name']))
                self.add_data_source(f)
                self.bs_conversion_stats_data[s_name] = parsed_data

        # Filter out samples matching ignored sample names
        self.bs_conversion_stats_data = self.ignore_samples(self.bs_conversion_stats_data)

        # Nothing found - raise a UserWarning to tell MultiQC
        if len(self.bs_conversion_stats_data) == 0:
            log.debug("Could not find any reports in {}".format(config.analysis_dir))
            raise UserWarning

        log.info("Found {} reports".format(len(self.bs_conversion_stats_data)))

        # Write parsed report data to a file
        self.write_data_file(self.bs_conversion_stats_data, 'multiqc_my_example')

        #Create a very basic table
        table_html = table.plot(self.bs_conversion_stats_data, headers)

        #Add a report section with said table
        self.add_section(
            description = 'Basic table',
            helptext = '''
            Filler help text
            ''',
            plot = table_html
        )

    def parse_reports(self, raw_data):
        """ Takes in the file contents from self.find_log_files"""

        parsed_data = dict()
        lines = raw_data.split("\n")
        headers = lines[0].split("\t")
        data_list = lines[1].split("\t")
        for data,header in zip(data_list,headers):
            if header == "Sample_Name":
                continue
            else:
                if isinstance(data, str):
                    parsed_data[header] = data
                else:
                    parsed_data[header] = data

        if len(parsed_data) == 0: return None
        return parsed_data


from lib.config import *
from lib.agent import Agent
from lib.episode import Episode
from lib.graph import Graph

# Predict expected return for each time step
agent = Agent(STATES, ACTIONS, REWARDS, HORIZON, DISCOUNT_FACTOR, POLICY, TRANSITIONS)
expected_return_under_policy = agent.expected_return_under_policy()

# Get expected rewards at end of episode
expected_rewards = {}
for state in STATES:
    expected_rewards[state] = round(expected_return_under_policy[state, HORIZON-1])

# Simulate an episode to get actual rewards
actual_rewards = {}
for state in STATES:
    episode = Episode(ACTIONS, STATES, REWARDS, HORIZON, POLICY, TRANSITIONS, state)
    actual_rewards[state] = 0
    for _ in range(EPISODES):
        actual_rewards[state] += episode.play()
    actual_rewards[state] /= EPISODES

# Compare predicted vs. actual rewards
print('Expected rewards:', expected_rewards)
print('Actual rewards:  ', actual_rewards)

# Draw state-action diagram
graph = Graph(STATES, ACTIONS, LABELS)
graph.draw()


import numpy as np
import glfw
from OpenGL.GL import *

draw_value = 4
draw_dict = {1:GL_POINTS, 2:GL_LINES, 3:GL_LINE_STRIP, 4:GL_LINE_LOOP, 5:GL_TRIANGLES, 6:GL_TRIANGLE_STRIP,
        7:GL_TRIANGLE_FAN, 8:GL_QUADS, 9:GL_QUAD_STRIP, 0:GL_POLYGON}
def key_callback(window, key, scancode, action, mods):
    global draw_value
    if key==glfw.KEY_1 and action == glfw.PRESS:
        draw_value = 1
    elif key==glfw.KEY_2 and action==glfw.PRESS:
        draw_value = 2
    elif key==glfw.KEY_3 and action==glfw.PRESS:
        draw_value = 3
    elif key==glfw.KEY_4 and action==glfw.PRESS:
        draw_value = 4
    elif key==glfw.KEY_5 and action==glfw.PRESS:
        draw_value = 5
    elif key==glfw.KEY_6 and action==glfw.PRESS:
        draw_value = 6
    elif key==glfw.KEY_7 and action==glfw.PRESS:
        draw_value = 7
    elif key==glfw.KEY_8 and action==glfw.PRESS:
        draw_value = 8
    elif key==glfw.KEY_9 and action==glfw.PRESS:
        draw_value = 9
    elif key==glfw.KEY_0 and action==glfw.PRESS:
        draw_value = 0
def render():
    global draw_value
    global draw_dict
    degree = np.linspace(0, 360, 13)
    d2r = [np.deg2rad(i) for i in degree]
    d2r = d2r[:12]
    vertex = [(np.cos(i), np.sin(i)) for i in d2r]
    glClear(GL_COLOR_BUFFER_BIT)
    glLoadIdentity()
    glBegin(draw_dict[draw_value])
    for i in vertex:
        glVertex2fv(i)
    glEnd()

def main():
    # Initialize the library
    if not glfw.init():
        return
    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(480, 480, "2016025996", None, None)
    if not window:
        glfw.terminate()
        return

    # Make the window's context current
    glfw.make_context_current(window)
    glfw.set_key_callback(window, key_callback)
    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        # Poll events
        glfw.poll_events()

        # Render here, e.g. using pyOpenGL
        render()

        # Swap front and back buffers
        glfw.swap_buffers(window)

    glfw.terminate()

if __name__ == "__main__":
    main()


import os
import shutil

dest = "../assets/"
src = "."

def copy(files,prefix):
    for f in files:
        if(os.path.isdir(prefix+f)):
           copy(os.listdir(prefix+f),prefix+f+"/")
        else:
            if( not f.endswith(".py")):
                shutil.copyfile((prefix+f),dest+f)

def main():
    copy(os.listdir('.'),"")

main()


def get_app_times(data):
    """
    This is horrible;
    I aim to make this func into a comprehension at some point.

    Gets list of tuples containing apps and the
    time spent on them, sorted by the latter
    """
    app_times = {}
    for app, descs in data.items():
        seconds_on_app = 0
        for desc, time_entries in descs.items():
            for time_entry in time_entries:
                seconds_on_app += time_entry['seconds']
        app_times[app] = seconds_on_app
    return sorted(app_times.items(), key=lambda x:x[1], reverse=True)


from Music_Genre_Dataset import music_genre_dataset
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

import numpy as np
import random

class music_genre_regression:
    def __init__(self, path):
        self.dataset = music_genre_dataset(path)

        self.train_data = []
        self.train_label= []
        self.test_data = []
        self.test_label= []

    def getShuffleIndexArr(self):
        if self.dataset.datas == []:
            self.dataset.readOriginData()

        n = len(self.dataset.labels)
        size = n // 10

        shuffleIndexArr = []
        for i in range(10):
            shuffleIndexArr.append(list(range(i * size, (i + 1) * size)))
            random.shuffle(shuffleIndexArr[-1])

        return shuffleIndexArr

    def getSplitIndex(self, foldIndex, shuffleIndexArr):
        patch = len(shuffleIndexArr[0]) // 5
        trainDataIndex = []
        testDataIndex = []

        for i in range(10):
            trainDataIndex += list(shuffleIndexArr[i][:patch * foldIndex]) + list(shuffleIndexArr[i][patch * (foldIndex + 1):])
            testDataIndex += list(shuffleIndexArr[i][patch * foldIndex: patch * (foldIndex + 1)])

        return np.array(trainDataIndex), np.array(testDataIndex)

    def getOriginData(self, foldIndex, shuffleIndexArr):
        if self.dataset.datas == []:
            self.dataset.readOriginData()

        trainDataIndex, testDataIndex = self.getSplitIndex(foldIndex, shuffleIndexArr)

        self.train_data, self.train_label = self.dataset.datas[trainDataIndex], self.dataset.labels[trainDataIndex]
        self.test_data, self.test_label = self.dataset.datas[testDataIndex], self.dataset.labels[testDataIndex]

        train_shape = (-1,) + (self.train_data.shape[-1],)
        self.train_data = self.train_data.reshape(train_shape)
        self.test_data = self.test_data.reshape(train_shape)

    def getFFTData(self, foldIndex, shuffleIndexArr):
        if self.dataset.FFTDatas == []:
            self.dataset.transferFFTData()

        trainDataIndex, testDataIndex = self.getSplitIndex(foldIndex, shuffleIndexArr)

        self.train_data, self.train_label = self.dataset.FFTDatas[trainDataIndex], self.dataset.labels[trainDataIndex]
        self.test_data, self.test_label = self.dataset.FFTDatas[testDataIndex], self.dataset.labels[testDataIndex]

        train_shape = (-1,) + (self.train_data.shape[-1],)
        self.train_data = self.train_data.reshape(train_shape)
        self.test_data = self.test_data.reshape(train_shape)

    def getSpectrogramData(self, foldIndex, shuffleIndexArr):
        if self.dataset.SpectrogramDatas == []:
            self.dataset.transferSpectrogramData()

        trainDataIndex, testDataIndex = self.getSplitIndex(foldIndex, shuffleIndexArr)

        self.train_data, self.train_label = self.dataset.SpectrogramDatas[trainDataIndex], self.dataset.labels[trainDataIndex]
        self.test_data, self.test_label = self.dataset.SpectrogramDatas[testDataIndex], self.dataset.labels[testDataIndex]

        train_shape = (-1,) + (self.train_data.shape[-1] * self.train_data.shape[-2],)
        self.train_data = self.train_data.reshape(train_shape)
        self.test_data = self.test_data.reshape(train_shape)

    def train(self):

        shuffleIndexArr = self.getShuffleIndexArr()

        for foldIndex in range(5):
            self.getSpectrogramData(foldIndex, shuffleIndexArr)
            model = LogisticRegression(max_iter = 10).fit(self.train_data, self.train_label)
            print("Accuracy = {}".format(accuracy_score(self.test_label, model.predict(self.test_data))))


from ltk import later, find, on, HBox, Input, Text, VBox
from dag import Node, NotSet, memoize, clear
import re

ROW_COUNT = 5
COLUMN_COUNT = 5

def convert(cell):
    try:
        return float(cell)
    except:
        return cell

class SpreadsheetCellModel(Node):
    models = {}
    script = None

    def __init__(self, key, value, listener):
        self.key = key
        self.models[key] = self
        Node.__init__(self, value, listener)

    def set(self, value):
        self.formula = None
        if value and value[0] == "=":
            value = value[1:]
        self.formula = value
        self.script = re.sub("([A-Z]+[0-9]+)", r"convert(SpreadsheetCellModel.models['\1'].get())", self.formula)
        inputs = [SpreadsheetCellModel.models[key] for key in re.findall("([A-Z]+[0-9]+)", value)]
        self.set_inputs(inputs)
        Node.set(self, value)
        for listener in self.listeners:
            listener()

    def get(self):
        try:
            self.error = False
            return eval(self.script) if self.script else ""
        except Exception as e:
            self.error = True
            return f"ðŸ˜ž {e}"
    def __repr__(self):
        return f"<Cell-{self.key}>"

class Blank(Text):
    classes = [ "spreadsheet-blank" ]

def resizable(element, handles, rowOrColumn, index):
    print('resizable', element, index)
    element.resizable()
    element.resizable("option", "handles", handles)
    element.resizable("option", "alsoResize", f".{rowOrColumn}-{index}")

class RowLabel(Text):
    classes = [ "spreadsheet-row-label" ]

    def __init__(self, value, index):
        Text.__init__(self, value)
        resizable(self.element, "s", "row", index)

class ColumnLabel(Text):
    classes = [ "spreadsheet-column-label" ]

    def __init__(self, value, index):
        Text.__init__(self, value)
        resizable(self.element, "e", "col", index)

class SpreadsheetCell(Input):
    cells = {}
    models = {}
    model = NotSet()
    updating = False
    current = None

    def __init__(self, value, row, column):
        Input.__init__(self)
        self.column = column
        self.row = row
        key = f"{chr(ord('A') + column)}{row}"
        SpreadsheetCell.cells[key] = self
        SpreadsheetCell.models[key] = self.model = SpreadsheetCellModel(key, value, self.model_changed)
        (self
            .on("focus", self.set_editor)
            .on("change", self.view_changed)
            .addClass(f"col-{column}")
            .addClass(f"row-{row}")
            .width(36)
            .height(34)
            .attr("id", key))
        self.model_changed()

    def set_editor(self):
        SpreadsheetCell.current = self
        find("#editor").val(self.model.formula or self.model.get())
        find("#value").text(self.model.get()).css("color", "#F99" if self.model.error else "#AAA")

    def model_changed(self):
        if self.updating: later(self.model_changed)
        try:
            self.updating = True
            self.element.val("ðŸ˜ž" if self.model.error else self.model.get())
            self.element.css("color", "#F99" if self.model.error else "black")
        finally:
            self.updating = False

    def view_changed(self):
        if self.updating: return
        try:
            self.updating = True
            self.model.set(self.element.val())
            self.set_editor()

        finally:
            self.updating = False

def create_row(row_index):
    row_label = RowLabel(row_index, row_index)
    cells = [ SpreadsheetCell("", row_index, column) for column in range(COLUMN_COUNT) ]
    return HBox(row_label, cells)

def update_cell():
    SpreadsheetCell.current.model.set(find("#editor").val())

def create_spreadsheet():
    editor = Input().attr("id", "editor")
    value = Text().css("border", "").attr("id", "value")
    blank = Blank()
    headers = HBox(blank, [ ColumnLabel(chr(ord('A') + column), column) for column in range(COLUMN_COUNT) ])
    rows = [ create_row(row) for row in range(1, COLUMN_COUNT) ]
    VBox(editor, value, headers, rows).render("#main")
    SpreadsheetCell.models["A1"].set("5")
    SpreadsheetCell.models["B1"].set("4")
    SpreadsheetCell.models["C1"].set("=A1+B1")
    SpreadsheetCell.models["A2"].set("'hello'")
    SpreadsheetCell.models["B2"].set("'world'")
    SpreadsheetCell.models["C2"].set("=A2.capitalize() + ' ' + B2.upper()")
    on(editor, "change", update_cell)

create_spreadsheet()


'Ejercicio: contar y buscar las palabras repetidas en el texto.'

text = "Creo que a veces es la gente de la que nadie espera nada, la que hace cosas que nadie puede imaginar. creo"

eliminar = ",;:.\n!\"´'"

text = text.lower()
'''se convierte el texto a minisculas'''

for puntuaciones in eliminar:
    text=text.replace(puntuaciones,'')
'''se aplica variable eliminar al texto con el fin de reemplazar carateres'''

texto = text.split()
'''se divide el texto a arreglo'''

diccionary = {}
'''se declara diccionario'''

for n in texto:
    '''se cuentan los elementos en el texto para ello se creo el diccionario
    la clave seran los elementos y el valor sera el conteo'''
    if n in diccionary:
        diccionary[n] +=1
    else:
        diccionary[n] =1

for n in diccionary:
    '''for para crear la frecuencia de los elementos en el diccionario'''
    frecuencia = diccionary[n]
    print(f"{n} = {frecuencia}")
    '''f funciona para darle el valor/formato correspondiente a n y frecuencia'''


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 21 02:03:06 2022

@author: nico
"""

import numpy as np

from pylatex import Document, Section, Subsection, Tabular, Math, TikZ, Axis, \
    Plot, Figure, Matrix, Alignat
from pylatex.utils import italic
import os

if __name__ == '__main__':
    path = '/home/nico/Documentos/Drought/Mediciones/figures/Validaciones_agromet/'
    #image_filename = os.path.join(os.path.dirname(path), 'test3_2012-2022_1.png')

    geometry_options = {"tmargin": "1cm", "lmargin": "0.5cm"}
    doc = Document(geometry_options=geometry_options)
    with doc.create(Section('Precipitation NaN')):
          with doc.create(Figure(position='h!')) as kitten_pic:
              #kitten_pic.add_image(image_filename, width='120px')
              image_filename = os.path.join(os.path.dirname(path), 'heatmap_dias_completos_mes.png')
              kitten_pic.add_image(image_filename, width='300px')
              kitten_pic.add_caption('Precipitación horaria pre>0 and pre < 50, agregación (suma) de la precipitación horaria entre 8am-8am, días completos sin falta de mediciones horarias')

    with doc.create(Section('Precipitation raw time series')):
          for figura in range(1,25):
              print(figura)
              with doc.create(Figure(position='h!')) as kitten_pic:
                  #kitten_pic.add_image(image_filename, width='120px')
                  image_filename = os.path.join(os.path.dirname(path), 'test3_2012-2022_'+str(figura)+'.png')
                  kitten_pic.add_image(image_filename, width='630px')
                  kitten_pic.add_caption('Time series of hourly precipitation, raw data. Y axes rage are 0-10 mm')

    doc.generate_pdf('Report_Agromet_Measurements_V0', clean_tex=False)
'''
    with doc.create(Section('The simple stuff')):
        doc.append('Some regular text and some')
        doc.append(italic('italic text. '))
        doc.append('\nAlso some crazy characters: $&#{}')
        with doc.create(Subsection('Math that is incorrect')):
            doc.append(Math(data=['2*3', '=', 9]))

        with doc.create(Subsection('Table of something')):
            with doc.create(Tabular('rc|cl')) as table:
                table.add_hline()
                table.add_row((1, 2, 3, 4))
                table.add_hline(1, 2)
                table.add_empty_row()
                table.add_row((4, 5, 6, 7))

    a = np.array([[100, 10, 20]]).T
    M = np.matrix([[2, 3, 4],
                   [0, 0, 1],
                   [0, 0, 2]])

    with doc.create(Section('The fancy stuff')):
        with doc.create(Subsection('Correct matrix equations')):
            doc.append(Math(data=[Matrix(M), Matrix(a), '=', Matrix(M * a)]))

        with doc.create(Subsection('Alignat math environment')):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(r'\frac{a}{b} &= 0 \\')
                agn.extend([Matrix(M), Matrix(a), '&=', Matrix(M * a)])

        with doc.create(Subsection('Beautiful graphs')):
            with doc.create(TikZ()):
                plot_options = 'height=4cm, width=6cm, grid=major'
                with doc.create(Axis(options=plot_options)) as plot:
                    plot.append(Plot(name='model', func='-x^5 - 242'))

                    coordinates = [
                        (-4.77778, 2027.60977),
                        (-3.55556, 347.84069),
                        (-2.33333, 22.58953),
                        (-1.11111, -493.50066),
                        (0.11111, 46.66082),
                        (1.33333, -205.56286),
                        (2.55556, -341.40638),
                        (3.77778, -1169.24780),
                        (5.00000, -3269.56775),
                    ]

                    plot.append(Plot(name='estimate', coordinates=coordinates))
    doc.generate_pdf('Report_Agromet_Measurements_V0', clean_tex=False)
'''


"""
URL configuration for studio_api project.

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

schema_view = get_schema_view(
   openapi.Info(
      title="3PM Studio API",
      default_version='v1',
      description="3pm Studio API v1"
   ),
   public=True,
   permission_classes=[permissions.AllowAny],
)

urlpatterns = [
    path("admin/", admin.site.urls),
    path("v1/users/", include("users.urls")),
    path("", include('health_check.urls')),
    path("v1/tokens/", include("tokens.urls")),
    path("v1/contracts/", include("contracts.urls")),
    path("v1/payments/", include("payments.urls")),
    path("v1/orders/", include("orders.urls")),
    path("v1/redeems/", include("redeems.urls")),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

if settings.DEBUG:
    urlpatterns = [
        # re_path(r'^api-doc(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
        re_path(r'^api-doc/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
        # re_path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),

    ] + urlpatterns


#!/usr/bin/python3
import signal
import sys, getopt, copy
import time, logging
from io import StringIO
import json
import yaml
import os
from temperaturereader import TemperatureReader,TemperatureReaderCrash
DEBUG = False
MAXERRORS = 10

def writeSensorData(address, SensorData, Config):
	datetime_local = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
	print("{} {} C: {} F: {}".format(datetime_local, Config["sensors"].get(address,address), SensorData[0], SensorData[1]))

def main(argv):
    global DEBUG
    if DEBUG:
        logging.basicConfig(format='%(asctime)s %(levelname)-2s %(message)s',
        level=logging.DEBUG,
        datefmt='%Y-%m-%d %H:%M:%S')
    else:
        logging.basicConfig(format='%(asctime)s %(levelname)-2s %(message)s',
        level=logging.INFO,
        datefmt='%Y-%m-%d %H:%M:%S')

    with open(os.path.dirname(os.path.realpath(__file__)) + '/config.yml', 'r') as file:
        Config = yaml.safe_load(file)
    errcounter = 0
    Reader = TemperatureReader(Config['serial'])
    Reader.startmeasurement()
    while errcounter<MAXERRORS:
        line = Reader.read()
        if line and len(line) != 0:
            #time.sleep(0.2)
            #continue
            #logging.info(line)
            try:
                obj = json.loads(line)
            except json.JSONDecodeError:
                logging.debug("json decode error: " + line)
                errcounter += 1
                time.sleep(0.3)
                continue
            valueerr = False
            for address in obj:
                if obj[address][0] == "85.00":
                    logging.debug("read value error C = " + obj[address][0])
                    valueerr = True
                    break
            if valueerr:
                logging.debug("Valueerror = ")
                time.sleep(0.3)
                errcounter += 1
                continue
            #print(obj);
            for i in obj:
                writeSensorData(i, obj[i], Config)
            break
    Reader.close()

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


#
# @lc app=leetcode id=724 lang=python3
#
# [724] Find Pivot Index
#

# @lc code=start
class Solution:
  def pivotIndex(self, nums: List[int]) -> int:
    N = len(nums)
    for i in range(1, N):
      nums[i] += nums[i-1]

    for i in range(N):
      if i == 0:
        if nums[N-1]-nums[0] == 0:
          return 0
      elif i == N-1:
        if nums[N-2] == 0:
          return N-1
      else:
        if nums[i-1] == nums[N-1]-nums[i]:
          return i

    return -1

# @lc code=end


# 2022-08-15 23:07:59.884729
# https://codeforces.com/problemset/problem/891/A
from collections import Counter
from functools import reduce
from math import gcd
import sys

_DEBUG = True
if not _DEBUG:
    input = sys.stdin.readline
    # print = sys.stdout.write

def proc(n, a):
    if all(e == 1 for e in a):
        return 0
    if any(e == 1 for e in a):
        return n - Counter(a)[1]
    if reduce(lambda x, y: gcd(x, y), a) > 1:
        return -1

    c = n
    while True:
        b = []
        for i in range(len(a) - 1):
            g = gcd(a[i], a[i + 1])
            b.append(g)
            if g == 1:
                return c
        a = b
        c += 1

    return c

n = int(input().strip())
a = list(map(int, input().strip().split()))
print(proc(n, a))


import time
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed

def f(a):
    time.sleep(1)
    return f"[{threading.current_thread().name}] {a} ** {a} = {a ** a}"

with ThreadPoolExecutor(max_workers=3) as pool:
    results = [pool.submit(f, i) for i in range(10)]

    for future in as_completed(results):
        print(future.result())


'''
author: Edgar Gironés
Date: 24.11.22
Module for the logging and testing of the churn prediction
'''
from os.path import exists
import logging
import pytest
import joblib
import churn_library as cls

pytest.main()

def test_import():
    '''
    test data import - this example is completed for
    you to assist with the other test functions
    '''
    try:
        df_test = cls.import_data("./data/bank_data.csv")
        logging.info("File loaded")
    except FileNotFoundError as err:
        logging.error("Testing import_eda: The file wasn't found")
        raise err

    try:
        assert df_test.shape[0] > 0
        assert df_test.shape[1] > 0
        logging.info('DF shape is good')
    except AssertionError as err:
        logging.error(
            "Testing import_data: The file doesn't appear to have rows and columns")
        raise err
    pytest.df_test = df_test
    return df_test

list_figures = ['./images/eda/churn.jpeg',
                './images/eda/customer_age.jpeg',
                './images/eda/marital_status.jpeg',
                './images/eda/trans_ct.jpeg',
                './images/eda/heatmap_variables.jpeg',
                './images/results/lr_results.jpeg',
                './images/results/rf_results.jpeg'
                ]

@pytest.mark.parametrize('file_name', list_figures)
def test_eda(file_name):
    '''
    assert if dataf file exists
    '''
    try:
        assert exists(file_name)
    except AssertionError as err:
        logging.error("Cannot create file %s", file_name)
    logging.info("Image %s in folder", file_name)

# assert if all columns are present in the new df
cat_columns = [
    'Gender',
    'Education_Level',
    'Marital_Status',
    'Income_Category',
    'Card_Category'
]

# assert if columns are in df
@pytest.mark.parametrize('column_name', cat_columns)
def test_encoder_helper(column_name):
    '''
    test encoder helper
    '''
    df_test = pytest.df_test
    df_test = cls.encoder_helper(df_test)
    try:
        assert column_name in df_test.columns
    except AssertionError as err:
        logging.error("Column cannot be created")
    return df_test

def test_perform_feature_engineering():
    '''
    test perform_feature_engineering
    '''
    df_test = pytest.df_test
    try:
        assert cls.perform_feature_engineering(df_test) is not None
    except AssertionError as err:
        logging.error("Cannot perform feature engineering")
    logging.info("Feature engineering performed")

models = ['./models/rfc_model.pkl', './models/logistic_model.pkl']

@pytest.mark.parametrize('model', models)
def test_load_models(model):
    '''
    assert if the models in pkl format exist
    '''
    try:
        assert joblib.load(model)
    except AssertionError as err:
        logging.error("Models not found")

logging.info("All passed!")
# if __name__ == "__main__":
# 	pass


from z3 import *

a = Bool('A')
b = Bool('B')
c = Bool('C')
d = Bool('D')
e = Bool('E')
f = Bool('F')
g = Bool('G')
h = Bool('H')
i = Bool('I')
j = Bool('J')

exp1 = And(Not(Or(a, Not(b))), Not(Or(Or(Not(c), d),Or(e, Not(f)))))
exp2 = And(And(Not(Or(g,h)), Xor(h, i)), And(i, j))

print(solve(And(exp1, exp2)))


import quill
import tkinter as tk

game = quill.Window()

def startup():
    game.sword_broken = quill.rpg.Item(game, "Broken Sword", {"weapon": {"type": "sword", "damage": 5}}, rarity="Common")
    game.potion_health_small = quill.rpg.Item(game, "Small Potion of Health", {"potion": {"type": "health", "amount": 15}},
                                          value=15, rarity="Common")

    game.loot_small_chest = quill.rpg.LootTable(game, "Small Chest", [game.sword_broken, game.potion_health_small])

    game.variable_state = tk.IntVar()
    game.variable_maximized = tk.BooleanVar()

    menu()

def menu(*args):
    game.enable()
    game.clear()

    game.insert_text("Maze Game", True, tag="Heading-4")

    game.insert_command("> Start", command=start)
    game.insert_command("> Options", command=options)
    game.insert_command("> Exit", command=game.exit)

    game.goto_end()
    game.disable()

def start(*args):
    game.enable()
    game.clear()

    game.insert_text("Chapter 1", tag="Heading-4")
    game.insert_text("- Awaken", tag="Heading-5")
    game.insert_new_line()

    game.insert_text("You wake up, surrounded by ")
    game.insert_trigger("stone walls", command=None)
    game.insert_text(".")

    game.goto_end()
    game.disable()

def options(*args):
    game.enable()
    game.clear()

    game.insert_text("Options", tag="Heading-3")
    game.insert_new_line()
    game.insert_new_line()

    game.insert_text("Window Options", tag="Heading-4")
    game.insert_new_line()
    game.insert_radiobutton("Normal", game.variable_state, 0, command=check_state)
    game.insert_radiobutton("Full Screen", game.variable_state, 1, command=check_state)
    game.insert_radiobutton("Border-less", game.variable_state, 2, command=check_state)
    game.insert_checkbutton("Maximized", game.variable_maximized, command=check_maximized)
    game.insert_new_line()

    game.insert_new_line()
    game.insert_command("< Back", command=menu)

    game.goto_end()
    game.disable()

def check_state(*args):
    if game.variable_state.get() == 0:
        game.add_borders()
        game.unfullscreen()

    elif game.variable_state.get() == 1:
        game.add_borders()
        game.fullscreen()

    elif game.variable_state.get() == 2:
        game.unfullscreen()
        game.remove_borders()

def check_maximized(*args):
    if game.variable_maximized.get():
        game.normal()
    else:
        game.maximise()

def main():
    startup()
    game.mainloop()

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
"""
Created on Tue Oct 19 23:02:56 2021

@author: Nico
"""

class spill:
    def __init__(self,spørsmål,alternativ,svar):
        self.spørsmål = spørsmål
        self.alternativ = alternativ
        self.svar = svar

    def __str__(self):
        spørsmål = f"""{self.spørsmål}
        1. {self.alternativ[0]}
        2. {self.alternativ[1]}
        3. {self.alternativ[2]}"""
        return spørsmål

    def sjekk_svar(self, svaret):
        if str(self.svar) == str(svaret):
            print("Svaret ditt er riktig")
        else:
            print("Svaret ditt er feil")

if __name__ == "__main__":
    spørsmål = "Hvilket pc-merke har jeg?"
    alternativ = ["Acer", "Lenovo", "Asus"]
    svar = 2

    klassen = spill(spørsmål, alternativ, svar)
    print((klassen))
    svaret = input("Svar: ")
    klassen.sjekk_svar(svaret)

    spørsmål = "Hva er best?"
    alternativ = ["Cola_zero", "Fanta", "Pepsi_max"]
    svar = 3

    klassen = spill(spørsmål, alternativ, svar)
    print(klassen)
    svaret = input("Svar: ")
    klassen.sjekk_svar(svaret)


import ply.lex as lex

tokens = [
    'LITERAL',
    'CONJ',
    'DISJ',
    'DOT',
    'OPERATOR',
    'OPENBR',
    'CLOSEBR'
]

t_LITERAL = r'[a-zA-Z_][a-zA-Z_0-9]*'

t_OPERATOR = r'\:\-'

t_CONJ = r'\,'

t_DOT = r'\.'

t_DISJ = r'\;'

t_OPENBR = r'\('

t_CLOSEBR = r'\)'

t_ignore = ' \t'

def t_newline(t):
    r'\n+'
    t.lexer.lineno += len(t.value)

template = 'Illegal character {0} at line {1} in position {2}'

def t_error(t):
    t.lexer.skip(1)
    raise Exception("Syntax error\n" + template.format(t.value[0], t.lineno, t.lexpos))

lexer = lex.lex()


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

datain = pd.read_excel('2019.11.1-2020.7.14进场.xlsx', header=4,
                       usecols=['箱号', '箱属', '箱尺', '进场日期', '进场时间', '好坏箱',
                                '当前好坏箱', '堆场', '区', '位', '进场准备时间'])[:-5]
datain = datain[datain['堆场'] == '1堆场']
dataout = pd.read_excel('2019.11.1-2020.7.14出场.xlsx', header=4,
                        usecols=['箱号', '箱属', '箱尺', '出场日期', '出场时间', '堆存天数', '当前好坏箱',
                                 '堆场', '区', '位', '列', '层', '出场准备时间', '车载确认时间'])[:-5]
# datarep = pd.read_excel('20191215-20191221-修箱报表.xlsx', header=4, usecols=['箱号', '状态日期', '堆场'])

damage_distribution = pd.DataFrame(np.arange(60).reshape((30, 2)),
                                   index=[['jan']*5 + ['feb']*5 + ['mar']*5 + ['apr']*5 + ['may']*5 + ['june']*5,
                                          ['COS', 'ONE', 'MSK', 'OOL', 'PIL']*6],
                                   columns=['好箱数', '坏箱数'])
damage_distribution.index.names = ['month', 'corporation']
damage_distribution.columns.names = ['好坏箱']

DMon = {}

damage_distribution_jan = datain[(datain['进场日期'] >= pd.Timestamp('2020-01-01 00:00:00')) &
                                 (datain['进场日期'] < pd.Timestamp('2020-02-01 00:00:00'))]
damage_distribution_feb = datain[(datain['进场日期'] >= pd.Timestamp('2020-02-01 00:00:00')) &
                                 (datain['进场日期'] < pd.Timestamp('2020-03-01 00:00:00'))]
damage_distribution_mar = datain[(datain['进场日期'] >= pd.Timestamp('2020-03-01 00:00:00')) &
                                 (datain['进场日期'] < pd.Timestamp('2020-04-01 00:00:00'))]
damage_distribution_apr = datain[(datain['进场日期'] >= pd.Timestamp('2020-04-01 00:00:00')) &
                                 (datain['进场日期'] < pd.Timestamp('2020-05-01 00:00:00'))]
damage_distribution_may = datain[(datain['进场日期'] >= pd.Timestamp('2020-05-01 00:00:00')) &
                                 (datain['进场日期'] < pd.Timestamp('2020-06-01 00:00:00'))]
damage_distribution_june = datain[(datain['进场日期'] >= pd.Timestamp('2020-06-01 00:00:00')) &
                                  (datain['进场日期'] < pd.Timestamp('2020-07-01 00:00:00'))]

DMon['jan'] = damage_distribution_jan
DMon['feb'] = damage_distribution_feb
DMon['mar'] = damage_distribution_mar
DMon['apr'] = damage_distribution_apr
DMon['may'] = damage_distribution_may
DMon['june'] = damage_distribution_june

for mon, cor in damage_distribution.index:
    damage_distribution.loc[mon, cor] = [len(DMon[mon][(DMon[mon]['箱属'] == cor) &
                                                       (DMon[mon]['好坏箱'] == '好箱')]),
                                         len(DMon[mon][(DMon[mon]['箱属'] == cor) &
                                                       (DMon[mon]['好坏箱'] == '坏箱')])]

# damage_distribution_month = datain[['箱属', '箱尺', '进场日期', '好坏箱']]
# damage_distribution_month['进场年月'] = damage_distribution_month['进场日期'].dt.month
# damage_distribution_month_cos = damage_distribution_month[damage_distribution_month['箱属'] == 'COS']
# sns.barplot(data=damage_distribution_month_cos, hue='好坏箱', x='进场年月')
# plt.show()
# data16in = datain[(datain['进场日期'] == pd.Timestamp('2019-12-16 00:00:00')) & (datain['堆场'] == '1堆场')]
# data16out = dataout[(dataout['出场日期'] == pd.Timestamp('2019-12-16 00:00:00')) & (dataout['堆场'] == '1堆场')]
# data16inout = pd.merge(data16in, data16out, on='箱号')
# data16rep = datarep[(datarep['状态日期'] == pd.Timestamp('2019-12-16 00:00:00')) & (datarep['堆场'] == '1堆场')]


# Interpretations for static stamp sequence operations.
# Will Blair - wdblair@cs.bu.edu

import patsolve

from z3 import *

# Get our solver
s = patsolve.solver

A = Array ("A", IntSort(), IntSort())
B = Array ("B", IntSort(), IntSort())

i, j, x, y, m, n = Ints("i j x y m n")

StampSeq = lambda name: Array (name, IntSort(), IntSort())
StampSeqSort = lambda : ArraySort (IntSort(), IntSort())

T0ype = DeclareSort ("t@ype")

# Some knowledge about sizeof
sizeof = Function ("sizeof", T0ype, IntSort())

a = Const ("a", T0ype)

s.add (
    ForAll (a, sizeof (a) > 0)
)

# Undefined Section of an Array

s.add (
    ForAll ([A, i], Implies (i < 0, A[i] == 0))
)

# The "nil" sequenc

nil = Function ('stampseq_nil', StampSeqSort())

s.add (
    ForAll (i, nil()[i] == 0)
)

# Sing

sing = Function ('stampseq_sing', IntSort(), StampSeqSort())

s.add (
    ForAll ([x, i], Select (sing(x), i) == Select(Store (nil(), 0, x), i))
)

# Cons

cons = Function ('stampseq_cons', IntSort(), StampSeqSort(),
                 StampSeqSort())

s.add (
    ForAll ([A, x], cons(x, A)[0] == x)
)

s.add (
    ForAll ([A, i, x], Implies (i > 0, cons(x, A)[i] == A[i-1]))
)

# Take

take = Function ('stampseq_take', StampSeqSort(), IntSort(),
                 StampSeqSort())

s.add (
    ForAll ([A, i, j], take(A, i)[j] == If(j < i, A[j], 0))
)

# Drop

drop = Function ('stampseq_drop', StampSeqSort(), IntSort(),
                 StampSeqSort())

s.add (
    ForAll ([A, i, j], drop(A, i)[j] == A[i+j])
)

# Insert

insert = Function ('stampseq_insert', StampSeqSort(), IntSort(),
                   IntSort(), StampSeqSort())

s.add (
    ForAll ([A, x, i, j], insert(A, i, x)[j] == If(j < i, A[j],
                                                   If(j == i, x, A[j-1]))
    )
)

# Append

append = Function ('stampseq_append', StampSeqSort(), IntSort(),
                   StampSeqSort(), IntSort(), StampSeqSort())

m, n = Int("m"), Int("n")

s.add (
    ForAll([A, B, m, n , i], append(A,m,B,n)[i] == If(i < m, A[i], B[i - m]))
)

# Sorting

def stampseq_sorted (xs, n):
    """
    The first n elements of xs are sorted.
    """
    i, j = Ints ("i j")

    return ForAll([i, j], Implies (
        And (0 <= i, i <= j, j < n),
        xs[i] <= xs[j])
    )

# This axiom is important for proving the ptr_offset method, but I think asserting
# it generally to Z3 causes proof times to go up too high. I want to be able to
# bind this assertion only in the scope of an individual function...

#l , i = Ints ('l i')

#s.add (
#    ForAll([l, i, a], Implies(i >= 0, ((l+(i*sizeof(a)))-l)/sizeof(a) == i))
#)


"""
A wrapper around publicly available pretrained models in PyTorch.
"""

import os
from typing import Optional, List, Dict, Union, Tuple
from itertools import chain

import torch
import torch.nn as nn
from torch.utils import model_zoo

from torchvision import models as torch_models
from visualpriors import taskonomy_network
import clip

from . import model_utils, pretrained_layers

_TORCHVISION_SEGMENTATION = [
    'deeplabv3_mobilenet_v3_large',
    'deeplabv3_resnet101',
    'deeplabv3_resnet50',
    'fcn_resnet101',
    'fcn_resnet50',
    'lraspp_mobilenet_v3_large'
]

_TORCHVISION_IMAGENET = [
    'alexnet',
    'convnext_base',
    'convnext_large',
    'convnext_small',
    'convnext_tiny',
    'densenet121',
    'densenet161',
    'densenet169',
    'densenet201',
    'efficientnet_b0',
    'efficientnet_b1',
    'efficientnet_b2',
    'efficientnet_b3',
    'efficientnet_b4',
    'efficientnet_b5',
    'efficientnet_b6',
    'efficientnet_b7',
    'efficientnet_v2_l',
    'efficientnet_v2_m',
    'efficientnet_v2_s',
    'googlenet',
    'inception_v3',
    'maxvit_t',
    'mnasnet0_5',
    'mnasnet0_75',
    'mnasnet1_0',
    'mnasnet1_3',
    'mobilenet_v2',
    'mobilenet_v3_large',
    'mobilenet_v3_small',
    'regnet_x_16gf',
    'regnet_x_1_6gf',
    'regnet_x_32gf',
    'regnet_x_3_2gf',
    'regnet_x_400mf',
    'regnet_x_800mf',
    'regnet_x_8gf',
    'regnet_y_128gf',
    'regnet_y_16gf',
    'regnet_y_1_6gf',
    'regnet_y_32gf',
    'regnet_y_3_2gf',
    'regnet_y_400mf',
    'regnet_y_800mf',
    'regnet_y_8gf',
    'resnet101',
    'resnet152',
    'resnet18',
    'resnet34',
    'resnet50',
    'resnext101_32x8d',
    'resnext101_64x4d',
    'resnext50_32x4d',
    'shufflenet_v2_x0_5',
    'shufflenet_v2_x1_0',
    'shufflenet_v2_x1_5',
    'shufflenet_v2_x2_0',
    'squeezenet1_0',
    'squeezenet1_1',
    'swin_b',
    'swin_s',
    'swin_t',
    'swin_v2_b',
    'swin_v2_s',
    'swin_v2_t',
    'vgg11',
    'vgg11_bn',
    'vgg13',
    'vgg13_bn',
    'vgg16',
    'vgg16_bn',
    'vgg19',
    'vgg19_bn',
    'vit_b_16',
    'vit_b_32',
    'vit_h_14',
    'vit_l_16',
    'vit_l_32',
    'wide_resnet101_2',
    'wide_resnet50_2'
]

__all__ = [
    'available_models'
]

def available_models(flatten: Optional[bool] = False) -> Union[Dict, List]:
    """
    List of supported models.

    Parameters:
        flatten (bool, optional): If True, returns a flattened list of all supported models.
                                  If False, returns a dictionary of model categories.

    Returns:
        Union[Dict, List]: List of supported models or a dictionary of model categories.
    """
    # Define categories and corresponding models
    all_models = {
        'imagenet': _TORCHVISION_IMAGENET,
        'segmentation': _TORCHVISION_SEGMENTATION,
        'taskonomy': ['taskonomy_%s' % t for t in taskonomy_network.LIST_OF_TASKS],
        'clip': ['clip_%s' % c for c in clip.available_models()]
    }

    # Return either a flattened list or the dictionary of model categories
    return list(chain.from_iterable(all_models.values())) if flatten else all_models

class ViTLayers(nn.Module):
    def __init__(self, parent_model: nn.Module, layer: str) -> None:
        """
        Initialize the ViTLayers module.

        Parameters:
            parent_model (nn.Module): The parent ViT model.
            layer (str): The layer to extract features up to (format: 'blockX' where X is the
             block number).

        Raises:
            RuntimeError: If the specified layer exceeds the total number of blocks in the parent
             model.
        """
        super(ViTLayers, self).__init__()
        self.parent_model = parent_model
        # TODO: support for conv_proj
        block = int(layer.replace('block', '')) + 1
        max_blocks = len(self.parent_model.encoder.layers)
        if block > max_blocks:
            raise RuntimeError(
                f'Layer {layer} exceeds the total number of {max_blocks} blocks.'
            )
        self.parent_model.encoder.layers = self.parent_model.encoder.layers[:block]
        delattr(self.parent_model, 'heads')

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Forward pass through the ViT model up to the specified layer.

        Parameters:
            x (torch.Tensor): The input tensor.

        Returns:
            torch.Tensor: The output tensor after processing up to the specified layer.
        """
        # Reshape and permute the input tensor
        x = self.parent_model._process_input(x)
        n = x.shape[0]

        # Expand the class token to the full batch
        batch_class_token = self.parent_model.class_token.expand(n, -1, -1)
        x = torch.cat([batch_class_token, x], dim=1)
        x = self.parent_model.encoder(x)
        return x

class ViTClipLayers(nn.Module):
    def __init__(self, parent_model: nn.Module, layer: str) -> None:
        """
        Initialize the ViTClipLayers module.

        Parameters:
            parent_model (nn.Module): The parent ViT-Clip model.
            layer (str): The layer to extract features up to (format: 'blockX' where X is the
             block number).

        Raises:
            RuntimeError: If the specified layer exceeds the total number of blocks in the parent
             model.
        """
        super(ViTClipLayers, self).__init__()
        self.parent_model = parent_model
        block = int(layer.replace('block', '')) + 1
        max_blocks = len(self.parent_model.transformer.resblocks)
        if block > max_blocks:
            raise RuntimeError(
                f'Layer {layer} exceeds the total number of {max_blocks} blocks.'
            )
        self.parent_model.transformer.resblocks = self.parent_model.transformer.resblocks[:block]

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Forward pass through the ViT-Clip model up to the specified layer.

        Parameters:
            x (torch.Tensor): The input tensor.

        Returns:
            torch.Tensor: The output tensor after processing up to the specified layer.
        """
        x = self.parent_model.conv1(x)  # shape = [*, width, grid, grid]
        x = x.reshape(x.shape[0], x.shape[1], -1)  # shape = [*, width, grid ** 2]
        x = x.permute(0, 2, 1)  # shape = [*, grid ** 2, width]
        x = torch.cat(
            [self.parent_model.class_embedding.to(x.dtype) + torch.zeros(
                x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device),
             x], dim=1
        )  # shape = [*, grid ** 2 + 1, width]
        x = x + self.parent_model.positional_embedding.to(x.dtype)
        x = self.parent_model.ln_pre(x)

        x = x.permute(1, 0, 2)  # NLD -> LND
        x = self.parent_model.transformer(x)
        x = x.permute(1, 0, 2)  # LND -> NLD
        return x

def _vit_features(model: nn.Module, layer: str) -> ViTLayers:
    """Creating a feature extractor from ViT network."""
    return ViTLayers(model, layer)

def _swin_features(model: nn.Module, layer: str) -> nn.Module:
    """Creating a feature extractor from SwinTransformer network."""
    layer = int(layer.replace('block', '')) + 1
    return nn.Sequential(*list(model.features.children())[:layer], model.permute)

def _sequential_features(model: nn.Module, layer: str, architecture: str,
                         avgpool: Optional[bool] = True) -> nn.Module:
    """Creating a feature extractor from sequential network."""
    if 'feature' in layer:
        layer = int(layer.replace('feature', '')) + 1
        features = nn.Sequential(*list(model.features.children())[:layer])
    elif 'classifier' in layer:
        layer = int(layer.replace('classifier', '')) + 1
        avgpool_layers = [model.avgpool, nn.Flatten(1)] if avgpool else []
        features = nn.Sequential(
            model.features, *avgpool_layers, *list(model.classifier.children())[:layer]
        )
    else:
        raise RuntimeError('Unsupported %s layer %s' % (architecture, layer))
    return features

def _vgg_features(model: nn.Module, layer: str) -> nn.Module:
    """Creating a feature extractor from VGG network."""
    return _sequential_features(model, layer, 'vgg')

def _alexnet_features(model: nn.Module, layer: str) -> nn.Module:
    """Creating a feature extractor from AlexNet network."""
    return _sequential_features(model, layer, 'alexnet')

def _mobilenet_features(model: nn.Module, layer: str, architecture: str) -> nn.Module:
    """Creating a feature extractor from MobileNet network."""
    if architecture in ['lraspp_mobilenet_v3_large', 'deeplabv3_mobilenet_v3_large']:
        layer = int(layer.replace('feature', '')) + 1
        return nn.Sequential(*list(model.children())[:layer])
    return _sequential_features(model, layer, 'mobilenet')

def _convnext_features(model: nn.Module, layer: str) -> nn.Module:
    """Creating a feature extractor from ComvNeXt network."""
    return _sequential_features(model, layer, 'convnext')

def _squeezenet_features(model: nn.Module, layer: str) -> nn.Module:
    """Creating a feature extractor from SqueezeNet network."""
    return _sequential_features(model, layer, 'squeezenet', avgpool=False)

def _efficientnet_features(model: nn.Module, layer: str) -> nn.Module:
    """Creating a feature extractor from EfficientNet network."""
    return _sequential_features(model, layer, 'efficientnet')

def _googlenet_features(model: nn.Module, layer: str) -> nn.Module:
    """Creating a feature extractor from GoogLeNet network."""
    l_ind = pretrained_layers.googlenet_cutoff_slice(layer)
    return nn.Sequential(*list(model.children())[:l_ind])

def _inception_features(model: nn.Module, layer: str) -> nn.Module:
    """Creating a feature extractor from Inception network."""
    l_ind = pretrained_layers.inception_cutoff_slice(layer)
    return nn.Sequential(*list(model.children())[:l_ind])

def _mnasnet_features(model: nn.Module, layer: str) -> nn.Module:
    """Creating a feature extractor from MnasNet network."""
    l_ind = int(layer.replace('layer', '')) + 1
    return nn.Sequential(*list(model.layers.children())[:l_ind])

def _shufflenet_features(model: nn.Module, layer: str) -> nn.Module:
    """Creating a feature extractor from ShuffleNet network."""
    l_ind = int(layer.replace('layer', '')) + 1
    return nn.Sequential(*list(model.children())[:l_ind])

def _densenet_features(model: nn.Module, layer: str) -> nn.Module:
    """Creating a feature extractor from DenseNet network."""
    return _sequential_features(model, layer, 'densenet')

def _clip_features(model: nn.Module, layer: str, architecture: str) -> nn.Module:
    """Creating a feature extractor from CLIP network."""
    clip_arch = architecture.replace('clip_', '')
    if layer == 'encoder':
        features = model
    else:
        if clip_arch in ['RN50', 'RN101', 'RN50x4', 'RN50x16', 'RN50x64']:
            features = _resnet_features(model, layer, is_clip=True)
        else:
            features = ViTClipLayers(model, layer)
    return features

def _maxvit_features(model: nn.Module, layer: str) -> nn.Module:
    """Creating a feature extractor from MaxVit network."""
    if 'block0' in layer:
        features = model.stem
    elif 'block' in layer:
        layer = int(layer[-1])
        features = nn.Sequential(model.stem, *list(model.blocks.children())[:layer])
    elif 'classifier' in layer:
        layer = int(layer.replace('classifier', '')) + 1
        features = nn.Sequential(
            model.stem, *list(model.blocks.children()), *list(model.classifier.children())[:layer]
        )
    else:
        raise RuntimeError('Unsupported regnet layer %s' % layer)
    return features

def _regnet_features(model: nn.Module, layer: str) -> nn.Module:
    """Creating a feature extractor from RegNet network."""
    if 'block0' in layer:
        features = model.stem
    elif 'block' in layer:
        layer = int(layer[-1])
        features = nn.Sequential(model.stem, *list(model.trunk_output.children())[:layer])
    else:
        raise RuntimeError('Unsupported regnet layer %s' % layer)
    return features

def _resnet_features(model: nn.Module, layer: str, is_clip: Optional[bool] = False) -> nn.Module:
    """Creating a feature extractor from ResNet network."""
    l_ind = pretrained_layers.resnet_cutoff_slice(layer, is_clip=is_clip)
    return nn.Sequential(*list(model.children())[:l_ind])

def model_features(model: nn.Module, architecture: str, layer: str) -> nn.Module:
    """
    Return features extracted from one layer.

    Parameters:
        model (nn.Module): The pretrained model.
        architecture (str): Name of the architecture.
        layer (str): Name of the layer.

    Raises:
        RuntimeError: If the specified layer is not supported for the given architecture.

    Returns:
        nn.Module: The features extracted from the specified layer.
    """
    if layer not in pretrained_layers.available_layers(architecture):
        raise RuntimeError(
            'Layer %s is not supported for architecture %s. Call pretrained_layers.available_layers'
            ' to see a list of supported layers for an architecture.' % (layer, architecture)
        )

    if architecture in _TORCHVISION_IMAGENET and layer == 'fc':
        features = model
    elif 'clip' in architecture:
        features = _clip_features(model, layer, architecture)
    else:
        if model_utils.is_resnet_backbone(architecture):
            features = _resnet_features(model, layer)
        elif 'regnet' in architecture:
            features = _regnet_features(model, layer)
        elif 'vgg' in architecture:
            features = _vgg_features(model, layer)
        elif architecture == 'alexnet':
            features = _alexnet_features(model, layer)
        elif architecture == 'googlenet':
            features = _googlenet_features(model, layer)
        elif architecture == 'inception_v3':
            features = _inception_features(model, layer)
        elif 'convnext' in architecture:
            features = _convnext_features(model, layer)
        elif 'densenet' in architecture:
            features = _densenet_features(model, layer)
        elif 'mnasnet' in architecture:
            features = _mnasnet_features(model, layer)
        elif 'shufflenet' in architecture:
            features = _shufflenet_features(model, layer)
        elif 'squeezenet' in architecture:
            features = _squeezenet_features(model, layer)
        elif 'efficientnet' in architecture:
            features = _efficientnet_features(model, layer)
        elif 'mobilenet' in architecture:
            features = _mobilenet_features(model, layer, architecture)
        elif 'maxvit' in architecture:
            features = _maxvit_features(model, layer)
        elif 'swin_' in architecture:
            features = _swin_features(model, layer)
        elif 'vit_' in architecture:
            features = _vit_features(model, layer)
        else:
            raise RuntimeError('Unsupported network %s' % architecture)

    return features

def _taskonomy_weights(network_name: str, weights: str) -> Union[str, None]:
    """Handling default Taskonomy weights."""
    if weights is None:
        return None
    if network_name == weights:
        feature_task = weights.replace('taskonomy_', '')
        weights = taskonomy_network.TASKONOMY_PRETRAINED_URLS[feature_task + '_encoder']
    return weights

def _torchvision_weights(network_name: str, weights: str) -> Union[str, None]:
    """Handling default torchvision weights."""
    if weights == 'none':
        return None
    return 'DEFAULT' if network_name == weights else weights

def _load_weights(model: nn.Module, weights: str) -> nn.Module:
    """Loading the weights of a network from URL or local file."""
    if weights in ['none', None]:
        pass
    elif 'https://' in weights or 'http://' in weights:
        checkpoint = model_zoo.load_url(weights, model_dir=None, progress=True)
        model.load_state_dict(checkpoint['state_dict'])
    elif os.path.exists(weights):
        checkpoint = torch.load(weights, map_location='cpu')
        model.load_state_dict(checkpoint['state_dict'])
    else:
        raise RuntimeError('Unknown weights: %s' % weights)
    return model

def get_pretrained_model(network_name: str, weights: str) -> nn.Module:
    """
    Load a network with or without pretrained weights.

    Parameters:
        network_name (str): Name of the network.
        weights (str): Path to the pretrained weights file.
        clip_cpu (bool): Load the CLIP model in CPU.

    Raises:
        RuntimeError: If the specified network is not supported.

    Returns:
        nn.Module: The pretrained model.
    """
    if network_name not in available_models(flatten=True):
        raise RuntimeError('Network %s is not supported.' % network_name)

    if 'clip_' in network_name:
        # Load CLIP model
        # TODO: support for None
        clip_version = network_name.replace('clip_', '')
        device = "cuda" if torch.cuda.is_available() and weights not in ['none', None] else "cpu"
        model, _ = clip.load(clip_version, device=device)
    elif 'taskonomy_' in network_name:
        # Load Taskonomy model
        model = taskonomy_network.TaskonomyEncoder()
        model = _load_weights(model, _taskonomy_weights(network_name, weights))
    else:
        # Load torchvision networks
        weights = _torchvision_weights(network_name, weights)
        net_fun = torch_models.segmentation if network_name in _TORCHVISION_SEGMENTATION else torch_models
        kwargs = {'aux_logits': False} if network_name in ['googlenet', 'inception_v3'] else {}
        model = net_fun.__dict__[network_name](weights=weights, **kwargs)

    return model

def get_image_encoder(network_name: str, model: nn.Module) -> nn.Module:
    """
    Returns the encoder block of a network.

    Parameters:
        network_name (str): Name of the network.
        model (nn.Module): The pretrained model.

    Returns:
        nn.Module: The encoder block of the network.
    """
    if 'clip' in network_name:
        return model.visual
    elif network_name in _TORCHVISION_SEGMENTATION:
        return model.backbone
    return model

def preprocess_mean_std(network_name: str) -> (Tuple[float], Tuple[float]):
    """
    Returns the mean and std used in pretrained preprocessing.

    Parameters:
        network_name (str): Name of the network.

    Returns:
        Tuple[float], Tuple[float]: Mean and std for preprocessing.
    """
    if 'clip_' in network_name:
        mean = (0.48145466, 0.4578275, 0.40821073)
        std = (0.26862954, 0.26130258, 0.27577711)
    elif 'taskonomy_' in network_name:
        mean = (0.5, 0.5, 0.5)
        std = (0.5, 0.5, 0.5)
    elif network_name in [
        *torch_models.list_models(module=torch_models.segmentation),
        *torch_models.list_models(module=torch_models)
    ]:
        mean = (0.485, 0.456, 0.406)
        std = (0.229, 0.224, 0.225)
    else:
        raise RuntimeError('The preprocess for architecture %s is unknown.' % network_name)

    return mean, std


from shared_food import SharedFood
from faker import Faker

fake = Faker()

food_names_list = [
    'danish', 'cheesecake', 'sugar',
    'Lollipop', 'wafer', 'Gummies',
    'sesame', 'beans',
    'pie', 'bar', 'Ice', 'oat']

first_name_list = ['Dani', 'Daniel', 'Alice', 'Johnny', 'Yogev', 'Sarah']
last_name_list = ['Coh', 'Daniel', 'Alice', 'Johnny', 'Yogev', 'Sarah']
# building_number = range(0,21)
# street_name = []
# city = []
# country = []
fake_address  = "herzl 8 tel aviv israel"

def faker_shared_food_generate(type=None, faker_mode=False):
    shared_food_attributes = {
        'food_title': fake.word(ext_word_list=food_names_list).capitalize(),
        'food_text': ' '.join(fake.sentence(ext_word_list=food_names_list).split(' ')[0:4]),
        # 'food_text':"'Cheesecake with a sprinkle of sugar'",
        # 'address': fake_address or f"{fake.street_address()}, {fake.city()}, {fake.country()}",
        'country':'israel',
        'city':'tel aviv',
        'street_name':'david ben gurion',
        'building_number':'8',
        'first_name': fake.first_name(),
        'last_name': fake.last_name(),
        'contact_phone': fake.phone_number(),
    }

    faked_attrs = {
            'created_at': fake.date(),
            'updated_at': fake.date(),
            'published': fake.boolean(),
    }

    if faker_mode:
        shared_food_attributes.update(faked_attrs)

    return shared_food_attributes.get(type) or faked_attrs.get(type) if type else shared_food_attributes

# print(faker_user_generate())
# print(faker_user_generate('food_title'))

# new_food_share = SharedFood(faker_shared_food_generate())
# print(vars(new_food_share))
# print(new_food_share.user_id)

# print(SharedFood.get_by_id(3))
SharedFood(faker_shared_food_generate())