def answer(l):
    # your code here

    def get_details(elevator):

        details = [None,None,None]
        detail_index = 0
        detail = ''

        last_dot = 0
        for i in range(0,len(elevator)):
            if elevator[i] != '.':
                detail += elevator[i]
            else:
                details[detail_index] = int(detail)
                detail_index += 1
                detail = ''
                last_dot = i+1

        details[detail_index] = int(elevator[last_dot:len(elevator)])
        return details

    def compare(elevator1,elevator2):
        elevator1_details = get_details(elevator1)
        elevator2_details = get_details(elevator2)

        for i in range(0,len(elevator1_details)):
            if elevator1_details[i] is None and elevator2_details[i] is not None:
                return -1

            if elevator1_details[i] is not None and elevator2_details[i] is None:
                return 1

            if elevator1_details[i] > elevator2_details[i]:
                return 1

            if elevator2_details[i] > elevator1_details[i]:
                return -1

        return 0

    return sorted(l,cmp=compare)


"""蒙特卡洛法计算无理数PI"""
import numpy as np
import matplotlib.pyplot as plt

# 绘制第一象限内的图形
def draw(count):
    in_ = 0
    out_ = 0
    plt.xlim(xmax=1, xmin=0)
    plt.ylim(ymax=1, ymin=0)
    for i in range(count):
        x = np.random.uniform(0, 1)
        y = np.random.uniform(0, 1)
        if (x ** 2 + y ** 2 < 1):
            in_ = in_ + 1
            plt.scatter(x, y, s=2, c="red")
        else:
            out_ = out_ + 1
            plt.scatter(x, y, s=2, c="blue")
        print('\r{:.2f}%'.format(i / count*100), end='')
    plt.title("n={} PI={}".format(count, in_ / (in_ + out_) * 4))
    plt.show()

# count = int(input("请输入生成点的数量:"))
draw(30000)


import heapq

def kthSmallest(iterable, k):
    smallest = []
    for value in iterable:
        print(smallest)
        heapq.heappush(smallest, -value)
        if len(smallest) > k:
            heapq.heappop(smallest)
    if (len(smallest) < k):
        return None
    return -smallest[0]

print(kthSmallest([8, 16, 80, 55, 32, 8, 38], 3))


import os
import torch
from fvcore.common.checkpoint import Checkpointer
from torch.utils import model_zoo

from detectron2.checkpoint import DetectionCheckpointer as _DetectionCheckpointer
from detectron2.utils import comm
from slender_det.utils.file_io import PathManager

class DetectionCheckpointer(_DetectionCheckpointer):
    def __init__(self, model, save_dir="", *, save_to_disk=None, **checkpointables):
        is_main_process = comm.is_main_process()
        super().__init__(
            model,
            save_dir,
            save_to_disk=is_main_process if save_to_disk is None else save_to_disk,
            **checkpointables,
        )
        self.path_manager = PathManager

def load_from_http(filename, map_location=None, model_dir=None):
    """load checkpoint through HTTP or HTTPS scheme path. In distributed
    setting, this function only download checkpoint at local rank 0.
    Args:
        filename (str): checkpoint file path with modelzoo or
            torchvision prefix
        map_location (str, optional): Same as :func:`torch.load`.
        model_dir (string, optional): directory in which to save the object,
            Default: None
    Returns:
        dict or OrderedDict: The loaded checkpoint.
    """
    rank, world_size = comm.get_rank(), comm.get_world_size()
    rank = int(os.environ.get("LOCAL_RANK", rank))
    if rank == 0:
        checkpoint = model_zoo.load_url(
            filename, model_dir=model_dir, map_location=map_location
        )
    if world_size > 1:
        torch.distributed.barrier()
        if rank > 0:
            checkpoint = model_zoo.load_url(
                filename, model_dir=model_dir, map_location=map_location
            )
    return checkpoint

def load_checkpoint_from_http(
    model,
    filename,
    map_location=None,
):
    checkpointer = Checkpointer(model)
    checkpoint = load_from_http(filename, map_location=map_location)

    checkpointer.logger.info("[Checkpointer] Loading from {} ...".format(filename))
    incompatible = checkpointer._load_model(checkpoint={"model": checkpoint})

    # handle some existing subclasses that returns None
    if incompatible is not None:
        checkpointer._log_incompatible_keys(incompatible)


import time

def d1_p1(numbers):
    count = 0
    max_calories = 0
    for number in numbers:
        if number:
            count += int(number)
            if count > max_calories:
                max_calories = count
        else:
            count = 0
    return max_calories

def d1(numbers, top):
    count = 0
    calories = []
    for number in numbers:
        if number:
            count += int(number)
        else:
            calories.append(count)
            count = 0
    if count:
        calories.append(count)
    calories.sort(reverse=True)
    return sum(calories[:top])

if __name__ == "__main__":
    replit_start_time = time.perf_counter()
    with open("d1.txt") as f:
        data = f.readlines()
    numbers = [x.strip() for x in data]

    print(d1(numbers, 1))
    print(d1(numbers, 3))

    # Keep this line at the end of your code
    replit_end_time = time.perf_counter()
    print("Elapsed time:", replit_end_time - replit_start_time)


import re

for _ in range(int(input())):
    try:

        # compile()
        # Regex are compiled into pattern objects using compile(), which have methods for various operations
        # such as searching for pattern matches or performing string substitutions.
        r = re.compile(input())
        print("True")
    except re.error:
        print("False")


import os
import hashlib
import sqlite3

def makeDB():
    mp3_path = "words_pronounce"
    if not os.path.exists( mp3_path ) :
        return
    for f in os.listdir( mp3_path ) :
        _name , _ext = os.path.splitext(f)
        path_f = os.path.join( mp3_path, f )
        with open( path_f ) as fp :
            data = fp.read()

            c.execute("INSERT or replace INTO pron VALUES ( ?,?)" , ( _name .decode( "utf8" ) , buffer(data) ) )
    pass

if __name__ == '__main__' :

    db_file = "pron.db"
    conn = sqlite3.connect(db_file)
    c = conn.cursor()

    c.execute( "drop table if exists pron "  )
    c.execute( '''create table if not exists pron
                    ( word text primary key ,  voice BLOB NOT NULL  ) ''' )

    makeDB()

    # c.execute( '''create UNIQUE index index_pron_word_voice on pron ( word , voice  ) ''' )
    c.execute( "vacuum" )

    conn.commit()
    conn.close()


"""
Write an algorithm to determine if a number is "happy".

A happy number is a number defined by the following process:
Starting with any positive integer, replace the number by the sum
of the squares of its digits, and repeat the process until the number
equals 1 (where it will stay), or it loops endlessly in a cycle which
does not include 1. Those numbers for which this process ends in 1 are
happy numbers.

Example:

Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
"""

class Solution:
    """
    Runtime: 32 ms, faster than 99.59% of Python3.
    Memory Usage: 13.2 MB, less than 54.55% of Python3.

    Algorithm sees a number it has seen before, then it follows that
    it will go on the same path and thus see it once again, creating
    an infinite loop. So a valid solution requires that all numbers
    seen on the way to reducing n to 1 be unique.
    """

    def isHappy(self, n: int) -> bool:
        memo = set()
        while n not in memo:
            memo.add(n)
            n = sum(int(x) ** 2 for x in str(n))
        return 1 in memo

if __name__ == "__main__":
    s = Solution()
    assert s.isHappy(19) is True
    assert s.isHappy(7) is True  # 7**2 = 49 -> 4**2 + 9**2 = 16 + 81 = 97 -> ...
    assert s.isHappy(1111111) is True  # 1**2 + ... + 1**2 = 7
    assert s.isHappy(0) is False


import asyncio
import logging
import inspect
import concurrent.futures
from azure.iot.device.common import handle_exceptions
from azure.iot.device.iothub.sync_handler_manager import (
    AbstractHandlerManager,
    HandlerManagerException,
    HandlerRunnerKillerSentinel,
    CLIENT_EVENT,
)
from . import loop_management

logger = logging.getLogger(__name__)

