#!/usr/bin/python3.9

from multiprocessing import Pool, Manager
import pymysql
import time, os, subprocess
import json

def init(maxP = 4):
    processingNum = maxP
    path = [""] * processingNum

    for i in range(processingNum):
        out_r, out_w = os.pipe()
        out_r, out_w = os.fdopen(out_r, "r"), os.fdopen(out_w, "w")

        subprocess.run(["isolate", '--cg', "--box-id=" + str(i + 1), "--cleanup"])
        subprocess.run(["isolate", '--cg', "--box-id=" + str(i + 1), "--init"], stdout = out_w)
        path[i] = out_r.readline().replace("\n", "") + "/box/"
        out_w.close()

    return path

def worker(Sol, wid, path, queue, busy):

    def compile_code(file_name, language):
        compilers = {
            "C" : "timeout 30 gcc %s -o %s_ -Wall -lm -O2 -std=c11",
            "CPP"   : "timeout 30 g++ %s -o %s_ -O2 -Wall -lm -std=c++17",
            "JAVA"   : "timeout 30 javac %s",
            "PYTHON2": '''timeout 30 python2 -c "import py_compile; py_compile.compile('%s', '%s_')"''',
            "PYTHON3": '''timeout 30 python3 -c "import py_compile; py_compile.compile('%s', '%s_')"'''
            }
        if language != "JAVA":
            cmd = compilers[language] % (file_name, file_name)
        else:
            cmd = compilers[language] % (file_name)
        p = subprocess.Popen(cmd, shell=True, cwd="/var/www/judger", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out,err =  p.communicate()

        if p.returncode == 0:
            return (True, "")

        return (False,err.decode())

    run = {
        "C" : "./",
        "CPP"   : "./",
        "JAVA"   : "/usr/lib/jvm/java-11-openjdk-amd64/bin/java",
        "PYTHON2": "/usr/bin/python",
        "PYTHON3": "/usr/bin/python3.7"
        }
    queue.put((1, Sol, 0))

    try:
        file_type = {'C': '.c', 'CPP':'.cpp','PYTHON2':'', 'PYTHON3':'', 'JAVA':'.java'}

        problem = json.loads(open("/var/www/problems/" + str(Sol[2]) + ".json", "r").read())

        file_name = "P" + str(Sol[2])
        subprocess.run(["cp", "/var/www/judger/solutions/" + str(Sol[0]) , path + file_name + file_type[Sol[1]]])

        status = {'Subproblems': []}

        tmp1, tmp2 = compile_code(path + file_name + file_type[Sol[1]], Sol[1])

        if Sol[1] == "JAVA":
            file_name += ""
        else:
            file_name += file_type[Sol[1]] + "_"

        if not tmp1:
            status['status'] = 9
            status['Description'] = tmp2.replace(path, "/")
            result = open("/var/www/judger/results/" + str(Sol[0]) + ".json", "w")
            result.write(json.dumps(status))
            result.close()
            queue.put((9 ,Sol, 0))
            busy[wid] = False
            return
        system_err = True
    except Exception as e:
        status['status'] = 10
        status['Description'] = e.replace(path, "/")
        result = open("/var/www/judger/results/" + str(Sol[0]) + ".json", "w")
        result.write(json.dumps(status))
        result.close()
        queue.put((10, Sol, 0))
        busy[wid] = False
        return

    score = 0
    final_status = True

    time_cost = 0
    memory_cost = 0
    testcase_num = 0
    # print("Compiled.")

    for j in problem["Subproblems"]:
        status['Subproblems'].append({"Testcases":[]})
        status['Subproblems'][-1]['Debugger'] = j['Debugger']
        result_status = True
        for k in j['Testcases']:
            try:
                input_file = open(path + "input", 'w')
                input_file.write(k[0])
                input_file.close()
            except Exception as e:
                status['Subproblems'][-1]["Testcases"].append({'status': 10, 'Time': 0, 'Memory': 0, 'Input':k[0], 'Answer':  k[1], 'Output': '', 'Description': str(e) + "Fatal error when importing input_file."})
                result_status = False
                continue;
            try:
                if run[Sol[1]] == "./":
                    subprocess.run(["isolate","--box-id=" + str(1+wid),'--time=' + str(int(k[2]) / 1000), '--cg', '--cg-mem=' + str(int(k[3]) * 1024), '--mem=' + str(int(k[3]) * 1024), "--stdin=input", "--stderr=err" , "--stdout=output" , "--meta=" + path + "meta", "--run", run[Sol[1]] + file_name])

                elif Sol[1] == "JAVA":
                    subprocess.run(["isolate","--box-id=" + str(1+wid),'--time=' + str(int(k[2]) / 1000), '--cg', '--cg-mem=' + str(int(k[3]) * 1536), '-p', "--stdin=input", "--stderr=err"  , "--stdout=output" , "--meta=" + path + "meta", "--run", run[Sol[1]] , file_name])

                else:
                    subprocess.run(["isolate","--box-id=" + str(1+wid),'--time=' + str(int(k[2]) / 500), '--cg', '--cg-mem=' + str(int(k[3]) * 1024), '--mem=' + str(int(k[3]) * 1024), "--stderr=err", "--stdin=input", "--stdout=output" , "--meta=" + path + "meta", "--run", run[Sol[1]] ,   file_name])

                try:
                    output_file = open(path + "output", "r")
                    output = output_file.read()
                    output_file.close()
                    output = output.replace(path, "/")
                except Exception:
                    output = ""

                try:
                    err_file = open(path + "err", "r")
                    err = err_file.read()
                    err = err.replace(path, "/")
                    err_file.close()
                except Exception:
                    err = ""

                meta_file = open(path + "meta", "r")
                meta = meta_file.read()
                meta_file.close()
                meta_file = {}
                for m in meta.split("\n"):
                    if ":" in m:
                        meta_file[m.split(":")[0]] = m.split(":")[1]

                time = memory = 0
                status_code = 0

                if 'status' in meta_file or ('exitcode' in meta_file and meta_file['exitcode'] != "0"):
                    status_code = {"RE": 7, "TO": 4, "SG": 7, "XX": 10}[meta_file['status']]

                    if 'exitsig' in meta_file and meta_file['exitsig'] == "11":
                        err = "錯誤編號 11：不允許的記憶體調用。"
                    elif 'exitsig' in meta_file:
                        err = "錯誤編號 " + meta_file['exitsig']

                if status_code == 0:
                    time = int(float(meta_file['time']) * 1000)
                    memory = round(int(meta_file['max-rss'])  / 1024, 1)
                    if output == k[1]:
                        status_code = 2
                        time_cost += time
                        memory_cost += memory
                        testcase_num += 1
                    elif output.strip() == k[1].strip():
                        status_code = 2
                        time_cost += time
                        memory_cost += memory
                        testcase_num += 1
                    elif (output.replace(" ", "").replace("\n", "").replace("   ", "").replace("\r", "") == k[1].replace(" ", "").replace("\n", "").replace("   ", "").replace("\r", "")):
                        status_code = 3
                        time_cost += time
                        memory_cost += memory
                        testcase_num += 1
                    elif len(output) >= 2 ** 32 and len(output) >= len(k[1]):
                        output = output[2 ** 16:]
                        status_code = 8
                    else:
                        status_code = 6
                if status_code != 2:
                    result_status = False
                status['Subproblems'][-1]["Testcases"].append({'status': status_code, 'Time': time, 'Memory': memory, 'Input':k[0], 'Answer':  k[1], 'Output': output, 'Description': err})
                # print("Ok!", time, "s", memory, "k")

            except Exception as e:
                result_status = False
                status['Subproblems'][-1]["Testcases"].append({'status': 10, 'Time': 0, 'Memory': 0, 'Input':k[0], 'Answer':  k[1], 'Output': '', 'Description': str(e) + "Fatal error when running."})

        status['Subproblems'][-1]['Score'] = j['Score']

        if result_status:
            score += j['Score']
            status['Subproblems'][-1]['GetScore'] = j['Score']
        else:
            status['Subproblems'][-1]['GetScore'] = 0
            result_status = True
            final_status = False

    status['status'] = 2 if final_status else 11;
    status['score'] = score
    status['time'] = round(time_cost / testcase_num, 1) if testcase_num != 0 else 0
    status['memory'] = round(memory_cost / testcase_num, 1) if testcase_num != 0 else 0

    # print("?", status)
    queue.put((status['status'], Sol, score, status))

#     result = open("/var/www/judger/results/" + str(Sol[0]) + ".json", "w")
#     result.write(json.dumps(status))
#     result.close()
    subprocess.run(['rm', '-r', path])
    subprocess.run(['mkdir', path])
    busy[wid] = False


#!/usr/bin/env python3

import os
import rospy
import rospkg

from qt_gui.plugin import Plugin
from python_qt_binding import loadUi
from python_qt_binding.QtWidgets import QWidget, QMainWindow

from motor_testbench.msg import *
# import rosbag
import time

class ControlCenter(Plugin):

    def __init__(self, context):
        # rospy.init_node('QtGUI_node', anonymous = True)
        super(ControlCenter, self).__init__(context)
        self.setObjectName('ControlCenter')

        # Create window
        self._widget = QMainWindow()
        # Load the UI resource
        ui_file = os.path.join(rospkg.RosPack().get_path('control_center'), 'resource', 'motor_testbench.ui')
        loadUi(ui_file, self._widget)
        self._widget.setObjectName('ControlCenterUi')

        # Add plugin pane name/number
        if context.serial_number() > 1:
            self._widget.setWindowTitle(self._widget.windowTitle() + (' (%d)' % context.serial_number()))
        context.add_widget(self._widget)

        # Connect the slider
        self.sl_joint_pos = self._widget.sliderj1
        self.sl_joint_pos.setMinimum(-180)
        self.sl_joint_pos.setMaximum(180)

        self.sl_kd_val = self._widget.kdSlider
        self.sl_kd_val.setMinimum(0)
        self.sl_kd_val.setMaximum(5)

        self.sl_kp_val = self._widget.kpSlider
        self.sl_kp_val.setMinimum(0)
        self.sl_kp_val.setMaximum(500)

        # Connect to the motorID input box
        self.motorID_input = self._widget.motorID_input

        # Connect the buttons
        self._widget.motor_connect.clicked[bool].connect(self.on_click_connect)
        self._widget.enable.clicked[bool].connect(self.on_click_enable)
        self._widget.disable.clicked[bool].connect(self.on_click_disable)
        self._widget.setZero.clicked[bool].connect(self.on_click_setZero)
        self._widget.sendControl.clicked[bool].connect(self.on_click_move)
        self.cb_enable_control = self._widget.enableControl
        self.cb_enable_control.toggled.connect(self.on_enable_control)

        # Message config
        self.state_pub_duration = 0.4 # s
        self.command_pub_duration = 0.15 # s
        self.rate = rospy.Rate(50)

        # Setup useful variables
        self.enable_control = True

    def on_click_connect(self):
        # # Make the motor number a slot into which the plugin connects to, that way we can yse the same plugin multiple times
        # Select the motorID upon an connect button is clicked
        self.motorID = int(self.motorID_input.toPlainText())

        # Initiate the corresponding state publishers
        self.state_channel = rospy.Publisher('motor_state/'+str(self.motorID)+'/', tmotor_cmd, queue_size=10)
        # Initiate control publishers
        self.command_channel = rospy.Publisher('motor_command/'+str(self.motorID)+'/', tmotor_cmd, queue_size = 10)

        # Subscribe to the response on CAN
        rospy.Subscriber('can_response/motor_'+str(self.motorID), tmotor_data, self.motor_response_callback)

    # Modify sliders based on if the control mode is enabled or not
    def on_enable_control(self):
        self.enable_control = self.cb_enable_control.isChecked()

    def on_click_enable(self):
        cmd = tmotor_cmd()
        cmd.status = True

        self.send_multiple_messages(cmd, self.state_channel, self.state_pub_duration)
        cmd = tmotor_cmd()
        cmd.position = 0
        cmd.velocity = 0
        cmd.torque = 0
        cmd.kp = 0
        cmd.kd = 0
        self.send_multiple_messages(cmd, self.command_channel, self.command_pub_duration)

    def on_click_disable(self):
        cmd = tmotor_cmd()
        cmd.position = 0
        cmd.velocity = 0
        cmd.torque = 0
        cmd.kp = 0
        cmd.kd = 0
        self.send_multiple_messages(cmd, self.command_channel, self.command_pub_duration)
        cmd = tmotor_cmd()
        cmd.status = False
        self.send_multiple_messages(cmd, self.state_channel, self.state_pub_duration)

    def on_click_setZero(self):
        cmd = tmotor_cmd()
        cmd.status = True
        cmd.setzero = True
        self.send_multiple_messages(cmd, self.state_channel, self.state_pub_duration)
        cmd = tmotor_cmd()
        cmd.position = 0
        cmd.velocity = 0
        cmd.torque = 0
        cmd.kp = 0
        cmd.kd = 0
        self.send_multiple_messages(cmd, self.command_channel, self.command_pub_duration)
        # Come out of set zero by re-arming the motor again
        # self.on_click_enable()

    def on_click_move(self):
        # Check if control is enabled
        if self.enable_control:
            cmd = tmotor_cmd()
            # Read the values from the sliders
            cmd.position = self.sl_joint_pos.value()
            cmd.velocity = 0
            cmd.torque = 0
            cmd.kp = self.sl_kp_val.value()
            cmd.kd = self.sl_kd_val.value()
            self.send_multiple_messages(cmd, self.command_channel, self.command_pub_duration)
        else:
            raise Exception('Control not enabled')

    # This is to ensure that the messages are reached even
    # with the constant rtr pings for data
    def send_multiple_messages(self, cmd, channel, pub_duration):
        # Send only one message, since RTR is off this should work as predicted
        channel.publish(cmd)
        # For continuous publish
        # # get current time
        # now = time.time()
        # # publish message for a preset duration of time
        # while ((time.time()-now) < pub_duration):
        #     channel.publish(cmd)
        #     self.rate.sleep()

    def motor_response_callback(self, data):
        # Also use the status to show color bulbs
        # The updated values pos, vel and torque can be stored here if required
        # If control is disabled
        self._widget.ui_pos.setText(str(data.position))
        self._widget.ui_vel.setText(str(data.velocity))
        self._widget.ui_tau.setText(str(data.torque))
        if not self.enable_control:
            # Set slider value based on the incoming encoder value
            self.sl_joint_pos.setValue(data.position)

    # TODO implementation of necessary routines
    def shutdown_plugin(self):
        # TODO unregister all publishers here
        pass

    def save_settings(self, plugin_settings, instance_settings):
        # TODO save intrinsic configuration, usually using:
        # instance_settings.set_value(k, v)
        pass

    def restore_settings(self, plugin_settings, instance_settings):
        # TODO restore intrinsic configuration, usually using:
        # v = instance_settings.value(k)
        pass


from datetime import datetime
import logging

import utility

#
# Scanner for MeteoVenezia weather stations alike stations
#
def scan_meteovenezia_alike(last_seen_timestamp, server, save=True, log=True):

  location_id=server["location_id"]
  server_name=server["name"]
  weather_station_url=server["url"]

  tree, _ =utility.get_tree(weather_station_url, location_id, server_name)
  if tree is None:
    return last_seen_timestamp

  timestamp_string=None
  timestamp_string_date=None
  timestamp_string_time=None
  try:
    timestamp_list = tree.xpath('/html/body/div[2]/table[2]/tbody/tr[1]/td[1]')
    timestamp_ele=timestamp_list[0].text.split('\xa0\xa0\xa0')
    timestamp_ele_1=timestamp_ele[0].strip()
    timestamp_ele_2=timestamp_ele[1].strip()

    timestamp_string=timestamp_ele_1+" "+timestamp_ele_2
    timestamp_obj=datetime.strptime(timestamp_string, "%d.%m.%Y %H:%M")

    timestamp_string=timestamp_obj.strftime("%d/%m/%Y %H:%M:%S")
    if last_seen_timestamp and last_seen_timestamp==timestamp_string:
      return last_seen_timestamp

    timestamp_string_date=timestamp_obj.strftime("%d/%m/%Y")
    timestamp_string_time=timestamp_obj.strftime("%H:%M:%S")

  except Exception as e:
    logging.exception(f'{utility.get_identification_string(location_id, server_name)}, exception getting timestamp: "{e}"!')

  if timestamp_string==last_seen_timestamp:
    # Weather station is not updating data
    logging.info(f'{utility.get_identification_string(location_id, server_name)}, timestamp_string: {timestamp_string}, last_seen_timestamp: {last_seen_timestamp}, skip saving!')
    # TODO Raise an alert
    return last_seen_timestamp

  wind_speed_knots=None
  try:
    wind_speed_elem = tree.xpath('/html/body/div/table[2]/tbody/tr[3]/td[1]')
    wind_speed=wind_speed_elem[0].text.strip()
    if wind_speed:
      wind_speed_knots=float(wind_speed)

  except Exception as e:
    logging.exception(f'{utility.get_identification_string(location_id, server_name)}, exception getting wind_speed_knots: "{e}"!')

  wind_gust_knots=None
  try:
    wind_gust_elem = tree.xpath('/html/body/div/table[2]/tbody/tr[3]/td[3]')
    wind_gust=wind_gust_elem[0].text.strip()
    if wind_gust:
      wind_gust_knots=float(wind_gust)

  except Exception as e:
    logging.exception(f'{utility.get_identification_string(location_id, server_name)}, exception getting wind_gust_knots: "{e}"!')

  wind_direction_deg=None
  try:
    wind_direction_ele = tree.xpath('/html/body/div/table[2]/tbody/tr[3]/td[2]')
    wind_direction=wind_direction_ele[0].text.strip()
    wind_direction=wind_direction.split('°')[0].strip()
    if wind_direction:
      wind_direction_deg=float(wind_direction)

  except Exception as e:
    logging.exception(f'{utility.get_identification_string(location_id, server_name)}, exception getting wind_direction_deg: "{e}"!')

  barometric_pressure_ssl_hPa=None
  try:
    barometric_pressure_ssl_ele = tree.xpath('/html/body/div/table[2]/tbody/tr[11]/td[2]')
    barometric_pressure_ssl=barometric_pressure_ssl_ele[0].text.split('hPa')[0].strip()
    if barometric_pressure_ssl:
      barometric_pressure_ssl_hPa=float(barometric_pressure_ssl)

  except Exception as e:
    logging.exception(f'{utility.get_identification_string(location_id, server_name)}, exception getting barometric_pressure_ssl_hPa: "{e}"!')

  rain_today_mm=None
  try:
    rain_today_ele = tree.xpath('/html/body/div/table[2]/tbody/tr[12]/td[3]')
    rain_today=rain_today_ele[0].text.split(' ')[1].strip()
    if rain_today:
      rain_today_mm=float(rain_today)

  except Exception as e:
    logging.exception(f'{utility.get_identification_string(location_id, server_name)}, exception getting rain_today_mm: "{e}"!')

  rain_rate_mmh=None
  try:
    rain_rate_ele = tree.xpath('/html/body/div/table[2]/tbody/tr[12]/td[2]')
    rain_rate=rain_rate_ele[0].text.split('mm/h')[0].strip()
    if rain_rate:
      rain_rate_mmh=float(rain_rate)

  except Exception as e:
    logging.exception(f'{utility.get_identification_string(location_id, server_name)}, exception getting rain_rate_mmh: "{e}"!')

  temperature_cels=None
  try:
    temperature_ele=tree.xpath('/html/body/div/table[2]/tbody/tr[7]/td[2]')
    temperature=temperature_ele[0].text
    temperature=temperature.split('°')[0].strip()
    if temperature:
      temperature_cels=float(temperature)

  except Exception as e:
    logging.exception(f'{utility.get_identification_string(location_id, server_name)}, exception getting temperature_cels: "{e}"!')

  rel_humidity=None
  try:
    humidity_ele = tree.xpath('/html/body/div/table[2]/tbody/tr[9]/td[2]')
    humidity=humidity_ele[0].text.split("%")[0].strip()
    if humidity:
      rel_humidity=float(humidity)/100

  except Exception as e:
    logging.exception(f'{utility.get_identification_string(location_id, server_name)}, exception getting rel_humidity: "{e}"!')

  perceived_temperature_cels=None
  try:
    perceived_temperature_ele=tree.xpath("/html/body/div/table[2]/tbody/tr[8]/td[2]")
    perceived_temperature=perceived_temperature_ele[0].text.split('°')[0]
    if perceived_temperature:
      perceived_temperature_cels=float(perceived_temperature)

  except Exception as e:
    logging.exception(f'{utility.get_identification_string(location_id, server_name)}, exception getting perceived_temperature_cels: "{e}"!')

  dew_point_cels=None
  try:
    dew_point_ele = tree.xpath('/html/body/div/table[2]/tbody/tr[10]/td[2]')
    dew_point=dew_point_ele[0].text.split('°')[0]
    if dew_point:
      dew_point_cels=float(dew_point)

  except Exception as e:
    logging.exception(f'{utility.get_identification_string(location_id, server_name)}, exception getting dew_point_cels: "{e}"!')

  meteo_data_dict={}
  meteo_data_dict["timestamp_string"]=timestamp_string
  meteo_data_dict["timestamp_string_date"]=timestamp_string_date
  meteo_data_dict["timestamp_string_time"]=timestamp_string_time
  meteo_data_dict["wind_speed_knots"]=wind_speed_knots
  meteo_data_dict["wind_direction_deg"]=wind_direction_deg
  meteo_data_dict["barometric_pressure_ssl_hPa"]=barometric_pressure_ssl_hPa
  meteo_data_dict["rain_today_mm"]=rain_today_mm
  meteo_data_dict["rain_rate_mmh"]=rain_rate_mmh
  meteo_data_dict["temperature_cels"]=temperature_cels
  meteo_data_dict["rel_humidity"]=rel_humidity
  meteo_data_dict["perceived_temperature_cels"]=perceived_temperature_cels
  meteo_data_dict["wind_gust_knots"]=wind_gust_knots
  meteo_data_dict["dew_point_cels"]=dew_point_cels

  if log:
    utility.log_sample(location_id, server_name, meteo_data_dict)

  if not utility.check_minimum_data(location_id, server_name, meteo_data_dict):
    return last_seen_timestamp

  utility.save(location_id, server_name, meteo_data_dict)
  return timestamp_string

if __name__=="__main__":
  utility.test_starter(10) # Location id


"""
survey123_attachments
Extract attachments from ESRI file geodatabase
Created By: mkimble
"""

import os, arcpy
from . import settings
from .logger_settings import api_logger

class DownloadAttachmentsFGDB:
   """
   Arguments
   ATTACHMENTS_TABLE: Path to attachment table
   BLOB_FIELD: Field name of Blob data type field in attachment table
   ATTACHMENTS_FIELD: Field name in attachment table that contains attachment name
   ATTACHMENTS_FOLDER: Output folder to export attachments to
   """
   def __init__(self, ATTACHMENTS_TABLE=settings.ATTACHMENTS_TABLE,
                BLOB_FIELD = settings.BLOB_FIELD,
                ATTACHMENTS_FIELD = settings.ATTACHMENTS_FIELD,
                ATTACHMENTS_FOLDER = settings.ATTACHMENTS_FOLDER):
      self.ATTACHMENTS_TABLE = ATTACHMENTS_TABLE
      self.BLOB_FIELD = BLOB_FIELD
      self.ATTACHMENTS_FIELD = ATTACHMENTS_FIELD
      self.ATTACHMENTS_FOLDER = ATTACHMENTS_FOLDER

   def extract_attachments(self):
      try:
         api_logger.info("[START] extract_attachments")
         with arcpy.da.SearchCursor(self.ATTACHMENTS_TABLE, [self.BLOB_FIELD, self.ATTACHMENTS_FIELD]) as cursor:
            for row in cursor:
               binary_rep = row[0]
               file_name = row[1]
               # save to disk
               open(self.ATTACHMENTS_FOLDER + os.sep + file_name, 'wb').write(binary_rep.tobytes())
         api_logger.info("[END] extract_attachments")
      except Exception as err:
         raise RuntimeError("** Error: extract_attachments Failed (" + str(err) + ")")


def eval_cached(self, statement, *args):
        """
        Evaluate a statement and cache the result before returning.

        Statements are evaluated inside the Trimesh object, and

        Parameters
        -----------
        statement : str
          Statement of valid python code
        *args : list
          Available inside statement as args[0], etc

        Returns
        -----------
        result : result of running eval on statement with args

        Examples
        -----------
        r = mesh.eval_cached('np.dot(self.vertices, args[0])', [0,0,1])
        """

        statement = str(statement)
        key = 'eval_cached_' + statement
        key += '_'.join(str(i) for i in args)

        if key in self._cache:
            return self._cache[key]

        result = eval(statement)
        self._cache[key] = result
        return result


# coding=utf-8
from __future__ import division

import logging

from nrnutils import Section, PROXIMAL
from model.mechanisms import pas_mechanism
from model.base import BaseNeuron

logger = logging.getLogger('morphology')

# geometry and topology

def create_soma(self, soma_L=15, soma_diam=15, soma_nseg=1, mechanisms=None, **kwargs):
    if mechanisms is None:
        mechanisms = self.mechanisms
    self.soma = Section(name='soma', L=soma_L, diam=soma_diam, nseg=soma_nseg, Ra=self.Ra, cm=self.cm,
                        mechanisms=mechanisms)
    self.sections.append(self.soma)

def create_axon(self, axon_L=100, axon_diam=0.2, mechanisms=None, **kwargs):
    if mechanisms is None:
        mechanisms = self.mechanisms
    self.axon = Section(name='axon', L=axon_L, diam=axon_diam, Ra=self.Ra, cm=self.cm,
                        mechanisms=mechanisms,
                        parent=self.soma,
                        connection_point=PROXIMAL)
    self.sections.append(self.axon)

def create_radial_dends(self, num_dendrites=1, parent=None, **kwargs):
    if parent is None:
        parent = self.soma
    self.radial_dends = []
    for i in range(num_dendrites):
        self.radial_dends.append(Section(name='radial_dends_{}'.format(i + 1),
                                         L=self.radial_L,
                                         diam=self.radial_diam,
                                         nseg=self.radial_nseg,
                                         Ra=self.Ra, cm=self.cm,
                                         mechanisms=self.mechanisms,
                                         parent=parent))
    self.sections += self.radial_dends

def create_sinks(self, num_sinks=1, parent=None, **kwargs):
    if parent is None:
        parent = self.soma
    self.sinks = []
    for i in range(num_sinks):
        self.sinks.append(Section(name='sink_{}'.format(i + 1),
                                         L=self.sink_L,
                                         diam=self.sink_diam,
                                         nseg=self.sink_nseg,
                                         Ra=self.Ra, cm=self.cm,
                                         mechanisms=self.mechanisms,
                                         parent=parent))
    self.sections += self.sinks

# noinspection PyAttributeOutsideInit
class MultiDend(BaseNeuron):
    """
    Soma with [num_dendrites] projecting from it.
    """

    def __init__(self, name="MultiDend", num_dendrites=1,
                 radial_l=50, radial_diam=2, radial_nseg=9,
                 reduced=False, call_geom_nseg=False,
                 *args, **kwargs):
        self.num_dendrites = num_dendrites
        self.radial_L = radial_l
        self.radial_diam = radial_diam
        self.radial_nseg = radial_nseg
        super(MultiDend, self).__init__(name, call_geom_nseg=call_geom_nseg, *args, **kwargs)

    def build_sections(self, soma_L=0.01, soma_diam=2, **kwargs):
        super(MultiDend, self).build_sections(soma_L=soma_L, soma_diam=soma_diam, **kwargs)
        self.soma.Ra = 0.2

        create_radial_dends(self, num_dendrites=self.num_dendrites)

        self.dend = self.radial_dends

    create_mechanisms = pas_mechanism

# noinspection PyAttributeOutsideInit
class MultiDendWithSink(MultiDend):
    def __init__(self, name="MultiDendWithSink",
                 sink_num=1, sink_l=50, sink_diam=2, sink_nseg=9,
                 *args, **kwargs):
        self.num_sinks = sink_num
        self.sink_L = sink_l
        self.sink_diam = sink_diam
        self.sink_nseg = sink_nseg
        super(MultiDendWithSink, self).__init__(name, *args, **kwargs)

    def build_sections(self, **kwargs):
        super(MultiDendWithSink, self).build_sections(**kwargs)

        create_sinks(self, num_sinks=self.num_sinks)

        self.dend = self.radial_dends + self.sinks

# noinspection PyAttributeOutsideInit,PyPep8Naming
class SingleDend(BaseNeuron):
    """
    Soma with a single dendrite and (optionally) an axon
    don't auto-calculate nseg
    """

    def __init__(self, name="SingleDend", call_geom_nseg=False, *args, **kwargs):
        super(SingleDend, self).__init__(name, call_geom_nseg=call_geom_nseg, *args, **kwargs)
        # reset soma area: set L and diam to 2.8012206 , so that area = 24.651565 (from rho = 0.1)
        # self.soma.L = 2.8012206
        # self.soma.diam = 2.8012206

    create_mechanisms = pas_mechanism

    def build_sections(self, dend_l=707, dend_diam=1., dend_nseg=81, axon=False, **kwargs):
        super(SingleDend, self).build_sections(**kwargs)
        if axon:
            create_axon(self, **kwargs)
        self.dend.append(Section(name='dend_1',
                                 L=dend_l, diam=dend_diam, nseg=dend_nseg, Ra=self.Ra, cm=self.cm,
                                 mechanisms=self.mechanisms,
                                 parent=self.soma))
        self.sections += self.dend


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

from multiprocessing import Process
import time
import datetime
# from server_link import LinkInfo
from server_limit import Limit
from server_rand import generateRandom
# from own_exception import dbEmpty
from logger import logger
from params import dataScheme
logger = logger('server_control', file_level=None, stream_level='DEBUG')

class ControlProcess(Process, dataScheme):
    """ """
    def __init__(self, *args, **kwargs):
        """ """
        dataScheme.__init__(self)
        Process.__init__(self)
        self.loop_interval = args[0]
        self.time_lvl2 = int(args[1])
        self.set_lvl1 = args[2]
        self.loop_number = args[3]
        self.nbr_client = args[4]
        self.db_process_profile = kwargs['process_profile']
        self.db_process_link = kwargs['process_link']
        self.db_process_tweet = kwargs['process_tweet']
        self.db_current_prof = kwargs['current_profile']
        self.db_current_link = kwargs['current_link']
        self.db_rand_2 = kwargs['rand_lvl2']
        self.db_rand_3 = kwargs['rand_lvl3']
        self.do_limit = Limit(self.loop_interval, max_user=True)
        self.limit = self.do_limit.calculing_limit()
        self.create_lock_file()

    def create_lock_file(self):
        """
        Create a lock file with a false value
        """
        with open('.lock_server_control', 'w') as f:
            f.write('false')

    def process_limit(self, nbr_client, size):
        """ """
        limit = self.do_limit.calculing_limit(nbr_client, size)
        logger.info('Max size sample. lvl1: {} - lvl2: {} - lvl3 - {}'.format(limit['lvl1'],
                                                                              limit['lvl2'],
                                                                              limit['lvl3']))
        return limit['lvl2'], limit['lvl3']

    def record_sample(self, loop_number, lvl2_size, lvl3_size):
        """
        Record the sample size taken for the loop
        """
        with open('sample_size', 'a') as f:
            f.write('{}::{}::LVL2 size - {} :: LVL3 size - {}'.format(datetime.datetime.now(),
                                                                      loop_number,
                                                                      lvl2_size,
                                                                      lvl3_size))
            f.write('\n')

    def check_lock(self):
        """
        Try to open the file with the client_id name, Check if a value
        "true" is in it, which means it has to pause. It helps to kill the
        running instance or doing other modification somewhere else
        """
        try:
            with open('.lock_server_control', 'r') as f:
                lock = f.readline().rstrip()
                if lock == 'true':
                    logger.info('Lock file is true, pause for 1 minute')
                    time.sleep(50)
                    logger.info('Start again in 10 sec')
                    time.sleep(5)
                    logger.info('Start again in 5 sec')
                    time.sleep(5)
        except FileNotFoundError:
            pass

    def keep_looking(self, db, query, lap_time=60):
        """
        Loop to keep checking until no record are return
        then exit
        """
        def check_todo(db, query):
            """ Check if there is still some profile or link to do """
            if query == 'todo':
                query = {'doing': {'$exists': False}, 'extra': {'$exists': False}}
            elif query == 'doing':
                query = {}
            return bool(db.find_one(query))

        lock = True
        while lock is True:
            lock = check_todo(db, query)
            time.sleep(lap_time)
        return

    def remove_extra_remaining(self, db):
        """ """
        query = query = {'doing': {'$exists': False}, 'extra': {'$exists': True}}
        db.delete_many(query)

    def recreate_lvl1(self):
        """
        Function to copy the set of lvl1 id_str created from the beggining
        to the new loop. Be sure to have the right one all the time instead of
        loosing it with some twitter errors
        """

        def generate_query(result):
            """
            Need to recreate the query after every insert otherwise some
            field are removed after the insertion in a db
            """
            query = result
            return query

        for id_str in self.set_lvl1:
            info_user = dict()
            info_user['id_str'] = int(id_str)
            info_user['loop_number'] = self.loop_number
            update ={'$unset': {'extra': ''}}

            search = generate_query(info_user)
            self.db_process_profile.update_one(search, update, upsert=True)
            search = generate_query(info_user)
            self.db_process_tweet.update_one(search, update, upsert=True)

            info_user['type_link'] = 'followers'
            search = generate_query(info_user)
            self.db_process_link.update_one(search, update, upsert=True)

            info_user['type_link'] = 'friends'
            search = generate_query(info_user)
            self.db_process_link.update_one(search, update, upsert=True)

    def remove_previous_loop(self, db):
        """ """
        db.delete_many({self.loop: self.loop_number})

    def run(self):
        """ """
        while True:
            # Continue to do activity and updating storing while client
            # Still have to do twitter call
            logger.info('New loop: {}'.format(self.loop_number))

            # logger.info('Clean the Rand_lvl2 db')
            # self.remove_previous_loop(self.db_rand_2)

            # logger.info('Clean the Rand_lvl3 db')
            # self.remove_previous_loop(self.db_rand_3)

            logger.info('Get lock until all links are finished')
            self.keep_looking(self.db_process_link, 'todo')
            self.check_lock()

            logger.info('Get lock until all profiles are finished')
            self.keep_looking(self.db_process_profile, 'todo')

            logger.info('Remove extra links')
            self.remove_extra_remaining(self.db_process_link)
            self.check_lock()

            logger.info('Remove extra profile')
            self.remove_extra_remaining(self.db_process_profile)
            self.check_lock()

            logger.info('Remove extra tweet')
            self.remove_extra_remaining(self.db_process_tweet)
            self.check_lock()

            logger.info('Wait until all links are done')
            self.keep_looking(self.db_process_link, 'doing')
            self.check_lock()

            logger.info('Wait until all profile are done')
            self.keep_looking(self.db_process_profile, 'doing')
            self.check_lock()

            logger.info('Calculate the limit of lvl2 and lvl3')
            lvl2_sample_size, lvl3_sample_size = self.process_limit(len(self.nbr_client), len(self.set_lvl1))

            logger.info('Record the sample size')
            self.record_sample(self.loop_number + 1, lvl2_sample_size, lvl3_sample_size)
            self.check_lock()

            logger.info('Pause until all tweets are completely finished')
            self.keep_looking(self.db_process_tweet, 'todo')

            logger.info('Get lock until all tweets are finished')
            self.keep_looking(self.db_process_tweet, 'doing')

            logger.info('Start the rand process')
            rand_list = []
            rand_list.append(generateRandom(2, self.db_process_profile,
                                            self.db_process_link,
                                            self.db_process_tweet,
                                            self.db_rand_2, lvl2_sample_size,
                                            self.loop_number))
            rand_list.append(generateRandom(3, self.db_process_profile,
                                            self.db_process_link,
                                            self.db_process_tweet,
                                            self.db_rand_3, lvl3_sample_size,
                                            self.loop_number))

            for rand_process in rand_list:
                rand_process.start()
                rand_process.join()
            self.check_lock()

            self.loop_number += 1
            # reset the number of client
            self.nbr_client = set()

            logger.info('Update the lvl1 to todo')
            self.recreate_lvl1()
            self.check_lock()

def main():
    """ """
    pass

if __name__ == '__main__':
    main()


import pandas as pd
from django.shortcuts import render
from rest_framework.generics import ListCreateAPIView, UpdateAPIView
from rest_framework.response import Response
from rest_framework import authentication, permissions
from rest_framework.response import Response
from sklearn.preprocessing import MinMaxScaler
import random
from django.views.decorators.csrf import ensure_csrf_cookie

from datetime import datetime
from Seasonality import daily_seasonality, weekly_seasonality
from timeseries.models import *
from .Serializers import *
from rest_framework.decorators import action
from Seasonality.daily_seasonality import Daily_Seasonality
from Seasonality.weekly_seasonality import Weekly_Seasonality
from .models import *
from Cycles_and_trends.cycle import cycle
from Cycles_and_trends.trends import trends

from Generator.Time_Series import Time_Series
from Noise.missing_values import missing_values
from Noise.noise import noise
from Noise.outliers import outliers
from Save.csv_file import csv_file
# Create your views here.
class simulator(ListCreateAPIView, UpdateAPIView):
    queryset = simulator_details.objects.all()
    serializer_class = timeseries_serializer

    def create(self, request, *args, **kwargs):
        data=request.data
        ts_serial = timeseries_serializer(data=data)
        configuration=data.pop('configuration')[0]
        seaonality=configuration.pop('seasonality')[0]
        #ts_serial=timeseries_serializer(data=data)
        if ts_serial.is_valid():
            ts_serial.save()
        configurationserializer=configuration_serializer(data=configuration)
        if configurationserializer.is_valid():
            configurationserializer.save()
        seasonalityserializer=seasonality_serializer(data=seaonality)
        if seasonalityserializer.is_valid():
            seasonalityserializer.save()

        return Response("Time series added",status=200)

    @action(detail=True, methods=['GET'])

    def run(self,request,*args, **kwargs):
        id = request.Get.get('id',-1)

        data = simulator_details.objects.filter(id=id)[0]

        #ts_serial = timeseries_serializer(data=data)
        configuration = data.pop('configuration')[0]
        seaonality = configuration.pop('seasonality')[0]
        Start_date = data["start_date"]
        End_date = data["end_date"]
        use_case_name = data['use_case_name']
        frequencies = configuration["Frequency"]

        frequency_type = seaonality["frequency_type"]
        phase_shift = seaonality["phase_shift"]
        amplitude = seaonality["amplitude"]
        noise_levels = [configuration["Noise_level"]]
        trend_levels = [configuration["Trend_coefficient"]]
        cyclic_periods = [configuration["Cycle_frequency"]]
        data_types = data["time_series_type"]
        percentage_outliers_options = [configuration["Outlier_percentage"]]
        Start_date = datetime.strptime(Start_date, "%Y-%m-%d")
        End_date = datetime.strptime(End_date, "%Y-%m-%d")
        data_size = (End_date - Start_date).days
        counter = 0
        meta_data = []
        for noise_level in noise_levels:
            for trend in trend_levels:
                for cyclic_period in cyclic_periods:
                    for percentage_outliers in percentage_outliers_options:
                        for data_type in data_types:
                            for _ in range(13):

                                counter += 1

                                # Generate time index

                                series = Time_Series(Start_date, End_date, frequencies)
                                date_rng = series.create_time_series()
                                daily_seasonal_component = 1
                                weekly_seasonal_component = 1
                                # Create components
                                if frequency_type == "Daily":

                                    Daily_seasonality = Daily_Seasonality()
                                    daily_seasonal_component = Daily_seasonality.add_daily_seasonality(date_rng)
                                elif frequency_type == "Weekly":
                                    Weekly_seasonality = Weekly_Seasonality()
                                    weekly_seasonal_component = Weekly_seasonality.add_weekly_seasonality(date_rng)
                                trnd = trends(trend, data_size=data_size,
                                              data_type=data_type)
                                trend_component = trnd.add_trend(date_rng)
                                cyclic_period = "exist"
                                Cycle = cycle(cyclic_period, season_type=data_type)
                                cyclic_component = Cycle.add_cycles(date_rng)

                                # Combine components and add missing values and outliers
                                if data_type == 'multiplicative':
                                    data = daily_seasonal_component * weekly_seasonal_component * trend_component * cyclic_component
                                else:
                                    data = daily_seasonal_component + weekly_seasonal_component + trend_component + cyclic_component
                                    # Create a MinMaxScaler instance
                                    scaler = MinMaxScaler(feature_range=(-1, 1))
                                    data = scaler.fit_transform(data.values.reshape(-1, 1))
                                    Noise = noise(noise_level)
                                    data = Noise.add_noise(data)
                                    Outliers = outliers(percentage_outliers)
                                    data, anomaly = Outliers.add_outliers(data)
                                    Missing_Value = missing_values(0.05)
                                    data = Missing_Value.add_missing_values(data)
                                    df = pd.DataFrame({'value': data, 'timestamp': date_rng, 'anomaly': anomaly})
                                    file = csv_file('sample_datasets/' + str(counter) + '.csv', df)
                                    file.save()
                                    meta_data.append({'id': str(counter) + '.csv',
                                                      'data_type': data_type,
                                                      'daily_seasonality': daily_seasonality,
                                                      'weekly_seasonality': weekly_seasonality,
                                                      'noise (high 30% - low 10%)': noise_level,
                                                      'trend': trend,
                                                      'cyclic_period (3 months)': cyclic_period,

                                                      'percentage_outliers': percentage_outliers,
                                                      'percentage_missing': 0.05,
                                                      'freq': frequencies})
                                    # generate_csv(list(zip(date_rng, data)), file_name)

                                    meta_data_df = pd.DataFrame.from_records(meta_data)
                                    meta_data_file = csv_file('sample_datasets/meta_data.csv', meta_data_df)
                                    meta_data_file.save()

        return Response("Time series created",status=200)

    @action(detail=True, methods=['GET'])
    def stop(self,request):
        self.get_object()
        return


'''
Loop over this for a row like this:

for c in range(1, 27):
        sheet.merge_cells(start_col=c+1, start_row=2, end_col=c+2, end_row=2)
        '''

nl = '\n'
print(nl)
# sheet.unmerge_cells('A1:A5') # HELP: error unmerge

# imports
import os
import openpyxl
from openpyxl.workbook import Workbook
from openpyxl.styles.colors import Color
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font, GradientFill, NamedStyle

# Set directory
print(os.getcwd())
os.chdir('C:\\Users\\pcurtis7\\Desktop\\_myScripts\\python_excel')
print(os.getcwd(), nl)

# create workbook
wb = openpyxl.Workbook()
print('type(workbook):', type(wb))
print('all.sheetnames:', wb.sheetnames)

# set sheets
sheet = wb.active
sheet.title = 'Daily_Rounds'
s0 = sheet
s1 = wb.create_sheet('Colors')
print('all.sheetnames:', wb.sheetnames)
print('wb.index(s0/Daily_Rounds) =', wb.index(s0))
print('wb.index(s1/Colors) =', wb.index(s1))

# help: how do you change the active sheet?
wb.active = wb.index(s0)
print('sheet/wb.active =', sheet)
wb.active = wb.index(s1)
print('sheet/wb.active =', sheet)
print('s1[1] =', s1[1])

wb.save('daily_log_v2_loops.xlsx')

# General styles
sheet.page_setup.orientation = sheet.ORIENTATION_PORTRAIT
highlight = NamedStyle(name="highlight")
highlight.font = Font(bold=True, size=12)
bd = Side(style='thick', color="000000")
highlight.border = Border(left=bd, top=bd, right=bd, bottom=bd)
# wb.add_named_style(highlight) # confirm if this adds to entire workbook
sheet['A1'].style = highlight
sheet['A41'].style = 'highlight'

# Merge Cells
# sheet.merge_cells(start_row=, start_column=, end_row=, end_column=)
# Rows 6-21

for c in range(1, 27):
        sheet.merge_cells(start_col=c+1, start_row=2, end_col=c+2, end_row=2)

''
start_col = [2, 4, 6, 8]
end_col = [x + 1 for x in start_col]

for i in range (1, 6):
  if i in [1, 4]:
    sheet.merge_cells(start_row=i, start_column=1, end_row=i, end_column=9)
  else:
    for col1, col2 in zip(start_col, end_col):
      sheet.merge_cells(start_row=i, start_column=col1, end_row=i, end_column=col2)
'''
Create a 'start' list with 2, 4, 6, & 8 integers
create an 'end' list that adds +1 for every integer in the 'start' list
For every value (named i) within the range 1 to 6, but not including 6:
  if i is either 1 or 4:
    merge cells starting with row range from 1 to 5, going from columns 1 to 9
  or else:
    for variables col1 & col2 in the zip() function calling start_col & end_col:
      merge cells within row i (range from 1 to 5), going from col1 to col2

I'm not exactly clear on everything here, specifically the objective of the zip() function and what value the col1 and col2 have.

I see the zip() defination but it's still not clear (must be 02:30am!):
  "The zip() function take iterables (zero or more), makes iterator that aggregates elements based on the iterables passed, and returns an iterator of tuples.
  Return Value from zip()
The zip() function returns an iterator of tuples based on the iterable object.
If no parameters are passed, zip() returns an empty iterator
If a single iterable is passed, zip() returns an iterator of 1-tuples. Meaning, the number of elements in each tuple is 1.
If multiple iterables are passed, ith tuple contains ith Suppose, two iterables are passed; one iterable containing 3 and other containing 5 elements. Then, the returned iterator has 3 tuples. It's because iterator stops when shortest iterable is exhaused."

Is my description correct?  What am I missing?
'''

'''
sheet.merge_cells(start_row=6, start_column=2, end_row=6, end_column=3) # SR1 CW Loop
sheet.merge_cells(start_row=6, start_column=4, end_row=6, end_column=5) # SR1 CW Loop
sheet.merge_cells(start_row=6, start_column=6, end_row=6, end_column=7) # SR1 CW Loop
sheet.merge_cells(start_row=6, start_column=8, end_row=6, end_column=9) # SR1 CW Loop
sheet.merge_cells(start_row=10, start_column=2, end_row=10, end_column=3) # PDU 11
sheet.merge_cells(start_row=10, start_column=4, end_row=10, end_column=5) # PDU 11
sheet.merge_cells(start_row=10, start_column=6, end_row=10, end_column=7) # PDU 11
sheet.merge_cells(start_row=10, start_column=8, end_row=10, end_column=9) # PDU 11
sheet.merge_cells(start_row=11, start_column=2, end_row=11, end_column=3) # PDU 9
sheet.merge_cells(start_row=11, start_column=4, end_row=11, end_column=5) # PDU 9
sheet.merge_cells(start_row=11, start_column=6, end_row=11, end_column=7) # PDU 9
sheet.merge_cells(start_row=11, start_column=8, end_row=11, end_column=9) # PDU 9
sheet.merge_cells(start_row=12, start_column=2, end_row=12, end_column=3) # PDU 2
sheet.merge_cells(start_row=12, start_column=4, end_row=12, end_column=5) # PDU 2
sheet.merge_cells(start_row=12, start_column=6, end_row=12, end_column=7) # PDU 2
sheet.merge_cells(start_row=12, start_column=8, end_row=12, end_column=9) # PDU 2
sheet.merge_cells(start_row=13, start_column=2, end_row=13, end_column=3) # PDU 4
sheet.merge_cells(start_row=13, start_column=4, end_row=13, end_column=5) # PDU 4
sheet.merge_cells(start_row=13, start_column=6, end_row=13, end_column=7) # PDU 4
sheet.merge_cells(start_row=13, start_column=8, end_row=13, end_column=9) # PDU 4
sheet.merge_cells(start_row=17, start_column=2, end_row=17, end_column=3) # PDU 1
sheet.merge_cells(start_row=17, start_column=4, end_row=17, end_column=5) # PDU 1
sheet.merge_cells(start_row=17, start_column=6, end_row=17, end_column=7) # PDU 1
sheet.merge_cells(start_row=17, start_column=8, end_row=17, end_column=9) # PDU 1
sheet.merge_cells(start_row=18, start_column=2, end_row=18, end_column=3) # PDU 8
sheet.merge_cells(start_row=18, start_column=4, end_row=18, end_column=5) # PDU 8
sheet.merge_cells(start_row=18, start_column=6, end_row=18, end_column=7) # PDU 8
sheet.merge_cells(start_row=18, start_column=8, end_row=18, end_column=9) # PDU 8
'''
wb.save('daily_log_v2_loops.xlsx')


#If the bill was $150.00, split between 5 people, with 12% tip.

#Each person should pay (150.00 / 5) * 1.12 = 33.6
#Format the result to 2 decimal places = 33.60

#Tip: There are 2 ways to round a number. You might have to do some Googling to solve this.ðŸ’ª

#Write your code below this line ðŸ‘‡
print("Welcome to the tip calculator!")

bill = float(input("What was the total bill? :\n"))
tip = int(input("How much tip would you like to give? 10, 12 or 15? :\n"))
tip /= 100
people = int(input("How many people to split the bill? :\n"))

pay = round((bill / people) + ((bill / people) * tip),2)

print(f"Each person should pay: ${pay}")


import pygame as pg
from libreria import*

if __name__ == '__main__':
    pg.init()
    pantalla = pg.display.set_mode((ancho,alto))
    img = pg.image.load('descarga.jpeg')
    fondo = pg.image.load('fondo1.png')
    info= fondo.get_rect()
    print(info)
    fondox=-100
    fondoy=-100
    velx=0
    vely=0
    reloj=pg.time.Clock()
    fin = False
    while not fin:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                fin = True
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_UP:
                    vely= 5
                    velx=0
                if event.key == pg.K_DOWN:
                    vely= -5
                    velx=0
                if event.key == pg.K_RIGHT:
                    velx= -5
                    vely=0
                if event.key == pg.K_LEFT:  #273 4 5 6
                    velx= 5
                    vely=0
                if event.key == pg.K_SPACE:
                    velx=0
                    vely=0

        # print(y)
        # print(fondoy)
        if fondox<((info[2]-ancho)*-1):
            fondox=(info[2]-ancho)*-1
            print(fondox)
            velx =0
        elif fondox>0:
            fondox=0
            velx=0
        else:
            fondox+=velx
        if fondoy<((info[3]-alto)*-1):
            fondoy=(info[3]-alto)*-1
            vely=0
        elif fondoy>0 :
            fondoy=0
            vely=0
        else:
            fondoy+=vely
        pantalla.fill(negro)
        pantalla.blit(fondo,[fondox,fondoy])
        pg.display.flip()
        reloj.tick(30)


import threading
import signal
import time
import sys
from Y5 import Y5
from gatt import Device, DeviceManager
from y5_util import dbus_to_string, int_to_byte, checksum

manager = DeviceManager(adapter_name='hci0')

def signal_handler(sig, frame):
    print("caught exception")
    manager.stop()
    device.disconnect()
    time.sleep(0.5)
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)

