import logging
from typing import Mapping, Any, Tuple
from uuid import UUID
from weakref import ref
import pickle as pkl
from datetime import datetime, timedelta

from PyQt5.QtCore import Qt, QRectF
from PyQt5.QtGui import QIcon, QGradient, QImage, QPixmap, QPainter, QPen, QBrush
from PyQt5.QtWidgets import (QGraphicsItem, QGraphicsObject, QGraphicsTextItem,
                             QGraphicsPixmapItem, QStyleOptionGraphicsItem, QWidget,
                             QGraphicsSceneMouseEvent, QGraphicsSceneDragDropEvent,
                             QGraphicsSceneContextMenuEvent, QGraphicsRectItem)

from uwsift.common import Flags
from .common import (CoordTransform, GFXC, MIMETYPE_TIMELINE_COLORMAP, MIMETYPE_TIMELINE_TRACK,
                     mimed_colormap, mimed_track, recv_mime, VisualState)

LOG = logging.getLogger(__name__)

def _wtf_recursion():
    from inspect import getouterframes, currentframe
    level = len(getouterframes(currentframe()))
    LOG.debug("frame boundingRect depth {}".format(level))

def _perform_context_menu(event, scene, track, frame) -> bool:
    """Custom context menu handler shared by QTrackItem and QFrameItem
    return true if the menu fully activated and did something
    """
    qm = scene.menu_for_track(track, frame)
    if qm is not None:
        # pos: QPointF = event.pos()
        # wdgt = event.widget()
        menu, lut = qm
        if not lut or not menu:
            LOG.warning("scene menu generator returned nothing to do")
            return False
        event.accept()
        sel = menu.exec_(event.screenPos())  # wdgt.mapToGlobal(pos.toPoint()))
        todo = lut.get(sel)
        if callable(todo):
            todo(scene=scene, track=track, frame=frame)
            return True
        else:
            return False

class QTrackItem(QGraphicsObject):
    """ A group of Frames corresponding to a timeline
    This allows drag and drop of timelines to be easier
    """
    frames = None  # Iterable[QFrameItem], maintained privately between track and frame
    _scene = None  # weakref to scene
    _scale: CoordTransform = None
    _track: str = None  # tracks are family::category, e.g. IMAGE:geo:toa_reflectance:11µm::GOESR-PUG:GOES-16:ABI:CONUS
    _z: int = None  # our track number as displayed, 0 being highest on screen, with larger Z going downward
    _title: str = None
    _subtitle: str = None
    _icon: QIcon = None  # e.g. whether it's algebraic or RGB
    # arbitrary key-value store for selecting by metadata;
    # in our case this often includes item family for seleciton
    _metadata: Mapping = None
    _tooltip: str = None
    _state: Flags = None  # VisualState Flags determine how it's being presented
    _colormap: [QGradient, QImage, QPixmap] = None
    _min: float = None
    _max: float = None
    _dragging: bool = False  # whether or not a drag is in progress across this item
    # position in scene coordinates is determined by _z level and starting time of first frame, minus _left_pad
    # bounds of the track in scene coordinates, assuming 0,0 corresponds to vertical center of left edge of
    # frame representation
    _bounds: QRectF = QRectF()
    _gi_title: QGraphicsTextItem = None
    _gi_subtitle: QGraphicsTextItem = None
    _gi_icon: QGraphicsPixmapItem = None
    _gi_colormap: QGraphicsPixmapItem = None

    def __init__(self, scene, scale: CoordTransform, track: str, z: int,
                 title: str, subtitle: str = None, icon: QIcon = None, metadata: dict = None,
                 tooltip: str = None, state: Flags = None, colormap: [QGradient, QImage] = None,
                 min: float = None, max: float = None):
        """Create a track and connect it to its Scene
        """
        super(QTrackItem, self).__init__()
        self.frames = []
        self._scene = ref(scene) if scene else None
        self._scale = scale
        self._track = track
        self._z = z
        self._title = title
        self._subtitle = subtitle
        self._icon = icon
        self._metadata = metadata or {}
        self._tooltip = tooltip
        self._state = Flags(state or [])
        self._colormap = colormap
        self._min, self._max = min, max
        self.setToolTip(tooltip or "{}\n{}".format(title, subtitle))
        self.setFlag(QGraphicsItem.ItemClipsChildrenToShape, enabled=True)
        self.update_pos_bounds()
        self._update_decorations()
        scene.add_track(self)
        self.setAcceptDrops(True)

    def addFrame(self, frame):
        self._scene().add_frame(frame)
        self.frames.append(frame)

    # @property
    # def scene(self):
    #     return self._scene()
    #
    # @scene.setter
    # def scene(self, s):
    #     self._scene = ref(s)

    @property
    def track(self) -> str:
        return self._track

    @property
    def scene_(self):  # can't use just .scene due to Qt C++ scene()
        return self._scene()

    @property
    def z(self) -> int:
        return self._z

    @z.setter
    def z(self, new_z: int):
        self._z = new_z

    @property
    def default_frame_pen_brush(self):
        return self._scene().default_frame_pen_brush

    def _update_decorations(self):
        """Add decor sub-items to self
        title, subtitle, icon, colormap
        these are placed left of the local origin inside the _left_pad area
        """
        scene = self._scene()
        if self._title:
            self._gi_title = it = self._gi_title or scene.addSimpleText(self._title)
            it.setParentItem(self)
            it.setPos(GFXC.track_title_pos)
        if self._subtitle:
            self._gi_subtitle = it = self._gi_subtitle or scene.addSimpleText(self._subtitle)
            it.setParentItem(self)
            it.setPos(GFXC.track_subtitle_pos)
        # FUTURE: add draggable color-map pixmap

    # commands to cause item updates and then propagate back to the scene

    def set_colormap(self, cmap: mimed_colormap):
        """Inform scene that the user wants all tracks in our family to use this colormap
        """
        LOG.warning("set colormap from dragged colormap not yet implemented")

    def insert_track_before(self, track: mimed_track):
        """Inform scene that user wants a dragged scene moved to before us in the z-order"""
        LOG.warning("reorder tracks using dragged track not yet implemented")

    # painting and boundaries

    def paint(self, painter: QPainter, option: QStyleOptionGraphicsItem, widget: QWidget = None):
        # LOG.debug("QTrackItem.paint")
        # _wtf_recursion()
        pen, brush = self._scene().default_track_pen_brush
        rect = self.boundingRect()
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setBrush(brush)
        painter.setPen(pen)

        # draw outer boundary
        painter.drawRoundedRect(rect, GFXC.track_corner_radius1, GFXC.track_corner_radius2, Qt.RelativeSize)

    def boundingRect(self) -> QRectF:
        #     if self._bounds is None:
        #         return self.update_pos_and_bounds()
        return self._bounds

    # click events / drag departures

    def mousePressEvent(self, event: QGraphicsSceneMouseEvent):
        LOG.debug("QTrackItem mouse-down")
        return super(QTrackItem, self).mousePressEvent(event)

    def mouseReleaseEvent(self, event: QGraphicsSceneMouseEvent):
        LOG.debug("QTrackItem mouse-up")
        return super(QTrackItem, self).mouseReleaseEvent(event)

    def contextMenuEvent(self, event: QGraphicsSceneContextMenuEvent):
        # pos = self.mapToScene(event.pos())
        if not _perform_context_menu(event, self.scene_, self._track, None):
            return super(QTrackItem, self).contextMenuEvent(event)

    # handle drag and drop arrivals

    def dragEnterEvent(self, event: QGraphicsSceneDragDropEvent):
        self._dragging = True

        # test the content being dragged to see if it's compatible; if so, accept event
        mime = event.mimeData()
        if mime.hasFormat(MIMETYPE_TIMELINE_COLORMAP):
            event.setAccepted(True)
        elif mime.hasFormat(MIMETYPE_TIMELINE_TRACK):
            # FIXME: implement animated re-arrange of tracks
            event.setAccepted(True)
        else:
            event.setAccepted(False)

    def dragLeaveEvent(self, event: QGraphicsSceneDragDropEvent):
        self._dragging = False
        event.setAccepted(False)

    def dropEvent(self, event: QGraphicsSceneDragDropEvent):
        colormap = recv_mime(event, MIMETYPE_TIMELINE_COLORMAP)
        if colormap is not None:
            self.set_colormap(colormap)
            return
        new_track_before = recv_mime(event, MIMETYPE_TIMELINE_TRACK)
        if new_track_before is not None:
            self.insert_track_before(new_track_before)
        _ = pkl.loads(event.mimeData().data())
        event.setAccepted(False)

    # working with Frames as sub-items, updating and syncing position and extents

    def _iter_frame_children(self):
        return list(self.frames)
        # children = tuple(self.childItems())
        # # LOG.debug("{} children".format(len(children)))
        # for child in children:
        #     if isinstance(child, QFrameItem):
        #         yield child

    def _time_extent_of_frames(self):
        """start time and duration of the frames held by the track
        """
        s, e = None, None
        for child in self._iter_frame_children():
            # y relative to track is 0
            # calculate absolute x position in scene
            # assert (child.uuid != self.uuid)
            t, d = child.td
            s = t if (s is None) else min(t, s)
            e = (t + d) if (e is None) else max(e, t + d)
        if e is None:
            LOG.info("empty track cannot determine its horizontal extent")
            return None, None
        return s, e - s

    def update_pos_bounds(self):
        """Update position and bounds of the Track to reflect current TimelineCoordTransform, encapsulating frames owned
        Note that the local x=0.0 corresponds to the time of the first frame in the track
        This is also the center of rotation or animation "handle" (e.g. for track dragging)
        """
        # starting time and duration of the track, computed from frames owned
        t, d = self._time_extent_of_frames()
        if (t is None) or (d is None):
            LOG.debug("no frames contained, cannot adjust size or location of QTrackItem")
            return
        LOG.debug("time extent of frames in track '{}/{}' is {} +{}".format(self._title, self._subtitle, t, d))
        # scene y coordinate of upper left corner
        # convert track extent to scene coordinates using current transform
        frames_left, frames_width = self._scale.calc_pixel_x_pos(t, d)
        screen_track_center_y = self._scale.calc_track_pixel_y_center(self.z)
        # track_left, track_width = self._scale.calc_pixel_x_pos(t - GFXC.track_left_pad,
        #     d + GFXC.track_left_pad + GFXC.track_right_pad)
        # set track position, assuming we want origin coordinate of track item to be centered vertically within item
        # bounds relative to position in scene, left_pad space to left of local origin (x<0),
        # frames and right-pad at x>=0
        self.prepareGeometryChange()
        self._bounds = QRectF(-GFXC.track_left_pad, -GFXC.track_height / 2,
                              frames_width + GFXC.track_left_pad + GFXC.track_right_pad, GFXC.track_height)
        LOG.debug("new track bounds: {}".format(self._bounds))
        # origin is at the start of the first frame contained. padding extends into negative x
        LOG.debug("track centerline placed at {},{}".format(frames_left, screen_track_center_y))
        self.setPos(frames_left, screen_track_center_y)
        self._update_decorations()

    def update_frame_positions(self, *frames):
        """Update frames' origins relative to self after TimelineCoordTransform has changed scale
        """
        myx = self.pos().x()  # my x coordinate relative to scene
        frames = tuple(frames) or self._iter_frame_children()
        for frame in frames:
            # y relative to track is 0
            # calculate absolute x position in scene
            x, _ = self._scale.calc_pixel_x_pos(frame.t)
            frame.prepareGeometryChange()
            frame.setPos(x - myx, 0.0)