class AsyncHandlerManager(AbstractHandlerManager):
    """Handler manager for use with asynchronous clients"""

    async def _receiver_handler_runner(self, inbox, handler_name):
        """Run infinite loop that waits for an inbox to receive an object from it, then calls
        the handler with that object
        """
        logger.debug("HANDLER RUNNER ({}): Starting runner".format(handler_name))

        # Define a callback that can handle errors in the ThreadPoolExecutor
        _handler_callback = self._generate_callback_for_handler("CLIENT_EVENT")

        # ThreadPool used for running handler functions. By invoking handlers in a separate thread
        # we can be safe knowing that customer code that has performance issues does not block
        # client code. Note that the ThreadPool is only used for handler FUNCTIONS (coroutines are
        # invoked on a dedicated event loop + thread)
        tpe = concurrent.futures.ThreadPoolExecutor(max_workers=4)
        while True:
            handler_arg = await inbox.get()
            if isinstance(handler_arg, HandlerRunnerKillerSentinel):
                # Exit the runner when a HandlerRunnerKillerSentinel is found
                logger.debug(
                    "HANDLER RUNNER ({}): HandlerRunnerKillerSentinel found in inbox. Exiting.".format(
                        handler_name
                    )
                )
                tpe.shutdown()
                break
            # NOTE: we MUST use getattr here using the handler name, as opposed to directly passing
            # the handler in order for the handler to be able to be updated without cancelling
            # the running task created for this coroutine
            handler = getattr(self, handler_name)
            logger.debug("HANDLER RUNNER ({}): Invoking handler".format(handler_name))
            if inspect.iscoroutinefunction(handler):
                # Run coroutine on a dedicated event loop for handler invocations
                # TODO: Can we call this on the user loop instead?
                handler_loop = loop_management.get_client_handler_loop()
                fut = asyncio.run_coroutine_threadsafe(handler(handler_arg), handler_loop)
                # Free up this object so the garbage collector can free it if necessary. If we don't
                # do this, we end up keeping this object alive until the next event arrives, which
                # might be a long time. Tests would flag this as a memory leak if that happened.
                del handler_arg
                fut.add_done_callback(_handler_callback)
            else:
                # Run function directly in ThreadPool
                fut = tpe.submit(handler, handler_arg)
                # Free up this object so the garbage collector can free it if necessary. If we don't
                # do this, we end up keeping this object alive until the next event arrives, which
                # might be a long time. Tests would flag this as a memory leak if that happened.
                del handler_arg
                fut.add_done_callback(_handler_callback)

    async def _client_event_handler_runner(self):
        """Run infinite loop that waits for the client event inbox to receive an event from it,
        then calls the handler that corresponds to that event
        """
        logger.debug("HANDLER RUNNER (CLIENT EVENT): Starting runner")
        _handler_callback = self._generate_callback_for_handler("CLIENT_EVENT")

        # ThreadPool used for running handler functions. By invoking handlers in a separate thread
        # we can be safe knowing that customer code that has performance issues does not block
        # client code. Note that the ThreadPool is only used for handler FUNCTIONS (coroutines are
        # invoked on a dedicated event loop + thread)
        tpe = concurrent.futures.ThreadPoolExecutor(max_workers=4)
        event_inbox = self._inbox_manager.get_client_event_inbox()
        while True:
            event = await event_inbox.get()
            if isinstance(event, HandlerRunnerKillerSentinel):
                # Exit the runner when a HandlerRunnerKillerSentinel is found
                logger.debug(
                    "HANDLER RUNNER (CLIENT EVENT): HandlerRunnerKillerSentinel found in event queue. Exiting."
                )
                tpe.shutdown()
                break
            handler = self._get_handler_for_client_event(event.name)
            if handler is not None:
                logger.debug(
                    "HANDLER RUNNER (CLIENT EVENT): {} event received. Invoking {} handler".format(
                        event, handler
                    )
                )
                if inspect.iscoroutinefunction(handler):
                    # Run a coroutine on a dedicated event loop for handler invocations
                    # TODO: Can we call this on the user loop instead?
                    handler_loop = loop_management.get_client_handler_loop()
                    fut = asyncio.run_coroutine_threadsafe(
                        handler(*event.args_for_user), handler_loop
                    )
                    # Free up this object so the garbage collector can free it if necessary. If we don't
                    # do this, we end up keeping this object alive until the next event arrives, which
                    # might be a long time. Tests would flag this as a memory leak if that happened.
                    del event
                    fut.add_done_callback(_handler_callback)
                else:
                    # Run a function directly in ThreadPool
                    fut = tpe.submit(handler, *event.args_for_user)
                    # Free up this object so the garbage collector can free it if necessary. If we don't
                    # do this, we end up keeping this object alive until the next event arrives, which
                    # might be a long time. Tests would flag this as a memory leak if that happened.
                    del event
                    fut.add_done_callback(_handler_callback)
            else:
                logger.debug(
                    "No handler for event {} set. Skipping handler invocation".format(event)
                )

    def _start_handler_runner(self, handler_name):
        """Create, and store a task for running a handler"""
        # Run the handler runner on a dedicated event loop for handler runners so as to be
        # isolated from all other client activities
        runner_loop = loop_management.get_client_handler_runner_loop()

        # Client Event handler flow
        if handler_name == CLIENT_EVENT:
            if self._client_event_runner is not None:
                # This branch of code should NOT be reachable due to checks prior to the invocation
                # of this method. The branch exists for safety.
                raise HandlerManagerException(
                    "Cannot create thread for handler runner: {}. Runner thread already exists".format(
                        handler_name
                    )
                )
            # Client events share a handler
            coro = self._client_event_handler_runner()
            future = asyncio.run_coroutine_threadsafe(coro, runner_loop)
            # Store the future
            self._client_event_runner = future

        # Receiver handler flow
        else:
            if self._receiver_handler_runners[handler_name] is not None:
                # This branch of code should NOT be reachable due to checks prior to the invocation
                # of this method. The branch exists for safety.
                raise HandlerManagerException(
                    "Cannot create task for handler runner: {}. Task already exists".format(
                        handler_name
                    )
                )
            # Each receiver handler gets its own runner
            inbox = self._get_inbox_for_receive_handler(handler_name)
            coro = self._receiver_handler_runner(inbox, handler_name)
            future = asyncio.run_coroutine_threadsafe(coro, runner_loop)
            # Store the future
            self._receiver_handler_runners[handler_name] = future

        _handler_runner_callback = self._generate_callback_for_handler_runner(handler_name)
        future.add_done_callback(_handler_runner_callback)

    def _stop_receiver_handler_runner(self, handler_name):
        """Stop and remove a handler runner task.
        All pending items in the corresponding inbox will be handled by the handler before stoppage.
        """
        logger.debug(
            "Adding HandlerRunnerKillerSentinel to inbox corresponding to {} handler runner".format(
                handler_name
            )
        )
        inbox = self._get_inbox_for_receive_handler(handler_name)
        inbox.put(HandlerRunnerKillerSentinel())

        # Wait for Handler Runner to end due to the sentinel
        logger.debug("Waiting for {} handler runner to exit...".format(handler_name))
        future = self._receiver_handler_runners[handler_name]
        future.result()
        # Stop tracking the task since it is now complete
        self._receiver_handler_runners[handler_name] = None
        logger.debug("Handler runner for {} has been stopped".format(handler_name))

    def _stop_client_event_handler_runner(self):
        """Stop and remove a handler task.
        All pending items in the client event queue will be handled by handlers (if they exist)
        before stoppage.
        """
        logger.debug("Adding HandlerRunnerKillerSentinel to client event queue")
        event_inbox = self._inbox_manager.get_client_event_inbox()
        event_inbox.put(HandlerRunnerKillerSentinel())

        # Wait for Handler Runner to end due to the stop command
        logger.debug("Waiting for client event handler runner to exit...")
        future = self._client_event_runner
        future.result()
        # Stop tracking the task since it is now complete
        self._client_event_runner = None
        logger.debug("Handler runner for client events has been stopped")

    def _generate_callback_for_handler_runner(self, handler_name):
        """Define a callback that can handle errors during handler runner execution"""

        def handler_runner_callback(completed_future):
            try:
                e = completed_future.exception(timeout=0)
            except Exception as raised_e:
                # This shouldn't happen because cancellation or timeout shouldn't occur...
                # But just in case...
                new_err = HandlerManagerException(
                    "HANDLER RUNNER ({}): Unable to retrieve exception data from incomplete task".format(
                        handler_name
                    )
                )
                new_err.__cause__ = raised_e
                handle_exceptions.handle_background_exception(new_err)
            else:
                if e:
                    # If this branch is reached something has gone SERIOUSLY wrong.
                    # We must log the error, and then restart the runner so that the program
                    # does not enter an invalid state
                    new_err = HandlerManagerException(
                        "HANDLER RUNNER ({}): Unexpected error during task".format(handler_name),
                    )
                    new_err.__cause__ = e
                    handle_exceptions.handle_background_exception(new_err)
                    # Clear the tracked runner, and start a new one
                    logger.debug("HANDLER RUNNER ({}): Restarting handler runner")
                    self._receiver_handler_runners[handler_name] = None
                    self._start_handler_runner(handler_name)
                else:
                    logger.debug(
                        "HANDLER RUNNER ({}): Task successfully completed without exception".format(
                            handler_name
                        )
                    )

        return handler_runner_callback


## PyBank Instructions

#In this challenge, you are tasked with creating a Python script to analyze the financial records of your company. You will give a set of financial data called [budget_data.csv](PyBank/Resources/budget_data.csv). The dataset is composed of two columns: "Date" and "Profit/Losses". (Thankfully, your company has rather lax standards for accounting, so the records are simple.)

#Your task is to create a Python script that analyzes the records to calculate each of the following:

#* The total number of months included in the dataset

#* The net total amount of "Profit/Losses" over the entire period

#* The changes in "Profit/Losses" over the entire period, and then the average of those changes

#* The greatest increase in profits (date and amount) over the entire period

#* The greatest decrease in profits (date and amount) over the entire period

#Import the necessary modules.
import os
import csv
from numpy import average

from sqlalchemy import LABEL_STYLE_DISAMBIGUATE_ONLY

#Allow Python to locate the .csv file
bank_data = os.path.join('Resources','budget_data.csv')

#Declare a variable to hold total Profit/Loss and a list to hold the values of Profit/Loss
total_p = 0
profit = []

#Declare a variable to hold the change in dates and the total number of months and list them appropriately
m_change = 0
last_m = 0
months = []

#Allow Python to read the .csv file we located
with open(bank_data,newline="") as csvfile:
    csvreader = csv.reader(csvfile, delimiter = ",")
    df_header = next(csvreader)
#Loop Through the list adding appropriate values to their respective lists
    for row in csvreader:
        months.append(row[0])
        profit.append(row[1])

        #Total months can be determined by grabbing the value of the length of the list.
        total_month = len(months)

        #Total Profit/Loss can be determined by added up the values stored in the second row of the file.
        total_p = total_p + int(row[1])

    #In order to calculate change in profit, we subtract the second row from the first and store their values respectively.
    profit = [int(i) for i in profit]
    change = [profit[i+1] - profit[i] for i in range(len(profit)-1)]

    #Then we take the sum total of the change in profit that we stored and divide it by the lenght of the list to gain AVERAGE PROFIT
    avg_p = sum(change)/len(change)

    #Round the result to 2 decimal places
    avg_p = round(avg_p,2)

    #Our Greatest Profit can be aquired through pulling the max value of individual profits we stored
    Greatest_i = max(change)

    #Similarly we can aquire the Greatest Loss through the min value
    Greatest_d = min(change)

    #We can display the dates of the values above by referencing their respective date in correspondance to the we Greatest Profit/Loss
    i_date = months[change.index(Greatest_i)]
    d_date = months[change.index(Greatest_d)]

#Final Print on the Terminal to display our results

print("Financial Analysis")
print("-----------------------------------------")
print(f"Total Months:   {str(total_month)}")
print(f"Total Profit: ${str(total_p)}")
print(f"Average Profit: ${str(avg_p)}")
print(f"Greatest Increase in Profit: {i_date} ${Greatest_i} ")
print(f"Greatest Loss: {d_date} ${Greatest_d}")
print("------------------------------------------")

#Exporting the results into a .txt file

with open('bank_data.txt', 'w') as text:
    text.write("Financial Analysis" + "\n")
    text.write("-----------------------------------------\n")
    text.write(f"Total Months:   {str(total_month)}"+"\n")
    text.write(f"Total Profit: ${str(total_p)}"+"\n")
    text.write(f"Average Profit: ${str(avg_p)}"+"\n")
    text.write(f"Greatest Increase in Profit: {i_date} ${Greatest_i}"+"\n ")
    text.write(f"Greatest Loss: {d_date} ${Greatest_d}"+"\n")
    text.write("------------------------------------------\n")