device = Y5(mac_address='71:59:87:7b:12:29', manager=manager)
device.connect()

#manager.run()
t = threading.Thread(target=manager.run)

t.start()
while device.write_char is None:
    time.sleep(1)

device.set_units(True)
device.set_12_hour(False)
device.set_time()
#time.sleep(2)
#device.tick()
#device.send_msg("TestTitle", "This is a test message!")
#device.step_history_read()
#device.set_hr_auto(True)
#device.power_setting(True, True)
#device.get_hr()
#for i in range(0, 5):
#    device.write_value(int_to_byte(28, 0, 0))
#    time.sleep(0.2)
#device.get_hr()
time.sleep(50)
t.join(0)
manager.stop()
device.disconnect()

# while True:
#    time.sleep(1)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 18 17:20:30 2021

@author: hmc
"""

import os
import base64
import json
import numpy as np
from tqdm import tqdm
from pycocotools.coco import COCO as _COCO
import datetime
from glob import glob
import cv2
from utils import label_list

with open("./labelme_sample.json", "r+") as f:
    data = json.load(f)
f.close()

sample = data["shapes"]

def area_of_polygon(polygon):
    polygon = np.array(polygon).astype(int)
    return cv2.contourArea(polygon)

def find_all_img_anns(coco):

    img_id_list = []
    ann_list = []

    for img_info in coco['images']:
        img_id_list.append(img_info['id'])
        ann_list.append([])

    print("START LOADING annotation data")

    for ann in tqdm(coco['annotations']):
        index = img_id_list.index(ann['image_id'])
        ann_list[index].append(ann)

    return coco['images'], ann_list

class COCO():
    def __init__(self, img_dir = None, ann_path = None, list_path = None):
        """
        Arguments Description
        Label_list -> coco category look-up table (dictionary format)

        COCO FORMAT STRUCTURE
        info
         - description : What data ?
         - url : where do you get this data ?
         - version : The version of annotation data
         - year : The year of generating annotation data
         - contributor : contributor's name
         - data_created : date
        images (list)
         - license : I don't know what it means exactly.
         - file_name : image filename
         - coco_url : MSCOCO TEAM'S Website. (Indicating an image on the website)
         - height : The height of an image
         - width : The width of an image
         - flickr_url : COCO data is generated by using flickr app.
         So, in here, the url of flickr exists.
         - id : image id. it is unique.
        licenses
         - url : indicate an institute's url having copyright of this data.
         - id : Maybe... institute's id ?
         - name : The institute's name
        annotations (list)
         when iscrowd : 1
         - segmentation
           - counts : uncompressed RLE format annotation data
           - size : uncompressed RLE format annotation data
           Please check https://github.com/cocodataset/cocoapi/issues/135
         when iscrowd : 0
         - segmentation
           - N-dimensional polygon's coordinates like x_1, y_1 ... x_N, y_N
         - area : Region of the segmentation polygon.
         - iscrowd : crowd target or not.
         - image_id : literally same
         - bbox : literally same
         - category_id : literally same
         - id : ??
        categories (list)
         - supercategory : High level concept category
         - id : Category number
         - category : Concrete category
         example, sup_cat : Furniture
                  cat : Chair
        """

        self.img_dir = img_dir
        self.COCO = _COCO(ann_path)
        self.image_ids = self.COCO.getImgIds()
        self._list = label_list(list_path = list_path)

    def load_image_info(self, img_idx):
        """
        image_info is dictionary having following structure

        {'license': 3,
         'file_name': 'COCO_val2014_000000391895.jpg',
         'coco_url': 'http://images.cocodataset.org/val2014/COCO_val2014_000000391895.jpg',
         'height': 360,
         'width': 640,
         'date_captured': '2013-11-14 11:18:45',
         'flickr_url': 'http://farm9.staticflickr.com/8186/8119368305_4e622c8349_z.jpg',
         'id': 391895
         }

        """
        image_info = self.COCO.loadImgs(self.image_ids[img_idx])[0]

        return image_info

    def load_annotation(self, image_index: int, encode_img: bool):

        image_info = self.load_image_info(img_idx=image_index)
        annotations_ids = self.COCO.getAnnIds(imgIds=self.image_ids[image_index], iscrowd=False)
        ann_data = self.coco.loadAnns(annotations_ids)
        # Partial annotation data based on an image id
        shapes = []

        for item_id, item in enumerate(ann_data):
            # bbox : x_min, y_min, width, height
            x_min, y_min, width, height = item['bbox']
            tmp_shape = {"label": self._list.cat_mapping(True, cat_id=str(item['category_id'])),
                         "points": [[x_min, y_min],[x_min+width, y_min + height]],
                         "group_id": None,
                         "shape_type": "rectangle",
                         "flags": {}
                         }

            shapes.append(tmp_shape)

        LABELME_FORMAT = {"version":"4.5.6", # If labelme is updated, you should change this value
                  "flags":{}, # You can use this value space customly.
                  "shapes":shapes, # Annotation items are in here
                  "imagePath":image_info['file_name'], # Image filename
                  "imageData":None, # Base64 encoding data
                  "imageHeight":image_info['height'],
                  "imageWidth":image_info['width']
                  }

        if encode_img == True:
            img = open(os.path.join(self.img_dir, image_info['file_name']), 'rb').read()
            LABELME_FORMAT["imageData"] = base64.b64encode(img).decode("utf-8")

        return LABELME_FORMAT

    def generate(self, img_dir, label_dir, output_path):
        VALID_IMAGE_FORMAT = ['jpg', 'png', 'jpeg', 'tiff']
        img_list = []
        ann_list = glob(os.path.join(label_dir, '*.json'))
        amount_of_ann = len(ann_list)

        for form in VALID_IMAGE_FORMAT:
            img_list += [glob(os.path.join(img_dir, "*.{}".format(form)))]

        if len(img_list) == 0:
            raise Exception("There is no valid images. Please check the image folder")

        if len(ann_list) == 0:
            raise Exception("There is no annotation files. Please check the annotation folder")

        now = datetime.datetime.now()

        data = dict(
            info=dict(
                description = "What kind of dataset?",
                version="v1.0",
                year=now.year,
                contributor="LEE KANG IL, AIRLAB",
                date_created=now.strftime("%Y-%m-%d %H:%M:%S.%f")
                ),
            images=[],
            annotations=[],
            categories = self._list.COCO_LIKE_MAP
            )

        for image_id, label_path in enumerate(ann_list):
            with open(os.path.join(label_dir, label_path), 'r+') as f:
                label_data = json.load(f)
            f.close()

            data["images"].append(
                dict(
                    file_name = label_data["imagePath"],
                    height = label_data["imageHeight"],
                    width = label_data["imageWidth"],
                    id = image_id,
                    )
                )

            for label_id in range(len(label_data["shapes"])):
                label_data[label_id]['label']
                if label_data[label_id]['shape_type'] == 'rectangle':
                    (x_min, y_min), (x_max, y_max) = label_data[label_id]['points']
                    bbox = [x_min, y_min, x_max-x_min, y_max-y_min]
                    area = bbox[2] * bbox[3]

                elif label_data[label_id]['shape_type'] == 'polygon':
                    polygon_pts = label_data[label_id]['points']
                    area = area_of_polygon(polygon_pts)
                    bbox = polygon_pts

                data["annotations"].append(
                    dict(
                        segmentation = [],
                        area = area,
                        iscrowd = 0,
                        image_id = image_id,
                        bbox = bbox, # x_min, y_min, w, h
                        category_id = self._list.cat_mapping(False,
                                                             cat_name = label_data[label_id]['label']),
                        id = str(image_id).zfill(len(str(amount_of_ann))) + str(label_id).zfill(3)
                        ))
                """
                If you don't want to set specific super cat. and etc, please set sup cat as None
                and the others are properly dealt.
                """

        with open(output_path, 'w') as out_file:
            json.dump(data, out_file, indent=4)


#!/usr/bin/env python
import os.path as osp
import xml.etree.ElementTree as ET
import os
import cv2
import numpy as np
import argparse
import pickle as pkl
"""
 Annotation format:
    [
        {
            'filename': 'a.jpg',
            'width': 1280,
            'height': 720,
            'ann': {
                'bboxes': <np.ndarray> (n, 4),
                'labels': <np.ndarray> (n, ),
                'bboxes_ignore': <np.ndarray> (k, 4), (optional field)
                'labels_ignore': <np.ndarray> (k, 4) (optional field)
            }
        },
        ...
    ]