class QFrameItem(QGraphicsObject):
    """A Frame
    For SIFT use, this corresponds to a single Product or single composite of multiple Products (e.g. RGB composite)
    QGraphicsView representation of a data frame, with a start and end time relative to the scene.
    Essentially a frame sprite
    """
    _state: Flags = None
    _track = None  # weakref to track we belong to
    _scale: CoordTransform = None
    _uuid: UUID = None
    _start: datetime = None
    _duration: timedelta = None
    _title: str = None
    _subtitle: str = None
    _thumb: QPixmap = None
    _metadata: Mapping = None
    _bounds: QRectF = QRectF()
    # decorations
    _gi_title = None
    _gi_subtitle = None

    def __init__(self, track: QTrackItem, scale: CoordTransform, uuid: UUID,
                 start: datetime, duration: timedelta, state: Flags,
                 title: str, subtitle: str = None, thumb: QPixmap = None,
                 metadata: Mapping[str, Any] = None):
        """create a frame representation and add it to a timeline track within a scene
        Args:
            track: which timeline to add it to
            state: initial state
            start: frame start time
            duration: frame duration
            title: title of frame
            subtitle: subtitle (below title, optional)
            thumb: thumbnail image (via pillow), optional, may not be displayed if space is not available
            uuid: UUID of workspace representation
        """
        super(QFrameItem, self).__init__()
        self._track = ref(track)
        self._state = Flags(state)
        self._scale = scale
        self._start = start
        self._duration = duration
        self._title = title
        self._subtitle = subtitle
        self._thumb = thumb
        self._metadata = metadata
        self._uuid = uuid
        self.setToolTip("{}\n{}".format(title, subtitle))
        # self._pen, self._brush = track.default_frame_pen_brush
        # if pen:
        #     LOG.debug('setting pen')
        #     self.setPen(pen)
        # if brush:
        #     LOG.debug('setting brush')
        #     self.setBrush(brush)
        track.addFrame(self)  # adds to track, which in turn adds to scene
        self.setParentItem(track)
        self.update_bounds()
        track.update_pos_bounds()
        track.update_frame_positions()
        self.setFlag(QGraphicsItem.ItemClipsChildrenToShape, enabled=True)
        self._update_decorations()
        # self.setAcceptDrops(True)

    def _update_decorations(self):
        """Add decor sub-items to self
        title, subtitle, icon, colormap
        these are placed left of the local origin inside the _left_pad area
        """
        scene = self.scene_
        if self._title:
            self._gi_title = it = self._gi_title or scene.addSimpleText(self._title)
            it.setParentItem(self)
            it.setPos(GFXC.frame_title_pos)
        if self._subtitle:
            self._gi_subtitle = it = self._gi_subtitle or scene.addSimpleText(self._subtitle)
            it.setParentItem(self)
            it.setPos(GFXC.frame_subtitle_pos)
        # FUTURE: add draggable color-map pixmap

    @property
    def scene_(self):
        trk = self._track()
        return trk.scene_

    @property
    def track(self):
        trk = self._track()
        return trk.track

    @property
    def uuid(self):
        return self._uuid

    @property
    def t(self) -> datetime:
        """Start time of frame"""
        return self._start

    @property
    def d(self) -> timedelta:
        """Duration of frame"""
        return self._duration

    @property
    def td(self) -> Tuple[datetime, timedelta]:
        return self._start, self._duration

    @property
    def state(self):
        return self._state

    @state.setter
    def state(self, new_state: VisualState):
        if new_state != self._state:
            self._state = new_state

    # painting and boundaries

    @property
    def pen_brush(self) -> Tuple[QPen, QBrush]:
        """Pen and brush to use, based on VisualState
        """
        pen, brush = self._track().default_frame_pen_brush
        s = self._state
        if VisualState.READY in s:
            brush = QBrush(Qt.green, Qt.SolidPattern)
        return pen, brush

    def paint(self, painter: QPainter, option: QStyleOptionGraphicsItem, widget: QWidget = None) -> None:
        # LOG.debug("QFrameItem.paint")
        pen, brush = self.pen_brush
        rect = self.boundingRect()
        painter.setBrush(brush)
        painter.setPen(pen)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.drawRoundedRect(rect, GFXC.frame_corner_radius, GFXC.frame_corner_radius, Qt.RelativeSize)
        # super(QFrameItem, self).paint(painter, option, widget)

    def boundingRect(self) -> QRectF:
        """return relative bounding rectangle, given position is set by Track parent as needed
        """
        # from inspect import getouterframes, currentframe
        # level = len(getouterframes(currentframe()))
        # LOG.debug("frame boundingRect depth {}".format(level))
        return self._bounds

    # internal recalculation / realignment

    def update_bounds(self):
        """set size and width based on current scaling
        position is controlled by the track, since we have to be track-relative
        """
        left = 0.0
        top = - GFXC.frame_height / 2
        height = GFXC.frame_height
        width = self._scale.calc_pixel_duration(self._duration)
        LOG.debug("width for {} is {} scene pixels".format(self._duration, width))
        old_bounds = self._bounds
        new_bounds = QRectF(left, top, width, height)
        if (old_bounds is None) or (new_bounds != old_bounds):
            self.prepareGeometryChange()
            self._bounds = new_bounds

    # # handle drag and drop
    # def dragEnterEvent(self, event: QGraphicsSceneDragDropEvent):
    #     event.setAccepted(False)
    #
    # def dragLeaveEvent(self, event: QGraphicsSceneDragDropEvent):
    #     event.setAccepted(False)
    #
    # def dropEvent(self, event: QGraphicsSceneDragDropEvent):
    #     event.setAccepted(False)

    # handle clicking
    def mousePressEvent(self, event: QGraphicsSceneMouseEvent):
        LOG.debug("QFrameItem mouse-down")
        return super(QFrameItem, self).mousePressEvent(event)

    def mouseReleaseEvent(self, event: QGraphicsSceneMouseEvent):
        LOG.debug("QFrameItem mouse-up")
        return super(QFrameItem, self).mouseReleaseEvent(event)

    def contextMenuEvent(self, event: QGraphicsSceneContextMenuEvent):
        LOG.debug("contextMenuEvent")
        trk = self._track()
        track = trk.track
        scene = trk.scene_
        if not _perform_context_menu(event, scene, track, self._uuid):
            return super(QFrameItem, self).contextMenuEvent(event)

class QTimeRulerItem(QGraphicsRectItem):
    """A ruler object showing the time dimension.

    An instance is at the top, bottom, or both ends of the Scene.

    """

    def __init__(self):
        super(QTimeRulerItem, self).__init__()


import pygame

# 游戏的初始化
pygame.init()

# 创建游戏的窗口
screen = pygame.display.set_mode((480, 700))

# 绘制背景图像
background = pygame.image.load("./images/background.png")
screen.blit(background, (0, 0))
# pygame.display.update()

# 绘制英雄的飞机
hero = pygame.image.load("./images/me1.png")
screen.blit(hero, (200, 500))

# 可以再所有绘制工作完成后，统一调用update方法
pygame.display.update()

# 创建时钟对象
clock = pygame.time.Clock()

# 游戏循环 -> 意味这游戏的正式开始
i = 0
while True:

    # 可以指定循环提内部代码的执行频率
    clock.tick(60)

    print(i)
    i += 1

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

pygame.quit()


import bge
from collections import OrderedDict
import 载具物理性质
import MathLib
import math

if not hasattr(bge, "__component__"):
    scene = bge.logic.getCurrentScene()

class MyVehicle(bge.types.KX_PythonComponent):
    args = OrderedDict([
    ])

    def start(self, args):
        self.载具 = 载具物理性质.载具物理(self.object)
        print(self.object.childrenRecursive)
        self.摄影机 = [obj for obj in self.载具.childrenRecursive if "Camera" in obj][0]

        self.摄影机跟随 = False

        # scene = bge.logic.getCurrentScene()
        # cam1 = scene.objects["Camera.002"]
        # cam2 = scene.objects["Camera.001"]

        # cam1.useViewport = True
        # cam2.useViewport = True
        # cam2.setOnTop()

        # width = bge.render.getWindowWidth()
        # height = bge.render.getWindowHeight()
        # print(width,height,'height----------------------------')

        # bottom = 0
        # top = height

        # # here are the boundaries for the right viewport
        # left_1 = 0
        # right_1 = width

        # # here are the boundaries for the left viewport
        # left_2 = 0
        # right_2 = int(width/2)

        # # set player viewports with player1 at the right, player 2 at the left
        # cam1.setViewport( right_2, int(height/2), width, height)
        # cam2.setViewport( 0, 0, right_2, int(height/2))

    def update(self):

        if self.摄影机跟随:
            self.载入摄像机()

    def 载入摄像机(self):

        车辆局部旋转 = self.载具.局部方向.to_euler()
        车辆局部旋转.rotate_axis('X', math.radians(-5.0))
        车辆局部旋转[1] = 0.0

        目标位置 = 车辆局部旋转.to_matrix()

        速度 = self.载具.DeltaTime*5
        self.摄影机.localOrientation = self.摄影机.localOrientation.lerp(目标位置, 速度)


import random
name = input("What's your name:")
print("Good Luck! ",name)

words = ['rainbow', 'computer', 'science', 'programming',
		'python', 'mathematics', 'player', 'condition',
		'reverse', 'water', 'board', 'geeks']

word = random.choice(words)

guesses = ''
turns = 12

while turns>0:
  fail = 0
  for char in word:
    if char in guesses:
      print(char)
    else:
      print("_")
      fail += 1

  if fail == 0:
      print("you win")
      print("the word is:",word)
      break;

  print("---------------------------")
  guess = input("guess a character:")
  guesses += guess

  if guess not in word:
    turns -= 1
    if turns == 0:
        print("you lose")
        break
    print("you entered incorrect ")
    print("you have ",turns," turns left")
    print("---------------------------")


"""Logging tools for libcflib"""
import os
import time
import builtins

from xonsh.tools import print_color

import libcflib.jsonutils as json
from libcflib.tools import expand_file_and_mkdirs

class Logger:
    """A logging object for fixie that stores information in line-oriented JSON
    format.
    """

    __inst = None

    def __new__(cls):
        # make the logger a singleton
        if Logger.__inst is None:
            Logger.__inst = object.__new__(cls)
        return Logger.__inst

    def __init__(self, filename=None):
        """
        Parameters
        ----------
        filename : str or None, optional
            Path to logfile, if None, defaults to $LIBCFLIB_LOGFILE.
        """
        self._filename = None
        self.filename = filename
        self._dirty = True
        self._cached_entries = ()

    def log(self, message, category="misc", data=None):
        """Logs a message, the timestamp, its category, and the
        and any data to the log file.
        """
        self._dirty = True
        entry = {"message": message, "timestamp": time.time(), "category": category}
        if data is not None:
            entry["data"] = data

        # write to log file
        json.appendline(entry, self.filename)
        # write to stdout
        msg = "{INTENSE_CYAN}" + category + "{PURPLE}:"
        msg += "{INTENSE_WHITE}" + message + "{NO_COLOR}"
        print_color(msg)

    def load(self):
        """Loads all of the records from the logfile and returns a list of dicts.
        If the log file does not yet exist, this returns an empty list.
        """
        if not os.path.isfile(self.filename):
            return []
        if not self._dirty:
            return self._cached_entries
        entries = json.loadlines(self.filename)
        self._dirty = False
        self._cached_entries = entries
        return entries

    @property
    def filename(self):
        value = self._filename
        if value is None:
            value = builtins.__xonsh__.env.get("LIBCFLIB_LOGFILE")
        return value

    @filename.setter
    def filename(self, value):
        if value is None:
            self._filename = value
        else:
            self._filename = expand_file_and_mkdirs(value)

LOGGER = Logger()


import numpy as np
import os
import cv2

def parse_raw(imgpath,image_size=(360,640),type_="uint8",show=False):
    width, height = image_size
    imgData = np.fromfile(imgpath, dtype=type_)
    channel = len(imgData) // (width * height)
    if channel==0 or channel==2 or channel > 4:
        raise Exception("This raw image channels must be 1 or 3 or 4")
    imgData = imgData.reshape(height, width, channel)
    if channel == 1:
        imgData = np.concatenate((imgData, imgData, imgData), axis=-1)
    elif channel == 4:#and (np.sum(imgData[...,-1])==0 or np.sum(imgData[...,-1])==255*width*height):
        imgData = imgData[...,:-1]
    else:
        raise Exception("This raw image alpha channel must be final")
    if show:
        cv2.imshow("raw", imgData)
        cv2.waitKey(2000)
    return imgData