import random
import re

from termcolor import colored

from app.load_data import numbers, names

def formatted_items(item_list):
    formatted = []
    for item in item_list:
        if item.quantity > 1:
            formatted.append(f"{numbers[item.quantity]} {colored(item.plural, 'yellow')}")
        else:
            formatted.append(colored(item.name, 'yellow'))
    return formatted

def comma_separated(words):
    """ Takes a list of words and returns a string """
    if len(words) >= 3:
        commas = ", ".join(words[0:-1])
        return f"{commas} and {words[-1]}"
    elif len(words) == 2:
        return f"{words[0]} and {words[1]}"
    else:
        return words[0]

def add_dicts_together(dict1, dict2):
    dict3 = dict(dict1)
    dict3.update(dict2)
    return dict3

def parse_inventory_action(words):
    words = words.lower().strip()
    words_s = words.split(" ")

    if words == "everything" or words == "all":
        quantity = "all"
        item_text = None

    elif re.match(r"\d* .*", words):
        quantity = int(words_s[0])
        item_text = " ".join(words_s[1:])

    elif words_s[0] in ("all", "the"):
        quantity = "all"
        item_text = " ".join(words_s[1:])

    elif words_s[0] in ("a", "an", "some"):
        quantity = 1
        item_text = " ".join(words_s[1:])

    elif words_s[0] in numbers.values():
        quantity = [k for k, v in numbers.items() if v == words_s[0]][0]
        item_text = " ".join(words_s[1:])

    elif words == "":
        item_text = None
        quantity = None

    else:
        quantity = "all"
        item_text = " ".join(words_s[0:])

    return quantity, item_text

def remove_little_words(phrase):
    if not isinstance(phrase, list):
        phrase = phrase.split(" ")
    return " ".join([word for word in phrase if word.lower() not in ('a', 'an', 'the', 'that', 'this', 'to')])

def odds(x):
    return bool(random.randint(1, int(x)) == 1)

def are_is(noun_list):
    quantity = len(noun_list)
    if quantity == 1:
        quantity = noun_list[0].quantity
    return f"{'are' if quantity > 1 else 'is'} {comma_separated(formatted_items(noun_list))}"

def capitalize_first(string):
    if not string[0].isalpha() and not string[0].isdigit():
        return f"{string[0:3]}{string[4].upper()}{string[5:]}"

def find_specifics(words, list_of_objects):
    # TODO first assume player spelled the thing right, then sort through everything
    specifics = []
    if list_of_objects is None:
        return specifics
    if words is None or words == '':
        return list_of_objects
    words = remove_little_words(words).split(' ')
    if any(word in ('all', 'everyone', 'everything') for word in words):
        return list_of_objects
    for word in words:
        for o in list_of_objects:
            for individual_word in remove_little_words(o.name).lower().split(' '):
                if (word.lower() in individual_word.lower() or word.lower() == individual_word.lower() or
                        word.lower() == o.plural.lower() or word.lower() in o.plural):
                    specifics.append(o)
                    break
    specifics = list(set(specifics))
    more_specifics = None
    if len(specifics) > 1:
        more_specifics = [x for x in specifics if x.name == ' '.join(words) or x.plural == ' '.join(words)]
    return specifics if not more_specifics else more_specifics

def the_name(unique_name):
    """ Returns a shortened version of unique_name - Bob the squirrel becomes Bob, a cat becomes the cat"""
    for name in names:
        if name in unique_name:
            return name
    else:
        return f"the {remove_little_words(unique_name)}"


from pymongo import MongoClient

# database
mongoClient = MongoClient('mongodb://localhost:27017/')
db = mongoClient['chatbot']
# collection = db['intent']

'''with open('bay.txt', 'r', encoding='utf-8') as f:
    lines = f.readlines()
    for line in lines:
        line = line.split(',')
        intent_msg = {'msg': line[0], 'intent':line[1].strip()}
        collection.update_one(intent_msg, {'$set': intent_msg}, upsert=True)'''

'''collection = db['kakao']
data = collection.find({})
for date in data:
    # timestamp = data['timestamp']
    timestamp = date['timestamp'].split(' ')
    print(timestamp)
    timesplit = timestamp[0].split(',')[0]
    timesplit = timesplit.split('/')
    year = timesplit[2]
    month = timesplit[0]
    day = timesplit[1]
    new_timestamp = year + '-' + month + '-' + day + ' ' + timestamp[1]
    print(new_timestamp, date['timestamp'])

    collection.update_one({'timestamp':date['timestamp']}, {'$set': {'timestamp':new_timestamp}})'''