"""

classes = ["holothurian","echinus","scallop","starfish"]
cat2label = {cat: i + 1 for i, cat in enumerate(classes)}
def convert(data_root):
    img_infos = []
    filenames = os.listdir(osp.join(data_root, "train", "image"))
    img_ids = [id.split('.')[0] for id in filenames]
    for img_id in img_ids:
        filename = osp.join(data_root, 'train', "image",
                            '{}.jpg'.format(img_id))
        # 需要打开才知道图片宽高,需要做一个annotation.json快速读取
        img_cv = cv2.imread(filename)

        img_info = dict(id=img_id, filename=filename, width=img_cv.shape[1], height=img_cv.shape[0])

        del img_cv

        #打开xml 获取object bbox信息
        xml_path = osp.join(data_root, 'train', "box",
                            '{}.xml'.format(img_id))
        tree = ET.parse(xml_path)
        root = tree.getroot()
        bboxes = []
        labels = []
        bboxes_ignore = []
        labels_ignore = []
        for obj in root.findall('object'):
            name = obj.find('name').text
            if name not in cat2label:
                continue
            label = cat2label[name]
            # difficult = int(obj.find('difficult').text)
            difficult = False
            bnd_box = obj.find('bndbox')
            bbox = [
                int(bnd_box.find('xmin').text),
                int(bnd_box.find('ymin').text),
                int(bnd_box.find('xmax').text),
                int(bnd_box.find('ymax').text)
            ]
            ignore = False
            # if self.min_size:
            #     assert not self.test_mode
            #     w = bbox[2] - bbox[0]
            #     h = bbox[3] - bbox[1]
            #     if w < self.min_size or h < self.min_size:
            #         ignore = True
            if difficult or ignore:
                bboxes_ignore.append(bbox)
                labels_ignore.append(label)
            else:
                bboxes.append(bbox)
                labels.append(label)
        if not bboxes:
            bboxes = np.zeros((0, 4))
            labels = np.zeros((0,))
        else:
            bboxes = np.array(bboxes, ndmin=2) - 1
            labels = np.array(labels)
        if not bboxes_ignore:
            bboxes_ignore = np.zeros((0, 4))
            labels_ignore = np.zeros((0,))
        else:
            bboxes_ignore = np.array(bboxes_ignore, ndmin=2) - 1
            labels_ignore = np.array(labels_ignore)
        ann = dict(
            bboxes=bboxes.astype(np.float32),
            labels=labels.astype(np.int64),
            bboxes_ignore=bboxes_ignore.astype(np.float32),
            labels_ignore=labels_ignore.astype(np.int64))
        img_info.setdefault("ann",ann)
        img_infos.append(img_info)
    return img_infos
def parse_args():
    parser = argparse.ArgumentParser(description='underwaterdataset train dataset to mmdetction ann json')
    parser.add_argument('--dir', help='dataset root dir path')
    parser.add_argument('--out', help='output result file(pkl file)')
    args = parser.parse_args()
    return args
if __name__ == '__main__':
    args = parse_args()
    assert args.out is not None and args.dir is not None
    import json
    img_infos = convert(args.dir)
    with open(args.out,"wb") as file_handler:
        pkl.dump(img_infos, file_handler)


import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')

import django
django.setup()

from blog.models import Blog
from django.contrib.auth.models import User

user = User.objects.first()

def add_data(title, main_image, content, user, status):
    data, created = Blog.objects.get_or_create(title=title,
                                            main_image=main_image,
                                            content=content,
                                            status=status,
                                            author=user)
    print(f'Data: {data}, Created: {created}')

def populate():
    for i,_ in enumerate(range(20)):
        add_data(f'test data-{i}', f'{i}.jpg', f'test content-{i}', user, 'PU')

if __name__ == '__main__':
    populate()


import re
from heapq import nlargest

class Analyzer():

    file = None
    words = []
    freq = []
    pairs = []

    def __init__(self):
        try:
            self.file = open("corpus.txt", "r")
        except:
            print("Couldn't load the corpus")

    def analyzeFreq(self):
        for line in self.file:
            #Spliting the lines into words using regular expressions
            words = re.findall(r"[\w]+", line)
            #for each word in the array check if it's in the global array of words, otherwise append it and increment the freq array at it' point
            for word in words:
                w = word.lower()
                if(w not in self.words):
                    self.words.append(w)
                    self.freq.append(1)
                else:
                    i = self.words.index(w)
                    self.freq[i] = self.freq[i] + 1

        for i in range(0, len(self.words)):
            self.pairs.append(tuple((self.words[i], self.freq[i])))
        topFreq = nlargest(10, self.freq)
        topMostFreqWords = []
        for pair in self.pairs:
            if(pair[1] in topFreq and (pair[0] not in topMostFreqWords)):
                topMostFreqWords.append(tuple((pair[0], pair[1])))
        return topMostFreqWords

a = Analyzer()
print(a.analyzeFreq())


from base64 import b64encode
from logging import getLogger
from os import remove, makedirs
from os.path import join, exists
from re import search

from decouple import config
from requests import get, post
from bs4 import BeautifulSoup

logger = getLogger(__name__)

class CapturarDados:
    """
    Classe responsável por capturar e processar dados do site do desafio, incluindo o download de anexos
    e conversão para Base64.
    """

    def __init__(self):
        """
        Inicializa a classe com o token e cabeçalhos padrão para as requisições.
        """
        self._token = None
        self._headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                          "Chrome/114.0.0.0 Safari/537.36 OPR/100.0.0.0"
        }

    def _capturar_token(self):
        """
        Captura o token CSRF do site e armazena internamente na classe.
        """
        response = get(url=config('BASE_URL'), headers=self._headers)
        conteudo_html = response.text
        try:
            self._token = search(pattern=r'(?<=csrf\"\svalue=\")(.*?)(?=")', string=conteudo_html).group()
        except AttributeError:
            logger.error("Não conseguiu capturar o token do site!")
            self._token = None

    def _consultar_codigo(self, codigo: int):
        """
        Consulta um código específico no site e retorna o conteúdo da página.
        """
        payload = {
            "csrf": self._token,
            "codigo": codigo,
        }
        response = post(url=config('BASE_URL'), headers=self._headers, data=payload)
        if response.status_code == 200:
            return response.text
        else:
            logger.info(f"Código {codigo} inexistente!")
            return None

    def _parser_dados(self, codigo: int, html_page: str):
        """
        Processa o conteúdo HTML da página, captura informações sobre arquivos e anexos.
        """
        dados_parseados = []
        soup = BeautifulSoup(markup=html_page, features='html.parser', parse_only=None)

        # Encontrar todas as divs que contêm informações sobre arquivos
        body = soup.find('body')
        divs = body.find_all('div', recursive=False)

        for div in divs[1:]:
            if 'arquivo' in div.get_text().lower():
                nome_particao_arquivo = div.find_next('div').get_text(strip=True)
                conteudo_arquivos = [
                    {
                        "nome_arquivo": tag_a.get_text(),
                        "href": tag_a['href'],
                        "base64": self._capturar_anexo(url_anexo=tag_a['href'])
                    }
                    for tag_a in div.find_all('a')
                ]

                dados_parseados.append({
                    "nome_particao_arquivo": nome_particao_arquivo,
                    "anexos": conteudo_arquivos,
                    "codigo_consultado": codigo,
                })
        return dados_parseados

    def _capturar_anexo(self, url_anexo: str):
        """
        Captura o conteúdo de um anexo e converte para Base64.
        """
        response = get(url=f"{config('BASE_URL')}{url_anexo}", headers=self._headers)
        return self._gerar_base64_anexo(nome=url_anexo, conteudo=response.content)

    @staticmethod
    def _gerar_base64_anexo(nome: str, conteudo: bytes):
        """
        Gera o conteúdo Base64 a partir de um arquivo.
        """
        try:
            nome_diretorio_temporario = 'tmp_files'

            if not exists(nome_diretorio_temporario):
                makedirs(nome_diretorio_temporario)

            caminho_completo_arquivo = join(nome_diretorio_temporario, nome)

            with open(caminho_completo_arquivo, 'wb') as file:
                file.write(conteudo)

            # Leitura do conteúdo do arquivo temporário
            with open(caminho_completo_arquivo, 'rb') as file:
                file_content = file.read()

            # Conversão para base64
            base64_content = b64encode(file_content).decode('utf-8')

            return base64_content

        except Exception as e:
            logger.error(f"Erro ao gerar base64 do arquivo {nome} | Erro: {e}")
            return None

        finally:
            try:
                remove(caminho_completo_arquivo)
            except Exception as e:
                logger.warning(f"Erro ao remover arquivo temporário {caminho_completo_arquivo}: | Erro: {e}")

    def capturar_dados_existentes(self, codigo: int):
        """
        Captura os dados existentes para um código específico.
        """
        if not self._token:
            self._capturar_token()
        conteudo_codigo = self._consultar_codigo(codigo=codigo)
        if conteudo_codigo:
            dados_parseados = self._parser_dados(codigo=codigo, html_page=conteudo_codigo)
            return dados_parseados

        return None


# https://www.hackerrank.com/challenges/ctci-is-binary-search-tree

""" Node is defined as
class node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
"""
arr = []
inlen = 0

def checkBST(root):
    global arr
    if root is None:
        return True
    if checkBST(root.left):
        arr.append(root.data)
        if len(arr)>=2:
            if arr[-1]>arr[-2]:
                return True and checkBST(root.right)
            else:
                return False
        else:
            return checkBST(root.right)
    else:
        return False

# def checkBST(root):
#     if root.left is None and root.right is None:
#         return True
#     elif root.left is None and root.data <= root.right.data:
#         return checkBST(root.right)
#     elif root.right is None and root.data >= root.left.data:
#         return checkBST(root.left)
#     elif root.left.data <= root.data <= root.right.data:
#         return checkBST(root.left) and checkBST(root.right)
#     else:
#         return False


from tkinter import *
import tkinter as tk
# from PIL import Image, ImageTk
import random
from logic import *  # imports all from logic

root = Tk()
root.title("Monopoly")
root.geometry("500x300")
# root.iconbitmap("logo1.ico") #download a gaming picture or something with .ico extension and keep it in the same folder and try it
root.configure(background='grey')

def gamescreen():
    player1 = Player(1)  # player 1 color is coral red
    player2 = Player(2)  # player 2 color is light purple
    player1.isTurn = True

    # button functions
    def endturn():
        P1_cash_balance['text'] = player1.money
        P2_cash_balance['text'] = player2.money
        if Lost(player1):
            print("Player 1 Ran out of  Money!")
            quit(1)
        if Lost(player2):
            print("Player 2 Ran out of Money!")
            quit(2)
        if player1.isTurn:
            player1.isTurn = False
            player2.isTurn = True
            player_turn['text'] = player2.name
            P2_rolldice_btn['state'] = 'active'
        else:
            player2.isTurn = False
            player1.isTurn = True
            player_turn['text'] = player1.name
            rolldice_btn['state'] = 'active'

    def diceRolled1():
        if player1.isTurn:
            buttons[player1.pos].configure(bg='SystemButtonFace')  # resets to default color
            player1.RollDice()
            print(player1.dieRoll)
            rolldice_btn['state'] = 'disabled'
            P1_position_n['text'] = propertydic[player1.pos].name
            buttons[player1.pos].configure(bg='coral1')  # test code
        else:
            print("Already Rolled " + player1.name)

    def diceRolled2():
        if player2.isTurn:
            buttons[player2.pos].configure(bg='SystemButtonFace')  # resets to default color
            player2.RollDice()
            print(player2.dieRoll)
            P2_rolldice_btn['state'] = 'disabled'
            P2_position_n['text'] = propertydic[player2.pos].name
            buttons[player2.pos].configure(bg='MediumPurple1')  # test code
        else:
            print("Already Rolled " + player2.name)

    # need checks here for right input!
    def player1owns():
        if propertydic[player1.pos].canBuy:
            player1.money = player1.money - propertydic[player1.pos].cost
            player1.owns.append(propertydic[player1.pos])
            P1_properties_n.insert('end', player1.owns[len(player1.owns) - 1].name)
            print("player 1 owns " + player1.owns[len(player1.owns) - 1].name + " now")
            P1_cash_balance['text'] = player1.money
        else:
            print("Cannot Buy This Property " + propertydic[player1.pos].name)

    def player2owns():
        if propertydic[player2.pos].canBuy:
            player2.money = player2.money - propertydic[player2.pos].cost
            player2.owns.append(propertydic[player2.pos])
            P2_properties_n.insert('end', player2.owns[len(player2.owns) - 1].name)
            print("player 2 owns " + player2.owns[len(player2.owns) - 1].name + " now")
            P2_cash_balance['text'] = player2.money
        else:
            print("Cannot Buy This Property " + propertydic[player2.pos].name)

    root.title("Monopoly")
    root.geometry("1500x720")
    root.configure(background='skyblue')

    entry_label.destroy()
    P1_label.destroy()
    P2_label.destroy()
    P1nameentered.destroy()
    P2nameentered.destroy()
    startbtn.destroy()
    entry_label.destroy()
    opt.destroy()

    if (city_selection.get().lower() == 'chicago'):
        # Note: propertydic is a dictionary using <i,Class Object: Property> where i is the i'th index of chicagoList
        #   using propertydic and searching by key[i] finds that {key,value} pair where the value is of class Property
        #                 therefore, that key[i] returns the object and all of it's members
        #                a range based for loop creates every instance of every property in a single line
        propertydic = {i: Property(name=name, pos=i, cost=0, isRailroad=0, isUtility=0) for i, name in
                       enumerate(chicagolist)}
        # print(propertydic[12].name) # prints comed
        setNoBuy(propertydic)
        setPrices(propertydic)

    elif (city_selection.get().lower() == 'new york'):
        propertydic = {i: Property(name=name, pos=i, cost=0, isRailroad=0, isUtility=0) for i, name in
                       enumerate(newyorklist)}
        setNoBuy(propertydic)
        setPrices(propertydic)

    else:
        propertydic = {i: Property(name=name, pos=i, cost=0, isRailroad=0, isUtility=0) for i, name in
                       enumerate(defaultlist)}
        setNoBuy(propertydic)
        setPrices(propertydic)

    buttons = createButtons(root)
    initializeButtons(propertydic, buttons)

    if (P1_name.get() == ""):
        P1_tag = Label(root, text="Player 1", font='20', height=1, width=8, bg='skyblue', state='disabled',
                       disabledforeground="darkblue")
        P1_tag.grid(row=1, column=15, padx=160)
    else:
        P1_tag = Label(root, text=P1_name.get(), font='20', height=1, width=8, bg='skyblue', state='disabled',
                       disabledforeground="darkblue")
        player1.name = P1_name.get()  # properly sets player name
        P1_tag.grid(row=1, column=15, padx=160)

    if (P2_name.get() == ""):
        P2_tag = Label(root, text="Player 2", font='20', height=1, width=8, bg='skyblue', state='disabled',
                       disabledforeground="darkblue")
        P2_tag.grid(row=1, column=20, padx=60)
    else:
        P2_tag = Label(root, text=P2_name.get(), font='20', height=1, width=8, bg='skyblue', state='disabled',
                       disabledforeground="darkblue")
        player2.name = P2_name.get()  # properly sets player name
        P2_tag.grid(row=1, column=20, padx=60)

        player_turn = Button(root, text=player1.name, height=2, width=8, bg='black', state='disabled',
                             disabledforeground="white")
        player_turn.grid(row=6, column=6)

    rolldice_btn = Button(root, text="P1 diceroll", height=2, width=8, command=diceRolled1)
    rolldice_btn.grid(row=6, column=4)

    P2_rolldice_btn = Button(root, text="P2 diceroll", height=2, width=8, command=diceRolled2)
    P2_rolldice_btn.grid(row=6, column=8)

    endturn_btn = Button(root, text="endturn", height=2, width=8, command=endturn)
    endturn_btn.grid(row=7, column=6, pady=5)

    P1_housebuy = Button(root, text="P1 buy" + '\n' + "house", height=2, width=8)
    P1_housebuy.grid(row=9, column=3)

    P2_housebuy = Button(root, text="P2 buy" + '\n' + "house", height=2, width=8)
    P2_housebuy.grid(row=9, column=5)

    P1_housesell = Button(root, text="P1 sell" + '\n' + "house", height=2, width=8)
    P1_housesell.grid(row=10, column=3)

    P2_housesell = Button(root, text="P2 sell" + '\n' + "house", height=2, width=8)
    P2_housesell.grid(row=10, column=5)

    P1_propertybuy = Button(root, text="P1 buy" + '\n' + "property", height=2, width=8, command=player1owns)
    P1_propertybuy.grid(row=9, column=7)

    P2_propertybuy = Button(root, text="P2 buy" + '\n' + "property", height=2, width=8, command=player2owns)
    P2_propertybuy.grid(row=9, column=9)

    P1_propertysell = Button(root, text="P1 sell" + '\n' + "property", height=2, width=8)
    P1_propertysell.grid(row=10, column=7)

    P2_propertysell = Button(root, text="P2 sell" + '\n' + "property", height=2, width=8)
    P2_propertysell.grid(row=10, column=9)

    main_label = Label(root, text="WELCOME TO MONOPOLY-WORLD", font='20', bg='skyblue', state='disabled',
                       disabledforeground="red")
    main_label.grid(row=2, column=3, columnspan=6, rowspan=4, pady=20)
    P1_position = tk.Label(root, text="Board Position:", font='20', height=1, width=11, bg='skyblue', state='disabled',
                           disabledforeground="brown")
    P1_position.grid(row=2, column=15, padx=160)
    P2_position = tk.Label(root, text="Board Position:", font='20', height=1, width=11, bg='skyblue', state='disabled',
                           disabledforeground="brown")
    P2_position.grid(row=2, column=20, padx=60)
    P1_cash = tk.Label(root, text="Cash Balance:", font='20', height=1, width=11, bg='skyblue', state='disabled',
                       disabledforeground="green")
    P1_cash.grid(row=4, column=15, padx=160)
    P2_cash = tk.Label(root, text="Cash Balance:", font='20', height=1, width=11, bg='skyblue', state='disabled',
                       disabledforeground="green")
    P2_cash.grid(row=4, column=20, padx=60)
    P1_properties = tk.Label(root, text="Properties:", font='20', height=1, width=11, bg='skyblue', state='disabled',
                             disabledforeground="purple")
    P1_properties.grid(row=6, column=15, padx=160)
    P2_properties = tk.Label(root, text="Properties:", font='20', height=1, width=11, bg='skyblue', state='disabled',
                             disabledforeground="purple")
    P2_properties.grid(row=6, column=20, padx=60)
    P1_properties_n = tk.Listbox(root, height=24, width=45)
    P1_properties_n.grid(row=7, column=15, rowspan=100)
    P2_properties_n = tk.Listbox(root, height=24, width=45)
    P2_properties_n.grid(row=7, column=20, rowspan=100)
    P1_cash_balance = tk.Label(root, text=player1.money, height=1, width=11, bg='skyblue', state='disabled',
                               disabledforeground="darkgreen")
    P1_cash_balance.grid(row=5, column=15, padx=160)
    P2_cash_balance = tk.Label(root, text=player2.money, height=1, width=11, bg='skyblue', state='disabled',
                               disabledforeground="darkgreen")
    P2_cash_balance.grid(row=5, column=20, padx=60)
    P1_position_n = tk.Label(root, text=propertydic[player1.dieRoll].name, height=3, width=14, bg='skyblue',
                             state='disabled', disabledforeground="brown")
    P1_position_n.grid(row=3, column=15, padx=160)
    P2_position_n = tk.Label(root, text=propertydic[player2.dieRoll].name, height=3, width=14, bg='skyblue',
                             state='disabled', disabledforeground="brown")
    P2_position_n.grid(row=3, column=20, padx=60)

P1_label = tk.Label(root, text="Player 1 name", font='20', bg='gray', state='disabled', disabledforeground="skyblue")
P1_label.grid(row=5, column=3, padx=0, pady=10)
P1_name = tk.StringVar()

P1nameentered = tk.Entry(root, width=15, textvariable=P1_name)
P1nameentered.grid(row=6, column=3, padx=20, pady=10)

P2_label = tk.Label(root, text="Player 2 name", font='20', bg='gray', state='disabled', disabledforeground="skyblue")
P2_label.grid(row=5, column=6, padx=10, pady=10)
P2_name = tk.StringVar()

P2nameentered = tk.Entry(root, width=15, textvariable=P2_name)
P2nameentered.grid(row=6, column=6, padx=20, pady=10)

startbtn = Button(root, text="Start Game", command=gamescreen)
startbtn.grid(row=9, column=4, pady=5)

entry_label = tk.Label(root, text="Enter city", font='20', bg='gray', state='disabled', disabledforeground="skyblue")
entry_label.grid(row=7, column=4)

options = ["Choose location", "Chicago", "New York"]
city_selection = tk.StringVar(root)

opt = tk.OptionMenu(root, city_selection, *options)
city_selection.set(options[0])
opt.grid(row=8, column=4)

button_quit = Button(root, text="Quit", command=root.quit)
button_quit.grid(row=13, column=4, pady=10)
root.mainloop()


from airflow import DAG
from airflow.operators.bash import BashOperator
from datetime import datetime, timedelta

default_args = {
    'owner': 'RecSys-02',
    'depends_on_past': False,  # 이전 DAG의 Task가 성공, 실패 여부에 따라 현재 DAG 실행 여부가 결정. False는 과거의 실행 결과 상관없이 매일 실행한다
    'start_date': datetime(2023, 2, 1),
    'retires': 1,  # 실패시 재시도 횟수
    'retry_delay': timedelta(minutes=1)  # 만약 실패하면 5분 뒤 재실행
    # 'priority_weight': 10 # DAG의 우선 순위를 설정할 수 있음
    # 'end_date': datetime(2022, 4, 24) # DAG을 마지막으로 실행할 Date
    # 'execution_timeout': timedelta(seconds=300), # 실행 타임아웃 : 300초 넘게 실행되면 종료
    # 'on_failure_callback': some_function # 만약에 Task들이 실패하면 실행할 함수
    # 'on_success_callback': some_other_function
    # 'on_retry_callback': another_function
}

# with 구문으로 DAG 정의
with DAG(
        dag_id='Train',
        default_args=default_args,
        schedule_interval='0 15 * * *',
        tags=['RecSys-02-Dags']
) as dag:
    # BashOperator 사용
    train = BashOperator(
        task_id='Train',  # task의 id
        bash_command='python /opt/ml/git/final-project-level3-recsys-02/bentoml/run_finetune_full.py'  # 실행할 bash command
    )

    shell = BashOperator(
        task_id='Shell',
        bash_command='cd /opt/ml/git/final-project-level3-recsys-02/bentoml && poetry shell',
    )

    pakage = BashOperator(
        task_id='Pakage',
        bash_command='python /opt/ml/git/final-project-level3-recsys-02/bentoml/my_bento_packer.py',
    )

    termination = BashOperator(
        task_id='Termination',
        bash_command='pkill -9 bentoml'
    )

    server = BashOperator(
        task_id='Server',
        bash_command='bentoml serve --port 30001 MyService:latest',
        depends_on_past=False
    )

    train >> shell >> pakage >> termination >> server


check = [0 for i in range(10)]
room = input()

six_nine = 0

for char in room:
    num = int(char)

    # 6 and 9 can be turned upside down
    if num == 6 or num == 9:
        six_nine += 1
        # 6 and 9 both used
        if six_nine == 2:
            check[6] += 1
            six_nine = 0
    else:
        check[num] += 1

# 6 and 9 were used odd times
if six_nine == 1:
    check[6] += 1

print(max(check))


import numpy as np
import datetime as dt
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func, and_

from flask import Flask, jsonify

engine = create_engine("sqlite:///hawaii.sqlite")

Base=automap_base()
Base.prepare(engine, reflect=True)

Measurements=Base.classes.measurement
Station=Base.classes.station

app=Flask(__name__)

@app.route("/")
def welcome():

    return(
        f"List all available API routes:
"
        f"/api/v1.0/precipitation
"
        f"/api/v1.0/stations
"
        f"/api/v1.0/tobs
"
        f"/api/v1.0/<start>
"
        f"/api/v1.0/<start>/<end>"
    )

@app.route("/api/v1.0/precipitation")
def Precipitation():
    session=Session(engine)
    results=session.query(Measurements.date, Measurements.prcp).\
                order_by(Measurements.date).all()
    prcp_list=[]
    for date, prcp in results:
        new_dict = {}
        new_dict[date] = prcp
        prcp_list.append(new_dict)

    session.close()

    return jsonify(prcp_list)

@app.route("/api/v1.0/stations")
def Stations():
    session=Session(engine)
    stations={}
    results=session.query(Station.station, Station.name).all()
    for s,name in results:
        stations[s]=name
    session.close()
    return jsonify(stations)

@app.route("/api/v1.0/tobs")
def tobs():
    session=Session(engine)

    last_date=session.query(Measurements.date).order_by(Measurements.date.desc()).first()

    last_year_date=(dt.datetime.strptime(last_date[0],'%Y-%m-%d') \
                    - dt.timedelta(days=365)).strftime('%Y-%m-%d')

    results =   session.query(Measurements.date, Measurements.tobs).\
                filter(and_(Measurements.date >=last_year_date, Measurements.station== "USC00519281")).\
                order_by(Measurements.date).all()

    tobs_date_list = []

    for date, tobs in results:
        new_dict = {}
        new_dict[date] = tobs
        tobs_date_list.append(new_dict)

    session.close()

    return jsonify(tobs_date_list)

@app.route("/api/v1.0/<start>")
def temp_range_start(start):
    session=Session(engine)
    return_list=[]
    results=session.query(Measurements.date, func.min(Measurements.tobs),\
                          func.avg(Measurements.tobs),\
                          func.max(Measurements.tobs)).\
                    filter(Measurements.date >=start).\
                    group_by(Measurements.date).all()
    for date, min,avg,max in results:
        new_dict={}
        new_dict["Date"]=date
        new_dict["TMIN"]=min
        new_dict["TAVG"]=avg
        new_dict["TMAX"]=max
        return_list.append(new_dict)

    session.close()

    return jsonify(return_list)

@app.route("/api/v1.0/<start>/<end>")
def temp_range_start_end(start,end):
    session=Session(engine)

    return_list=[]

    results=session.query(Measurements.date, func.min(Measurements.tobs),\
                          func.avg(Measurements.tobs),\
                          func.max(Measurements.tobs)).\
                    filter(and_(Measurements.date >=start, Measurements.date<= end)).\
                    group_by(Measurements.date).all()
    for date, min,avg,max in results:
        new_dict={}
        new_dict["Date"]=date
        new_dict["TMIN"]=min
        new_dict["TAVG"]=avg
        new_dict["TMAX"]=max
        return_list.append(new_dict)

    session.close()

    return jsonify(return_list)

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


from handlers.base import BaseHandler
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
import time

class AAA:
    def __init__(self):
        self.executor = ThreadPoolExecutor()

    @run_on_executor
    def aaa(self):
        time.sleep(1)

class TestHandler(BaseHandler):
    async def get(self):
        print('get')
        # res = await self.get_external('http://www.baidu.com')
        # print('end-baidu')
        a = AAA()
        await a.aaa()
        print('end')
        self.write("Hello, world!")

class TestESHandler(BaseHandler):
    """
    ES实现
    """
    async def get(self):
        t = self.get_argument('t', 1)
        # es = AsyncES()
        print('start')
        info = await self.es.info()
        print('end info')
        # g = await self.es.search(index='ecommerce', doc_type='products')
        # print('end')
        self.success_response({'data': len(info)})


import time
from dqrobotics import *  # Despite what PyCharm might say, this is very much necessary or DQs will not be recognized
import rospy
from sas_robot_driver import RobotDriverInterface, RobotDriverProvider

rospy.init_node('my_node_name', disable_signals=True)
try:
    # Initialize the RobotDriveProvider
    rdp = RobotDriverProvider('my_test_robot')

    # Initialize the RobotDriverInterface
    rdi = RobotDriverInterface('my_test_robot')

    # Wait for RobotDriverInterface to be enabled
    while not rdi.is_enabled():
        time.sleep(0.1)
        # Send positions and limits from the RobotDriverProvider to the RobotDriverInterface
        # RobotDriverInterface will be enabled when those values are received
        rdp.send_joint_states([1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12])
        rdp.send_joint_limits(([-5, -5, -5, -5], [5, 5, 5, 5]))

    # Read the values sent by the RobotDriverProvider
    print(rdi.get_joint_positions())
    print(rdi.get_topic_prefix())

except KeyboardInterrupt:
    print("Interrupted by user")


import numpy as np

def expectation(signal):
    sig_sum = 0
    for i in range(len(signal)):
        sig_sum += signal[i]
    expect = sig_sum / len(signal)
    return expect

def correlate(x, y, t):
    x_expectation = expectation(x)
    y_expectation = expectation(y)
    x_length = len(x)
    sig_sum = 0
    for time in range(x_length - t):
        sig_sum += (x[time] - x_expectation) * (y[time + t] - y_expectation)
    corr = sig_sum / (x_length - 1)
    return corr

def correlation(x, y, step):
    correlations = np.zeros(step)
    for t in range(step):
        correlations[t] = correlate(x, y, t)
    return correlations

def correlation_list(x, y, step):
    correlations = list()
    for t in range(step):
        correlations.append(correlate(x, y, t))
    return correlations

def autocorrelation(x, step):
    return correlation(x, x, step)


import os
from flask import Flask, flash, redirect, request
from flask import (url_for, current_app as app)
from werkzeug.utils import secure_filename

import casparser

app = Flask(__name__)
UPLOAD_FOLDER = './uploads/'
ALLOWED_EXTENSIONS = {'pdf'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

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

@app.route("/parse", methods=['POST'])
def parse_cas():
    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['file']
    # If the user does not select a file, the browser submits an
    # empty file without a filename.
    if file.filename == '':
        flash('No selected file')
        return redirect(request.url)
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        upload_path = os.path.join(app.config['UPLOAD_FOLDER'])
        file.save(upload_path, filename)
        return casparser.read_cas_pdf(upload_path + filename, "password", output="json")

# favicon
@app.route('/favicon.ico')
def favicon():
    return url_for('static', filename='/assets/favicon.ico')


#shell sort starts with unsorted array
#selects one element and moves it multiple positions at a time.
# similiar to insertion sort

#first compute gap n/2 (n = number of elements)

#Start from first element, compare it to  element at gap left and right

def shell_sort(array):
    gap = len(array) // 2
    n = len(array) - 1

    while gap > 0:
        i = gap
        while i < len(array):
            temp = array[i]
            j = i - gap
            while j >= 0 and array[j] > temp:
                array[j + gap] = array[j]
                j = j - gap
                array[j + gap] = temp
            i = i + 1
        gap = gap // 2

    return array

array = [ 3,5,2,6,4,5,7,8]
shell_sort(array)
print(array)


from scipy.optimize import linprog

def get_objective(line):
  arr = line.split()
  res = []
  for i in range(0, len(arr), 2):
    if arr[i][0]=='+' or arr[i][0]=='-':
      num = float(arr[i][1:])
    else:
      num = float(arr[i])
    if arr[i][0]=='-':
      num = -num
    res.append(num)
  return res

def get_less_than_inequality(line, n_vars):
  arr = line.split()
  res = []
  prev_var = -1
  for i in range(0, len(arr)-2, 2):
    cur_var = int(arr[i+1].split('_')[1])
    for j in range(cur_var-prev_var-1):
      res.append(0)
    if arr[i][0]=='+' or arr[i][0]=='-':
      num = float(arr[i][1:])
    else:
      num = float(arr[i])
    if arr[i][0]=='-':
      num = -num
    res.append(num)
    prev_var = cur_var
  for j in range(n_vars-len(res)):
    res.append(0)

  i = len(arr)-1
  if arr[i][0]=='+' or arr[i][0]=='-':
    num = float(arr[i][1:])
  else:
    num = float(arr[i])
  if arr[i][0]=='-':
    num = -num

  return res, num

def read_model(file_name):
  print('Reading model.... All equations must be in less than equal to form')
  c = []
  A = []
  b = []
  f = open(file_name, 'r')
  line = f.readline().strip()
  maximize = False
  while line!='':
    #print(line)
    while line[0]=='#':
      line = f.readline().strip()
    if line=='maximize:' or line=='minimize:':
      type='objective'
      if line=='maximize:':
        maximize = True
    elif line=='subject to:':
      type='constraints'
    else:
      if type=='objective':
        c = get_objective(line)
        if maximize:
          c = convert_min_to_max(c)
      elif type=='constraints':
        coeff, cons = get_less_than_inequality(line, len(c))
        A.append(coeff)
        b.append(cons)
    line = f.readline().strip()
  f.close()
  return c, A, b

def convert_min_to_max(c):
  c = [-x for x in c]
  return c

def run_lin_prog(file_name):
  print('Running linear program')
  c, A, b = read_model(file_name)
  bounds = []
  for i in range(len(c)):
    bounds.append((0, None))
  res = linprog(c, A_ub=A, b_ub=b, bounds=bounds)
  print(res)

#run_lin_prog('simple.txt')
run_lin_prog('farmer.txt')