def format_read(input_path, raw_w = 360, raw_h = 640):
    if input_path.endswith(".raw"):
        input_data = parse_raw(input_path,image_size=(raw_w,raw_h),type_="uint8",show=False)
    else:
        input_data = input_path

    if isinstance(input_data, str) and os.path.exists(input_data):
        img = cv2.imread(input_data)
        src_img = img.copy()
    elif isinstance(input_data, np.ndarray):
        src_img = input_data.copy()
    return  src_img
def format_to_raw(src_img, c_in = 3, c_out = 3):
    ch


S=input()
k=5
import heapq
hq = []
hq2=[]
combo=0
ans=0
charging=0
for i,x in enumerate(S):
  charging-=1
  if charging>0:
    continue
  if x == "-":
    continue
  else:
    while(hq and hq[0][0]<i):
      k+=hq[0][1]
      heapq.heappop(hq)
    while(hq2 and hq2[0]<i):
      combo+=1
      heapq.heappop(hq2)
    if k>0 and x=="N":
      heapq.heappush(hq,(i+6,1))
      heapq.heappush(hq2,i+1)
      ans+=10*(1+(combo//10 *0.1))
      k-=1
    elif k>2 and x =="C":
      heapq.heappush(hq,(i+8,3))
      heapq.heappush(hq2,i+3)
      ans+=50*(1+(combo//10 * 0.1))
      charging=2.5
      k-=3

print(int(ans))


from itertools import chain
'''
regards to
http://www.redblobgames.com/pathfinding/a-star/implementation.html
and
https://github.com/melkir/A-Star-Python
'''
class SquareGrid:
	def __init__(self, width, height):
		self.width = width
		self.height = height
		self.walls = []

	def in_bounds(self, id):
		(x, y) = id
		return 0 <= x < self.width and 0 <= y < self.height

	def passable(self, id):
		return id not in self.walls

	def neighbors(self, id):
		(x, y) = id
		results = [(x+1, y), (x, y-1), (x-1, y), (x, y+1)]
		if (x + y) % 2 == 0: results.reverse() # aesthetics
		results = filter(self.in_bounds, results)
		results = filter(self.passable, results)
		return results

class GridWithWeights(SquareGrid):
	def __init__(self, width, height):
		super().__init__(width, height)
		self.weights = {}

	def cost(self, from_node, to_node):
		return self.weights.get(to_node, 1) # 1 as default value

import heapq
class PriorityQueue:
    def __init__(self):
        self.elements = []

    def empty(self):
        return len(self.elements) == 0

    def put(self, item, priority):
        heapq.heappush(self.elements, (priority, item))

    def get(self):
        return heapq.heappop(self.elements)[1]

def heuristic(a, b):
    (x1, y1) = a
    (x2, y2) = b
    return abs(x1 - x2) + abs(y1 - y2)

def a_star_search(graph, start, goal):
    frontier = PriorityQueue()
    frontier.put(start, 0)
    came_from = {}
    cost_so_far = {}
    came_from[start] = None
    cost_so_far[start] = 0

    while not frontier.empty():
        current = frontier.get()

        if current == goal:
            break

        for next in graph.neighbors(current):
            new_cost = cost_so_far[current] + graph.cost(current, next)
            if next not in cost_so_far or new_cost < cost_so_far[next]:
                cost_so_far[next] = new_cost
                priority = new_cost + heuristic(goal, next)
                frontier.put(next, priority)
                came_from[next] = current

    return came_from, cost_so_far

def reconstruct_path(came_from, start, goal):
	current = goal
	path = []
	while current != start:
		path.append(current)
		current = came_from[current]
	path.append(start) # optional
	path.reverse() # optional
	return path

# own stuff
chitons = []
with open("input15.txt") as file:
    for line in file:
        line = [int(x) for x in line.strip()]
        iterations = [line]
        for i in range(4):
            iterations.append([x+1 if x<9 else 1 for x in iterations[-1]])
        chitons.append(list(chain(*iterations)))

lines_per_block = len(chitons)
for i in range(4):
    new_lines = []
    for line in chitons[-lines_per_block:]:
        new_lines.append([x+1 if x<9 else 1 for x in line])
    chitons += new_lines

WIDTH = len(chitons[0])
HEIGHT = len(chitons)
# creating weighed grid graph
chiton_grid = GridWithWeights(WIDTH, HEIGHT)
for y in range(HEIGHT):
    for x in range(WIDTH):
        chiton_grid.weights[(x,y)] = chitons[y][x]

START = (0,0)
GOAL = (WIDTH - 1, HEIGHT - 1)

came_from, cost_so_far = a_star_search(chiton_grid, START, GOAL)
print(cost_so_far[GOAL])
# print(reconstruct_path(came_from, START, GOAL))


from django.core.management.base import BaseCommand
from ghpcfe.models import WorkbenchPreset

class Command(BaseCommand):
    """Helper to create workbenches with preset types
    """
    help = (
        "Seeds default presets into the workbench preset model so normal "
        "users can create workbenches of an approved machine type"
    )

    # def add_arguments(self, parser):
    #     parser.add_argument('poll_ids', nargs='+', type=int)

    def handle(self, *args, **options):
        self.stdout.write("Populating Workbench Presets...", ending="\n")

        # create small preset
        wbpreset1 = WorkbenchPreset()
        wbpreset1.name = "Small - 1x core with 3840 Memory"
        wbpreset1.machine_type = "n1-standard-1"
        wbpreset1.category = "Recommended"
        wbpreset1.save()
        self.stdout.write(
            str(wbpreset1)
            + ", Machine Type: "
            + wbpreset1.machine_type
            + ", Category: "
            + wbpreset1.category,
            ending="\n",
        )

        # create medium preset
        wbpreset2 = WorkbenchPreset()
        wbpreset2.name = "Medium - 2x cores with 7680 Memory"
        wbpreset2.machine_type = "n1-standard-2"
        wbpreset2.category = "Recommended"
        wbpreset2.save()
        self.stdout.write(
            str(wbpreset2)
            + ", Machine Type: "
            + wbpreset2.machine_type
            + ", Category: "
            + wbpreset2.category,
            ending="\n",
        )

        # create large preset
        wbpreset3 = WorkbenchPreset()
        wbpreset3.name = "Large - 4x cores with 15360 Memory"
        wbpreset3.machine_type = "n1-standard-4"
        wbpreset3.category = "Recommended"
        wbpreset3.save()
        self.stdout.write(
            str(wbpreset3)
            + ", Machine Type: "
            + wbpreset3.machine_type
            + ", Category: "
            + wbpreset3.category,
            ending="\n",
        )

        # create X-large preset
        wbpreset4 = WorkbenchPreset()
        wbpreset4.name = "X-Large - 8x cores with 30720 Memory"
        wbpreset4.machine_type = "n1-standard-8"
        wbpreset4.category = "Recommended"
        wbpreset4.save()
        self.stdout.write(
            str(wbpreset4)
            + ", Machine Type: "
            + wbpreset4.machine_type
            + ", Category: "
            + wbpreset4.category,
            ending="\n",
        )

        self.stdout.write("Completed populating Workbench PResets", ending="\n")


import base64

import os

import pywhatkit

from PyQt5 import QtWidgets, QtCore, QtGui

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self):

        super().__init__()

        # Set up the GUI

        self.setWindowTitle("Paint AI")

        self.setGeometry(100, 100, 600, 300)

        self.central_widget = QtWidgets.QWidget()

        self.setCentralWidget(self.central_widget)

        self.layout = QtWidgets.QVBoxLayout()

        self.central_widget.setLayout(self.layout)

        # Add a label and line edit for the prompt

        self.prompt_label = QtWidgets.QLabel("Prompt:")

        self.prompt_line_edit = QtWidgets.QLineEdit()

        self.layout.addWidget(self.prompt_label)

        self.layout.addWidget(self.prompt_line_edit)

        # Add a label and combo box for the style

        self.style_label = QtWidgets.QLabel("Style:")

        self.style_combo_box = QtWidgets.QComboBox()

        self.style_combo_box.addItems([

            "default", "paint", "hdr", "polygon", "gouache",

            "realistic", "comic", "line-art", "malevolent", "meme",

            "throwback", "ghibli", "melancholic", "provenance", "darkfantasy",

            "fantasy", "mystical", "hd", "synthwave", "vibrant", "blacklight"

        ])

        self.layout.addWidget(self.style_label)

        self.layout.addWidget(self.style_combo_box)

        # Add buttons for generating the image and downloading it

        self.generate_button = QtWidgets.QPushButton("Generate")

        self.generate_button.clicked.connect(self.generate_image)

        self.download_button = QtWidgets.QPushButton("Download")

        self.download_button.clicked.connect(self.download_image)

        self.layout.addWidget(self.generate_button)

        self.layout.addWidget(self.download_button)

        # Store the generated image as an instance variable

        self.generated_image = None

    def generate_image(self):

        # Get the prompt and style from the user input

        prompt = self.prompt_line_edit.text()

        style = self.style_combo_box.currentText()

        # Generate the image using the pywhatkit library

        self.generated_image = pywhatkit.image_to_ascii_art(prompt, "paint", style)

        # Display the generated image in a label

        image_bytes = base64.b64decode(self.generated_image.split(",")[1])

        image_data = QtCore.QByteArray(image_bytes)

        image = QtGui.QImage.fromData(image_data)

        self.image_label = QtWidgets.QLabel()

        self.image_label.setPixmap(QtGui.QPixmap.fromImage(image))

        self.layout.addWidget(self.image_label)

    def download_image(self):

        if self.generated_image:

            # Get the filename from the user

            filename, _ = QtWidgets.QFileDialog.getSaveFileName(

                self, "Save Image", "", "Image Files (*.png *.jpg *.bmp)")

            if filename:

                # Save the generated image to the specified file

                with open(filename, "wb") as f:

                    f.write(base64.b64decode(self.generated_image.split(",")[1]))

if __name__ == "__main__":

    app = QtWidgets.QApplication([])

    main_window = MainWindow()

    main_window.show()

    app.exec_()


import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt

# Reading the csv file from git repositry
df=pd.read_csv("Non_linear_Regression\china_gdp.csv")
# Cheaking or looking the dataset
print(df.head())
# Selecting the data and normalizing it by somple method.
x_data,y_data=df['Year'],df['Value']
xdata =x_data/max(x_data)
ydata =y_data/max(y_data)
# Selecting or spliting data into train and test in random order
msk = np.random.rand(len(df)) < 0.8
x_train = xdata[msk]
x_test = xdata[~msk]
y_train = ydata[msk]
y_test = ydata[~msk]

# Analysing our data that how it look like and know which type of regression can be used.
plt.scatter(x_train,y_train)
# Using sigmoid function according to our dataset
def sigmoid(x,b1,b2):
  return 1/( 1+ np.exp(-b1*(x-b2)) )

# With curve_fit selecting the best non linear line.
from scipy.optimize import curve_fit
popt,pocv=curve_fit(sigmoid,x_train,y_train)

# Predicting the output for test set.
predict=sigmoid(x_test,*popt)
# Comparing our prediction and real output by visualization.
plt.scatter(x_test,y_test)
plt.plot(x_test,predict)
plt.show()
from sklearn.metrics import r2_score
print("Mean absolute error: ",np.mean(np.absolute(predict-y_test)))
print("R2 score: ",r2_score(y_test,predict))


import math
import numpy as np

## this section of code is mainly the reuse of [11]

class MCTS:

    def __init__(self, net, env, args):

        self.net=net
        self.env=env
        self.args=args

        self.visit_count = {}
        self.mean_action_value = {}
        self.prior_probability = {}
        self.terminal_state = {}
        self.total_visit_count = {}
        self.available_actions = {}

    def getboardstr(self, board):
        finalstr=''
        for k1 in range(self.args['RowNum']):
            for k2 in range(self.args['ColNum']):
                if board[k1][k2]!=0:
                    playerstr='%s' %int(board[k1][k2])
                    k1str='%s' %int(k1)
                    k2str='%s' %int(k2)
                    finalstr=finalstr+playerstr+'('+k1str+','+k2str+')#'
        return finalstr

    def simulate(self, board, player):

        for k in range(self.args['search_num']):
            self.search(board, player)
        board_str=self.getboardstr(board)
        return self.available_actions[board_str].copy(), self.visit_count[board_str].copy()

    def search(self, board, player):

        board_str=self.getboardstr(board)
        if board_str not in self.prior_probability:
            return -self.expand(board, player)
        index=self.select(board_str)
        action=self.available_actions[board_str][index]
        next_board, next_player=self.env.next_state(board, action, player)
        next_board_str=self.getboardstr(next_board)
        if next_board_str not in self.terminal_state:
            self.terminal_state[next_board_str]=self.env.is_terminal_state(next_board, action, player)
        value=0
        if self.terminal_state[next_board_str] is None:
            value=self.search(next_board, next_player)
        elif self.terminal_state[next_board_str]==player:
            value=1
        self.backup(board_str, index, value)
        return -value

    def select(self, board_str):

        max_value=-math.inf
        best_index=None
        for i in range(len(self.available_actions[board_str])):
            cur_value = self.args['c_puct'] * self.prior_probability[board_str][i] * math.sqrt(
                self.total_visit_count[board_str]) / (1.0 + self.visit_count[board_str][i])
            cur_value += self.mean_action_value[board_str][i]
            if cur_value > max_value:
                max_value=cur_value
                best_index=i
        return best_index

    def backup(self, board_str, index, value):

        self.mean_action_value[board_str][index] = (self.mean_action_value[board_str][index] * self.visit_count[board_str][
            index] + value) / (self.visit_count[board_str][index] + 1.0)
        self.visit_count[board_str][index] += 1
        self.total_visit_count[board_str] += 1

    def expand(self, board, player):

        policy, value=self.net.predict(board, player)
        board_str=self.getboardstr(board)
        actions=self.env.available_actions(board)
        self.available_actions[board_str]=actions
        self.prior_probability[board_str] = policy[actions] / sum(policy[actions])
        self.total_visit_count[board_str] = 1
        self.mean_action_value[board_str] = np.zeros(len(actions))
        self.visit_count[board_str] = np.zeros(len(actions))
        return value


import unittest

def letters_and_numbers(array):
    '''
    17.5 Letters and Numbers: Given an array filled with letters and numbers,
    find the longest subarray with an equal number of letters and numbers.
    '''

    # array:       x  z -5 4  d -2  g  t  4  a  q  w  p  7  8  n
    # array_bool:  1  1  0 0  1  0  1  1  0  1  1  1  1  0  0  1
    # zeros:       0  0  1 2  2  3  3  3  4  4  4  4  4  5  6  6
    # ones:        1  2  2 2  3  3  4  5  5  6  7  8  9  9  9 10
    # diff:       -1 -2 -1 0 -1  0 -1 -2 -1 -2 -3 -4 -5 -4 -3 -4
    array_bool = [isinstance(a, str) for a in array]

    zeros = [0] * len(array_bool)
    n_zeros = 0
    ones = [0] * len(array_bool)
    n_ones = 0

    for i in range(len(array_bool)):
        if array_bool[i] is False:
            n_zeros += 1
        else:
            n_ones += 1

        zeros[i] = n_zeros
        ones[i] = n_ones

    diff = [n_zeros - n_ones for n_zeros, n_ones in zip(zeros, ones)]

    occurances = {}

    for i in range(len(diff)):
        el = diff[i]

        if el not in occurances:
            index = i
            length = 0
        else:
            index, _ = occurances[el]
            length = i - index

        occurances[el] = (index, length)

    max_length = 0

    for _, (index, length) in occurances.items():
        if max_length <= length:
            max_length = length

    min_index = len(array) - 1

    for _, (index, length) in occurances.items():
        if length == max_length and index < min_index:
            min_index = index

    return array[min_index + 1:min_index + 1 + max_length]

class LettersAndNumbersTest(unittest.TestCase):
    def test_letters_and_numbers(self):
        array = ['x', 'z', -5, 4, 'd', -2, 'g', 't', 4, 'a', 'q', 'w', 'p', 7, 8, 'n']
        actual = letters_and_numbers(array)
        expected = ['z', -5, 4, 'd', -2, 'g', 't', 4]

        self.assertEqual(expected, actual)

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


from itertools import *
from z3 import *

row_rules = [
  [17, 4],
  [17, 1, 3],
  [14, 2, 3],
  [12, 1, 3],
  [9, 2, 2, 1],

  [2, 7, 1, 4],
  [4, 4, 3, 1, 1],
  [1, 3, 2, 1, 3, 1, 1],
  [3, 2, 3, 2],
  [3, 1, 2, 3, 1],

  [2, 5, 2, 1, 3, 1],
  [1, 8, 1, 2, 3],
  [1, 11, 1, 1],
  [2, 1, 2, 6, 4, 2],
  [1, 1, 4, 3, 1],

  [2, 2, 1, 3, 2],
  [1, 2, 3, 1],
  [1, 2, 1, 3],
  [4, 2, 1],
  [3, 1, 2],

  [3, 2, 1],
  [3, 1, 1, 2],
  [3, 2, 1],
  [3, 2, 2],
  [3, 2, 1],

  [4, 3, 2],
  [2, 3, 3, 1],
  [3, 4, 4],
  [6, 1, 1],
  [4],
]

col_rules = [
  [3, 2, 2, 1, 1, 11],
  [3, 3, 2, 1, 2, 11],
  [3, 4, 2, 3, 6, 2],
  [3, 4, 3, 6, 1],
  [3, 7, 1, 6],

  [3, 4, 4, 7],
  [3, 2, 6, 6],
  [3, 8, 3, 1],
  [3, 8, 2, 1],
  [3, 8, 2, 2],

  [3, 6, 1, 1],
  [3, 3, 2, 6],
  [3, 1, 4, 5],
  [3, 4, 2, 5],
  [6, 7, 1, 4],

  [6, 9, 2, 4],
  [6, 1, 9, 1, 3],
  [6, 4, 9, 2, 3],
  [4, 6, 9, 1, 2],
  [2, 1, 3, 9, 2, 2],

  [4, 1, 2, 11, 1],
  [6, 5, 9, 2],
  [7, 6, 6, 4],
  [6, 6, 4, 6],
  [1, 7, 6, 1, 8],

  [1, 1, 3, 6, 10],
  [2, 1, 1, 4, 12],
  [2, 1, 2, 1, 1, 14],
  [3, 1, 3, 16],
  [3, 4, 18],
]

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

def cell(x, y):
  return Bool(f"cell-{x},{y}")

def row(y):
  return [cell(x, y) for x in range(0, len(col_rules))]

def col(x):
  return [cell(x, y) for y in range(0, len(row_rules))]

s = Solver()

for x, col_rule in enumerate(col_rules):
  stripe_name = f"col-{x}"
  stripe_constraints = col_rule
  stripe = col(x)
  group_count = len(stripe_constraints)
  group_start = [Int(f"{stripe_name}-{i}-start") for i in range(0, group_count)]
  group_end = [Int(f"{stripe_name}-{i}-end") for i in range(0, group_count)]

  # # Start and end of each group
  for i in range(0, group_count):
    s.add(group_start[i] >= 0, group_start[i] < len(stripe))
    s.add(group_end[i] >= 0, group_end[i] < len(stripe))
    s.add(group_end[i] - group_start[i] == stripe_constraints[i] - 1)

  # Gap between each group and following group
  for i, j in pairwise(range(0, group_count)):
    s.add(group_start[j] >= group_end[i] + 2)

  # Cells
  for k in range(0, len(stripe)):
    cell_in_specific_group = [
        And(k >= group_start[i], k <= group_end[i])
        for i in range(0, group_count)
    ]
    s.add(stripe[k] == Or(*cell_in_specific_group))

for y, row_rule in enumerate(row_rules):
  stripe_name = f"row-{y}"
  stripe_constraints = row_rule
  stripe = row(y)
  group_count = len(stripe_constraints)
  group_start = [Int(f"{stripe_name}-{i}-start") for i in range(0, group_count)]
  group_end = [Int(f"{stripe_name}-{i}-end") for i in range(0, group_count)]

  # # Start and end of each group
  for i in range(0, group_count):
    s.add(group_start[i] >= 0, group_start[i] < len(stripe))
    s.add(group_end[i] >= 0, group_end[i] < len(stripe))
    s.add(group_end[i] - group_start[i] == stripe_constraints[i] - 1)

  # Gap between each group and following group
  for i, j in pairwise(range(0, group_count)):
    s.add(group_start[j] >= group_end[i] + 2)

  # Cells
  for k in range(0, len(stripe)):
    cell_in_specific_group = [
        And(k >= group_start[i], k <= group_end[i])
        for i in range(0, group_count)
    ]
    s.add(stripe[k] == Not(Or(*cell_in_specific_group)))

s.check()
m = s.model()

for y in range(0, len(row_rules)):
  row = "".join(["█" if m[cell(x,y)] else " " for x in range(0, len(col_rules))])
  print(row)


import re

def is_spam(text):
    # Check for signs of spam
    spam_words = ['광고', '지원금', '입장코드', '상한가', '수익률', '안전거래', '경품', '당첨', '무료체험', '회원가입', '추천']
    spam_url_pattern = r'https?://\S*'
    phone_number_pattern = r'\d{2,4}-\d{3,4}-\d{4}'

    text = text.lower()

    # Count number of spam words and check for spam URLs and phone numbers in the text
    spam_count = 0
    for word in spam_words:
        spam_count += text.count(word.lower())

    urls = re.findall(spam_url_pattern, text)
    phone_numbers = re.findall(phone_number_pattern, text)

    # Classify as spam if at least two spam words or one spam word with spam url or phone number
    if spam_count >= 2 or (spam_count >= 1 and (len(urls) > 0 or len(phone_numbers) > 0)):
        return True
    else:
        return False


"""myproject URL Configuration

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

urlpatterns = [

]
from django.urls import path
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)

from myapp.views import (
    RegisteredUserView,
    UserLoginView,
    BlogCreateView,
    BlogList,
    CommentCreateView,
    CommentReplyView

)

urlpatterns = [
    path("admin/", admin.site.urls),
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('api/register/', RegisteredUserView.as_view(), name='register'),
    path('api/login/', UserLoginView.as_view(), name='user-login'),
    path('api/blogpost/', BlogCreateView.as_view(), name='blogpost'),
    path('api/comment/<int:blog_id>/', CommentCreateView.as_view(), name='comment'),
    path('blogs/', BlogList.as_view(), name='blog-list'),
    path('api/reply/', CommentReplyView.as_view(), name='blog-list'),
]


from collections import defaultdict
import re

def parse(claim):
    r = re.compile(r'#(\d+) @ (\d+),(\d+): (\d+)x(\d+)')
    c = re.match(r, claim)
    (id, x, y, w, h) = c.groups()
    return (id, int(x), int(y), int(w), int(h))

def solve(input):
    claims = list(map(parse, input))

    fabric = defaultdict(int)
    for (_, x ,y, w, h) in claims:
        for i in range(w):
            for j in range(h):
                fabric[(x+i,y+j)] += 1

    count = 0
    for f in fabric.values():
        if f > 1:
            count += 1
    print(count)

# with open('test.txt', 'r') as f:
#     input = f.read().splitlines()
#     solve(input)

with open('input.txt', 'r') as f:
    input = f.read().splitlines()
    solve(input)


colors = {
    "Classic":{
        "Charm":111,
        "Cake":230,
        "Chaos":220,
        "Caution":124,
        "Cove":29,
        "Coral":175
    },
    "Modern":{
        "White":255,
        "Faux-Fur":188,
        "Sugar":231,
        "Marble":195,
        "Satin":189,
        "Plush":225

    },
    "Grayscale":{
        "Black":232,
        "Shadow":234,
        "Iron":238,
        "Stone":242,
        "Concrete":250,
        "White":254
    },
    "Weather":{
        "Overcast":59,
        "Mist":60,
        "Clear":45,
        "Sunny":11,
        "Light Snow":66,
        "Blizzard":75,
        "Cloudy":59,
        "Partly cloudy":61,
        "Snow":63,
        "Fog":15
    },
    "Temperature":{
        "Extremecold":17,
        "Freezing":19,
        "Cold":21,
        "Chilly":25,
        "Moderate":27,
        "Normal":36,
        "Temperate":72,
        "Warm":70,
        "Verywarm":11,
        "Hot":88,
        "Veryhot":52
    },
    "MISC":{
        "Error":160,
        "Success":118,
        "Loading":190
    }
}

def cringePrinter():
    i = 1
    print()
    print("MODERN PALETTE:")
    for k, v in colors["Modern"].items():
        if i % 3 == 0:
            print(f'\x1b[38;5;{v}m' + str(f"{k}") + u'\u001b[0m', end='\n')
        else:
            print(f'\x1b[38;5;{v}m' + str(f"{k}") + u'\u001b[0m', end=' ')
        i += 1
    print()
    print("CLASSIC PALETTE:")
    for k, v in colors["Classic"].items():
        if i % 3 == 0:
            print(f'\x1b[38;5;{v}m' + str(f"{k}") + u'\u001b[0m', end='\n')
        else:
            print(f'\x1b[38;5;{v}m' + str(f"{k}") + u'\u001b[0m', end=' ')
        i += 1
    print()
    print("GRAYSCALE PALETTE:")
    for k, v in colors["Grayscale"].items():
        if i % 3 == 0:
            print(f'\x1b[38;5;{v}m' + str(f"{k}") + u'\u001b[0m', end='\n')
        else:
            print(f'\x1b[38;5;{v}m' + str(f"{k}") + u'\u001b[0m', end=' ')
        i += 1
    print("TEMP PALETTE:")
    for k, v in colors["Temperature"].items():
        if i % 3 == 0:
            print(f'\x1b[38;5;{v}m' + str(f"{k}") + u'\u001b[0m', end='\n')
        else:
            print(f'\x1b[38;5;{v}m' + str(f"{k}") + u'\u001b[0m', end=' ')
        i += 1
    print()

def getPalette(color):
    for key in colors:
        for k in colors[key]:
            if color == k:
                palette = key
                return palette
    return None

def cringe(text, color=None, palette=None):
    try:
        if palette is None:
            palette = getPalette(color)
        return str(f'\x1b[38;5;{colors[palette][color]}m' + str(f"{text}") + u'\u001b[0m')
    except:
        return "!!! COLOR ERROR !!!"


from typing import List

class Solution:
    def duplicateZeros_bf(self, arr: List[int]) -> None:
        """
        Do not return anything, modify arr in-place instead.
        """
        i, n = 0, len(arr)
        while i < n - 1:
            if arr[i] == 0:
                for j in reversed(range(i + 1, n)):
                    arr[j] = arr[j - 1]
                i += 2
            else:
                i += 1
        return arr

    def duplicateZeros(self, arr: List[int]) -> None:
        n = len(arr)
        j = n + arr.count(0)

        for i in reversed(range(n)):
            j = j - 1
            if j < n:
                arr[j] = arr[i]
            if arr[i] == 0:
                j = j - 1
                if j < n:
                    arr[j] = arr[i]
        return arr

def test():
    sol = Solution()
    cases = [
        [1, 0, 2, 3, 0, 4, 5, 0],
        [1, 2, 3],
        [],
        [0],
        [1, 0],
        [0, 1],
    ]
    for case in cases:
        print(sol.duplicateZeros(case))

if __name__ == '__main__':
    test()


import random

def get_random_num(min, max):
    """
    this function gets two numbers and returns one random number
    :param
    `min`= minimum number,
    `max`= maximuim number
    :return
    Random integer.
    """
    #try:
    r = random.randint(min, max)
    #except:
        #r = random.randint(int(min), int(max))
    return r

def get_random_operation():

    """
    @param: no Args
    :)
    ------------------------------------
    @return: a random char
    """
    return random.choice(['+', '-', '*'])

def operation(n1, n2, o):
    """

    do the operation
    """
    p = f"{n1} {o} {n2}"
    if o == '+': a = n1 + n2
    elif o == '-': a = n1 - n2
    else: a = n1 * n2
    return p, a

def math_quiz():
    """
    Executes a math quiz game by presenting math problems and evaluating user answers.

    This function runs a simple math quiz game. It prompts the user with math problems
    and evaluates the user's input against the correct answer. The user's score is calculated
    based on correct answers.

    The user is presented with a set number of questions determined by the value of `t_q`.

    Parameters:
    None

    Returns:
    None
    """

    s = 0
    t_q = 3 #3.14159265359

    print("Welcome to the Math Quiz Game!")
    print("You will be presented with math problems, and you need to provide the correct answers.")

    for _ in range(t_q):
        n1 = get_random_num(1, 10); n2 = get_random_num(1, 5); o = get_random_operation()

        PROBLEM, ANSWER = operation(n1, n2, o)
        print(f"\nQuestion: {PROBLEM}")
        useranswer = input("Your answer: ")
        useranswer = int(useranswer)

        if useranswer == ANSWER:
            print("Correct! You earned a point.")
            s += -(-1)
        else:
            print(f"Wrong answer. The correct answer is {ANSWER}.")

    print(f"\nGame over! Your score is: {s}/{t_q}")

if __name__ == "__main__":
    math_quiz()


import sys
from spalloc import (
    config, ProtocolClient, ProtocolError, ProtocolTimeoutError,
    SpallocServerException)

# The acceptable range of server version numbers
VERSION_RANGE_START = (0, 1, 0)
VERSION_RANGE_STOP = (5, 0, 1)

class Terminate(Exception):
    def __init__(self, code, *args):
        super().__init__()
        self._code = code
        args = list(args)
        message = args.pop(0) if args else None
        if message is None:
            self._msg = None
        elif args:
            self._msg = message.format(*args)
        else:
            self._msg = message

    def exit(self):
        if self._msg is not None:
            sys.stderr.write(self._msg + "\n")
        sys.exit(self._code)

def version_verify(client, timeout):
    version = tuple(map(int, client.version(timeout=timeout).split(".")))
    if not (VERSION_RANGE_START <= version < VERSION_RANGE_STOP):
        raise Terminate(2, "Incompatible server version ({})",
                        ".".join(map(str, version)))

class Script(object):
    def __init__(self):
        self.client_factory = ProtocolClient

    def get_parser(self, cfg):
        """ Return a set-up instance of :py:class:`argparse.ArgumentParser`
        """
        raise NotImplementedError

    def verify_arguments(self, args):
        """ Check the arguments for sanity and do any second-stage parsing\
            required.
        """

    def body(self, client, args):
        """ How to do the processing of the script once a client has been\
            obtained and verified to be compatible.
        """

    def build_server_arg_group(self, server_args, cfg):
        server_args.add_argument(
            "--hostname", "-H", default=cfg["hostname"],
            help="hostname or IP of the spalloc server (default: %(default)s)")
        server_args.add_argument(
            "--port", "-P", default=cfg["port"], type=int,
            help="port number of the spalloc server (default: %(default)s)")
        server_args.add_argument(
            "--timeout", default=cfg["timeout"], type=float, metavar="SECONDS",
            help="seconds to wait for a response from the server (default: "
            "%(default)s)")
        server_args.add_argument(
            "--ignore_version", default=cfg["ignore_version"], type=bool,
            help="Ignore the server version (WARNING: could result in errors) "
                 "default: %(default)s)")

    def __call__(self, argv=None):
        cfg = config.read_config()
        parser = self.get_parser(cfg)
        server_args = parser.add_argument_group("spalloc server arguments")
        self.build_server_arg_group(server_args, cfg)
        args = parser.parse_args(argv)

        # Fail if server not specified
        if args.hostname is None:
            parser.error("--hostname of spalloc server must be specified")
        self.verify_arguments(args)

        try:
            with self.client_factory(args.hostname, args.port) as client:
                if not args.ignore_version:
                    version_verify(client, args.timeout)
                self.body(client, args)
                return 0
        except (IOError, OSError, ProtocolError, ProtocolTimeoutError) as e:
            sys.stderr.write("Error communicating with server: {}\n".format(e))
            return 1
        except SpallocServerException as srv_exn:
            sys.stderr.write("Error from server: {}\n".format(srv_exn))
            return 1
        except Terminate as t:
            t.exit()


#! /usr/bin/env python3

"""
Create environment variables from a hierarchy of configuration files.

Return codes:
0: no error
2: file not found
3: invalid json
4. could not substitute environment variable
"""

import argparse
import logging
import subprocess
import os
import pprint
import sys
from pathlib import Path
from datetime import datetime
import json
import re

lvs_vars = [
    'TOP_SOURCE',
    'TOP_LAYOUT',
    'LAYOUT_FILE',
    'EXTRACT_FLATGLOB',
    'EXTRACT_ABSTRACT',
    'EXTRACT_TYPE',
    'LVS_FLATTEN',
    'LVS_NOFLATTEN',
    'LVS_IGNORE',
    'LVS_SPICE_FILES_TO_FIX',
    'LVS_SPICE_FILES',
    'LVS_VERILOG_FILES'
]

def substitute_env_variables(input_string, env):
    """ Return the string after replacing all environment variables ($varname) with the corresponding values from the environment.

    Only handles simple variables $[A-Za-z0-9_]*. Does not handle ${varname}, $$, etc.
    Missing variables are fatal errors.
    """
    string = input_string
    if "$" in string:
        words = re.findall(r'\$\w+', string)  # returns a list of all environment variables used.
        for w in words:
            env_var = w[1:]  # remove leading '$'
            if env_var in env:
                string = string.replace(w, env.get(env_var), 1)  # only replace first occurence. Others will be replaced later.
            else:
                print(f"ERROR: couldn't find environment variable {w} used in {input_string}", file=sys.stderr)
                sys.exit(4)

    return string

def parse_config_file(json_file, lvs_env):
    """ Parses a json file which may reference other json files and uses the values to set environment variables.

    List values are accumulated while scalar values are overwritten when processing sub files.
    Duplicate list values are silently ignored.
    json syntax errors are fatal errors.
    """
    if not os.path.exists(f"{json_file}"):
        print(f"ERROR: Could not find configuration file {json_file}", file=sys.stderr)
        sys.exit(2)

    print(f"Loading LVS environment from {json_file}", file=sys.stderr)
    try:
        with open(json_file, "r") as f:
            data = json.load(f)
        for key, value in data.items():
            if type(value) == list:
                exports = lvs_env[key].split() if key in lvs_env else []  # current environment list values
                for val in value:
                    val = substitute_env_variables(val, lvs_env)
                    if val not in exports:  # only add if not already in list
                        exports.append(val)
                        if key == 'INCLUDE_CONFIGS':  # load child configs
                            lvs_env['INCLUDE_CONFIGS'] += " " + val  # prevents loading same config twice
                            parse_config_file(val, lvs_env)
                if key != 'INCLUDE_CONFIGS':  # the value of the INCLUDE_CONFIGS key is already updated before the recursive call.
                    lvs_env[key] = ' '.join(exports)
            else:  # value is not a list. new value overrides any previous value.
                value = substitute_env_variables(value, lvs_env)
                lvs_env[key] = value
    except Exception as err:
        print(type(err), file=sys.stderr)
        print(err.args, file=sys.stderr)
        print(f"ERROR: with file {json_file}", file=sys.stderr)
        sys.exit(3)

def clear_env(env, keys):
    """ Clear any previous setting for keys in the environment.
    """
    for key in keys:
        if key in env:
            del env[key]
            print(f"unset {key}")

def print_env(env, keys):
    """ Print assignment statements for keys in env.
    """
    for key in keys:
        if key in env:
            print(f"export {key}='{env[key]}'")
            #pprint.pprint({key: env[key]}, stream=sys.stderr)
        else:
            print(f"export {key}=")
            #pprint.pprint({key: ''}, stream=sys.stderr)

def set_lvs_env(config_file, design_name):
    """ Print a list of shell export commands to set LVS variables.

    Any errors are fatal.
    """
    lvs_env = os.environ.copy()
    clear_env(lvs_env, lvs_vars)
    lvs_env['INCLUDE_CONFIGS'] = f"{config_file}"
    lvs_env['DESIGN_NAME'] = design_name
    parse_config_file(config_file, lvs_env)
    print_env(lvs_env, lvs_vars)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Creates the LVS environment')
    parser.add_argument('--config_file', '-c', required=True, help='LVS config file')
    parser.add_argument('--design_name', '-d', required=False, help='Top source override')
    args = parser.parse_args()
    config_file = Path(args.config_file)
    set_lvs_env(config_file, args.design_name)


import turtle

sc1 = turtle.Screen()

def draw_Spiral(step, iterations):
    """Draws a spiral in python"""
    turtle_Car = turtle.Turtle()
    turtle_Car.speed(10)
    for n in range(1,iterations):
        turtle_Car.forward(step)
        turtle_Car.left(360/n)

    sc1.exitonclick()

draw_Spiral(2,1000)


import os
import tkinter as Tk
import project_path as pp

class ToolWidget:
    GENERIC_CONFIGS = {
        'level_1_label_frame': {
            'bd': 0,
            'bg': '#26262B',
            'fg': '#FFFFFF',
            'font': ('Raleway', 18),
            'relief': Tk.RIDGE
        },
        'level_2_label_frame': {
            'bd': 4,
            'fg': '#FFFFFF',
            'bg': '#26262B',
            'font': ('Raleway', 14),
            'relief': Tk.RIDGE
        },
        'button': {
            'bd': 4,
            'bg': '#5F646D',
            'activebackground': '#FFFFFF',
            'activeforeground': '#000000',
            'font': ('Raleway', 14),
            'compound': Tk.LEFT,
            'width': 150
        }
    }

    def button_pressed(self, button):
        print(button)

    def build_landmark_markers_label_frame(self):
        self.landmark_markers_label_frame = Tk.LabelFrame(master=self.markers_label_frame,
                                                          text='Landmarks',
                                                          cnf=ToolWidget.GENERIC_CONFIGS['level_2_label_frame'])
        self.landmark_markers_label_frame.grid({'row': 0, 'column': 0, 'sticky': Tk.N + Tk.W})

        center_image = Tk.PhotoImage(file=os.path.join(pp.resrc_folder_path, 'VideoAnnotator', 'SB', 'images', 'center.png')),
        self.center_button = Tk.Button(master=self.landmark_markers_label_frame,
                                       text='Center',
                                       image=center_image,
                                       command=lambda: self.button_pressed('center'),
                                       cnf=ToolWidget.GENERIC_CONFIGS['button'])
        self.center_button.image = center_image
        self.center_button.grid({'padx': 10, 'pady': 10, 'ipadx': 5, 'ipady': 5, 'row': 0, 'column': 0, 'sticky': Tk.W})

        node_image = Tk.PhotoImage(file=os.path.join(pp.resrc_folder_path, 'VideoAnnotator', 'SB', 'images', 'node.png')),
        self.node_button = Tk.Button(master=self.landmark_markers_label_frame,
                                     text='Node',
                                     image=node_image,
                                     command=lambda: self.button_pressed('node'),
                                     cnf=ToolWidget.GENERIC_CONFIGS['button'])
        self.node_button.image = node_image
        self.node_button.grid({'padx': 10, 'pady': 10, 'ipadx': 5, 'ipady': 5, 'row': 0, 'column': 1, 'sticky': Tk.E})

    def build_coins_markers_label_frame(self):
        self.coins_markers_label_frame = Tk.LabelFrame(master=self.markers_label_frame,
                                                       text='Coins',
                                                       cnf=ToolWidget.GENERIC_CONFIGS['level_2_label_frame'])
        self.coins_markers_label_frame.grid({'row': 1, 'column': 0, 'sticky': Tk.N + Tk.W})

        red_coin_image = Tk.PhotoImage(file=os.path.join(pp.resrc_folder_path, 'VideoAnnotator', 'SB', 'images', 'red coin.png')),
        self.red_coin_button = Tk.Button(master=self.coins_markers_label_frame,
                                         text='Red Coin',
                                         image=red_coin_image,
                                         command=lambda: self.button_pressed('red_coin'),
                                         cnf=ToolWidget.GENERIC_CONFIGS['button'])
        self.red_coin_button.image = red_coin_image
        self.red_coin_button.grid({'padx': 10, 'pady': 10, 'ipadx': 5, 'ipady': 5, 'row': 0, 'column': 0, 'sticky': Tk.W})

        green_coin_image = Tk.PhotoImage(file=os.path.join(pp.resrc_folder_path, 'VideoAnnotator', 'SB', 'images', 'green coin.png')),
        self.green_coin_button = Tk.Button(master=self.coins_markers_label_frame,
                                           text='Green Coin',
                                           image=green_coin_image,
                                           command=lambda: self.button_pressed('green_coin'),
                                           cnf=ToolWidget.GENERIC_CONFIGS['button'])
        self.green_coin_button.image = green_coin_image
        self.green_coin_button.grid({'padx': 10, 'pady': 10, 'ipadx': 5, 'ipady': 5, 'row': 0, 'column': 1, 'sticky': Tk.E})

    def build_bot_markers_label_frame(self):
        self.bot_markers_label_frame = Tk.LabelFrame(master=self.markers_label_frame,
                                                     text='Bot',
                                                     cnf=ToolWidget.GENERIC_CONFIGS['level_2_label_frame'])
        self.bot_markers_label_frame.grid({'row': 2, 'column': 0, 'sticky': Tk.N + Tk.W})

        bot_image = Tk.PhotoImage(file=os.path.join(pp.resrc_folder_path, 'VideoAnnotator', 'SB', 'images', 'bot.png')),
        self.bot_button = Tk.Button(master=self.bot_markers_label_frame,
                                    text='Bot',
                                    image=bot_image,
                                    command=lambda: self.button_pressed('bot'),
                                    cnf=ToolWidget.GENERIC_CONFIGS['button'])
        self.bot_button.image = bot_image
        self.bot_button.grid({'padx': 10, 'pady': 10, 'ipadx': 5, 'ipady': 5, 'row': 0, 'column': 0, 'sticky': Tk.W})

    def build_markers_label_frame(self):
        self.markers_label_frame = Tk.LabelFrame(master=self.root,
                                                 text='Markers',
                                                 cnf=ToolWidget.GENERIC_CONFIGS['level_1_label_frame'])
        self.markers_label_frame.grid({'padx': 15, 'pady': 15, 'row': 0, 'column': 0, 'sticky': Tk.N + Tk.W})
        self.build_landmark_markers_label_frame()
        self.build_coins_markers_label_frame()
        self.build_bot_markers_label_frame()

    def build_options_label_frame(self):
        self.options_label_frame = Tk.LabelFrame(master=self.root,
                                                 text='Options',
                                                 cnf=ToolWidget.GENERIC_CONFIGS['level_1_label_frame'])
        self.options_label_frame.grid({'padx': 15, 'pady': 15, 'row': 1, 'column': 0, 'sticky': Tk.N + Tk.W})

        undo_image = Tk.PhotoImage(file=os.path.join(pp.resrc_folder_path, 'VideoAnnotator', 'SB', 'images', 'undo.png')),
        self.undo_button = Tk.Button(master=self.options_label_frame,
                                     text='Undo',
                                     image=undo_image,
                                     command=lambda: self.button_pressed('undo'),
                                     cnf=ToolWidget.GENERIC_CONFIGS['button'])
        self.undo_button.image = undo_image
        self.undo_button.grid({'padx': 10, 'pady': 10, 'ipadx': 5, 'ipady': 5, 'row': 0, 'column': 0, 'sticky': Tk.W})

        clear_image = Tk.PhotoImage(file=os.path.join(pp.resrc_folder_path, 'VideoAnnotator', 'SB', 'images', 'clear.png')),
        self.clear_button = Tk.Button(master=self.options_label_frame,
                                      text='Clear',
                                      image=clear_image,
                                      command=lambda: self.button_pressed('clear'),
                                      cnf=ToolWidget.GENERIC_CONFIGS['button'])
        self.clear_button.image = clear_image
        self.clear_button.grid({'padx': 10, 'pady': 10, 'ipadx': 5, 'ipady': 5, 'row': 0, 'column': 1, 'sticky': Tk.W})

        save_image = Tk.PhotoImage(file=os.path.join(pp.resrc_folder_path, 'VideoAnnotator', 'SB', 'images', 'save.png')),
        self.save_button = Tk.Button(master=self.options_label_frame,
                                     text='Save',
                                     image=save_image,
                                     command=lambda: self.button_pressed('save'),
                                     width=ToolWidget.GENERIC_CONFIGS['button']['width'] * 2 + 40,
                                     cnf=ToolWidget.GENERIC_CONFIGS['button'])
        self.save_button.image = save_image
        self.save_button.grid({'padx': 10, 'pady': 10, 'ipadx': 5, 'ipady': 5, 'row': 1, 'column': 0, 'columnspan': 2})

    def build_widget(self):
        self.root = Tk.Tk()
        self.root.configure({'bg': '#26262B'})
        self.root.title("Marker Panel")
        self.root.resizable(0, 0)
        self.build_markers_label_frame()
        self.build_options_label_frame()

    def run(self):
        self.root.mainloop()

def main():
    tw = ToolWidget()
    tw.build_widget()
    tw.run()

if __name__ == '__main__':
    main()


import os

from django.http import JsonResponse
from django.shortcuts import render, get_object_or_404, redirect

# Create your views here.
from django.urls import reverse
from django.urls import reverse_lazy
from django.views import View
from django.views.generic import DeleteView
from django.views.generic import FormView
from django.views.generic import ListView

from albums.forms import AddImagesForm,CreatAlbumForm
from albums.models import Album, Photo
from bowling.settings import MEDIA_URL

class AlbumsListView(ListView):
    model = Album
    template_name = 'albums/albums_list.html'

class AlbumDetailView(View):
    def get(self,request,pk):
        album=get_object_or_404(Album,pk=pk)
        return render(request,'albums/album_detail.html',{
            'form':AddImagesForm,
            'photos':Photo.objects.filter(album_id=pk),
            'album':album
        })

    def post(self,request,pk):
        if request.FILES:
            album=get_object_or_404(Album,pk=pk)
            photos=[]
            photos_id={}
            for f in request.FILES.getlist('images'):
                photo = Photo.objects.create(
                    image=f,
                    album=album
                )
                photo.save()
                photos.append(str(photo.image))
                photos_id[str(photo.image)]=photo.id
            return JsonResponse({
                'new_photos':photos,
                'photos_id':photos_id
            },status=200,safe=False)
        else:
            return JsonResponse("Файлы не выбраны",status=500)

class CreateAlbumView(FormView):
    model = Album
    form_class = CreatAlbumForm
    template_name = 'albums/add_album.html'
    success_url = reverse_lazy('album:albums_list')

    def form_valid(self, form):
        album=form.save()
        album.save()
        return super().form_valid(form)

class AlbumDeletelView(DeleteView):
    model = Album
    success_url = reverse_lazy('album:albums_list')

class AlbumEditlView (View):
    def get(self,request,pk):
        album=get_object_or_404(Album,pk=pk)
        form = CreatAlbumForm(initial={
            'name':album.name,
            'cover':album.cover,
            'tournament':album.tournament
        })
        return render(request,'albums/edit_album.html',{'form':form,'album_id':pk})

    def post(self,request,pk):
        instance = get_object_or_404(Album, pk=pk)
        form=CreatAlbumForm(request.POST,request.FILES,instance=instance)
        if form.is_valid():
            form.save()
            return redirect(reverse('album:album_detail',kwargs={'pk':pk}))
        else:
            return render(request,'albums/edit_album.html',{'form':form,'album_id':pk})

class PhotoDeleteView(View):
    def post(self,request,album_id,photo_id):
        try:
            photo = Photo.objects.get(id=photo_id)
            photo.image.delete()
            photo.delete()
            return JsonResponse("ok",status=200,safe=False)
        except Exception:
            return JsonResponse("Oops",status=500,safe=False)


import datetime

import pandas as pd

from . import util

# Previous year OES gets released in May
if datetime.date.today().month > 6:
    CUR_YEAR = datetime.date.today().year - 1
else:
    CUR_YEAR = datetime.date.today().year - 2

def _get_zip_urls(year):
    """Return urls for zip files based on pattern.

    Parameters
    ----------
    year : string
        4 digit year in string format 'YYYY'.

    Returns
    -------
    dict
    """

    suffix = f'oesm{year[2:]}'
    code = 4

    return {
        'national': f'https://www.bls.gov/oes/special.requests/{suffix}'
            'nat.zip',
        'state': f'https://www.bls.gov/oes/special.requests/{suffix}'
            'st.zip',
        'area': f'https://www.bls.gov/oes/special.requests/{suffix}ma.zip',
        'industry': f'https://www.bls.gov/oes/special.requests/{suffix}in'
            f'{code}.zip'}

def _get_filenames(year, industry_scope=None):
    """Return filenames for oes files based on pattern.

    Parameters
    ----------
    year : string
        4 digit year in string format 'YYYY'.

    Returns
    -------
    dict.

    """
    if industry_scope == None:
        prefix = 'natsector'
    elif (industry_scope == 5) or (industry_scope == 6):
        prefix = 'nat5d_6d'
    else:
        prefix = 'nat{}d'.format(industry_scope)

    return {
        'national': f'oesm{year[2:]}nat/national_M{year}_dl.xlsx',
        'state': f'oesm{year[2:]}st/state_M{year}_dl.xlsx',
        'metros': f'oesm{year[2:]}ma/MSA_M{year}_dl.xlsx',
        'metros-divisions': f'oesm{year[2:]}ma/aMSA_M{year}_dl.xlsx' ,
        'non-metros': f'oesm{year[2:]}ma/BOS_M{year}_dl.xlsx',
        'industry': f'oesm{year[2:]}in4/{prefix}_M{year}_dl.xlsx'
    }

def get_data(year=CUR_YEAR, cut_by='national', area_focus=None,
    industry_scope=None,rtype='dataframe', set_missing_figures_as_na=True):
    """Get a dataset from the Occupational Employment Statistics (OES).

    The OES database contains statistics for various occupations.
    Primary statistics include wage, salary and total employment by occupation.

    Default behavior returns occupational data at a national
    level. This behavior can be overridden by adding options.

    Intended usage is to return a pandas dataframe for easy data
    analysis. This can be overwridden to return a primitive i/o object for
    different data processing decisions.

    Parameters
    ----------
    year : str
        year must be in form 'YYYY'. This package only supports OES after 2014
    cut_by : str
        Get occupation figures that are either cut by location
        or industry. Only three options are allowed: `state`, `area`,
        or `industry`. If not specified, default behavior is
        to return nationwide figures.
    area_focus : str
        If `cut_by = area` then an `area_focus` must also be
        specifed. Options include: metros, metro-divisions, or non-metros
    industry_scope : int, or None
        If `cut_by = industry` then an `industry_scope` must also be specified.
        Options include 3, 4, 5 or 6 digit scope.
        If not specified, then the default is top level sectors (i.e 2 digit).
        Industry scope describes the level of industry granularity. Higher the
        scope, the more granular the industries will be.
    set_missing_figures_as_na : bool, Default = True
        BLS uses ['*', '**', '#', '~'] to designate missing non-numeric figures
        in columns that have numeric statistics, such as hourly wage. This
        mismatch converts the whole column to an object and not a number type.
        By keeping this argument to True, this symbols will get converted
        to NA values allowing these columns to be calculated and treated as
        numbers.
    rtype : str
        Default behavior is to return a pandas dataframe.
        If you want a primitive i/o object that supports open(),
        then specify rtype='io'.

    Returns
    -------
    pd.Dataframe, or io file like object

    Usage:

    >>> df = get_data(2017, cut_by='state')
    >>> df.head()
       AREA  ST    STATE OCC_CODE  ...   A_PCT75 A_PCT90 ANNUAL HOURLY
    0     1  AL  Alabama  00-0000  ...     52020   78690    NaN    NaN
    1     1  AL  Alabama  11-0000  ...    133360  188860    NaN    NaN
    2     1  AL  Alabama  11-1011  ...         #       #    NaN    NaN
    3     1  AL  Alabama  11-1021  ...    147860       #    NaN    NaN
    4     1  AL  Alabama  11-1031  ...     24630   47510   True    NaN

    [5 rows x 25 columns]

    """
    if int(year) < 2014:
        raise ValueError(f'Year:{year}. OES only supports years post 2014.')
    if int(year) > CUR_YEAR:
        raise ValueError(f'Year:{year}. OES data not available yet.')

    if industry_scope != None and industry_scope not in range(3, 7):
        raise ValueError(f'Industry scope:{industry_scope}. '
            'Not a valid industry scope. Options include ints from 3 to 6')

    OES_ZIP_URLS = _get_zip_urls(str(year))
    OES_FILENAMES = _get_filenames(str(year), industry_scope)

    zip_url = OES_ZIP_URLS.get(cut_by)
    if zip_url == None:
        raise ValueError('"{}" is not a valid cut_by option\n' \
            'valid options include:\n{}' \
            .format(cut_by, [k for k in OES_ZIP_URLS.keys()]))

    if cut_by == 'area':
        filename = OES_FILENAMES.get(area_focus)
        if filename == None:
            raise ValueError('"{}" is not a valid area focus\n' \
                'valid options include:\n{}' \
                .format(area_focus, ['metros', 'metros-divisions', 'non-metros']))
    else:
        filename = OES_FILENAMES.get(cut_by)

    fp = util.get_file(zip_url, filename)

    if set_missing_figures_as_na:
        na_values = ['*', '**', '#', '~']
    else:
        na_values = []

    if rtype == 'dataframe':
        return pd.read_excel(fp, na_values = na_values)
    elif rtype == 'io':
        return fp
    else:
        raise ValueError('{} is not a valid return type\n' \
            'valid return types are `dataframe` or `io`' \
            .format(rtype))


from pyomo.environ import *
import numpy as np

cijr = []
fjr = []
with open("./Test_Instances/RAND2000_120-80.txt") as instanceFile:
  n = int(instanceFile.readline())
  clientsFacilitiesSizeStr = instanceFile.readline().strip().split(" ")
  instanceFile.readline()
  for phase in range(2):
    for i in range(1, len(clientsFacilitiesSizeStr)):
      if phase == 0:
        fjr.append([])
        for j in range(int(clientsFacilitiesSizeStr[i])):
          fjr[i-1].append(float(instanceFile.readline().strip().split(" ")[0]))
      else:
        nextLine = instanceFile.readline().strip()
        cijr.append([])
        j = 0
        while(nextLine != ""):
          nextLineNumbers = nextLine.split(" ")
          cijr[i-1].append([])
          for nextLinenumber in nextLineNumbers:
            cijr[i-1][j].append(float(nextLinenumber))
          j+=1
          nextLine = instanceFile.readline().strip()
    instanceFile.readline()
  instanceFile.close()
#cijr = np.array(
#  [
#    np.array([
#      [1,1000,1000],
#      [15000,2,15000],
#      [20000,20000,3],
#      [1,40000,40000]
#    ]),
#    np.array([
#      [10000,5,10000,10000,20000],
#      [30000,23000,3,24000,18000],
#      [28000,35000,21000,4,33000]
#    ]),
#    np.array([
#      [16, 14],
#      [2, 18000],
#      [20000, 3],
#      [20000, 2],
#      [24, 25]
#    ])
#  ]
#)

#fjr = np.array(
#  [
#    [10,15,20],
#    [17,20,25,30,18],
#    [48,50]
#  ]
#)

I = range(len(cijr[0]))

J = range(len(cijr[0][0]))

R = range(1, len(fjr)+1)
RM1 = range(1, len(fjr))

yjrIndexes = []
zirabIndexes = []
for r in R:
  for j in range(len(fjr[r-1])):
    yjrIndexes.append((r,j))

for i in I:
  for r in RM1:
    for a in range(len(cijr[r])):
      for b in range(len(cijr[r][0])):
        zirabIndexes.append((i,r,a,b))

model = ConcreteModel()

model.vij1 = Var(I, J, domain=Binary)
model.yjr = Var(yjrIndexes, domain=Binary)
model.zirab = Var(zirabIndexes, domain=Binary)

model.constraints = ConstraintList()

for i in I:
  model.constraints.add(sum(model.vij1[i, j] for j in J) == 1)
  for j1 in J:
    model.constraints.add(sum(model.zirab[i,1,j1,b] for b in range(len(cijr[1][0]))) == model.vij1[i,j1])
    model.constraints.add(model.vij1[i,j1] <= model.yjr[1,j1])
  for r in range(2, len(fjr) + 1):
    if(r <= len(fjr) - 1):
      for a in range(len(cijr[r])):
        model.constraints.add(sum(model.zirab[i,r,a,b] for b in range(len(cijr[r][0]))) == sum(model.zirab[i,r-1,bp,a] for bp in range(len(cijr[r-1]))))

    for b in range(len(cijr[r-1][0])):
      model.constraints.add(sum(model.zirab[i,r-1,a,b,] for a in range(len(cijr[r-1]))) <= model.yjr[r, b])

model.objective = Objective(
  expr = sum(sum(cijr[0][i][j1]*model.vij1[i,j1] for j1 in J) for i in I) + sum(sum(sum(sum(cijr[r][a][b]*model.zirab[i,r,a,b] for b in range(len(cijr[r][0])))for a in range(len(cijr[r]))) for r in RM1) for i in I) + sum(sum(fjr[r-1][j]*model.yjr[r,j] for j in range(len(fjr[r-1]))) for r in R),
  sense=minimize
)

results = SolverFactory('cplex').solve(model)
results.write()
#if results.solver.status:
#  model.pprint()

#model.constraints.display()


# https://www.interviewbit.com/problems/repeat-and-missing-number-array/

'''
Problem:
You are given a read only array of n integers from 1 to n.
Each integer appears exactly once except A which appears twice and B which is missing.
Return A and B.
'''

def repeatedNumber(A):
	size = len(A) + 1
	count = [0] * size

	for val in A:
		count[val] += 1
		res1 = 0
		res2 = 0

	for idx, val in enumerate(count):
		if val == 2:
			res1 = idx
		if val == 0:
			res2 = idx

	return res1, res2

A = [int(i) for i in input().split()]
print(repeatedNumber(A))

Arrays/Repeat and Missing Number Array.py


import time, datetime, requests
from common.utils.LoggingUtil import LoggingController

class AddPoiUtil():

    def __init__(self, env):
        self.log4py = LoggingController()
        self.poi_type = {
            '交通检查': '10002',
            '封路': '10003',
            '施工': '10006',
            '拥堵': '10007',
            '积水': '10008',
            '浓雾': '10010',
            '结冰': '10011',
            '交通事故': '10013',
            '实时路况': '10015'
        }
        self.__env = env
        self.path = None
        if self.__env == 'online':
            self.path = r'https://dzt.xxxxxxxxxx.com/deva/pc/pathAndPoi/no/addInfo'
        else:
            self.path = r'https://dzt-test.xxxxxxxxx.com/deva/pc/pathAndPoi/no/addInfo'

    def get_data(self, poi_type, direction, lat, lon):
        data = {
            "uploadUser": "123",
            "sn": 'ZD802B1932L00622',
            "sourceType": '10003',  # 新鲜事
            "poiType": poi_type,  # 交通检查
            "direction": direction,
            "nickName": "小松鼠艾德蒙",
            "likeNum": 1,
            "lat": lat,
            "lon": lon,
            "uploadTimestamp": int(round(time.time() * 1000)),
            "timeOutTimestamp": int(str((time.mktime(time.strptime((datetime.datetime.now() + datetime.timedelta(days=3)).strftime("%Y-%m-%d 00:00:00"), '%Y-%m-%d %H:%M:%S'))) * 1000).split(".")[0]),
            "uploadAddress": "安定门外大街",
            "headImgUrl": "http://yycp-static-1255510688.cos.ap-beijing.myqcloud.com/sso-server-image/1592476328925.png?sign=q-sign-algorithm%3Dsha1%26q-ak%3DAKIDvfAPQlotZ1IJ5T8cKm02oKkxub2FfySs%26q-sign-time%3D1592476329%3B1592620329%26q-key-time%3D1592476329%3B1592620329%26q-header-list%3D%26q-url-param-list%3D%26q-signature%3D66cc5afe29f73df008113bf21b8586793c151239",
            "type": 1,
            "data": "[{\"url\":\"http://petchfile-1255510688.cos.ap-beijing.myqcloud.com/sso-server-image/1592546939076.mp4?sign=q-sign-algorithm%3Dsha1%26q-ak%3DAKIDCWfcNwD5PXVWLxwejccR3Tiz5zhIkx0T%26q-sign-time%3D1592546939%3B1592550539%26q-key-time%3D1592546939%3B1592550539%26q-header-list%3D%26q-url-param-list%3D%26q-signature%3D74a4058ad7579ea210dafcf78d7a19460cffb899\",\"thumbnail\":\"http://petchfile-1255510688.cos.ap-beijing.myqcloud.com/sso-server-image/1592546956790.png?sign=q-sign-algorithm%3Dsha1%26q-ak%3DAKIDCWfcNwD5PXVWLxwejccR3Tiz5zhIkx0T%26q-sign-time%3D1592546956%3B1592550556%26q-key-time%3D1592546956%3B1592550556%26q-header-list%3D%26q-url-param-list%3D%26q-signature%3Dcc9a35349fc55e433f934af88df576ae792b3987\"}]"
        }
        return data

    def add_poi(self, poi_type, direction, lat, lon):
        r = requests.post(url=self.path, json=self.get_data(poi_type, direction, lat, lon))
        print(r.json())

if __name__ == '__main__':
    env = 'qa'
    a = AddPoiUtil(env)
    a.add_poi(a.poi_type['封路'], 180, 39.966487, 116.407653)


"""
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:
Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
"""

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

class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        # 特殊情况
        if not head:
            return None
        if not head.next:
            return head
        old_tail = head
        # 用来统计链表的长度
        length = 1
        # 找到原先的尾部
        while old_tail.next:
            old_tail = old_tail.next
            length += 1
        # 先把链表闭成环
        old_tail.next = head
        # 找到新的尾部 : (length - k % length - 1)th node
        # 和新的头部 : (length - k % length)th node
        new_tail = head
        for i in range(length - k % length - 1):
            new_tail = new_tail.next
        new_head = new_tail.next
        # 断开闭环
        new_tail.next = None
        return new_head
"""
思路：先找到原先的尾结点，将链表闭成环。再根据length - k % length - 1找到新的尾结点以及length - k % length找到新的头结点，从此处断开即可。
"""


import win32gui
import win32com.client
import re
import keyboard
import pytesseract
import ctypes
import win32api
import time

pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract'

from tkinter import *
from pyrobot import Robot

user32 = ctypes.windll.user32

def main():

	awareness = ctypes.c_int()
	errorCode = ctypes.windll.shcore.GetProcessDpiAwareness(0, ctypes.byref(awareness))
	errorCode = ctypes.windll.shcore.SetProcessDpiAwareness(2)

	root = createMainWindow()
	root.mainloop()

def getRulerData(picSize):

	#Find the ruler window from google earth
	#rulerWindow = win32gui.FindWindow('Qt5QWindowToolSaveBits', None)
	rulerWindow = win32gui.FindWindow(None, 'Ruler')

	if not rulerWindow:
		print("Unable to find ruler window")
		return null

	box = win32gui.GetWindowRect(rulerWindow)

	left = round(box[0])
	top = round(box[1])
	right = round(box[2])
	bottom = round(box[3])

	robot = Robot()
	img = robot.take_screenshot((left, top, right, bottom))

	#Make the image larger so the characters can be detected better
	width, height = img.size
	newsize = ((width*int(picSize)), (height*int(picSize)))
	img = img.resize(newsize)
	#img.save('enhanced.png')

	#Convert the image into readable data to use
	text = pytesseract.image_to_string(img)

	try:

		#Get the map length value from the ruler image
		ml1 = re.search(r"(Map .+:.+\d)", text)
		mt1 = ml1.group()
		ml2 = re.search(r"(\d.+)", mt1)
		mt2 = ml2.group()
		mt3 = mt2.replace(',', '')
		mt4 = mt3.replace(' ', '')
		mt5 = mt4.replace('.', '')
		mt6 = "%.2f" % (int(mt5) / 100.00)
		length = mt6

		#Get the heading value from the ruler image
		h1 = re.search(r"(Head.+:.+\d)", text)
		ht1 = h1.group()
		h2 = re.search(r"(\d.+)", ht1)
		ht2 = h2.group()
		ht3 = ht2.replace(',', '')
		ht4 = ht3.replace(' ', '')
		ht5 = ht4.replace('.', '')
		ht6 = "%.2f" % (int(ht5) / 100.00)
		heading = ht6

		#Put the length and heading into a single string and return it
		rulerdata = length + " " + heading
		return rulerdata

	except:
		print("Unable to read values")
		print(text)
		return 0

def sendMinecraftMessage(rulerData, pointType, origin):

	#Find the minecraft window
	minecraftWindow = win32gui.FindWindow("GLFW30", None)
	win32gui.SetForegroundWindow(minecraftWindow)
	minecraft = win32gui.GetFocus()

	minMessage = '/' + pointType + ' ' + origin + ' ' + rulerData

	shell = win32com.client.Dispatch('WScript.Shell')

	for x in minMessage:
		shell.SendKeys(x)

	keyboard.press_and_release('enter')
	keyboard.press_and_release('t')

def sendConnectMessage():

	#Find the minecraft window
	minecraftWindow = win32gui.FindWindow("GLFW30", None)
	win32gui.SetForegroundWindow(minecraftWindow)
	minecraft = win32gui.GetFocus()

	minMessage = '/pointsconnect'

	shell = win32com.client.Dispatch('WScript.Shell')

	for x in minMessage:
		shell.SendKeys(x)

	keyboard.press_and_release('enter')
	keyboard.press_and_release('t')

def createMainWindow():

	root = Tk()
	root.title('Auto Outline Tool')
	root.geometry("356x300")
	root.configure(bg = "#5DADE2")

	cmdSetupFrame = Frame(root,
		width=20,
		height=10,
		bg = "#5DADE2"
		)

	originFrame = Frame(cmdSetupFrame,
		width=20,
		height=10,
		bg = "#5DADE2"
		)

	pointTypeFrame = Frame(cmdSetupFrame,
		width=20,
		height=10,
		bg = "#5DADE2"
		)

	picSizeFrame = Frame(cmdSetupFrame,
		width=20,
		height=10,
		bg = "#5DADE2"
		)

	connectPointsFrame = Frame(root,
		width=20,
		height=10,
		bg = "#5DADE2"
		)

	rFrame = Frame(connectPointsFrame,
		width=20,
		height=10,
		bg = "#5DADE2"
		)

	cmdSetup = Label(root,
		text ="Command Setup",
		width = 50,
		height = 2,
		bg = "#5DADE2"
		)

	originPoint = Label(originFrame,
		text = "Origin Point",
		width = 10,
		height = 2,
		bg = "#5DADE2"
		)

	originEntry = Entry(originFrame,
		width = 10,
		bg = "White"
		)

	picSize = Label(picSizeFrame,
		text = "Picture Expansion by",
		width = 15,
		height = 2,
		bg = "#5DADE2"
		)

	picSizeEntry = Entry(picSizeFrame,
		width = 10,
		bg = "White"
		)
	picSizeEntry.insert(0, "6")

	pointType = Label(pointTypeFrame,
		text = "Point type",
		width = 20,
		height = 2,
		bg = "#5DADE2"
		)

	clicked = StringVar()
	clicked.set("point")

	pointDrop = OptionMenu(pointTypeFrame,
		clicked,
		"point",
		"point15",
		"point2"
		)
	pointDrop.configure(bg = "White")

	connectPoints = Label(connectPointsFrame,
		text = "Connect Points",
		width = 50,
		height = 2,
		bg = "#5DADE2"
		)

	r = BooleanVar()
	r.set("No")

	r1 = Radiobutton(rFrame,
		text="Yes",
		variable=r,
		value=True,
		bg = "#5DADE2"
		)
	r2 = Radiobutton(rFrame,
		text="No",
		variable=r,
		value=False,
		bg = "#5DADE2"
		)

	calculateBtn = Button(root,
		text="Calculate point",
		width = 25,
		height = 2,
		bg = "White",
		command=lambda: calculatePoint(clicked.get(), originEntry.get(), picSizeEntry.get(), r.get())
		)

	cmdSetup.grid(row=0,column=1)

	cmdSetupFrame.grid(row=1,column=1)

	pointTypeFrame.grid(row=0,column=0)
	pointType.pack()
	pointDrop.pack()

	originFrame.grid(row=0,column=1)
	originPoint.pack()
	originEntry.pack()

	picSizeFrame.grid(row=0,column=2)
	picSize.pack()
	picSizeEntry.pack()

	connectPointsFrame.grid(row=2,column=1)
	connectPoints.pack()
	rFrame.pack()
	r1.grid(row=0,column=0)
	r2.grid(row=0,column=1)
	calculateBtn.grid(row=3,column=1)

	return root

def calculatePoint(pointType, origin, picSize, radio):

	rulerData = getRulerData(picSize)

	if rulerData != 0:
		sendMinecraftMessage(rulerData, pointType, origin)
		time.sleep(1)
		if radio != False:
			sendConnectMessage()

main()


import unittest
import os
import numpy as np

import msi.msimanipulations as msimani
from msi.io.nrrdreader import NrrdReader
from msi.io.nrrdwriter import NrrdWriter
from msi.test import helpers

class TestNrrdWriter(unittest.TestCase):

    def setUp(self):
        # setup file and the path where it shall be written to
        self.msi = helpers.getFakeMsi()
        self.fileUriToWrite = "testfile.nrrd"

    def tearDown(self):
        # remove the hopefully written file
        os.remove(self.fileUriToWrite)

    def test_imageWriterCreatesFile(self):
        writer = NrrdWriter(self.msi)
        writer.write(self.fileUriToWrite)
        self.assertTrue(os.path.isfile(self.fileUriToWrite),
                        "file was written to disk")

    def test_imageWriterCreatesCorrectFile(self):

        writer = NrrdWriter(self.msi)
        writer.write(self.fileUriToWrite)

        reader = NrrdReader()
        msi = reader.read(self.fileUriToWrite)
        self.assertTrue(msi == helpers.getFakeMsi(),
                                       "image correctly written and read")

    def test_write_one_d_image_works(self):
        writer = NrrdWriter(self.msi)
        msimani.calculate_mean_spectrum(self.msi)
        writer.write(self.fileUriToWrite)

        reader = NrrdReader()
        msi = reader.read(self.fileUriToWrite)
        np.testing.assert_array_equal(msi.get_image(),
                                      np.array([1, 2, 3, 4, 5]),
                                      "1d image correctly written and read")