def openText():
    collection = db['preprocess']
    with open('synonym.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        synonym = {}
        for line in lines:
            line = line.split(',')
            line[1] = line[1].strip()
            synonym[line[0]] = line[1]
            update = {'type':'synonym', 'word':line[0], 'sub':line[1]}
            collection.update_one({'type':'synonym', 'word':line[0]}, {'$set': update}, upsert=True)

    with open('stopwords.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        stopwords = []
        for line in lines:
            line = line.split(',')
            line[0] = line[0].strip()
            stopwords.append(line[0])
            update = {'type': 'stopwords', 'word': line[0]}
            collection.update_one({'type':'stopwords', 'word':line[0]}, {'$set':update}, upsert=True)

    with open('custom_vocab.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        custom_vocab = []
        for line in lines:
            line = line.split(',')
            line[0] = line[0].strip()
            custom_vocab.append(line[0])
            update = {'type':'custom_vocab', 'word':line[0]}
            collection.update_one({'type':'custom_vocab', 'word':line[0]}, {'$set':update}, upsert=True)

    with open('split.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        split_words = {}
        for line in lines:
            line = line.split(',')
            line[1] = line[1].strip()
            split_words[line[0]] = line[1]
            update = {'type':'split', 'word':line[0], 'sub':line[1]}
            collection.update_one({'type':'split', 'word':line[0]}, {'$set':update}, upsert=True)
    return synonym, stopwords, custom_vocab, split_words

openText()


import os
import pathlib

import pytest

from geolib.models.dsettlement.dsettlement_parserprovider import *
from geolib.models.dsettlement.internal import (
    Boundaries,
    Curves,
    Layers,
    PiezoLine,
    PiezoLines,
    Points,
)
from tests.utils import TestUtils

class Test_DSettlementInputParser:
    @pytest.mark.unittest
    def test_instantiate(self):
        parser = DSettlementInputParser()
        assert parser is not None
        assert len(parser.suffix_list) == 1

    @pytest.fixture
    def parsed_dsettlement_testfile(self):
        # 1. Define test data
        test_folder = TestUtils.get_local_test_data_dir("dsettlement")
        test_file = pathlib.Path(os.path.join(test_folder, "bm1-1.sli"))
        parser = DSettlementInputParser()
        parsed_structure = None

        # 2. Verify initial expectations
        assert os.path.exists(test_file), "Test file does not exist."

        # 3. Run test
        parsed_structure = parser.parse(test_file)

        # 4. Verify expectations
        assert parsed_structure, "No structure was parsed."
        assert isinstance(parsed_structure, DSettlementStructure)

        return parsed_structure

    @pytest.mark.systemtest
    def test_given_testfile_when_parse_then_geometryadded(
        self, parsed_dsettlement_testfile: DSettlementStructure
    ):
        # 1. Define test data.
        geometry_data_key = "geometry_data"
        parsed_structure = parsed_dsettlement_testfile
        keys_in_structure = {
            "points": Points,
            "curves": Curves,
            "boundaries": Boundaries,
            "layers": Layers,
            "world_co__ordinates": str,
        }

        # 2. Verify expectations.
        parsed_struct_asdict = dict(parsed_structure)
        assert geometry_data_key in parsed_struct_asdict.keys(), (
            "" + "Geometry should be wrapping the piezo lines and " + "was not imported."
        )
        geometry_dict: dict = dict(parsed_struct_asdict[geometry_data_key])
        errors: list = []
        for key, key_type in keys_in_structure.items():
            if not (key in geometry_dict.keys()):
                errors.append(f"Key {key} has not been parsed.")
            elif not (isinstance(geometry_dict[key], key_type)):
                errors.append(
                    f"Key type {key_type} expected, "
                    + f"but got {type(geometry_dict[key])}."
                )

        if errors:
            parsed_errors = "\n".join(errors)
            pytest.fail("Not all properties were parsed correctly: " + f"{parsed_errors}")

    @pytest.mark.systemtest
    def test_given_testfile_when_parse_then_piezovaluesadded(
        self, parsed_dsettlement_testfile: DSettlementStructure
    ):
        # 1. Define test data
        geometry_data_key = "geometry_data"
        piezo_lines_key = "piezo_lines"
        piezolines_key = "piezolines"
        expected_piezolines_curves = [[4]]
        parsed_structure = parsed_dsettlement_testfile

        # 2. Verify final expectations.
        parsed_struct_asdict = dict(parsed_structure)
        assert geometry_data_key in parsed_struct_asdict.keys(), (
            "" + "Geometry should be wrapping the piezo lines and " + "was not imported."
        )

        geometry_dict = dict(parsed_struct_asdict[geometry_data_key])
        assert piezo_lines_key in geometry_dict.keys(), (
            "" + "The piezo key was not found as parsed structure."
        )
        assert isinstance(geometry_dict[piezo_lines_key], PiezoLines)

        piezo_lines_dict = dict(geometry_dict[piezo_lines_key])
        assert piezolines_key in piezo_lines_dict.keys()
        assert len(piezo_lines_dict[piezolines_key]) == len(expected_piezolines_curves), (
            "" + "The generated piezolines were not as expected."
        )

        for idx, piezoline in enumerate(piezo_lines_dict[piezolines_key]):
            assert piezoline.curves == expected_piezolines_curves[idx]

    @pytest.mark.systemtest
    def test_given_testfilewithmultiplelineboundaries_then_addedcorrectly(self):
        # 1. Define test data
        test_folder = TestUtils.get_local_test_data_dir("dsettlement")
        test_file = pathlib.Path(os.path.join(test_folder, "2dgeom_with10.sli"))
        parser = DSettlementInputParser()
        expected_values = [
            [41],
            [40],
            [39],
            [38],
            [37],
            [36],
            [35],
            [34],
            [33],
            [29, 30, 31, 32],
            [29, 30, 31, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28],
            [29, 30, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28],
            [
                29,
                3,
                4,
                5,
                6,
                7,
                8,
                9,
                10,
                11,
                12,
                13,
                14,
                15,
                16,
                17,
                18,
                19,
                20,
                21,
                22,
                23,
                24,
                25,
                26,
                27,
                28,
            ],
            [
                1,
                2,
                3,
                4,
                5,
                6,
                7,
                8,
                9,
                10,
                11,
                12,
                13,
                14,
                15,
                16,
                17,
                18,
                19,
                20,
                21,
                22,
                23,
                24,
                25,
                26,
                27,
                28,
            ],
        ]

        # 2. Verify initial expectations
        assert os.path.exists(test_file), "Test file does not exist."

        # 3. Run test
        parsed_model = parser.parse(test_file)

        # 4. Verify expectations
        assert parsed_model, "No structure was parsed."
        parsed_boundaries = parsed_model.geometry_data.boundaries
        assert len(parsed_boundaries.boundaries) == len(expected_values)
        for struct_id, expected_value in enumerate(expected_values):
            assert parsed_boundaries.boundaries[struct_id].id == struct_id
            assert parsed_boundaries.boundaries[struct_id].curves == expected_value

class Test_DSettlementOutputParser:
    @pytest.mark.unittest
    def test_instantiate(self):
        parser = DSettlementOutputParser()
        assert parser is not None
        assert len(parser.suffix_list) == 1

class Test_DSettlementParserProvider:
    @pytest.mark.integrationtest
    def test_instantiate(self):
        parser_provider = DSettlementParserProvider()
        assert parser_provider
        assert parser_provider.input_parsers is not None
        assert isinstance(parser_provider.input_parsers[0], DSettlementInputParser)
        assert parser_provider.input_parsers[0].suffix_list

        assert parser_provider.output_parsers is not None
        assert isinstance(parser_provider.output_parsers[0], DSettlementOutputParser)
        assert parser_provider.output_parsers[0].suffix_list


from rest_framework import generics
from rest_framework import filters

from django_filters.rest_framework import DjangoFilterBackend

from igloo.models import Experiment, ExperimentStatus, ExperimentSchedule
from igloo.serializers import ExperimentSerializer, ExperimentStatusSerializer, ExperimentDetailSerializer, ExperimentScheduleSerializer
from igloo.filters import ExperimentFilter, ExperimentScheduleFilter

class ExperimentList(generics.ListCreateAPIView):
    queryset = Experiment.objects.all()
    serializer_class = ExperimentSerializer
    filter_backends = [filters.OrderingFilter,
                       filters.SearchFilter,
                       DjangoFilterBackend]
    filterset_class = ExperimentFilter
    filterset_fields = ['code', 'status']
    search_fields = ['title']
    ordering_fields = ['impact', 'confidence',
                       'ease', 'created_at', 'updated_at']

class ExperimentDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Experiment.objects.all()
    serializer_class = ExperimentDetailSerializer

class ExperimentStatusList(generics.ListCreateAPIView):
    queryset = ExperimentStatus.objects.all()
    serializer_class = ExperimentStatusSerializer

class ExperimentStatusDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = ExperimentStatus.objects.all()
    serializer_class = ExperimentStatusSerializer

class ExperimentScheduleList(generics.ListCreateAPIView):
    queryset = ExperimentSchedule.objects.all()
    serializer_class = ExperimentScheduleSerializer
    filter_backends = [filters.OrderingFilter, DjangoFilterBackend]
    filterset_class = ExperimentScheduleFilter
    filterset_fields = ['start_date', 'end_date', 'progressing']
    ordering_fields = ['start_date', 'end_date']

class ExperimentScheduleDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = ExperimentSchedule.objects.all()
    serializer_class = ExperimentScheduleSerializer


#!/usr/bin/env python3

from Practice_Python.functions import pick_random_word

WORD = pick_random_word().strip()   # Remove all whitespace

if __name__ == '__main__':
    print(WORD)
    guesses = 0
    build_word = list('_' * len(WORD))

    print('>>> Welcome to Hangman! You have 6 guessed. Good luck!')
    print('_ ' * len(WORD))

    while guesses < 6:
        guess = input('>>> Guess your letter: ').upper()    # Just to make sure
        while len(guess) != 1:
            guess = input('>>> Guess your letter: ').upper()

        if guess in WORD:
            i = 0
            for letter in WORD:
                if guess == letter:
                    if build_word[i] == letter:
                        print('Already guessed. Try another letter.')
                        # guesses -= 1
                        break
                    else:
                        build_word[i] = letter
                i += 1

            print(' '.join(build_word))

            if '_' not in build_word:
                print('Hooray! You guessed the word!')
                break   # End the game
        else:
            print('Incorrect!')
            guesses += 1

        print('Guesses left: ', (6 - guesses))


import json
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required

@login_required
def who_am_i(request):
    return JsonResponse({'username': request.user.username})

@login_required
def tell_me_something(request):
    if request.method != 'POST':
        response = JsonResponse({'error': 'Method not allowed'})
        response.status_code = 405
    else:
        body = json.loads(request.body)
        response = JsonResponse({'message_was': body['message']})
    return response


# diccionario de ventas
ventas = {}

# registrar las ventas
ventas["Producto1"] = 10
ventas["Producto2"] = 5
ventas["Producto3"] = 3

# Actualizar cantidad vendida de un producto existente
ventas["Producto2"] = ventas["Producto2"] + 2
##ventas["Producto2"] += 2

# Calcular el total de ventas diarias
total_ventas= sum(ventas.values())

# Imprimir el registro de ventas y el total de ventas diarias
print("Registro de ventas:")
for producto, cantidad in ventas.items():
    print(producto + ": " + str(cantidad))

print("Total de ventas diarias: " + str(total_ventas))

Otro/Código _registro_ventas_ (Click aquí para descargar).py


import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('T11.jpeg',0)
img = cv2.medianBlur(img,5)

ret,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
            cv2.THRESH_BINARY,11,2)
th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
            cv2.THRESH_BINARY,11,2)

titles = ['Original Image', 'Global Thresholding (v = 127)',
            'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
images = [img, th1, th2, th3]
#print(images[0])
#plt.subplot(2,2,1),plt.imshow(images[0],'gray')
plt.subplot(2,2,1),plt.imshow(images[1],'gray')
plt.subplot(2,2,2),plt.imshow(images[2],'gray')
plt.subplot(2,2,3),plt.imshow(images[3],'gray')
#for i in images():
#    plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
#    plt.title(titles[i])
#    plt.xticks([]),plt.yticks([])
plt.show()
'''
img = cv2.imread('T11.jpeg',0)
blur = cv2.GaussianBlur(img,(5,5),0)

# find normalized_histogram, and its cumulative distribution function
hist = cv2.calcHist([blur],[0],None,[256],[0,256])
hist_norm = hist.ravel()/hist.max()
Q = hist_norm.cumsum()

bins = np.arange(256)

fn_min = np.inf
thresh = -1

for i in xrange(1,256):
    p1,p2 = np.hsplit(hist_norm,[i]) # probabilities
    q1,q2 = Q[i],Q[255]-Q[i] # cum sum of classes
    b1,b2 = np.hsplit(bins,[i]) # weights

    # finding means and variances
    m1,m2 = np.sum(p1*b1)/q1, np.sum(p2*b2)/q2
    v1,v2 = np.sum(((b1-m1)**2)*p1)/q1,np.sum(((b2-m2)**2)*p2)/q2

    # calculates the minimization function
    fn = v1*q1 + v2*q2
    if fn < fn_min:
        fn_min = fn
        thresh = i

# find otsu's threshold value with OpenCV function
ret, otsu = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
print(thresh,ret)
'''


from fastapi import APIRouter, UploadFile, Body, Depends, status
from fastapi.responses import JSONResponse
from ..models.reports import Report
from aiomysql.connection import Connection
from ..database import Database
from ..database.reports import makeReport, getReportById
from ..utils.classify_disease import classify, disease_inference
import datetime

report_router = APIRouter()

@report_router.post("")
async def generate_report(xray: UploadFile, user_id: str = Body(...), conn: Connection = Depends(Database.get_db)):

    img_id = f"UR_{datetime.datetime.now().strftime('%m_%d_%Y_%H_%M_%S')}.png"
    with open(f"app/static/images/{img_id}", 'wb') as file:
        pic_data = await xray.read()
        file.write(pic_data)

    disease = await classify(img_id)

    report = Report(title=disease, user_id=user_id, image_id=img_id)

    if disease != "No Finding":
        report.description = disease_inference[disease]["description"]
        report.symptoms = disease_inference[disease]["symptoms"]
        report.treatment = disease_inference[disease]["treatment"]

    id = await makeReport(report, conn)
    report = report.dict()
    report["id"] = id

    return JSONResponse(content=report, status_code=status.HTTP_200_OK)

@report_router.get("/{id}")
async def report_id(id: str, conn: Connection = Depends(Database.get_db)):
    report_data = await getReportById(id, conn)

    return JSONResponse(content=report_data, status_code=status.HTTP_200_OK)


import re
from abc import ABCMeta, abstractmethod

from discord.ext.commands import BadArgument, Converter

class InvalidArgument(BadArgument):
    pass

class QSConverter(Converter, metaclass=ABCMeta):
    @classmethod
    async def convert(cls, ctx, arg: str) -> str:
        return cls.parse(arg)

    @classmethod
    @abstractmethod
    def parse(cls, arg: str) -> str:
        ...

class EmbedColor(QSConverter):
    COLORS = {
        'blue': 0x3498db,
        'blurple': 0x7289da,
        'dark blue': 0x206694,
        'dark gold': 0xc27c0e,
        'dark gray': 0x607d8b,
        'dark green': 0x1f8b4c,
        'dark grey': 0x607d8b,
        'dark magenta': 0xad1457,
        'dark orange': 0xa84300,
        'dark purple': 0x71368a,
        'dark red': 0x992d22,
        'dark teal': 0x11806a,
        'dark theme': 0x36393f,
        'darker gray': 0x546e7a,
        'darker grey': 0x546e7a,
        'default': 0x000000,
        'gold': 0xf1c40f,
        'green': 0x2ecc71,
        'greyple': 0x99aab5,
        'light gray': 0x979c9f,
        'light grey': 0x979c9f,
        'lighter gray': 0x95a5a6,
        'lighter grey': 0x95a5a6,
        'magenta': 0xe91e63,
        'orange': 0xe67e22,
        'pink': 0xffa1dd,
        'purple': 0x9b59b6,
        'red': 0xe74c3c,
        'teal': 0x1abc9c,

        'clear': 0,
        'random': 'random',
    }

    @classmethod
    def parse(cls, arg):
        arg = arg.strip().replace('_', ' ')
        if arg in cls.COLORS:
            return str(cls.COLORS[arg])
        elif re.match(r"^#?[0-9a-fA-F]{6}$", arg):
            return str(int(arg.lstrip("#"), 16))
        else:
            raise InvalidArgument(f"Invalid color: {arg}! Valid colors are any hexcode and {', '.join(cls.COLORS)}")

class MonsterConverter(QSConverter):
    @classmethod
    def parse(cls, arg):
        if re.fullmatch(r'-?\d+', arg):
            return arg
        else:
            raise InvalidArgument(f"Invalid monster ID: {arg}! Make sure only a numeric ID is passed.")


from aws_cdk.core import Construct, Stack, Stage, Environment, CfnOutput
from cdk_pipeline_ecs.ApplicationStack import ApplicationStack
from cdk_pipeline_ecs.DatabaseStack import DatabaseStack
from cdk_pipeline_ecs.WebServiceStack import WebServiceStack

class ApplicationStage(Stage):
    load_balancer_address: CfnOutput = None
    gateway_url: CfnOutput = None

    def __init__(self, scope: Construct, id: str, **kwargs):
        super().__init__(scope, id, **kwargs)

        env = kwargs['env']

        db_stack = DatabaseStack(
            self,
            "DatabaseStack"
        )

        app_stack = ApplicationStack(
            self,
            "ApplicationStack",
            env=env
        )

        web_service_stack = WebServiceStack(
            self,
            "WebServiceStack",
            db_stack.demo_table
        )

        self.load_balancer_address = CfnOutput(
            app_stack,
            "LbAddress",
            value=f"http://{app_stack.load_balancer_dns_name}"
        )

        self.gateway_url = CfnOutput(
            web_service_stack,
            "GatewayUrl",
            value=web_service_stack.gw_url
        )


import itertools

import numpy as np
import pytest
import torch

from ..internal_graph import *
from ..torchir_passes import *

def _build_flattening_test_graph():
    # This test graph is:
    #    graph(
    #        %1 : (Tensor[1, 1], (Tensor[1, 2], Tensor[1, 3]))
    #    ):
    #    %2, %3 = tupleunpack[](%1)
    #    %4, %5 = tupleunpack[](%3)
    #    %6 = tupleconstruct[](%2, %4)
    #    %7 = tupleconstruct[](%6, %5)
    #    return (%7)
    #
    # And if you were to run the graph it would turn
    #    (a, (b, c))
    # into
    #    ((a, b), c)

    graph_params = {}
    graph_inputs = OrderedDict()
    graph_inputs["1"] = (
        torch.rand(1, 1),
        (
            torch.rand(1, 2),
            torch.rand(1, 3),
        ),
    )
    graph_nodes = [
        InternalTorchIRNode(
            inputs=["1"],
            outputs=["2", "3"],
            kind="tupleunpack",
        ),
        InternalTorchIRNode(
            inputs=["3"],
            outputs=["4", "5"],
            kind="tupleunpack",
        ),
        InternalTorchIRNode(
            inputs=["2", "4"],
            outputs=["6"],
            kind="tupleconstruct",
        ),
        InternalTorchIRNode(
            inputs=["6", "5"],
            outputs=["7"],
            kind="tupleconstruct",
        ),
    ]
    graph_outputs = ["7"]

    return InternalTorchIRGraph(
        nodes=graph_nodes,
        params=graph_params,
        inputs=graph_inputs,
        outputs=graph_outputs,
    )

class TestTorchPasses:
    """Class containing tests for InternalTorchIR optimization passes.
    """

    @pytest.fixture
    def set_random_seeds(self):
        torch.manual_seed(1)
        np.random.seed(1)

    def test_flatten_input_values(self):
        graph = _build_flattening_test_graph()

        flatten_graph_input_values(graph)

        # The graph input tuple should have been flattened.
        np.testing.assert_equal(len(graph.inputs.keys()), 3)
        # Tuple flattening should introduce two new ops.
        np.testing.assert_equal(len(graph.nodes), 6)
        # The new ops at the beginning of the graph should be a tupleconstruct.
        np.testing.assert_equal(graph.nodes[0].kind, "tupleconstruct")
        np.testing.assert_equal(graph.nodes[1].kind, "tupleconstruct")
        # The inputs to the tupleconstructs should be the new flattened inputs.
        input_names = [k for k in graph.inputs.keys()]
        np.testing.assert_equal(input_names[1:], graph.nodes[0].inputs)
        np.testing.assert_equal(input_names[0], graph.nodes[1].inputs[0])
        np.testing.assert_equal(graph.nodes[0].outputs[0], graph.nodes[1].inputs[1])
        # The last inserted tuple construct should produce the input for the
        # next op.
        np.testing.assert_equal(graph.nodes[1].outputs[0], graph.nodes[2].inputs[0])

    def test_flatten_output_values(self):
        graph = _build_flattening_test_graph()

        flatten_graph_output_values(graph)

        # The graph output tuple should have been flattened.
        np.testing.assert_equal(len(graph.outputs), 3)
        # The outputs of the graph should come from intermediate ops.
        np.testing.assert_equal(graph.outputs[0], graph.nodes[0].outputs[0])
        np.testing.assert_equal(graph.outputs[1], graph.nodes[1].outputs[0])
        np.testing.assert_equal(graph.outputs[2], graph.nodes[1].outputs[1])

    def test_transform_inplace_ops_graph(self):
        # The test graph is:
        #    graph(
        #        %x : Tensor[1],
        #    ):
        #      %1 = constant[value=0]()
        #      %2 = constant[value=10]()
        #      %3 = listconstruct[](%1)
        #      %4 = append[](%3, %2)
        #      return (%3)
        graph_params = {}
        graph_inputs = OrderedDict()
        graph_inputs["x"] = torch.rand(1)
        graph_nodes = [
            InternalTorchIRNode(
                inputs=[],
                attr={"value": 0},
                outputs=["1"],
                kind="constant",
            ),
            InternalTorchIRNode(
                inputs=[],
                attr={"value": 10},
                outputs=["2"],
                kind="constant",
            ),
            InternalTorchIRNode(
                inputs=["1"],
                outputs=["3"],
                kind="listconstruct",
            ),
            InternalTorchIRNode(
                inputs=["3", "2"],
                outputs=["4"],
                kind="append",
            ),
        ]
        graph_outputs = ["3"]
        graph = InternalTorchIRGraph(
            nodes=graph_nodes,
            params=graph_params,
            inputs=graph_inputs,
            outputs=graph_outputs,
        )
        for node in graph.nodes:
            node.parent = graph

        transform_inplace_ops(graph)

        np.testing.assert_equal(len(graph.outputs), 1)
        np.testing.assert_equal(graph.outputs[0], graph.nodes[-1].outputs[0])

    def test_transform_inplace_ops_loop(self):
        # The test graph is:
        #    graph(
        #        %x : Tensor[1],
        #    ):
        #      %1 = constant[value=True]()
        #      %2 = constant[value=-1]()
        #      %3 = constant[value=10]()
        #      %4 = listconstruct[](%2)
        #       = loop[](%3, %1)
        #        block(%i.1):
        #          %6 = append[](%4, %i.1)
        #        return (%1)
        #    return (%4)
        graph_params = {}
        graph_inputs = OrderedDict()
        graph_inputs["x"] = torch.rand(1)
        loop_block = InternalTorchIRBlock(
            inputs=["i.1"],
            outputs=["1"],
            nodes=[
                InternalTorchIRNode(
                    inputs=["4", "i.1"],
                    outputs=["6"],
                    kind="append",
                ),
            ],
        )
        loop_block.nodes[0].parent = loop_block
        loop_node = InternalTorchIRNode(
            inputs=["3", "1"],
            outputs=[],
            kind="loop",
            blocks=[loop_block],
        )
        loop_block.parent = loop_node
        graph_nodes = [
            InternalTorchIRNode(
                inputs=[],
                attr={"value": True},
                outputs=["1"],
                kind="constant",
            ),
            InternalTorchIRNode(
                inputs=[],
                attr={"value": -1},
                outputs=["2"],
                kind="constant",
            ),
            InternalTorchIRNode(
                inputs=[],
                attr={"value": 10},
                outputs=["3"],
                kind="constant",
            ),
            InternalTorchIRNode(
                inputs=["2"],
                outputs=["4"],
                kind="listconstruct",
            ),
            loop_node,
        ]
        graph_outputs = ["4"]
        graph = InternalTorchIRGraph(
            nodes=graph_nodes,
            params=graph_params,
            inputs=graph_inputs,
            outputs=graph_outputs,
        )
        for node in graph.nodes:
            node.parent = graph

        transform_inplace_ops(graph)

        # There should be an additional input to the loop.
        np.testing.assert_equal(len(loop_node.inputs), 3)
        # That input should be the output of the previous op.
        np.testing.assert_equal(loop_node.inputs[2], graph.nodes[3].outputs[0])
        # The loop block should have an additional input.
        np.testing.assert_equal(len(loop_block.inputs), 2)
        # The loop block's new input should be the input to append.
        np.testing.assert_equal(loop_block.inputs[1], loop_block.nodes[0].inputs[0])
        # The loop block should have an additional output.
        np.testing.assert_equal(len(loop_block.outputs), 2)
        # Append's output should be returned from the loop block.
        np.testing.assert_equal(loop_block.outputs[1], loop_block.nodes[0].outputs[0])
        # The loop should now have an output.
        np.testing.assert_equal(len(loop_node.outputs), 1)
        # The loop's name should now be the name of its output.
        np.testing.assert_equal(loop_node.name, loop_node.outputs[0])
        # That graph output should now be the output of the graph.
        np.testing.assert_equal(loop_node.outputs[0], graph.outputs[0])

    @pytest.mark.xfail(reason="rdar://64235006")
    def test_transform_inplace_ops_if(self):
        # The test graph is:
        #    graph(
        #        %x : Tensor[1],
        #    ):
        #      %1 = constant[value=True]()
        #      %2 = constant[value=0]()
        #      %3 = constant[value=1]()
        #      %4 = listconstruct[](%2)
        #       = if[](%1)
        #        block0():
        #          %5 = append[](%4, %3)
        #        return ()
        #        block1():
        #          %6 = append[](%4, %2)
        #        return ()
        #    return (%4)
        graph_params = {}
        graph_inputs = OrderedDict()
        graph_inputs["x"] = torch.rand(1)
        if_true_block = InternalTorchIRBlock(
            inputs=[],
            outputs=[],
            nodes=[
                InternalTorchIRNode(
                    inputs=["4", "3"],
                    outputs=["5"],
                    kind="append",
                ),
            ],
        )
        if_true_block.nodes[0].parent = if_true_block
        if_false_block = InternalTorchIRBlock(
            inputs=[],
            outputs=[],
            nodes=[
                InternalTorchIRNode(
                    inputs=["4", "2"],
                    outputs=["6"],
                    kind="append",
                ),
            ],
        )
        if_false_block.nodes[0].parent = if_false_block
        if_node = InternalTorchIRNode(
            inputs=["1"],
            outputs=[],
            kind="if",
            blocks=[if_true_block, if_false_block],
        )
        if_true_block.parent = if_node
        if_false_block.parent = if_node
        graph_nodes = [
            InternalTorchIRNode(
                inputs=[],
                attr={"value": True},
                outputs=["1"],
                kind="constant",
            ),
            InternalTorchIRNode(
                inputs=[],
                attr={"value": 0},
                outputs=["2"],
                kind="constant",
            ),
            InternalTorchIRNode(
                inputs=[],
                attr={"value": 1},
                outputs=["3"],
                kind="constant",
            ),
            InternalTorchIRNode(
                inputs=["2"],
                outputs=["4"],
                kind="listconstruct",
            ),
            if_node,
        ]
        graph_outputs = ["4"]
        graph = InternalTorchIRGraph(
            nodes=graph_nodes,
            params=graph_params,
            inputs=graph_inputs,
            outputs=graph_outputs,
        )
        for node in graph.nodes:
            node.parent = graph

        transform_inplace_ops(graph)

        # The true block should now have an output.
        np.testing.assert_equal(len(if_true_block.outputs), 1)
        # The true block should output the result of the append op.
        np.testing.assert_equal(if_true_block.outputs[0], if_true_block.nodes[0].outputs[0])
        # The false block should now have an output.
        np.testing.assert_equal(len(if_false_block.outputs), 1)
        # The false block should output the result of the append op.
        np.testing.assert_equal(if_false_block.outputs[0], if_false_block.nodes[0].outputs[0])
        # The if op should have an additional output.
        np.testing.assert_equal(len(if_node.outputs), 1)
        # The if's name should now be the name of its output.
        np.testing.assert_equal(if_node.name, if_node.outputs[0])
        # The graph output should be the if op output.
        np.testing.assert_equal(if_node.outputs[0], graph.outputs[0])


import requests
import json

VERIFY_SSL = False

def add_view_to_post(post_url):
    # Define the url where the flask app is running

    # url = 'http://localhost:5001/start'
    url = "http://ec2-35-170-69-10.compute-1.amazonaws.com/start"
    # url = "http://172.31.3.120:80/start"
    # Define the payload to be sent to the server

    payload = {
        'url': post_url
    }

    # Make a POST request to the server
    response = requests.post(url, json=payload, verify=VERIFY_SSL)

    # If the request was successful
    if response.status_code == 200:
        # Get the JSON response body
        data = response.json()

        # Print the results
        print(f"View added: {data['view_added']}")
        print(f"Total views: {data['total_views']}")

    else:
        print("An error occurred while trying to add a view to the post.")

import boto3
def restart_ec2_instance(instance_id):
    ec2 = boto3.client('ec2', region_name='us-west-1')

    print("Stopping instance...")
    ec2.stop_instances(InstanceIds=[instance_id])

    waiter = ec2.get_waiter('instance_stopped')
    waiter.wait(InstanceIds=[instance_id])

    print("Starting instance...")
    ec2.start_instances(InstanceIds=[instance_id])
# if __name__ == "__main__":
post_url = "https://t.me/globaltradecrypto/74"
add_view_to_post(post_url)

restart_ec2_instance("i-019ea4cc4bb7b17a6")


import PySimpleGUI as sg
import time
import scoring
from essential_generators import DocumentGenerator

#default Settings
guiFont = ("Verdana", 16)
inputFont = ("Verdana", 20)
sg.theme('DarkGrey11')
textBoxSize = (30, 8)

inputCol = [
    [sg.Text("Type in this box", font=guiFont)],
    [sg.Multiline(key="inputText", size=textBoxSize, no_scrollbar=True, font=inputFont)],
    [sg.Button("Submit")]
]

testCol = [
    [sg.Text("Text to type", font=guiFont)],
    [sg.Multiline(key="randomText", size=textBoxSize, no_scrollbar=True, font=inputFont, disabled=True)],
]

buttonRow = [[[sg.Button('Start'), sg.Button('View Data')], sg.Text("Score: ", key="score", font=guiFont)]]

layout = [[sg.Column(inputCol, vertical_alignment='top'), sg.Column(testCol, vertical_alignment='top'), buttonRow]]

window = sg.Window("Type Training by Vlad Apostol", layout, size=(1000, 420))

while True:
    event, value = window.read()
    if event == "Start":
        randomText = DocumentGenerator().sentence()
        window['randomText'].update(randomText)
        start = time.time()
    if event == "Submit":
        end = time.time()
        result = scoring.calculateScore(value['inputText'], value['randomText'], start, end)
        window['inputText'].update('')
        window['randomText'].update('')
        window['score'].update(result)
    if event == "View Data":
        print(scoring.returnGraph())
    if event == sg.WINDOW_CLOSED:
        break

window.close()


import argparse
import json
import sys
import pickle

import matplotlib.pyplot as plt
import numpy as np
from numpy import random
from scipy.integrate import odeint
from scipy.interpolate import interp1d
from scipy.optimize import fsolve

plt.rcParams.update({'font.size': 16, 'axes.labelsize': 'large'})
frac = 0.94 # updated with command line

G = 6.67e-11 # gravitational constant, m3/kg/s2
YEAR = 365*24*3600. # a year in seconds
MA = 1e6*YEAR       # a Ma in seconds
RM = 1740e3 # moon radius
RC = 400e3  # moon core radius
RE = 6370e3 # earth radius
MM = 5.972e24 # moon mass
ME = 7.348e22 # earth mass
D0 = 100e3  # initial depth at which the crust starts to crystallize
VOL_MANTLE = 4*np.pi*(RM**3 - RC**3)/3

# this needs to be defined only once
LATENT = 3e5   # latent heat of crystallization, J/kg
RHO = 3300.      # average crustal density, kg
CP = 1000.       # specific heat of the crust, J/K/kg
GRAD_TL = 2.5e-4 #

# orbital
A0 = RE

with open("fit.p", "rb") as f:
    fit = pickle.load(f)

def Mg_to_PCS(Mg):
    '''Converts a Mg# to an equivalent PCS value given plag fraction.'''
    pcs = np.linspace(83, 97, 500)
    inv = []
    for value in Mg:
        v = np.polynomial.polynomial.polyval(frac, fit) - value
        inv.append(pcs[np.where(v > 0)[0][-1]])
    return np.array(inv)

def PCS_to_Mg(target):
    '''Converts a PCS value to an equivalent Mg# given plag fraction.'''
    target_ = target*100
    pcs = np.linspace(83, 97, 500)
    ret = []
    for p in target_:
        idx = np.where(p > pcs)[0][-1]
        mg = np.polynomial.polynomial.polyval(frac, fit)[idx]
        ret.append(max(mg, 0))
    return ret

def area(r):
    '''Returns area of the shell at radius RM-r.'''
    a = 4.*np.pi*(RM-r)**2
    return a

def volume(r):
    '''Returns volume of the shell between RM-r and RM-D0.'''
    v = 4.*np.pi*((RM-r)**3 - (RM-D0)**3)/3
    return v

def partitioning(y):
    '''Takes crustal thickness as input and returns PCS.'''
    mean_crust = 0.5*(y[0]+y[2])
    v = 4.*np.pi*(RM**3 - (RM-mean_crust)**3)/3
    return 0.85 + v/VOL_MANTLE

def isotherm(y, T=800):
    '''Returns the depth of an isotherm for a given timestep.'''
    TS = 250
    TM = 1600
    return np.array([y[0], y[2]])*(T-TS)/(TM-TS)

def radio(t):
    '''Returns radioactive heating as a function of time since t0 (in years)'''
    t0 = 4.5e9
    t *= 1e6 # t is given in Ma
    constants = {
        '238U': {'H': 9.46e-5, 'tau': 4.47e9, 'x': 0.9928, 'c0': 20.3e-9},
        '235U': {'H': 5.69e-4, 'tau': 7.04e8, 'x': 0.0071, 'c0': 20.3e-9},
        '232Th': {'H': 2.64e-5, 'tau': 1.40e10, 'x': 1, 'c0': 79.5e-9},
        '40K': {'H': 2.92e-5, 'tau': 1.25e9, 'x': 1.19e-4, 'c0': 240e-6},
    }
    heat = 0
    for el in constants.values():
        heat += el['c0']*el['H']*el['x']*np.exp((t0-t)*np.log(2)/el['tau'])
    return heat

def get_depths(y, mixing='normal-middle', X=20e3):
    '''Generate a distribution of depth-of-origin given a mixing model.'''
    N = 1000
    depths_ns, depths_fs = [], []
    mu, std = {}, {}

    db_mu = {
        'low': {'ns':24.9e3, 'fs':25.8e3},
        'middle': {'ns':24.9e3, 'fs':25.8e3},
        'high': {'ns':24.9e3, 'fs':25.8e3}
    }

    db_std = {
        'low': {'ns':9.4e3, 'fs':10.2e3},
        'middle': {'ns':9.4e3, 'fs':10.2e3},
        'high': {'ns':9.4e3, 'fs':10.2e3}
    }

    mixmodel = mixing.split('-')
    if mixmodel[0] == 'uniform':
        depths_ns = random.rand(N)*X
        depths_fs = random.rand(N)*X
    elif mixmodel[0] == 'normal':
        if mixmodel[1] == 'centered':
            mu['ns'] = db_mu['middle']['ns']
            mu['fs'] = mu['ns']
            std['ns'] = db_std['middle']['ns']
            std['fs'] = std['ns']
        else:
            mu['ns'] = db_mu[mixmodel[1]]['ns']
            mu['fs'] = db_mu[mixmodel[1]]['fs']
            std['ns'] = db_std[mixmodel[1]]['ns']
            std['fs'] = db_std[mixmodel[1]]['fs']
        while len(depths_ns) < N:
            r = random.normal(loc=mu['ns'], scale=std['ns'])
            if r > 1 and r < max(y[:, 0]):
                depths_ns.append(r)
        while len(depths_fs) < N:
            r = random.normal(loc=mu['fs'], scale=std['fs'])
            if r > 1 and r < max(y[:, 2]):
                depths_fs.append(r)
    else:
        print("This shouldn't happen.")
        sys.exit(1)

    return depths_ns, depths_fs

def plot_results(time, y, iso_n, iso_f, c, a, hfs_n, hfs_f, mixing, run, suffix=''):
    '''Generate a series of plots stored in img/'''

    # crust size evolution
    _, ax = plt.subplots(1, 1, figsize=(8, 8))

    ax.plot(time, y[:, 0]/1e3, 'r', label='nearside', lw=2)
    if run != "symmetrical":
        ax.plot(time, y[:, 2]/1e3, 'g', label='farside', lw=2)
        ax.legend(loc='best')
    ax.set_xlabel("Time [Ma]")
    ax.set_ylabel("Crustal thickness [km]")
    ax.set_xlim(0, max(time))
    ax.set_ylim(0, 70)
    ax.grid()

    plt.savefig("img/evolution"+suffix+".png", format="png", bbox_inches="tight")

    # isotherm depth
    _, ax = plt.subplots(1, 1, figsize=(8, 8))

    ax.plot(time, iso_n/1e3, 'r', label='nearside', lw=2)
    if run != "symmetrical":
        ax.plot(time, iso_f/1e3, 'g', label='farside', lw=2)
        ax.legend(loc='best')
    ax.set_xlabel("Time [Ma]")
    ax.set_ylabel("800 K isotherm depth [km]")
    ax.set_xlim(0, max(time))
    ax.set_ylim(0, 1.05*max(iso_n)/1e3)
    ax.grid()

    plt.savefig("img/isotherms"+suffix+".png", format="png", bbox_inches="tight")

    # composition profile [in Mg#]
    _, ax = plt.subplots(1, 1, figsize=(8, 8))

    ax.plot(PCS_to_Mg(c), y[:, 0]/1e3, 'r', label='nearside', lw=2)
    if run != "symmetrical":
        ax.plot(PCS_to_Mg(c), y[:, 2]/1e3, 'g', label='farside', lw=2)
        ax.legend(loc='best')
    ax.set_xlabel("Magnesium number [-]")
    ax.set_ylabel("Crustal thickness [km]")
    ax.set_ylim(70, 0)
    ax.grid()

    plt.savefig("img/composition"+suffix+".png", format="png", bbox_inches="tight")

    # orbital distance
    _, ax = plt.subplots(1, 1, figsize=(8, 8))

    ax.plot(time, a, 'k', lw=2)
    ax.set_xlabel("Time [Ma]")
    ax.set_ylabel("Semimajor axis [R$_{earth}$]")
    ax.set_xscale("log")
    ax.set_ylim(0, 60)
    ax.set_xlim(min(time), max(time))
    ax.grid()

    plt.savefig("img/semimajor"+suffix+".png", format="png", bbox_inches="tight")

    # surface properties
    _, ax = plt.subplots(1, 1, figsize=(8, 8))

    ax.plot(time, hfs_n, 'r', lw=2, label='nearside')
    ax.plot(time, hfs_f, 'g', lw=2, label='farside')
    ax.axhline(1361, color='k', ls='--')
    ax.set_xlabel("Time [Ma]")
    ax.set_ylabel("Surface heat flow [W/m$^2$]")
    ax.set_xscale("log")
    ax.set_yscale("log")
    ax.set_xlim(min(time), max(time))
    ax.legend(loc='best')
    ax.grid()

    plt.savefig("img/surface_hf"+suffix+".png", format="png", bbox_inches="tight")

    # composition sample
    _, ax = plt.subplots(1, 1, figsize=(8, 8))

    depths_ns, depths_fs = get_depths(y, mixing=mixing)
    compo_NS = interp1d(y[:, 0], PCS_to_Mg(c))
    compo_FS = interp1d(y[:, 2], PCS_to_Mg(c))

    bins = np.linspace(40, 80, 41)
    ax.hist(compo_NS(depths_ns), bins=bins, normed=1, facecolor='red', alpha=0.5, label='nearside')
    if run != "symmetrical":
        ax.hist(compo_FS(depths_fs), bins=bins, normed=1,
                facecolor='green', alpha=0.5, label='farside')
        ax.legend(loc='best')

    ax.set_xlabel("Magnesium number [-]")
    ax.set_ylabel("Normalized distribution")
    ax.set_xlim(50, 75)
    ax.set_yticks(np.arange(0, 0.55, 0.1))
    ax.grid()

    plt.savefig("img/distribution"+suffix+".png", format="png", bbox_inches="tight")

def generate_runs(ARGS):
    '''Generate a list of parameter sets to explore phase space.'''
    parameters = []
    for i in range(ARGS.num):
        if ARGS.delay is None:
            delay = random.random()
        else:
            delay = ARGS.delay
        if ARGS.plag is None:
            plag = random.uniform(0.8, 0.97)
        else:
            plag = ARGS.plag
        frac = plag
        parameters.append({'run': ARGS.run, 'mixing': ARGS.mixing,
                           'delay': delay, 'k2Q': ARGS.k2Q, 'plag': plag})

    return parameters

class Evolution:
    def __init__(self, run, delay, k2Q, plag, mixing='normal-middle'):
        self.run = run
        self.mixing = mixing
        self.time = np.logspace(-6, 2, 1000) # in Ma
        self.output = 0
        self.compo = 0
        self.k2Q = k2Q
        self.plag = plag
        self.semimajor = A0
        self.delay = delay

    def orbital_distance(self, t):
        def orbit(a, t):
            '''Eq. 4.213 from SSD'''
            res = 2/13*a**(13./2)*(1-(A0/a)**(13./2))
            res -= 3/2*self.k2Q*(G/ME)**0.5*RE**5*MM*t
            return res
        r = fsolve(orbit, self.semimajor*RE, factor=10, args=(t*MA))[0]
        return max(A0, r)

    def get_heat_flow(self, side, t, d, phi, model):
        '''Heat flow from a conductive profile in the crust. Maximum value is
           set to the radiative heat flow.'''
        self.semimajor = self.orbital_distance(t)/RE

        S0 = 1361
        Ts = 331
        sig = 5.67e-8
        if side == 'NS' and model != 'symmetrical':
            Ts = ((S0/2 + 4*S0*(5/self.semimajor)**2)/sig)**0.25

        q = 2*(1600-Ts)/min(d, np.sqrt(t*MA*1e-6))
        return q

    def deriv(self, y, t, model, phi, delay=0):
        '''
        Effective cooling rate determines the crystallization rate:
            Qsurf - Qradio = (latent + cooling)*dr/dt
        The only difference is that Qsurf is larger on the farside.
        '''
        denumFS = area(y[2])*LATENT*RHO + RHO*volume(y[2])*CP*GRAD_TL
        numFS = (self.get_heat_flow('FS', t, y[2], phi, model)*area(0) - radio(t)*RHO*VOL_MANTLE)

        denumNS = area(y[0])*LATENT*RHO + RHO*volume(y[0])*CP*GRAD_TL
        numNS = (self.get_heat_flow('NS', t, y[0], phi, model)*area(0) - radio(t)*RHO*VOL_MANTLE)

        if model == "delay" and t < delay:
            denumNS *= 1e5

        return np.array([y[1], MA*numNS/denumNS, y[3], MA*numFS/denumFS])

    def solve(self, phi=0.0):
        yinit = np.array([1.0, 0.0, 1.0, 0.0])
        self.output = odeint(self.deriv, yinit, self.time,
                             args=(self.run, phi, self.delay), rtol=1e-1)

        tfinal = np.where(self.output[:, 2] > 70e3)[0][0]
        self.output = self.output[:tfinal]
        self.time = self.time[:tfinal]

        self.compo = np.zeros(len(self.output))
        self.iso_n = np.zeros(len(self.output))
        self.iso_f = np.zeros(len(self.output))
        self.hfs_n = np.zeros(len(self.output))
        self.hfs_f = np.zeros(len(self.output))
        self.orbit = np.zeros(len(self.output))

        for i, t in enumerate(self.time):
            self.compo[i] = partitioning(self.output[i])
            self.iso_n[i], self.iso_f[i] = isotherm(self.output[i])
            self.hfs_n[i] = self.get_heat_flow('NS', t, self.output[i][0], phi, self.run)
            self.hfs_f[i] = self.get_heat_flow('FS', t, self.output[i][2], phi, self.run)
            self.orbit[i] = self.orbital_distance(t)/RE

        print("tfinal: %.1f Ma, crust ns/fs: %.1f/%.1f km" % (
            self.time[-1],
            self.output[-1, 0]/1e3,
            self.output[-1, 2]/1e3))

    def get_mg_distribution(self, mixing='normal-middle'):
        y = self.output
        c = self.compo

        depths, depths_fs = get_depths(y, mixing=mixing)

        compo_ns = interp1d(y[:, 0], PCS_to_Mg(c))
        mg_ns = compo_ns(depths)

        compo_fs = interp1d(y[:, 2], PCS_to_Mg(c))
        mg_fs = compo_fs(depths_fs)

        return [mg_ns.mean(), mg_ns.std(), mg_fs.mean(), mg_fs.std()]

    def get_crust_stats(self):
        idx = np.where(self.delay < self.time)[0][0]
        return self.output[-1, 0], self.output[-1, 2], self.output[idx, 2]

    def plot(self, args):
        suffix = '-'
        for k, v in args.items():
            if k == 'delay':
                suffix += "%s:%.2f-" % (k, v)
            else:
                suffix += "%s:%s-" % (k, v)
        suffix = suffix[:-1]

        plot_results(self.time,
                     self.output,
                     self.iso_n,
                     self.iso_f,
                     self.compo,
                     self.orbit,
                     self.hfs_n,
                     self.hfs_f,
                     mixing=self.mixing,
                     run=self.run,
                     suffix=suffix)

if __name__ == '__main__':

    PARSER = argparse.ArgumentParser()
    PARSER.add_argument('-r', '--run', default='delay', type=str,
                        choices=['delay', 'symmetrical'],
                        help="Run type")
    PARSER.add_argument('-m', '--mixing', default='normal-middle', type=str,
                        choices=['normal-low', 'normal-middle', 'normal-high',
                                 'uniform', 'normal-centered'],
                        help="Mixing model")
    PARSER.add_argument('-d', '--delay', type=float,
                        help="Delay in Ma between near and farside cooling")
    PARSER.add_argument('--plag', type=float,
                        help="Plag fraction in anorthosite")
    PARSER.add_argument('--k2Q', type=float, default=0.024,
                        help="k2/Q ratio for the Earth")
    PARSER.add_argument('--plot', default=False, action="store_true",
                        help="If true, plot run output in img/ folder")
    PARSER.add_argument('-n', '--num', default=10, type=int,
                        help="Number of runs")
    ARGS = PARSER.parse_args()

    d = generate_runs(ARGS)
    out_stats = []

    for i, params in enumerate(d):
        print(params)
        s = Evolution(**params)
        s.solve()

        if ARGS.plot:
            s.plot(params)

        stats = s.get_mg_distribution()

        params['nearside_mean'] = stats[0]
        params['nearside_std'] = stats[1]
        params['farside_mean'] = stats[2]
        params['farside_std'] = stats[3]

        crustns, crustfs, front = s.get_crust_stats()

        params['nearside_crust'] = crustns
        params['farside_crust'] = crustfs
        params['front'] = front

    with open('dat/data.txt', 'w') as outfile:
        json.dump(d, outfile)


import contextlib
import filecmp
import os

import tensorflow as tf

from tfx import version
from tfx.tools.cli.container_builder import dockerfile
from tfx.tools.cli.container_builder import labels
from tfx.utils import test_case_utils

_FAKE_VERSION = '0.23.0'

_test_dockerfile_content = '''FROM tensorflow/tfx:%s
WORKDIR /pipeline
COPY ./ ./
ENV PYTHONPATH="/pipeline:${PYTHONPATH}"''' % _FAKE_VERSION

class DockerfileTest(test_case_utils.TfxTest):

  def setUp(self):
    super().setUp()
    self._testdata_dir = os.path.join(
        os.path.abspath(os.path.dirname(__file__)), 'testdata')
    # change to a temporary working dir such that
    # there is no setup.py in the working dir.
    self.enter_context(test_case_utils.change_working_dir(self.tmp_dir))

    self._test_dockerfile = os.path.abspath('.test_dockerfile')
    with open(self._test_dockerfile, 'w') as f:
      f.writelines(_test_dockerfile_content)

  @contextlib.contextmanager
  def _patchVersion(self, ver):
    old_version = version.__version__
    old_base_image = labels.BASE_IMAGE
    version.__version__ = ver
    labels.BASE_IMAGE = 'tensorflow/tfx:%s' % ver
    yield
    labels.BASE_IMAGE = old_base_image
    version.__version__ = old_version

  def testGenerate(self):
    generated_dockerfile_path = labels.DOCKERFILE_NAME
    with self._patchVersion(_FAKE_VERSION):
      dockerfile.Dockerfile(filename=generated_dockerfile_path)
      self.assertTrue(
          filecmp.cmp(self._test_dockerfile, generated_dockerfile_path))

  def testGenerateWithBaseOverride(self):
    generated_dockerfile_path = labels.DOCKERFILE_NAME
    dockerfile.Dockerfile(
        filename=generated_dockerfile_path,
        base_image='my_customized_image:latest')
    self.assertTrue(
        filecmp.cmp(
            os.path.join(self._testdata_dir, 'test_dockerfile_with_base'),
            generated_dockerfile_path))

  def testDevVersionRequirement(self):
    with self._patchVersion('0.23.0.dev'):
      with self.assertRaisesRegex(ValueError,
                                  'Cannot find a base image automatically'):
        dockerfile.Dockerfile(filename=labels.DOCKERFILE_NAME)

if __name__ == '__main__':
  tf.test.main()


import unittest

from ccm.lib.actr import *

class MyModel(ACTR):
  focus=Buffer()
  retrieve=Buffer()
  dm=Memory(retrieve)
  pgc=PMPGC()
  compiler=PMCompile(keep='focus',request='dm.request',retrieve='retrieve')

  def init():
    dm.add('pattern a 7')
    dm.add('pattern b 3')

  def prod1(focus='see ?x'):
    dm.request('pattern ?x ?')
    focus.set('remember ?x')

  def prod2(focus='remember ?x',retrieve='pattern ?x ?y'):
    focus.set('say ?y')
    self.success()
    self.stop()

class TestScheduler(unittest.TestCase):
  def setUp(self):
    pass

  def test_compile(self):
        m=MyModel()

        m.focus.set('see a')
        m.run()
        self.assertEqual(str(m.focus.chunk),'say 7')
        self.assertAlmostEqual(m.now(),0.15)

        m.focus.set('see a')
        m.run()
        self.assertEqual(str(m.focus.chunk),'say 7')
        self.assertAlmostEqual(m.now(),0.20)

        m.focus.set('see b')
        m.run()
        self.assertEqual(str(m.focus.chunk),'say 3')
        self.assertAlmostEqual(m.now(),0.35)

        m.focus.set('see b')
        m.run()
        self.assertEqual(str(m.focus.chunk),'say 3')
        self.assertAlmostEqual(m.now(),0.40)

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


from flask import Flask, request
import json
from database import *
import payment

import logging
import coloredlogs

loggerTest = logging.getLogger("bee_TEST")
loggerTest.setLevel(logging.DEBUG)
coloredlogs.install(level='DEBUG', logger=loggerTest, milliseconds=True, fmt='[%(levelname)s]-> %(message)s')

app = Flask(__name__)

# CRUD - READ requests
@app.route('/get_all_users')
def get_all_users():
    all_users_dict = get_all_users_from_db()
    all_users_resp = {}
    all_users_resp['users'] = all_users_dict
    all_users_resp['code'] = 200
    return json.dumps(all_users_resp)

@app.route('/set_current_active_user', methods=['POST'])
def set_current_active_user():
    new_vehicle_name = request.json["vehicle_name"]
    resp = {}
    resp['msg'] = "Success"
    resp['code'] = 200
    return json.dumps(resp)

@app.route('/get_all_vehicles')
def get_all_vehicles():
    all_vehicles_dict = get_all_vehicles_from_db()
    all_vehicles_resp = {}
    all_vehicles_resp['vehicles'] = all_vehicles_dict
    all_vehicles_resp['code'] = 200
    return json.dumps(all_vehicles_resp)

@app.route('/get_all_vehicle_items')
def get_all_vehicle_items():
    all_vehicle_items_dict = get_all_vehicle_items_from_db()
    all_vehicle_items_resp = {}
    all_vehicle_items_resp['items'] = all_vehicle_items_dict
    all_vehicle_items_resp['code'] = 200
    return json.dumps(all_vehicle_items_resp)

@app.route('/get_all_user_vehicle_items', methods=['POST'])
def get_all_user_vehicle_items():
    selected_user_name = request.json["user_name"]
    all_vehicle_items_dict = get_all_user_vehicle_items_from_db(selected_user_name)
    all_vehicle_items_resp = {}
    all_vehicle_items_resp['items'] = all_vehicle_items_dict
    all_vehicle_items_resp['code'] = 200
    return json.dumps(all_vehicle_items_resp)

# CRUD - CREATE requests
@app.route('/create_new_user', methods=['POST'])
def create_new_user():
    new_user_name = request.json["user_name"]
    create_user(new_user_name)
    resp = {}
    resp['msg'] = "Success"
    resp['code'] = 200
    return json.dumps(resp)

@app.route('/create_new_vehicle', methods=['POST'])
def create_new_vehicle():
    new_vehicle_name = request.json["vehicle_name"]
    create_vehicle(user_name="BeeSuppDefUser", user_vehicle_name=new_vehicle_name)
    resp = {}
    resp['msg'] = "Success"
    resp['code'] = 200
    return json.dumps(resp)

''' TODO
@app.route('/create_new_vehicle_item', methods=['POST'])
def create_new_vehicle_item():
    new_item_category = request.json["new_item_category"]
    new_item_name = request.json["new_item_name"]
    new_item_description = request.json["new_item_description"]
    new_item_price = request.json["item_name"]
    new_item_category = request.json["item_name"]
    new_vehicle_item = request.json["item_name"]
    create_vehicle_item(new_item_category, new_item_name, new_item_description, new_item_price, new_item_image, "BeeSuppDefVehicle", "BeeSuppDefUser")
    resp = {}
    resp['msg'] = "Success"
    resp['code'] = 200
    return json.dumps(resp)
'''

@app.route('/buy_vehicle_item', methods=['POST'])
def buy_vehicle_item():
    buy_item_name = request.json["buy_item_name"]
    loggerTest.warning("satin alinan: " + buy_item_name)
    pay_res = payment.buy(buy_item_name)
    resp = {}
    if pay_res:
        resp['msg'] = "Success"
        resp['code'] = 200
        change_item_owner(buy_item_name, "Ertan")
    else:
        resp['msg'] = "Failure"
        resp['code'] = 1001
    return json.dumps(resp)

@app.route('/logged_user', methods=['POST'])
def logged_user():
    logged_user_id = request.json["user_id"]
    if logged_user_id == 0:
        loggerTest.warning("log user alinan: Kivanc")
    else:
        loggerTest.warning("log user alinan: Ertan")
    resp = {}
    resp['msg'] = "Success"
    resp['code'] = 200
    return json.dumps(resp)

if __name__ == "__main__":
    init_database_tables()
    app.run(debug=True, host='0.0.0.0', port=5888)