import numpy as np
import torch
import random

class EarlyStopping():
    def __init__(self, min_delta = 0, patience = 0):
        self.min_delta = min_delta
        self.patience = patience
        self.wait = 0
        self.stopped_epoch = 0
        self.best = -np.Inf
        self.stop_training = False

    def on_epoch_end(self, epoch, current_value):
        if np.greater((current_value - self.min_delta), self.best):
            self.best = current_value
            self.wait = 0
        else:
            self.wait += 1
            if self.wait > self.patience:
                self.stopped_epoch = epoch
                self.stop_training = True
        return self.stop_training

def seed_worker(worker_id):
    worker_seed = torch.initial_seed() % 2**32
    np.random.seed(worker_seed)
    random.seed(worker_seed)


import sys, getopt, os

def camiToKrona(argv):

	rankArr = ["superkingdom", "phylum", "class", "order", "family", "genus", "species", "strain", "dummy"]
	camiOutput = ''
	outFile = ''

	try:
		opts, args = getopt.getopt(argv, "i:o:", [])
	except getopt.GetoptError:
		print('-i <input> -o <output>')

	for opt, arg in opts:
		if opt in ("-i",):
			camiOutput = open(arg)
		elif opt in ("-o",):
			outFile = open(arg, 'w')

	#look for smallest taxonomic rank
	rank = ""
	rankIdx = 0
	for line in camiOutput:
		if "@" in line or "#" in line:
			continue
		if rankArr[rankIdx] in line:
			rank = rankArr[rankIdx]
		else:
			rankIdx += 1

	sumOfValues = 0.0
	camiOutput.seek(0)
	for line in camiOutput:
		if "@" in line or "#" in line:
			continue
		line = line.rstrip("\n")
		if line == "":
			continue
		line = line.split("\t")
		if rank == line[1]:
			sumOfValues += float(line[4])
			outFile.write(line[4] + "\t" + line[3].replace("|","\t") + "\n")
		else:
			outFile.write("0.0" + "\t" + line[3].replace("|","\t") + "\n")
	outFile.write(str(100 - sumOfValues))
	outFile.close()

camiToKrona(sys.argv[1:])


import turtle as t
from turtle import Screen
import random

# random walk generator

tim = t.Turtle()
t.colormode(255)

def random_color():
    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)
    colors = (r, g, b)
    return colors

direction = [0, 90, 180, 270]

tim.pensize(width=15)
tim.speed('fastest')

for _ in range(100):
    tim.color(random_color())
    tim.forward(30)
    tim.setheading(random.choice(direction))

screen = Screen()
screen.exitonclick()


def IsValid(n):
    if n <= 0 or n % 2 == 0:
        return False
    else :
        return True

def GambarSegitiga(n):
    if IsValid(n) == False:
        print("Masukan tidak valid")
    else: # Udah pasti ganjil (True)
        for i in range (1, n+1):
            daritengah = abs((n+1)/2 - i)
            kosong = 2 * daritengah
            baris = " "*int(kosong) + "*"*int(n-kosong)
            print(baris)

n = int(input(""))
GambarSegitiga(n)


import tkinter as tk
import tkinter.messagebox
import schedule

class ScheduleGUI:
    _CANVAS_WIDTH = 600
    _CANVAS_HEIGHT = 600
    _NUMBER_OF_DAYS = 5
    _TIME_LABEL_WIDTH = _CANVAS_WIDTH / (_NUMBER_OF_DAYS + 1) / 2
    _BLOCK_WIDTH = (_CANVAS_WIDTH - _TIME_LABEL_WIDTH) / _NUMBER_OF_DAYS
    _BLOCK_COLORS = ("white", "orange red", "pale green", "dodger blue", "turquoise", "goldenrod", "violet", "steelblue1")

    def _switchSchedule(self, forward):
        if not self.isSchedulesInit:
            raise ValueError("ScheduleGUI._switchSchedule: schedules not init")

        if forward:
            self.scheduleIndex += 1
            if self.scheduleIndex == len(self.schedules):
                self.scheduleIndex = 0
        else:
            self.scheduleIndex -= 1
            if self.scheduleIndex == -1:
                self.scheduleIndex = len(self.schedules) - 1
        self._drawSchedule()

    def _initEmptyGUI(self, root: tk.Tk):
        # create frame
        frame = tk.Frame(root, bg="grey", width=400, height=40)
        frame.pack(fill='x')
        #create buttons
        def switchForward():
            self._switchSchedule(True)
        def switchBackward():
            self._switchSchedule(False)
        self._forwardButton = tk.Button(frame, text="Next", command=switchForward)
        self._forwardButton.pack(side="right", padx=10)
        self._forwardButton.config(state='disabled')
        self._backButton = tk.Button(frame, text="Previous", command=switchBackward)
        self._backButton.pack(side="right", padx=10)
        self._backButton.config(state='disabled')
        #create index label
        self.indexLabel = tk.Text(frame, height=1, padx=10, width=6)
        self.indexLabel.configure(inactiveselectbackground=self.indexLabel.cget("selectbackground"))
        self.indexLabel.pack(side="left")
        #create code label
        self.codeLabel = tk.Text(frame, height=1, padx=10, borderwidth=0)
        self.codeLabel.configure(inactiveselectbackground=self.codeLabel.cget("selectbackground"))
        self.codeLabel.pack(side="left")
        # invoke canvas
        self.canvas = tk.Canvas(root, width=ScheduleGUI._CANVAS_WIDTH, height=ScheduleGUI._CANVAS_HEIGHT)
        self.canvas.pack()

    @staticmethod
    def _getCanvasY(minutes, minMinutes, maxMinutes):
        return (minutes - minMinutes) / (maxMinutes - minMinutes) * ScheduleGUI._CANVAS_HEIGHT

    def _drawSchedule(self):
        if not self.isSchedulesInit:
            raise ValueError("ScheduleGUI._drawSchedule: schedules not init")

        self.canvas.delete("all")

        classes = self.schedules[self.scheduleIndex].classes
        minHour = min(classes, key=lambda currClass : currClass.classTime.start).classTime.start.hour
        minMinutes = minHour * 60
        maxHour = max(classes, key=lambda currClass : currClass.classTime.start).classTime.end.hour + 1
        maxMinutes = maxHour * 60
        for i in range(len(classes)):
            currClass = classes[i]
            currColor = ScheduleGUI._BLOCK_COLORS[i % len(ScheduleGUI._BLOCK_COLORS)]
            for day in currClass.days.days:
                startMin = currClass.classTime.start.getTotalMinutes()
                endMin = currClass.classTime.end.getTotalMinutes()
                x = day * ScheduleGUI._BLOCK_WIDTH + ScheduleGUI._TIME_LABEL_WIDTH
                yStart = ScheduleGUI._getCanvasY(startMin, minMinutes, maxMinutes)
                w = ScheduleGUI._BLOCK_WIDTH
                yEnd = ScheduleGUI._getCanvasY(endMin, minMinutes, maxMinutes)
                self.canvas.create_rectangle(x, yStart, x + w, yEnd, fill=currColor)
                self.canvas.create_text(x, yStart, anchor="nw",text="%s: %s\n%s - %s" % (currClass.getFullName(), currClass.code, currClass.classTime.start.getFormatted(), currClass.classTime.end.getFormatted()))

        HOUR_LABEL_HEIGHT = ScheduleGUI._getCanvasY(minHour + 1, minHour, maxHour)
        for i in range(minHour, maxHour + 1):
            self.canvas.create_text(0, (i - minHour) * HOUR_LABEL_HEIGHT, anchor="nw", text=str(i))

        self.codeLabel.config(state='normal')
        self.codeLabel.delete(1.0, 'end')
        self.codeLabel.insert('end', ",".join(str(i) for i in self.schedules[self.scheduleIndex].getClassCodes()))
        self.codeLabel.config(state='disabled')

        self.indexLabel.config(state='normal')
        self.indexLabel.delete(1.0, 'end')
        self.indexLabel.insert('end', self.scheduleIndex)
        self.indexLabel.config(state='disabled')

    def initSchedules(self, schedules: [schedule.Schedule]):
        self.isSchedulesInit = True
        self.schedules = schedules
        self.scheduleIndex = 0

        self._forwardButton.config(state='normal')
        self._backButton.config(state='normal')

        self._drawSchedule()

    def promptForLoadFiles(self) -> bool:
        return tkinter.messagebox.askyesno("Schedule Creator", "Load saved course files?")

    def __init__(self, root: tk.Tk):
        self.isSchedulesInit = False
        self.schedules = []
        self.scheduleIndex = 0
        self._initEmptyGUI(root)


'''
05 영상의 명암비 조절

명암비(Contrast)란?
- 밝은 곳과 어두운 곳 사이에 드러나는 밝기 정도의 차이
- 컨트라스트, 대비
- 명암비가 높으면 밝은 부분과 어두운 부분의 픽셀 값의 차이가 커서 조금 더 선명해보인다.

기본적인 명암비 조절 함수
dst(x, y) = saturate(s·src(x, y))
- s = 0.5인 경우 : 최대 픽셀 값이 128이라 전체적으로 어두워 진다.
- s = 2인 경우 : 전체적으로 255가 되는 부분이 많아서 하얗게 보이는 부분이 많다.

효과적인 명암비 조절 함수
dst(x, y) = saturate(src(x, y) + (src(x, y) - 128)·α)
(1 + α) * src(x, y) - 128 * α  # 위의 식과 같다.

히스토그램 스트레칭(Histogram stretching)
- 영상의 히스토그램이 그레이스케일 전 구간에서 걸쳐 나타나도록 변경하는 선형 변환 기법 (양쪽으로 늘려주는 과정에서 중간 중간 픽셀 값이 없는 구간이 생긴다.)

정규화 함수
cv2.normalize(src, dst, alpha=None, beta, None, norm_type=None, dtype=None, mask=None) -> dst
- src: 입력 영상
- dst: 결과 영상 (스트레칭에서는 None 값으로 주면 된다.)
- alpha: (노름 정규화인 경우) 목표 노름 값, (원소 값 범위 정규화인 경우) 최솟값
- beta: (원소 값 범위 정규화인 경우) 최댓값
- norm_type: 정규화 타입. NORM_INF, NORM_L1, NORM_L2, NORM_MINMAX.  # NORM_MINMAX를 선택한 후 alpha에 0 beta에 255를 대입한다.
- dtype: 결과 영상의 타입
- mask: 마스크 영상

히스토그램 스트레칭 변환 함수
(f(x, y) -G(min)) / (G(max) - G(min)) * 255  # 변환 함수의 직선의 방정식
'''

import sys
import numpy as np
import matplotlib.pyplot as plt
import cv2

def getGrayHistImage(hist):
    imgHist = np.full((100, 256), 255, dtype=np.uint8)

    histMax = np.max(hist)
    for x in range(256):
        pt1 = (x, 100)
        pt2 = (x, 100 - int(hist[x, 0] * 100 / histMax))
        cv2.line(imgHist, pt1, pt2, 0)

    return imgHist

def contrast1():
    src = cv2.imread('img/lenna.bmp', cv2.IMREAD_GRAYSCALE)

    if src is None:
        print('Image load failed!')
        sys.exit()

    alpha = 1.0

    # np.clip을 활용해 0과 255 사이의 값으로 제한하고 astype()을 사용해 float형에서 uint8로 변경한다.
    dst = np.clip((1 + alpha) * src - 128 * alpha, 0, 255).astype(np.uint8)

    cv2.imshow('src1', src)
    cv2.imshow('dst1', dst)
    cv2.waitKey()

    cv2.destroyAllWindows()

def contrast2():
    src = cv2.imread('img/Hawkes.jpg', cv2.IMREAD_GRAYSCALE)

    if src is None:
        print('Image load failed!')
        sys.exit()

    dst = cv2.normalize(src, None, 0, 255, cv2.NORM_MINMAX)  # src가 만약 실수로 저장되어 있으면 dtype=np.uint8을 지정해야 한다.

    # numpy 라이브러리를 사용하여 직접 정규화한다. 위의 결과(dst)와 같다.
    gmin = np.min(src)
    gmax = np.max(src)
    dst2 = np.clip((src - gmin) / (gmax - gmin) * 255., 0, 255).astype(np.uint8)

    hist = cv2.calcHist([src], [0], None, [256], [0,256])
    histImg = getGrayHistImage(hist)

    hist2 = cv2.calcHist([dst], [0], None, [256], [0, 256])
    histImg2 = getGrayHistImage(hist2)

    hist3 = cv2.calcHist([dst2], [0], None, [256], [0, 256])
    histImg3 = getGrayHistImage(hist3)

    cv2.imshow('src2', src)
    cv2.imshow('dst2', dst)
    cv2.imshow('histImg', histImg)
    cv2.imshow('histImg2', histImg2)
    cv2.imshow('histImg3', histImg3)
    cv2.waitKey()

    cv2.destroyAllWindows()

contrast1()
contrast2()


#!/usr/bin/env python3

from dataclasses import dataclass
from functools import partial, reduce
import os
from pathlib import Path
from typing import Annotated, List
from typing_extensions import assert_never

from PIL import Image
import numpy as np
import tyro

from utils.common import setup_logging
from utils.data import (
    add_border,
    blend_rgba_image_array,
    create_scene_from_single_camera_image_collection,
    create_scene_from_video,
    psnr,
    side_by_side,
)
from utils.types import RGBColor, SceneCreationOptions

@dataclass(frozen=True, kw_only=True)
class Concatenate:
    image_paths: tyro.conf.Positional[List[Path]]
    # output image save path, the path will be overwritten with a warning
    out: Path
    # if specified, concatenate vertically instead of horizontally
    vertical: bool=False
    # gap between adjacent images, in pixels
    gap: int=0
    # border in pixels
    border: int=0
    bg: RGBColor=(1.0, 1.0, 1.0)

@dataclass(frozen=True, kw_only=True)
class Metrics:
    gt: Path
    image_paths: tyro.conf.Positional[List[Path]]
    psnr: bool=True
    bg: RGBColor=(1.0, 1.0, 1.0)

@dataclass(frozen=True, kw_only=True)
class CreateScene:
    # path to a video or a directory of image collection
    src: tyro.conf.Positional[Path]

    # where to write the images and transforms_{train,val,test}.json
    root_dir: Path

    # how many frames to extract per second, only required when src is a video
    fps: int | None=None

    scene_opts: tyro.conf.OmitArgPrefixes[SceneCreationOptions]

CmdCat = Annotated[
    Concatenate,
    tyro.conf.subcommand(
        name="cat",
        prefix_name=False,
        description="concatenate images horizontally or vertically",
    ),
]
CmdMetrics = Annotated[
    Metrics,
    tyro.conf.subcommand(
        name="metrics",
        prefix_name=False,
        description="compute metrics between images",
    ),
]
CmdCreateScene = Annotated[
    CreateScene,
    tyro.conf.subcommand(
        name="create-scene",
        prefix_name=False,
        description="create a instant-ngp-compatible scene from a video or a directory of images",
    ),
]

Args = CmdCat | CmdCreateScene | CmdMetrics

def main(args: Args):
    logger = setup_logging("utils", level="DEBUG")
    if isinstance(args, Concatenate):
        if args.out.is_dir():
            logger.error("output path '{}' is a directory".format(args.out))
            exit(1)
        if args.out.exists():
            logger.warn("output path '{}' exists and will be overwritten".format(args.out))
            if not os.access(args.out, os.W_OK):
                logger.error("output path '{}' is readonly".format(args.out))
                exit(2)
        if args.out.suffix.lower() not in map(lambda x: "." + x, ["jpg", "jpeg", "png", "tif", "tiff", "bmp", "webp"]):
            logger.warn("the file extension '{}' might not be supported".format(args.out.suffix))

        images = list(map(
            lambda img: blend_rgba_image_array(img, bg=args.bg) if img.shape[-1] == 4 else img,
            map(np.asarray, map(Image.open, args.image_paths)),
        ))
        height, width = images[0].shape[:2]
        oimg = reduce(
            partial(
                side_by_side,
                height=(None if args.vertical else height),
                width=(width if args.vertical else None),
                vertical=args.vertical,
                gap=args.gap,
            ),
            images,
        )
        oimg = add_border(oimg, border_pixels=args.border)
        logger.info("saving image ...")
        Image.fromarray(np.asarray(oimg)).save(args.out)
        logger.info("image ({}x{}) saved to '{}'".format(oimg.shape[1], oimg.shape[0], args.out))

    elif isinstance(args, Metrics):
        gt_image = np.asarray(Image.open(args.gt))
        if gt_image.shape[-1] == 4:
            gt_image = blend_rgba_image_array(gt_image, bg=args.bg)
        images = list(map(
            lambda img: blend_rgba_image_array(img, bg=args.bg) if img.shape[-1] == 4 else img,
            map(np.asarray, map(Image.open, args.image_paths)),
        ))
        for impath, img in zip(args.image_paths, images):
            if args.psnr:
                logger.info("psnr={} ({})".format(psnr(gt_image, img), impath))

    elif isinstance(args, CreateScene):
        if args.src.is_dir():
            create_scene_from_single_camera_image_collection(
                raw_images_dir=args.src,
                scene_root_dir=args.root_dir,
                opts=args.scene_opts,
            )
        else:
            assert args.fps is not None, "must specify extracted frames per second via --fps for video source"
            create_scene_from_video(
                video_path=args.src,
                scene_root_dir=args.root_dir,
                fps=args.fps,
                opts=args.scene_opts,
            )

    else:
        assert_never("tyro already ensures subcommand passed here are valid, this line should never be executed")

if __name__ == "__main__":
    args = tyro.cli(Args)
    main(args)


"""Twitch.tv uses OAuth2 for authorization.
We use the Implicit Grant Workflow.
The user has to visit an authorization site, login, authorize
PyTwitcher. Once he allows PyTwitcher, twitch will redirect him to
:data:`pytwitcherapi.REDIRECT_URI`.
In the url fragment, there is the access token.

This module features a server, that will respond to the redirection of
the user. So if twitch is redirecting to :data:`pytwitcherapi.REDIRECT_URI`,
the server is gonna send a website, which will extract the access token,
send it as a post request and give the user a response,
that everything worked.
"""
import logging
import os
import sys

import oauthlib.oauth2
import pkg_resources

from pytwitcherapi import constants

if sys.version_info[0] == 3:
    from http import server
else:
    import BaseHTTPServer as server

log = logging.getLogger(__name__)

class RedirectHandler(server.BaseHTTPRequestHandler):
    """This request handler will handle the redirection of the user
    when he grants authorization to PyTwitcher and twitch redirects him.
    """

    extract_site_url = '/'
    success_site_url = '/success'

    def _set_headers(self):
        """Set the response and headers

        :returns: None
        :raises: None
        """
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self, ):
        """Handle GET requests

        If the path is '/', a site which extracts the token will be generated.
        This will redirect the user to the '/sucess' page, which shows
        a success message.

        :returns: None
        :rtype: None
        :raises: None
        """
        urld = {self.extract_site_url: 'extract_token_site.html',
                self.success_site_url: 'success_site.html'}
        site = urld.get(self.path)
        if not site:
            log.debug("Requesting false url on login server.")
            self.send_error(404)
            return
        log.debug('Requesting the login server. Responding with %s.', urld)
        self._set_headers()
        self._write_html(site)

    def _write_html(self, filename):
        """Read the html site with the given filename
        from the data directory and write it to :data:`RedirectHandler.wfile`.

        :param filename: the filename to read
        :type filename: :class:`str`
        :returns: None
        :rtype: None
        :raises: None
        """
        datapath = os.path.join('html', filename)
        sitepath = pkg_resources.resource_filename('pytwitcherapi', datapath)
        with open(sitepath, 'r') as f:
            html = f.read()
        self.wfile.write(html.encode('utf-8'))

    def do_POST(self, ):
        """Handle POST requests

        When the user is redirected, this handler will respond with a website
        which will send a post request with the url fragment as parameters.
        This will get the parameters and store the original redirection
        url and fragments in :data:`LoginServer.tokenurl`.

        :returns: None
        :rtype: None
        :raises: None
        """
        log.debug('POST')
        self._set_headers()
        # convert the parameters back to the original fragment
        # because we need to send the original uri to set_token
        # url fragments will not show up in self.path though.
        # thats why we make the hassle to send it as a post request.
        # Note: oauth does not allow for http connections
        # but twitch does, so we fake it
        ruri = constants.REDIRECT_URI.replace('http://', 'https://')
        self.server.set_token(ruri + self.path.replace('?', '#'))

class LoginServer(server.HTTPServer):
    """This server responds to the redirection of the user
    after he granted authorization.
    """

    def __init__(self, session):
        """Initialize a new server.

        The server will be on :data:`constants.LOGIN_SERVER_ADRESS`.

        :param session: the session that needs a token
        :type session: :class:`requests_oauthlib.OAuth2Session`
        :raises: None
        """
        server.HTTPServer.__init__(self,
                                   constants.LOGIN_SERVER_ADRESS,
                                   RedirectHandler)
        self.session = session
        """The session that needs a token"""

    def set_token(self, redirecturl):
        """Set the token on the session

        :param redirecturl: the original full redirect url
        :type redirecturl: :class:`str`
        :returns: None
        :rtype: None
        :raises: None
        """
        log.debug('Setting the token on %s.' % self.session)
        self.session.token_from_fragment(redirecturl)

class TwitchOAuthClient(oauthlib.oauth2.MobileApplicationClient):
    """This is a client needed for :class:`oauthlib.oauth2.OAuth2Session`.
    It fixes the Authorization header for twitch.

    Usually the Authorization Header looks like this::

        {'Authorization': 'Bearer <<token>>'}

    But Twitch needs it to be like this::

        {'Authorization': 'OAuth <<token>>'}

    So we override :meth:`TwitchOAuthClient._add_bearer_token` to fix the header.
    """

    def _add_bearer_token(self, *args, **kwargs):
        """Add a bearer token to the request uri, body or authorization header.

        This is overwritten to change the headers slightly.
        """
        s = super(TwitchOAuthClient, self)
        uri, headers, body = s._add_bearer_token(*args, **kwargs)
        authheader = headers.get('Authorization')
        if authheader:
            headers['Authorization'] = authheader.replace('Bearer', 'OAuth')
        return uri, headers, body


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
import pytest
import time
import sys
import basefunc

def put_real_postal(element):
    element.send_keys("250")

def put_replacement_postal(element):
    element.send_keys("000")

def test_change_data():

    browser = webdriver.Firefox()
    browser.get(basefunc.BASEURL)

    basefunc.login(browser, 'id', 'pass')
    time.sleep(2)

    #reszta danych kontaktowych
    browser.find_element_by_css_selector("#ui-id-4").click()
    browser.find_element_by_css_selector("#tabContents-6 > h2 > span:nth-child(1) > a").click()
    time.sleep(1)
    postal_code = browser.find_element_by_css_selector("#primaryAddress\.postalCode")
    postal_code.click()
    postal_code_text = postal_code.text

    for i in range(0,3):
        postal_code.send_keys(Keys.BACK_SPACE)

    if(postal_code_text == "00-250"):
        put_replacement_postal(postal_code)
    else:
        put_real_postal(postal_code)

    browser.find_element_by_css_selector("#save").click()

    time.sleep(1)

    #weryfikacja
    new_data = browser.find_element_by_css_selector("#patronContactInfo > div > div > span:nth-child(5)").text
    assert new_data != postal_code_text

    basefunc.logout(browser)
    browser.quit()


import os
import subprocess as sp
import time
# from mmcv import Config
# from mmdet.datasets import build_dataset

from summit_tools.img2coco import create_test_json
from summit_tools.GF_sar_submission_v2 import creat_submission

import argparse

def parse_args():
    parser = argparse.ArgumentParser(description='summit fianal result ')
    parser.add_argument('input', default='data/summit_test/images')
    parser.add_argument('--result_json', default='output.json.bbox.json')
    parser.add_argument('output', default='work_dirs/submission')

    args = parser.parse_args()
    return args

def run_cmd(cmd):
    cp = sp.run(cmd,shell=True, capture_output=True, encoding = "utf-8")
    if cp.returncode != 0:
        error = f"""Something wrong has happend when running command [{cmd}]:{cp.stderr}"""
        raise Exception(error)
    return cp.stdout, cp.stderr

def main():
    args = parse_args()
    classnames = ('A220', 'A330', 'A320/321', 'Boeing737-800', 'Boeing787', 'ARJ21', 'other')
    start_time = time.time()
    # get test_images annotation .json file
    try:
        create_test_json(args.input)
    except:
        print("fail to get test_images annotation .json file")
        raise
    # get detection result: .json file
    print('begining to test')
    try:
        run_cmd('python tools/test.py models/ppyoloe_plus_s_fast_8xb8-240e_no-val_ms_sar/ppyoloe_plus_s_fast_8xb8-240e_no-val_ms_sar.py models/ppyoloe_plus_s_fast_8xb8-240e_no-val_ms_sar/epoch_220.pth  --tta  --json-prefix "output.json"')
        # run_cmd('python tools/test.py models/rtmdet_x_syncbn_fast_8xb32-300e_sar_ms/rtmdet_x_syncbn_fast_8xb32-300e_sar_ms.py models/rtmdet_x_syncbn_fast_8xb32-300e_sar_ms/epoch_270.pth --json-prefix "output.json"')
    except Exception:
        print('*********************test failed************************')
        raise

    # creat xml annotations
    creat_submission(args.result_json, args.output, classnames)

    run_cmd('rm test.csv && rm test.json && rm output.json.bbox.json')

    print('finshed the submission!!!')
    print('total time:', time.time() - start_time)

if __name__=="__main__":
    main()


import csv
import logging

# third party imports
from elasticsearch.exceptions import ConnectionError, NotFoundError
from urllib3.exceptions import ProtocolError

# CubicWeb specific imports
# library specific imports
from cubicweb_francearchives.dataimport.sqlutil import delete_from_filename
from cubicweb_francearchives.storage import S3BfssStorageMixIn

from cubicweb_frarchives_edition.rq import rqjob

def log_results(log, deleted, ids, not_found, forbidden):
    if deleted:
        log.info("deleted %s FindingAids: %s", len(deleted), "; ".join(deleted))
    if not_found:
        log.error(
            "could not find %d FindingAids with stable_ids/eadids: %s",
            len(not_found),
            "; ".join(not_found),
        )
    if forbidden:
        log.error(
            "you have no permission to delete %d FindingAids: %s",
            len(forbidden),
            ", ".join(forbidden),
        )

@rqjob
def delete_findingaids(cnx, filepath):
    """Delete FindingAids.

    :param Connection cnx: CubicWeb database connection
    :param filepath: filename of a temporary csv file with 1 column: stable_id_or_eadid
    """
    log = logging.getLogger("rq.task")
    st = S3BfssStorageMixIn(log=log)
    try:
        with st.storage_read_file(filepath) as fp:
            ids = [row[0] for row in csv.reader(fp)]
    except Exception as err:
        log.error(f'unable to read stable ids from "{filepath}", please check file contents: {err}')
        return
    if len(ids) <= 1:
        log.warning("empty list of stable ids / eadids")
        return
    # drop header
    ids = ids[1:]
    log.info(f'found {len(ids)} identifiers to delete from "{filepath}"')
    not_found = []
    deleted = []
    forbidden = []
    for irid in ids:
        rset = cnx.execute(
            """Any X, S, N WHERE X is FindingAid, X stable_id S,
               X findingaid_support FS?, FS data_name N,
               X stable_id %(id)s OR X eadid %(id)s""",
            {"id": irid},
        )
        if not rset:
            not_found.append(irid)
            continue
        for entity, stable_id, filename in rset.iter_rows_with_entities():
            if not entity.cw_has_perm("delete"):
                forbidden.append(
                    "csv_id: {}, stable id: {}, filename: {})".format(
                        irid, stable_id, filename or ""
                    )
                )
            try:
                delete_from_filename(
                    cnx, stable_id, is_filename=False, interactive=False, esonly=False
                )
                # no commit here because it is already done in sqlutil.delete_from_filename
                cnx.vreg["services"].select("sync", cnx).sync([("delete", entity)])
            except (ConnectionError, ProtocolError, NotFoundError):
                log.error(
                    "elasticsearch indexation failed for FindingAid %s", entity.absolute_url()
                )
            except Exception:
                log.error("unable to delete FindingAid %s ", entity.absolute_url())
                log.error("abort deletion")
                log_results(log, deleted, ids, not_found, forbidden)
                return
            deleted.append(
                "csv_id: {}, stable id: {}, filename: {})".format(irid, stable_id, filename or "")
            )
    log_results(log, deleted, ids, not_found, forbidden)
    # delete the temporary file
    st.storage_delete_file(filepath)


import esper

from cast_away.components.graphics.emitter import Emitter

class EmitterProcessor(esper.Processor):
    def process(self, dt):
        for ent, emitter in self.world.get_component(Emitter):
            emitter._arcade_emitter.update()
            if emitter._arcade_emitter.can_reap():
                self.world.delete_entity(ent)

def init(world):
    world.add_processor(EmitterProcessor())


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun  7 22:15:21 2019

@author: vikram
"""
import re
with open('simpsons_phone_book.txt',mode='rt') as file:
    for line in file:
        if line[0]=='J':
         if re.findall(r'(Neu)',line):
          print(line)


import pandas as pd
import numpy as np
from gensim.models import Word2Vec
import jieba
import time
from sklearn.preprocessing import LabelEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, roc_auc_score
from sklearn.ensemble import RandomForestClassifier

# 读取动作片评论数据集
data = pd.read_csv(r'./整理后数据/merged_action.csv')

# 加载Word2Vec模型
model = Word2Vec.load(r'./segmentation_wordcloud/word2vec模型/word2vec_action.model').wv

# 定义获取特征矩阵的函数
def getVector_v1(cutWords, word2vec_model):
    count = 0
    article_vector = np.zeros(word2vec_model.vector_size)
    for cutWord in cutWords:
        if cutWord in word2vec_model.key_to_index:
            article_vector += word2vec_model.get_vector(cutWord)
            count += 1
    if count != 0:
        return article_vector / count
    else:
        return np.zeros(word2vec_model.vector_size)

# 分词处理
list_all = []
data['评论内容'] = data['评论内容'].astype(str)
for sentence in data['评论内容']:
    words = list(jieba.cut(sentence))
    list_all.append(words)

# 生成特征矩阵
startTime = time.time()
vector_list = []
i = 0
for cutWords in list_all:
    i += 1
    if i % 1000 == 0:
        print('前%d 篇评论形成词向量花费%.2f 秒' % (i, time.time() - startTime))
    vector = getVector_v1(cutWords, model)
    vector_list.append(vector)
X = np.array(vector_list)
print('Total Time You Need To Get X: %.2f 秒' % (time.time() - startTime))
X.dump('sat_dissat_vector.txt')

# 标签编码
labelEncoder = LabelEncoder()
y = labelEncoder.fit_transform(data['情感'])

# 划分数据集
train_X, test_X, train_y, test_y = train_test_split(X, y, test_size=0.3, random_state=0)

# 构建逻辑回归模型
logistic_model = LogisticRegression()
logistic_model.fit(train_X, train_y)
logistic_score = logistic_model.score(test_X, test_y)

# 输出分类报告
report = classification_report(test_y, logistic_model.predict(test_X), labels=[0, 1], target_names=['正向情感', '负向情感'],zero_division=1)
print(report)

# 计算AUC值
auc_score = roc_auc_score(test_y, logistic_model.predict_proba(test_X)[:, 1], multi_class='ovr')
print('AUC Score:', auc_score)

# 构建随机森林模型
rf = RandomForestClassifier(
    criterion='entropy',
    n_estimators=10000,
    min_samples_split=100,
    min_weight_fraction_leaf=0.05
)
rf.fit(train_X, train_y)
y_pred = rf.predict(test_X)
print('分类预测值：', y_pred)


from environment import Environment

if __name__ == '__main__':
    environment = Environment()
    print('\n\033[1mBoth Trained - Seller First\033[0m')
    environment.train(train_both=False, train_agent='Seller')
    environment.test()
    print('\n\033[1mBoth Trained - Buyer First\033[0m')
    environment.train(train_both=False, train_agent='Buyer')
    environment.test()


import requests
from bs4 import BeautifulSoup
from dotenv import load_dotenv
import os
import spotipy
from spotipy.oauth2 import SpotifyOAuth
load_dotenv()

CLIENT_ID = os.environ.get("client_id")
CLIENT_SECRET = os.environ.get("client_secret")

spotify = spotipy.Spotify(auth_manager=SpotifyOAuth(scope="playlist-modify-private",
                                                    client_id=CLIENT_ID,
                                                    client_secret=CLIENT_SECRET,
                                                    redirect_uri="http://example.com",
                                                    cache_path="token.txt"))

date = input("which year's top 100 songs do you want to make a Spotify list? Type the date in this format YYYY-MM-DD: ")
year = date.split("-")[0]

# Creates a better looking date
new_date = ""
for i, element in enumerate(reversed(date.split("-"))):
    new_date += element
    if i < 2:
        new_date += "/"

response = requests.get(url=f"https://www.billboard.com/charts/hot-100/{date}/")
website = response.text

soup = BeautifulSoup(website, "html.parser")

titles = soup.select("li > ul > li > h3")
song_titles = [title.getText(strip=True) for title in titles]

# Creating a list of song uris
song_uris = []
for title in song_titles:
    try:
        song_uri = spotify.search(q=f"track:{title} year:{year}", type="track")["tracks"]["items"][0]["uri"]
    except IndexError:
        print("Couldn't find one song for this date.")
    else:
        song_uris.append(song_uri)

user = spotify.current_user()
user_id = user["id"]
playlist_name = f"Top 100 {new_date}"
playlist = spotify.user_playlist_create(user=user_id, name=playlist_name, public=False)
playlist_id = playlist["id"]

spotify.user_playlist_add_tracks(user=user_id, playlist_id=playlist_id, tracks=song_uris)


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

    n = int(input())

    a = [int(x) for x in input().split()]

    b = [int(x) for x in input().split()]

    a.sort()

    b.sort()

    ok = 1

    for i in range(n):

        if a[i]==b[i]:

            continue

        if a[i]+1==b[i]:

            continue

        ok = 0

    if ok==0:

        print("NO")

    else:

        print("YES")


import random
from math import pi

import rospy
import actionlib
from geometry_msgs.msg import PoseStamped
from tf.transformations import quaternion_from_euler
import simple_moveit_interface as smi_
import cob_pick_place_action.msg  # pylint: disable=import-error

def setup_environment():
	psi = smi_.get_planning_scene_interface()
	rospy.sleep(1.0)

	#smi_.clear_attached_object("arm_7_link")
	smi_.clear_attached_object("arm_left_7_link")
	#smi_.clear_objects()
	smi_.clear_objects()

	### Add a floor
	smi_.add_ground()

	### Add table
	pose = PoseStamped()
	pose.header.frame_id = "/base_footprint"
	pose.header.stamp = rospy.Time.now()
	pose.pose.position.x = -0.9
	pose.pose.position.y = 0
	pose.pose.position.z = 0.39
	pose.pose.orientation.x = 0
	pose.pose.orientation.y = 0
	pose.pose.orientation.z = 0
	pose.pose.orientation.w = 1

	psi.add_box("bookcase", pose, size=(0.5, 1.5, 0.78))

	rospy.sleep(1.0)

def cob_pick_action_client():
	pick_action_client = actionlib.SimpleActionClient('cob_pick_action', cob_pick_place_action.msg.CobPickAction)

	pick_action_client.wait_for_server()

	setup_environment()

	# Creates a goal to send to the action server.
	goal = cob_pick_place_action.msg.CobPickGoal()
	#goal.object_class = 18
	#goal.object_name = "yellowsaltcube"
	#goal.object_class = 50
	#goal.object_name = "instantsoup"
	#goal.object_class = 103
	#goal.object_name = "instanttomatosoup"
	goal.object_class = 5001
	goal.object_name = "pringles"
	goal.object_pose.header.stamp = rospy.Time.now()
	goal.object_pose.header.frame_id = "base_footprint"

	### cob3
	#goal.object_pose.pose.position.x = random.uniform(-0.8, -0.6)
	#goal.object_pose.pose.position.y = random.uniform(-0.3,  0.3)
	#goal.object_pose.pose.position.z = random.uniform( 0.8,  1.1)
	#goal.object_pose.pose.orientation.x, goal.object_pose.pose.orientation.y, goal.object_pose.pose.orientation.z, goal.object_pose.pose.orientation.w = quaternion_from_euler(random.uniform(-pi/2, pi/2),random.uniform(-pi/2, pi/2),random.uniform(-pi/2, pi/2))
	#goal.gripper_type = "sdh"
	#goal.gripper_side = ""

	### cob4
	goal.object_pose.pose.position.x = 0.617 + random.uniform(-0.1, 0.1)
	goal.object_pose.pose.position.y = 0.589 + random.uniform(-0.1, 0.1)
	goal.object_pose.pose.position.z = 0.979 + random.uniform(-0.1, 0.1)
	goal.object_pose.pose.orientation.x, goal.object_pose.pose.orientation.y, goal.object_pose.pose.orientation.z, goal.object_pose.pose.orientation.w = quaternion_from_euler(random.uniform(-pi/2, pi/2),random.uniform(-pi/2, pi/2),random.uniform(-pi/2, pi/2))
	#goal.object_pose.pose.orientation.x, goal.object_pose.pose.orientation.y, goal.object_pose.pose.orientation.z, goal.object_pose.pose.orientation.w = quaternion_from_euler(-1.571, -0.000, -1.400)
	goal.gripper_type = "sdhx"
	#goal.gripper_side = ""
	goal.gripper_side = "left"

	#goal.grasp_database = "KIT"
	goal.grasp_database = "OpenRAVE"
	#goal.grasp_database = "ALL"
	#goal.grasp_id = 2
	goal.support_surface = "bookcase"

	# Sends the goal to the action server.
	pick_action_client.send_goal(goal)

	# Waits for the server to finish performing the action.
	finished_before_timeout=pick_action_client.wait_for_result(rospy.Duration(300, 0))

	if finished_before_timeout:
		state=pick_action_client.get_state()
		print("Action finished: %s"%state)
	else:
		print("Action did not finish within timeout")
	return

if __name__ == '__main__':
	try:
		# Initializes a rospy node so that the SimpleActionClient can
		# publish and subscribe over ROS.
		rospy.init_node('CobPickAction_client_py')
		cob_pick_action_client()
	except rospy.ROSInterruptException:
		print("program interrupted before completion")


# -*- coding: utf-8 -*-
"""
Created on Wed Aug 17 16:47:30 2016

@author: timothee.boulet
"""
def areAnagrams(str1, str2):
    # Sort both strings
    str1 = ''.join(sorted(str1))
    str2 = ''.join(sorted(str2))

    # Compare sorted strings
    for i in xrange(len(str1)):
        if str1[i] != str2[i]:
            return 0
    return 1

k=5
current=3
temp=[]
found=False
while True:
    test=k**3
    test_str=str(test)
    match=False
    if len(test_str)==current:
        for i,first in enumerate([numbers[0] for numbers in temp]):
            if areAnagrams(test_str, str(first))==1:
                match=True
                temp[i].append(test)
                break
        if match==False:
            temp.append([test])

    else:
        for i in xrange(len(temp)):
            if len(temp[i])==5:
                found=True
                print(min(temp[i]))
                break
        if found==True:
            break

        current=len(test_str)
        temp=[[test]]

    k+=1


#Escreva um programa para aprovar o emprestimo bancario para compra de uma casa.
# O programa deve perguntar o valor da casa a comprar, o salario e a quantidade de anos a pagar.
# O valor da prestação mensal não pode ser superior a 30% do salario.
# Calcule o valor da prestação como sendo o valor da casa a comprar dividido pelo número de meses a pagar.

casa=float(input("Qual é o valor da casa a comprar: "))
salario=float(input("Qual é o valor do seu Salario: "))
anos=int(input("Qual é a quantidade de anos a ser paga?"))
meses=anos*12
prestação=casa/meses
conta=salario*30/100
if prestação<=conta:
    print(f"Eprestimo Aprovado!! e o valor da prestação é de R${prestação:6.2f} e a quantidade é: {meses} Meses.")
else:
    print(f"Infelismente seu Eprestimo não foi Aprovado!!")

IPP(introduçãoa Programação Python)/Cap 4/Exercicio 4.9.py


# imports from system
from concurrent.futures import ThreadPoolExecutor as executor
import json, time
from typing import List, Optional
from datetime import datetime as dt

# import from packages
import requests
import pandas as pd
import pendulum

#import from app
from DBtransactions.DBtypes import Observation

__all__ = ["fetch"]

def build_url(fulltck: str, limit=None) -> str:
    """
    build the url of request to the BCB's api
    """""
    tck= fulltck.split(".")[1].upper()
    tck_new = tck if len(tck) > 2 else "0" + tck
    if not limit:
        return f"http://api.bcb.gov.br/dados/serie/bcdata.sgs.{tck_new}/dados?formato=json"
    return f"http://api.bcb.gov.br/dados/serie/bcdata.sgs.{tck_new}/dados/ultimos/{limit}?formato=json"

def _process(resp:requests.models.Response) -> Optional[dict]:
    """
    handles the successful response to a request the bcb api
    """
    if resp.ok:
        try:
            tck = str(int((resp.url).split("bcdata.sgs.")[1].split("/dados")[0]))
            obs = resp.json()
            return [Observation(**{'series_id': f"BCB.{tck}",
                                   'dat': pendulum.from_format(o['data'], "DD/MM/YYYY").to_date_string(),
                                   'valor': o['valor']}) for o in obs if o['valor']]
        except:
            print(f"Could not process {resp.url}")
            return None
    else:
        print(f"Failed request {resp.url}")
        return None

def fetch(tickers: List[str], limit: Optional[int]=None) -> List[Observation]:
    """
    Fetch the observations from the bcb's api.
    """
    urls = (build_url(tck, limit=limit) for tck in tickers)

    def _pos_process(obs):
        if obs is not None:
            return obs

    with requests.session() as session:
        with executor() as e:
            js = e.map(lambda url:_process(session.get(url)), list(urls))
    return list(filter(_pos_process, js))


from data.external_data import CovidData

from pyomo.environ import *
import numpy as np
from pyomo.opt import SolverFactory
import pyomo.environ

class TransOpt:

    def __init__(self, data):
        self.data = data

    def create_model(self, df_cases, time_horizon=28,start_day=120, n1=20000, n2=300, n3=100, n4=150):

        def haversine_np(lon1, lat1, lon2, lat2):
            """
            Calculate the great circle distance between two points
            on the earth (specified in decimal degrees)

            All args must be of equal length.

            """
            lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])

            dlon = lon2 - lon1
            dlat = lat2 - lat1

            a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2

            c = 2 * np.arcsin(np.sqrt(a))
            miles = 3959 * c
            return miles

        df_geo = self.data.df_geo.copy().reset_index()
        dc_geo = self.data.dc_geo.copy().reset_index()
        production_geo = self.data.production_geo.copy().reset_index()

        temp = dc_geo.assign(A=1).merge(df_geo.assign(A=1), on='A').drop('A', 1)
        temp['distance'] = haversine_np(temp['longitude_x'], temp['latitude_x'], temp['longitude_y'], temp['latitude_y'])
        distance_matrix_demand = temp.set_index(['FIPS_x', 'FIPS_y'])['distance'].to_dict()

        temp = production_geo.assign(A=1).merge(dc_geo.assign(A=1), on='A').drop('A', 1)
        temp['distance'] = haversine_np(temp['longitude_x'], temp['latitude_x'], temp['longitude_y'], temp['latitude_y'])
        distance_matric_production = temp.set_index(['FIPS_x', 'FIPS_y'])['distance'].to_dict()

        temp = dc_geo.assign(A=1).merge(dc_geo.assign(A=1), on='A').drop('A', 1)
        temp['distance'] = haversine_np(temp['longitude_x'], temp['latitude_x'], temp['longitude_y'], temp['latitude_y'])
        distance_matrix_dc = temp.set_index(['FIPS_x', 'FIPS_y'])['distance'].to_dict()

        miles_per_day = 650
        transit_time_dc_dem = {k:int(v/miles_per_day) + 1 for k,v in distance_matrix_demand.items()}
        transit_time_dc_dc = {k:int(v/miles_per_day) + 1 for k,v in distance_matrix_dc.items()}
        transit_time_prod_dc = {k:int(v/miles_per_day) + 1 for k,v in distance_matric_production.items()}
        # Creation of a Concrete Model
        self.model = ConcreteModel()

        holding_capacities = {'47137':160000,'56027':60000, '41033': 25000, '39109': 120000}
        start_capacities = {'47137':n1,'56027':n2, '41033': n3, '39109': n4}
        production_capacity = {'13103':500000,'26119':250000, '38027': 100000}
        shipping_times = None

        self.model.dcs = Set(initialize=holding_capacities.keys(), doc='DC')
        self.model.demand_nodes = Set(initialize=df_geo['FIPS'], doc='Demand_nodes')
        self.model.production_nodes = Set(initialize=production_capacity.keys())
        self.model.t = Set(initialize=range(time_horizon), doc='horizon')

        demand = dict()
        for k,v in df_cases.iloc[start_day:start_day + time_horizon].reset_index().drop(columns = 'date').to_dict().items():
            for kk, vv in v.items():
                demand[k,kk] = vv

        self.model.holding_capacities = Param(self.model.dcs, initialize=holding_capacities, doc='Holding Capacity of DC i in cases per day')
        self.model.production_capacities = Param(self.model.production_nodes, initialize=production_capacity, doc='Holding Capacity of DC i in cases per day')

        self.model.demand = Param(self.model.demand_nodes, self.model.t, initialize=demand, doc='Demand at market j in cases')

        self.model.dist_mat_dem = Param(self.model.dcs,self.model.demand_nodes, initialize=distance_matrix_demand, doc='Distance in miles')
        self.model.dist_mat_dc = Param(self.model.dcs,self.model.dcs, initialize=distance_matrix_dc, doc='Distance in miles from dc to dc')
        self.model.dist_mat_prod_dc = Param(self.model.production_nodes, self.model.dcs, initialize= distance_matric_production, doc = 'distacne in miled to prod plants to DCs')
        #  Scalar f  freight in dollars per case per thousand miles  /90/ ;
        self.model.freight_cost_dc_dem = Param(initialize=0.01, doc='Freight in dollars per case per mile from a dc to a demand node')
        self.model.freight_cost_dc_dc = Param(initialize = 0.002, doc = 'Freight cost from dc to dc in dollars per case per mile')
        self.model.storage_cost = Param(initialize=0.001, doc = 'cost of storing case at dc')
        self.model.production_cost = Param(initialize = 0.009, doc = 'production price per unit')

        def cost_init(model, i, j):
            return model.freight_cost_dc_dem * (model.dist_mat_dem[i,j] + 10.0) / 1000.0

        def cost_dc(model,i,j):
            if i != j:
                val = model.freight_cost_dc_dc* (model.dist_mat_dc[i,j] + 10.0)/1000.0
                return val
            else:
                return 1000.0

        def cost_prod_dc(mode, i ,j):
            return self.model.freight_cost_dc_dc *  (self.model.dist_mat_prod_dc[i,j] + 10.0)/1000.0

        self.model.c = Param(self.model.dcs, self.model.demand_nodes, initialize=cost_init, doc='Transport cost in thousands of dollar per case')
        self.model.c_dc = Param(self.model.dcs, self.model.dcs, initialize=cost_dc, doc = 'transport cost from dc to dc cheaper than other freight cost')
        self.model.c_prod = Param(self.model.production_nodes, self.model.dcs, initialize=cost_prod_dc, doc = 'transport cost from prod to dc cheaper than other freight cost')

        self.model.cases_dc_dem = Var(self.model.dcs, self.model.demand_nodes, self.model.t, bounds=(0.0,None), doc='Shipment quantities in case to demand')
        self.model.cases_held = Var(self.model.dcs, self.model.t, bounds = (0,None), doc = 'cases held at dc')
        self.model.cases_dc_dc = Var(self.model.dcs, self.model.dcs, self.model.t, bounds=(0.0,None), doc = 'shipment quantities in cases between dcs')
        self.model.cases_produced = Var(self.model.production_nodes, self.model.t, bounds = (0.0,None), doc = 'number of units produced')
        self.model.cases_prod_dc = Var(self.model.production_nodes, self.model.dcs, self.model.t, bounds=(0.0,None), doc = 'shipment quantities in cases between production and dcs')

        self.model.continuity_cases = ConstraintList()
        for dc in self.model.dcs:
            for t in self.model.t:
                if t == 0:
                    self.model.continuity_cases.add(self.model.cases_held[dc,t] == start_capacities[dc])
                else:
                    const = self.model.cases_held[dc,t-1]
                    try:
                        const -= sum(self.model.cases_dc_dem[dc, demand_node, t+transit_time_dc_dem[dc,demand_node]] for demand_node in self.model.demand_nodes)
                    except:
                        pass
                    try:
                        const -= sum(self.model.cases_dc_dc[dc,dc2,t+transit_time_dc_dc[dc,dc2]] for dc2 in self.model.dcs)
                    except:
                        pass
                    try:
                        const += sum(self.model.cases_dc_dc[dc1, dc, t+transit_time_dc_dc[dc1,dc]] for dc1 in self.model.dcs)
                    except:
                        pass
                    try:
                        const += sum(self.model.cases_prod_dc[prod_node, dc, t+transit_time_prod_dc[prod_node,dc]] for prod_node in self.model.production_nodes)
                    except:
                        pass

                    self.model.continuity_cases.add(self.model.cases_held[dc,t] == const)

        def supply_rule(model, i,t):
            return sum(model.cases_dc_dem[i,j,t] for j in model.demand_nodes) <= model.cases_held[i,t]
        self.model.supply = Constraint(self.model.dcs, self.model.t, rule=supply_rule, doc='Observe supply limit at plant i')

        def production_rule(model, i, t):
            return model.cases_produced[i,t] <= production_capacity[i]
        self.model.produce = Constraint(self.model.production_nodes, self.model.t, doc='production capacities')

        def production_shipped_rule(model, i, t):
            return model.cases_produced[i, t] == sum(model.cases_prod_dc[i,dc,t] for dc in model.dcs) + 100
        self.model.production_continuity = Constraint(self.model.production_nodes, self.model.t, rule = production_shipped_rule, doc = 'production continuity')

        def demand_rule(model, j,t):
            return sum(model.cases_dc_dem[i,j,t] for i in model.dcs) >= model.demand[j,t] * 0.2
        self.model.demand_constr = Constraint(self.model.demand_nodes, self.model.t, rule=demand_rule, doc='Satisfy demand at market j')

        self.model.demand_costs = sum(self.model.c[i,j]*self.model.cases_dc_dem[i,j,t] for i in self.model.dcs for j in self.model.demand_nodes for t in self.model.t)
        self.model.dc_inter_costs = sum(self.model.c_dc[i,j]*self.model.cases_dc_dc[i,j,t] for i in self.model.dcs for j in self.model.dcs for t in self.model.t)
        self.model.storage_costs = sum(self.model.cases_held[dc,t] * self.model.storage_cost for dc in self.model.dcs for t in self.model.t)
        self.model.prod_trans_costs = sum(self.model.c_prod[i,j]*self.model.cases_prod_dc[i,j,t] for i in self.model.production_nodes for j in self.model.dcs for t in self.model.t)
        self.model.production_costs = sum(self.model.cases_produced[prod,t] * self.model.production_cost for prod in self.model.production_nodes for t in self.model.t)
        self.model.difference_in_demand = sum(sum(self.model.cases_dc_dem[i,j,t] for i in self.model.dcs) +  1*self.model.demand[j,t] for j in self.model.demand_nodes for t in self.model.t)

        def objective_rule(model):
            return model.demand_costs + model.storage_costs + model.dc_inter_costs + model.production_costs + model.prod_trans_costs + 1000000.0*model.difference_in_demand
        self.model.objective = Objective(rule=objective_rule, sense=minimize, doc='Define objective function')
        return self

    def solve(self):
        opt = SolverFactory("cbc", executable='C:\\Users\\Sam Cox\\Documents\\cbc\\Cbc-windeps-win64-msvc15-mtd\\bin\\cbc.exe')
        self.results = opt.solve(self.model)
        return self

if __name__ == '__main__':
    data = CovidData()
    data.get_county_cases()
    data.get_county_coordinates()
    trans_opt = TransOpt(data)
    trans_opt.create_model(trans_opt.data.df_cases)
    trans_opt.solve()
    trans_opt.model.objective.display()
    trans_opt.results.write()
    m= trans_opt.model

    print([[trans_opt.model.cases_produced[i, t].value for i in trans_opt.model.production_nodes] for t in trans_opt.model.t])
    print([[trans_opt.model.cases_held[i, t].value for i in trans_opt.model.dcs] for t in trans_opt.model.t])
    print(trans_opt.model.demand_costs(), trans_opt.model.storage_costs(), trans_opt.model.production_costs(), trans_opt.model.dc_inter_costs(), trans_opt.model.difference_in_demand())
    print([[[m.cases_prod_dc[prod,dc,t].value for prod in trans_opt.model.production_nodes] for dc in m.dcs] for t in m.t])


import os
import moviepy.video.io.ImageSequenceClip as mv

ro = '/home/na/1_Face_morphing/2_data/3_ganformer_v3/5_latentcode_exp/'
src_path = ro + '1_use_fixed_image/'
fps = 1

folder = os.listdir(src_path)
for fold in folder:
    if os.path.isdir(src_path + fold) is False:
        continue
    dst_path = src_path + fold + '.mp4'

    img_list = os.listdir(src_path + fold)
    img_list.sort()

    image_files = [os.path.join(src_path + fold, img)
                   for img in img_list
                   if img.endswith(".png")]
    clip = mv.ImageSequenceClip(image_files, fps=fps)

    clip.write_videofile(dst_path)


from django.shortcuts import render

import requests
import json
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status

class Divvy_Bikes(APIView):
    def post(self,request):
        try:
            response = requests.get("https://gbfs.divvybikes.com/gbfs/en/station_status.json")
            data = response.json()
            total_docks_avl = 0
            total_bikes_avl = 0
            total_station_active = 0
            total_bikes_reserved = 0

            for i in data["data"]["stations"]:
                total_docks_avl += i["num_docks_available"]
                total_bikes_avl += i["num_bikes_available"]
                if i["station_status"]=="active":
                    total_station_active += 1

            response1 = requests.get("https://gbfs.divvybikes.com/gbfs/en/free_bike_status.json")
            data1 = response1.json()
            for i in data1["data"]["bikes"]:
                total_bikes_reserved += i["is_reserved"]

            return Response({
                "Total Docks Avl":total_docks_avl,
                "Total Bikes Avl":total_bikes_avl,
                "Total Station Active":total_station_active,
                "Total Bikes Reserved":total_bikes_reserved
            },status=status.HTTP_200_OK)
        except:
            return Response({"message":"something went wrong"},status=status.HTTP_500_INTERNAL_SERVER_ERROR)


'''
Un tipo abstracto de datos es un determinado objeto que trata de obtener un tipo de infomacion por ejmeplo int float etc.
Una estructura de datos es la manera en programacion en la que yo construyo y organizo
tipos complejos de datos son aquellos que estan formados por multiples componentes como list o diccionary
'''

class CreditCard:
    def __init__(self, customer, idCard, limit):

        self.__customer = customer
        self.__idCard = idCard
        self.__limit = limit
        self.__balance = 0

class complejo:  #clase para crear numeros complejos
    def __init__(self, Re=0, Im=0):
        self.Re = Re
        self.Im = Im

    def __str__(self):
        if self.Re == 0 and self.Im == 0:
            give = "0"
        elif self.Re == 0:
            give = str(self.Im) + "i"
        elif self.Im == 0:
            give = str(self.Re)
        else:
            give = "{} + {}i".format(self.Re, self.Im)
        return give

    def __add__(self, z):
        r = complejo()
        r.Re = self.Re + z.Re
        r.Im = self.Im + z.Im
        return r

    def __sub__(self, z):
        r = complejo()
        r.Re = self.Re - z.Re
        r.Im = self.Im - z.Re
        return r

    def mod(self):
        operacion = (self.Re**2 + self.Im**2)**0.5
        return operacion

z1 = complejo(3, 4)
z2 = complejo(8, 5)
print(z1.mod())
print(z1+z2)
print(z1)

Estructura de datos y algoritmos/Tipos de datos abstractos/Abstraccion.py


import copy
from enum import IntEnum
from typing import List, Optional, Sequence, Tuple

from tetris.constants import (
    BOARD_HEIGHT,
    BOARD_WIDTH,
    LINE_CLEAR_SCORES,
    BoardState,
    Cell,
)
from tetris.piece import Piece

class Action(IntEnum):
    NOOP = 0
    ROTATE_ANTICLOCKWISE = 1
    ROTATE_CLOCKWISE = 2
    MOVE_LEFT = 3
    MOVE_RIGHT = 4
    HARD_DROP = 5

class Board:
    board: BoardState
    piece: Optional[Piece]
    running: bool

    def __init__(self) -> None:
        self.board = [[None] * BOARD_WIDTH for _ in range(BOARD_HEIGHT)]
        self.piece = None

    def set_piece(self, piece: Piece) -> None:
        """Sets a piece to be the current piece being controlled.

        Args:
            piece (Piece): A Tetris piece.
        """

        self.piece = piece

    def is_game_running(self) -> bool:
        """Checks the board to see if there are any cells filled in the top playable row.
           If there are, the player has lost the game.

        Returns:
            bool: False if the board has any pieces in the top row else True.
        """

        return self.board[1].count(None) == BOARD_WIDTH

    def copy(self) -> BoardState:
        """Copies the internal board state.

        Returns:
            BoardState: The board.
        """

        return copy.deepcopy(self.board)

    def get_changes(self, old_board: BoardState) -> List[Tuple[str, int, int]]:
        """Identifies differences between the current board and another board state.

        Args:
            old_board (BoardState): The board to compare against.

        Returns:
            List[Tuple[str, int, int]]: A list of changes in the form (cell_value, y, x).
        """

        return [
            ("N" if not self.board[i][j] else self.board[i][j], i, j)
            for i, row in enumerate(old_board)
            for j, piece_type in enumerate(row)
            if self.board[i][j] != piece_type
        ]

    def find_lines_to_clear(self) -> List[int]:
        """Iterates through each row in the board to see if it's full and can be cleared.

        Returns:
            List[int]: Indices of each row that needs to be cleared.
        """

        return [i for i in reversed(range(BOARD_HEIGHT)) if None not in self.board[i]]

    def clear_lines(self, line_indices: List[int]) -> int:
        """Removes each row to be cleared from the board and adds empty rows to the top.
           Gets the score based on how many rows have been cleared.

        Args:
            line_indices (List[int]): The list of index rows to be cleared.

        Returns:
            int: The score that the number of cleared lines are worth.
        """

        if not line_indices:
            return 0

        for i in sorted(line_indices, reverse=True):
            del self.board[i]

        self.board = [
            [None] * BOARD_WIDTH for _ in range(len(line_indices))
        ] + self.board

        return LINE_CLEAR_SCORES[len(line_indices)]

    def update_board(self, old: List[Cell], new: List[Cell]) -> None:
        """Updates the board based on old and new locations of the current piece.

        Lists can be empty if no changes.

        Args:
            old (List[Cell]): The old (y, x) coordinates of the piece to be removed.
            new (List[Cell]): The new (y, x) coordinates of the piece to be added.
        """

        for old_cell in old:
            if 0 <= old_cell[0] < BOARD_HEIGHT and 0 <= old_cell[1] < BOARD_WIDTH:
                self.board[old_cell[0]][old_cell[1]] = None
            else:
                raise RuntimeError("Cell out of bounds of the board.")

        for new_cell in new:
            if 0 <= new_cell[0] < BOARD_HEIGHT and 0 <= new_cell[1] < BOARD_WIDTH:
                self.board[new_cell[0]][new_cell[1]] = self.piece.piece_type
            else:
                raise RuntimeError("Cell out of bounds of the board.")

    def spawn_piece(self) -> bool:
        """Spawns the board object's current piece on the board.

        If this piece has spawned inside another piece, set it to landed.

        Returns:
            bool: Whether the piece could be spawned successfully
        """

        new_piece_location = self.piece.spawn_piece()
        for coord in new_piece_location:
            if self.board[coord[0]][coord[1]]:
                self.piece.landed = True
                return False

        self.update_board([], new_piece_location)

        return True

    def move_piece_left(self) -> None:
        """Moves the current piece left and updates board if required."""

        old, new = self.piece.move_left(self.board)

        if (old is None) ^ (new is None):
            raise RuntimeError("Error computing piece move left.")

        if old and new:
            self.update_board(old, new)

    def move_piece_right(self) -> None:
        """Moves the current piece right and updates board if required."""

        old, new = self.piece.move_right(self.board)

        if (old is None) ^ (new is None):
            raise RuntimeError("Error computing piece move right.")

        if old and new:
            self.update_board(old, new)

    def rotate_piece_clockwise(self) -> None:
        """Rotates the current piece clockwise and updates board if required."""

        old, new = self.piece.rotate_clockwise(self.board)

        if (old is None) ^ (new is None):
            raise RuntimeError("Error computing piece rotate clockwise.")

        if old and new:
            self.update_board(old, new)

    def rotate_piece_anticlockwise(self) -> None:
        """Rotates the current piece anticlockwise and updates board if required."""

        old, new = self.piece.rotate_anticlockwise(self.board)

        if (old is None) ^ (new is None):
            raise RuntimeError("Error computing piece rotate anticlockwise.")

        if old and new:
            self.update_board(old, new)

    def fall(self) -> None:
        """Drops the current piece one position if it has not yet landed and updates the board if required."""

        self.piece.landed = self.piece.has_landed(self.board)
        if not self.piece.landed:
            old, new = self.piece.fall()

            if (old is None) ^ (new is None):
                raise RuntimeError("Error computing piece fall.")

            self.update_board(old, new)

    def apply_action(self, action: Action) -> None:
        """Applies an action to the current board.

        Args:
            action (Action): The action to apply.
        """

        if action == Action.HARD_DROP:
            while not self.piece.landed:
                self.fall()
            return
        elif action == Action.ROTATE_ANTICLOCKWISE:
            self.rotate_piece_anticlockwise()
        elif action == Action.ROTATE_CLOCKWISE:
            self.rotate_piece_clockwise()
        elif action == Action.MOVE_LEFT:
            self.move_piece_left()
        elif action == Action.MOVE_RIGHT:
            self.move_piece_right()

        self.fall()

    def with_move(self, action: Action) -> "Board":
        """Copies and returns the current board with a single action applied.

        Args:
            action (Action): The action to apply.

        Returns:
            Board: A copy of the current board with the action applied.
        """

        return self.with_moves([action])

    def with_moves(self, actions: Sequence[Action]) -> "Board":
        """Copies and returns the current board with the sequence of actions applied.

        Args:
            actions (List[Action]): A list of actions to perform.

        Returns:
            Board: A copy of the current board with the actions applied.
        """

        board = copy.deepcopy(self)

        for action in actions:
            board.apply_action(action)

            if board.piece.landed:
                break

        return board

    def __getitem__(self, y):
        """Accesses board rows."""

        return self.board[y]


import datetime
from typing import List, Optional

import numpy as np
from ..common import (
    ActionType, Context, DataSource, Processor, ProcessorFactory, TradingFrequency,
    Position, ProcessorAction, Mode, DATETIME_TYPE, DAYS_IN_A_QUARTER)
from ..stock_universe import IntradayVolatilityStockUniverse

NUM_UNIVERSE_SYMBOLS = 20
EXIT_TIME = datetime.time(16, 0)
# 3 hours only works if 1 hour and 2 hours are not triggered
PARAMS = [(10, 1), (13, 1), (25, 1.75), (30, 2.25), (37, 2.25)]

class H2lHourProcessor(Processor):

    def __init__(self,
                 lookback_start_date: DATETIME_TYPE,
                 lookback_end_date: DATETIME_TYPE,
                 data_source: DataSource,
                 output_dir: str) -> None:
        super().__init__(output_dir)
        self._positions = dict()
        self._stock_universe = IntradayVolatilityStockUniverse(lookback_start_date,
                                                               lookback_end_date,
                                                               data_source,
                                                               num_stocks=NUM_UNIVERSE_SYMBOLS)

    def get_trading_frequency(self) -> TradingFrequency:
        return TradingFrequency.FIVE_MIN

    def setup(self, hold_positions: List[Position], current_time: Optional[DATETIME_TYPE]) -> None:
        to_remove = [symbol for symbol, position in self._positions.items()
                     if position['status'] != 'active']
        for symbol in to_remove:
            self._positions.pop(symbol)

    def get_stock_universe(self, view_time: DATETIME_TYPE) -> List[str]:
        return list(set(self._stock_universe.get_stock_universe(view_time) +
                        list(self._positions.keys())))

    def process_data(self, context: Context) -> Optional[ProcessorAction]:
        if self.is_active(context.symbol):
            return self._close_position(context)
        elif (context.symbol not in self._positions or
              self._positions[context.symbol]['status'] == 'pending'):
            return self._open_position(context)

    def _open_position(self, context: Context) -> Optional[ProcessorAction]:
        t = context.current_time.time()
        if t >= EXIT_TIME:
            return
        interday_closes = context.interday_lookback['Close']
        # Avoid short squeeze caused by retail trader
        if max(interday_closes[-1], context.current_price) / interday_closes[-5] > 4:
            return
        market_open_index = context.market_open_index
        if market_open_index is None:
            return
        intraday_closes = context.intraday_lookback['Close'][market_open_index:]
        if len(intraday_closes) < 10:
            return
        if context.current_price > np.min(intraday_closes):
            return
        if abs(context.current_price / context.prev_day_close - 1) > 0.5:
            return
        intraday_opens = context.intraday_lookback['Open'][market_open_index:]
        if intraday_opens[-1] > context.prev_day_close > intraday_closes[-1]:
            return
        if interday_closes[-1] > 10 * np.min(interday_closes[-DAYS_IN_A_QUARTER:]):
            return
        h2l_avg = context.h2l_avg
        h2l_std = context.h2l_std
        lower_threshold = max(h2l_avg - 3 * h2l_std, -0.5)
        for n, z in PARAMS:
            if len(intraday_closes) < n:
                continue
            current_loss = context.current_price / intraday_closes[-n] - 1
            z0 = 0.1 if t < datetime.time(11, 0) or t > datetime.time(15, 0) else 0
            upper_threshold = h2l_avg - (z + z0) * h2l_std
            is_trade = lower_threshold < current_loss < upper_threshold
            if is_trade or (context.mode == Mode.TRADE and current_loss < upper_threshold * 0.8):
                self._logger.debug(f'[{context.current_time.strftime("%F %H:%M")}] [{context.symbol}] '
                                   f'Current loss: {current_loss * 100:.2f}%. N: {n}. '
                                   f'Threshold: {lower_threshold * 100:.2f}% ~ {upper_threshold * 100:.2f}%. '
                                   f'Current price {context.current_price}.')
            if is_trade:
                self._positions[context.symbol] = {'entry_time': context.current_time,
                                                   'status': 'pending', 'n': n}
                return ProcessorAction(context.symbol, ActionType.BUY_TO_OPEN, 1)

    def _close_position(self, context: Context) -> Optional[ProcessorAction]:
        position = self._positions[context.symbol]
        intraday_closes = context.intraday_lookback['Close']
        index = -position['n'] - (context.current_time - position['entry_time']).seconds // 300
        stop_loss = False
        if len(intraday_closes) >= abs(index):
            current_loss = context.current_price / intraday_closes[index] - 1
            lower_threshold = max(context.h2l_avg - 3 * context.h2l_std, -0.5)
            stop_loss = current_loss < lower_threshold
        if (stop_loss or
                context.current_time >= position['entry_time'] + datetime.timedelta(minutes=35) or
                context.current_time.time() >= EXIT_TIME):
            self._logger.debug(f'[{context.current_time.strftime("%F %H:%M")}] [{context.symbol}] '
                               f'Closing position. Current price {context.current_price}.')
            position['status'] = 'inactive'
            return ProcessorAction(context.symbol, ActionType.SELL_TO_CLOSE, 1)

class H2lHourProcessorFactory(ProcessorFactory):

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

    def create(self,
               lookback_start_date: DATETIME_TYPE,
               lookback_end_date: DATETIME_TYPE,
               data_source: DataSource,
               output_dir: str,
               *args, **kwargs) -> H2lHourProcessor:
        return H2lHourProcessor(lookback_start_date, lookback_end_date, data_source, output_dir)


print("Cost of PINK tickets:")
p_cost = int(input())

print("Cost of GREEN tickets:")
g_cost = int(input())

print("Cost of RED tickets:")
r_cost = int(input())

print("Cost of ORANGE tickets:")
o_cost = int(input())

print("How much must be raised with ticket sales?")
total = int(input())

total = [total,total,total,total]

pink = [0,0,0,0]
green = [0,0,0,0]
red = [0,0,0,0]
orange = [0,0,0,0]

while total[0] > 0:
    while total[0] >= o_cost:
            total[0] = total[0] - o_cost
            orange[0] += 1
    while total[0] >= r_cost:
            total[0] = total[0] - r_cost
            red[0] += 1
    while total[0] >= g_cost:
            total[0] = total[0] - g_cost
            green[0] += 1
    while total[0] >= p_cost:
            total[0] = total[0] - p_cost
            pink[0] += 1

while total[1] > 0:
    while total[1] >= r_cost:
        total[1] = total[1] - r_cost
        red[1] += 1
    while total[1] >= g_cost:
        total[1] = total[1] - g_cost
        green[1] += 1
    while total[1] >= p_cost:
        total[1] = total[1] - p_cost
        pink[1] += 1

while total[2] > 0:
    while total[2] >= g_cost:
        total[2] = total[2] - g_cost
        green[2] += 1
    while total[2] >= p_cost:
        total[2] = total[2] - p_cost
        pink[2] += 1

while total[3] > 0:
    while total[3] >= p_cost:
        total[3] = total[3] - p_cost
        pink[3] += 1

combinations = list()
for i in range(4):
    combinations.append([pink[4-1-i], green[4-1-i], red[4-1-i], orange[4-1-i]])

combinations = set(combinations)
print(combinations)


from django.urls import path,include
from .import views

urlpatterns = [
    path('blog/category/<str:cats>/',views.CategoryView,name='blog.list'),
    path('blog/<int:pk>', views.BlogDetailview.as_view(),name='blog.detail'),
    path('blog/new', views.BlogCreateView.as_view(),name='blog.new'),
    path('blog/<int:pk>/edit', views.BlogUpdateView.as_view(),name='blog.edit'),
    path('blog/<int:pk>/delete', views.BlogDeleteView.as_view(),name='blog.delete'),
    path('blog/upload', views.upload,name='uploads'),
    path('blog/upload/file', views.file_upload),
    path('blog/upload/photo', views.photo_list,name="photo.list"),
    # path('blog/upload/photo/pdf', views.download_pdf,name="pdf"),
]


import numpy as np
import time
import random

""" A = []
for i in range(0,10000):
    n = random.randint(-1000,1000)
    A.append(n)

t0 = time.clock()

t1 = time.clock() - t0
print("first implementation ", t1)
"""

S = "aabbccder"
C= [1,5,6,7,10,2,5,6,9]
cost = 0

for index in range(len(S)-1):
    if S[index] == S[index + 1]:
        cost += C[index]

print(cost)


"""Structure selection methods from feature matrices."""
from warnings import warn

import numpy as np

def select_initial_rows(
    femat, n_select=10, method="leverage", num_external_terms=0, keep_indices=None
):
    """Select structures to initialize an empty CE project.

    Args:
        femat(2D arrayLike):
            Correlation vectors of each structure.
        n_select(int): optional
            Number of structures to select. Default is 10.
        method(str): optional
            The method used to select structures. Default is
            base on leverage score, which minimizes the Frobenius
            norm difference between the covariance matrix of all
            structures and the covariance matrix of a selection.
            "random" is also supported.
        num_external_terms(int): optional
            Number of external terms in cluster subspace. These
            terms should not be compared in a structure selection.
        keep_indices(list of int): optional
            Indices of structures that must be selected. Usually
            those of important ground state structures.

    Returns:
        list of int:
            Indices of selected rows in the feature matrix,
            corresponding to the selected structures.
    """
    # Leave out external terms.
    a = np.array(femat)[:, : len(femat[0]) - num_external_terms]
    n, d = a.shape

    if keep_indices is None:
        keep_indices = []
    n_keep = len(keep_indices)
    if n_keep > n:
        raise ValueError("Can not keep more structures than provided!")
    if n_keep > n_select:
        warn(
            "Keeping more structures than to be selected!"
            " Cannot select new structures."
        )
        return keep_indices
    if n_select > n:
        warn(
            "Structures to select more than provided,"
            " will select all provided structures."
        )
        return list(range(n))
    dn = n_select - n_keep

    selected_indices = np.array(keep_indices, dtype=int)
    available_indices = np.setdiff1d(np.arange(n, dtype=int), keep_indices)

    cov = a.T @ a  # Covariance matrix of features.

    for _ in range(dn):
        if method == "leverage":
            errs = []
            for trial_index in available_indices:
                trial_indices = np.append(selected_indices, trial_index)
                a_trial = a[trial_indices, :]
                cov_trial = a_trial.T @ a_trial
                errs.append(np.sum((cov - cov_trial) ** 2))

            select_index = available_indices[np.argmin(errs)]

        elif method == "random":
            select_index = np.random.choice(available_indices)

        else:
            raise NotImplementedError

        selected_indices = np.append(selected_indices, select_index)
        available_indices = np.setdiff1d(available_indices, [select_index])

    return selected_indices.tolist()

# TODO: implement composition dependent domain matrices. (not urgent)
def select_added_rows(
    femat,
    old_femat,
    n_select=10,
    method="leverage",
    keep_indices=None,
    num_external_terms=0,
    domain_matrix=None,
):
    """Select structures to add to an existing CE project.

    We select structures by minimizing the leverage score under a
    certain domain matrix, or fully at random.
    Refer to `T. Mueller et al. <https://doi.org/10.1103/PhysRevB.82.184107>`_

    Args:
        femat(2D arraylike):
            Correlation vectors of new structures.
        old_femat(2D arraylike):
            Existing old feature matrix.
        n_select(int): optional
            Number of structures to select. Default is 10.
        method(str): optional
            The method used to select structures. Default is
            by maximizing leverage score reduction ("leverage").
            "random" is also supported.
        keep_indices(list of int): optional
            Indices of structures that must be selected. Usually
            those of important ground state structures.
        num_external_terms(int): optional
            Number of external terms in cluster subspace. These
            terms should not be compared in a structure selection.
        domain_matrix(2D arraylike): optional
            The domain matrix used to compute leverage score. By
            default, we use an identity matrix.

    Returns:
        list of int:
            Indices of selected rows in the feature matrix,
            corresponding to the selected structures.
    """
    # Leave out external terms.
    a = np.array(femat)[:, : len(femat[0]) - num_external_terms]
    old_a = np.array(old_femat)[:, : len(old_femat[0]) - num_external_terms]
    n, d = a.shape
    if domain_matrix is None:
        domain_matrix = np.eye(d)
    domain_matrix = np.array(domain_matrix)
    # Using an identity matrix as the domain matrix by default.

    if keep_indices is None:
        keep_indices = []
    n_keep = len(keep_indices)
    if n_keep > n:
        raise ValueError("Can not keep more structures than provided!")
    if n_keep > n_select:
        warn(
            "Keeping more structures than to be selected!"
            " Cannot select new structures."
        )
        return keep_indices
    if n_select > n:
        warn(
            "Structures to select more than provided,"
            " will select all provided structures."
        )
        return list(range(n))
    dn = n_select - n_keep

    selected_indices = np.array(keep_indices, dtype=int)
    available_indices = np.setdiff1d(np.arange(n, dtype=int), keep_indices)

    # Used Penrose-Moore inverse
    for _ in range(dn):
        if method == "leverage":
            # Update feature matrix.
            prev_a = np.concatenate((old_a, a[selected_indices, :]), axis=0)
            prev_cov = prev_a.T @ prev_a
            prev_inv = np.linalg.pinv(prev_cov)
            reductions = []
            for trial_index in available_indices:
                trial_indices = np.append(selected_indices, trial_index)
                trial_a = np.concatenate((old_a, a[trial_indices, :]), axis=0)
                trial_cov = trial_a.T @ trial_a
                trial_inv = np.linalg.pinv(trial_cov)
                # By assertion, should all be <= 0.
                reductions.append(
                    np.sum(np.multiply((trial_inv - prev_inv), domain_matrix))
                )

            select_index = available_indices[np.argmin(reductions)]

        elif method == "random":
            select_index = np.random.choice(available_indices)

        else:
            raise NotImplementedError

        selected_indices = np.append(selected_indices, select_index)
        available_indices = np.setdiff1d(available_indices, [select_index])

    return selected_indices.tolist()


#/usr/bin/python3

#String Equivalence Model Solver

#Copyright (c) 2017 Adam Labecki

#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:

#The above copyright notice and this permission notice shall be included in all
#copies or substantial portions of the Software.

#For further details see LICENSE

from sympy import Symbol
from sympy.abc import*
from sympy.logic.boolalg import to_cnf
from sympy.logic.boolalg import Not, And, Or
from sympy.logic.inference import satisfiable, valid
from mpmath import*
from itertools import product
import sys
from copy import deepcopy
from shutil import copyfile
from itertools import*
import os
import re
from sympy import simplify

from se_classes import*
from se_functions import*
#from win32 import win32print

commands = {
	"1": "Get SE models of a logic program (from file with one program)",
	"2": "Check if logic program  A entails logic program B (from file with two programs)",
	"3": "Exit"
}

additionA = {
	"1": "Write models to .txt",
	"2": "Add rule to program and regenerate SE Models",
	"3": "Remove rule from program and regenerate SE Models",
	"4": "Return to Primary Commands"
}

additionB = {
	"1": "Write models to .txt",
	"2": "Add rule to program A and regenerate SE Models",
	"3": "Add rule to program B and regenerate SE Models",
	"4": "Remove rule from program A and regenerate SE Models",
	"5": "Remove rule from program B and regenerate SE Models",
	"6": "Return to Primary Commands"
}

second = "SECOND"

if sys.stdin.isatty() == False:
	single = True

	file = sys.stdin.readlines()
	for line in file:
		if second in line:
  			single = False
	if single == True:
		propositions = obtain_atomic_formulas(file)

		rules = construct_program(file, "A")		# parses input text, make a Rule object for each rule, saves objects in dictionary

		model = initialize(rules, propositions, "A")
		rep = "{"+"}"
		for m in model:
	 		if str(m.X) == "set()":
	 			m.X = rep
	 		if str(m.Y) == "set()":
	 			m.Y = rep
	 		print("< %s, %s >" % (m.X, m.Y))
		print("\n")
		#file.close()
	else:
		propositions = obtain_atomic_formulas(file)
		rulesA = construct_program(file, "A")		# parses input text, make a Rule object for each rule, saves objects in dictionary
		#print("number of rules: %s" % len(rules))
		rulesB = construct_program(file, "B")		# parses input text, make a Rule object for each rule, saves objects in dictionary
		modelA = initialize(rulesA, propositions, "A")
		modelB = initialize(rulesB, propositions, "B")

		rep = "{"+"}"
		for m in modelA:
			if str(m.X) == "set()":
				m.X = rep
			if str(m.Y) == "set()":
				m.Y = rep
			print("< %s, %s >" % (m.X, m.Y))
		print("\n")
		print(second)
		print("\n")
		for m in modelB:
			if str(m.X) == "set()":
				m.X = rep
			if str(m.Y) == "set()":
				m.Y = rep
			print("< %s, %s >" % (m.X, m.Y))

else:
	print("\n \n")
	print ("=================================================================================== ")
	print("____________________________________________________________________________________\n")
	print("--------------- Welcome to the Strong Equivalence Solver ---------------------------")
	print("_____________________________________________________________________________________ \n")
	print ("==================================================================================== \n")

	while(True):
		do = ""
		while do not in commands.keys():
			for k, v in sorted(commands.items()):
				print("%s: %s" % (k, v))
			print("\n")
			do = input()
		if(do == "3"):
			sys.exit()
		if(do == "1"):
			res = get_file()
			if len(res) == 0:
				continue
			file = res[0]
			file_name = res[1]
			file.seek(0)
			propositions = obtain_atomic_formulas(file)
			file.seek(0)
			rules = construct_program(file, "A")		# parses input text, make a Rule object for each rule, saves objects in dictionary
			file.seek(0)
			#print("number of rules: %s" % len(rules))
			print("Program rules: ")
			for r in rules.values():
				print (r.name, r.item)
			model = initialize(rules, propositions, "A")
			print("\n")
			print("----------------------------------------------------------------------------------")
			print("Models")
			print("----------------------------------------------------------------------------------")
			rep = "{"+"}"
			for m in model:
				if str(m.X) == "set()":
					m.X = rep
				if str(m.Y) == "set()":
					m.Y = rep
				print("< %s, %s >" % (m.X, m.Y))
			print("\n")
			file.close()

			more = True
			while more == True:
				print("Would you like to do anything else with this program?---------------------------")
				for k, p in sorted(additionA.items()):
					print("%s: %s" % (k, p))
				print("\n")
				opt = ""
				while (opt not in additionA.keys()):
					opt = input()
				if opt == "1":
					save = create_txt_single(model, rules)
					#print(save)
				if opt == "2":
					print("Please enter a new rule to add to the Program")
					new_rule = input()
					#_file = open(res[1], "a+")
					add_rule(new_rule, rules)
					print("Program Rules:")
					for rule in rules.values():
						print (rule.item)
					print("\n")
					add_proposition(new_rule, propositions)
					#augment_programA(new_rule, res[1])
					print("%s has been added to the program" % (new_rule))
					print("Push 'enter' to get the new models:")
					input()
					#file = open(res[1], "r")
					model = initialize(rules, propositions, "A")
					rep = "{"+"}"
					for m in model:
						if str(m.X) == "set()":
							m.X = rep
						if str(m.Y) == "set()":
							m.Y = rep
						print("< %s, %s >" % (m.X, m.Y))
					print("\n")

				if opt == "3":
					print("Which of the following rules would you like to remove from the Program?")
					for k, v in sorted(rules.items()):
						print(v.item)
					drop = input()
					drop = re.sub(r'\s+', '', drop)
					drop = drop.strip()
					flag = False
					dummy = deepcopy(rules)
					for d, dum in dummy.items():
						comp = re.sub(r'\s+', '', dum.item)
						comp = comp.strip()
						if drop == comp:
							#key = get_rule_name_from_item(drop, rules)
							#print("key: %s" % (key))
							#rules.pop(key)
							rules.pop(d)
							print("%s has been removed from the program\n" % (drop))
							print("Program Rules:")
							for k, v in sorted(rules.items()):
								print(v.item)
							print("Push 'enter' to get the new models:")
							input()
							#file = open(res[1], "r")
							model = initialize(rules, propositions, "A")
							for m in model:
								if str(m.X) == "set()":
									m.X = rep
								if str(m.Y) == "set()":
									m.Y = rep
								print("< %s, %s >" % (m.X, m.Y))
							print("\n")
							flag = True
					if flag == False:
						print("%s is not one of the rules in the program" % (drop))

				if opt == "4":
					more = False

		elif(do == "2"):
			res = get_file()
			file = res[0]
			file_name = res[1]
			file.seek(0)
			propositions = obtain_atomic_formulas(file)
			#print("Propositions A:")
			#for p in propositions:
			#	print (p)

			file.seek(0)
			rulesA = construct_program(file, "A")		# parses input text, make a Rule object for each rule, saves objects in dictionary
			file.seek(0)
			#print("number of rules: %s" % len(rules))
			print("Program A rules: ")
			for r in rulesA.values():
				print (r.name, r.item)
			file.seek(0)

			rulesB = construct_program(file, "B")		# parses input text, make a Rule object for each rule, saves objects in dictionary
			file.seek(0)
			#print("number of rules: %s" % len(rules))
			print("Program B rules: ")
			for r in rulesB.values():
				print (r.name, r.item)

			modelA = initialize(rulesA, propositions, "A")
			modelB = initialize(rulesB, propositions, "B")

			results(modelA, modelB)

			file.close()

			more = True
			while more == True:
				print("Would you like to do anything else with these programs?-------------------------")
				for k, p in sorted(additionB.items()):
					print("%s: %s" % (k, p))
				print("\n")
				opt = ""
				while (opt not in additionB.keys()):
					opt = input()
				if opt == "1":
					save = create_txt_double(modelA, modelB, rulesA, rulesB)
					#print_models(save)
				if opt == "2":
					print("Please enter a new rule to add to Program A")
					new_rule = input()
					#_file = open(res[1], "a+")
					add_rule(new_rule, rulesA)
					print("Program A Rules:")
					for rule in rulesA.values():
						print (rule.item)
					print("\n")
					add_proposition(new_rule, propositions)
					#augment_programA(new_rule, res[1])
					print("%s has been added to program A" % (new_rule))
					print("Push 'enter' to get the new models:")
					input()
					#file = open(res[1], "r")
					modelA = initialize(rulesA, propositions, "A")
					modelB = initialize(rulesB, propositions, "B")
					results(modelA, modelB)
				if opt == "3":
					print("Please enter a new rule to add to Program B")
					new_rule = input()
					#_file = open(res[1], "a+")
					add_rule(new_rule, rulesB)
					print("Program B Rules:")
					for rule in rulesB.values():
						print (rule.item)
					print("\n")
					add_proposition(new_rule, propositions)
					#augment_programA(new_rule, res[1])
					print("%s has been added to program B" % (new_rule))
					print("Push 'enter' to get the new models:")
					input()
					#file = open(res[1], "r")
					modelA = initialize(rulesA, propositions, "A")
					modelB = initialize(rulesB, propositions, "B")
					results(modelA, modelB)

					#add_rule(new_rule, rules)

				if opt == "4":
					print("Which of the following rules would you like to remove from Program A?")
					for k, v in sorted(rulesA.items()):
						print(v.item)
					drop = input()
					drop = re.sub(r'\s+', '', drop)
					drop = drop.strip()
					flag = False
					dummy = deepcopy(rulesA)
					for d, dum in sorted(dummy.items()):
						comp = re.sub(r'\s+', '', dum.item)
						comp = comp.strip()
						if drop == comp:
							rulesA.pop(d)
							#key = get_rule_name_from_item(drop, rulesA)
							#print("key: %s" % (key))
							#rulesA.pop(key)
							print("%s has been removed from program A\n" % (drop))
							print("Program A Rules:")
							for k, v in sorted(rulesA.items()):
								print(v.item)
							print("Push 'enter' to get the new models:")
							input()
							#file = open(res[1], "r")
							modelA = initialize(rulesA, propositions, "A")
							modelB = initialize(rulesB, propositions, "B")
							results(modelA, modelB)
							flag = True
					if flag == False:
						print("%s is not one of the rules in program A" % (drop))

				if opt == "5":
					print("Which of the following rules would you like to remove from Program B?")
					for k, v in sorted(rulesB.items()):
						print(v.item)
					drop = input()
					drop = re.sub(r'\s+', '', drop)
					drop = drop.strip()
					dummy = deepcopy(rulesB)
					for d, dum in dummy.items():
						comp = re.sub(r'\s+', '', dum.item)
						comp = comp.strip()
						if drop == comp:
							rulesB.pop(d)
							#key = get_rule_name_from_item(drop, rulesB)
							#print("key: %s" % (key))
							#rulesB.pop(key)
							print("%s has been removed from program B\n" % (drop))
							print("Program B Rules:")
							for k, v in sorted(rulesB.items()):
								print(v.item)
							print("Push 'enter' to get the new models:")
							input()
							#file = open(res[1], "r")
							modelA = initialize(rulesA, propositions, "A")
							modelB = initialize(rulesB, propositions, "B")
							results(modelA, modelB)
							flag = True
					if flag == False:
						print("%s is not one of the rules in program A" % (drop))

				if opt == "6":
					more = False

		elif(do == "3"):
			print("\n")
			print("Goodbye \n")

		else:
			print("\n")
			print("I'm sorry, could you repeat your command? \n")


# import colorgram
# colors = colorgram.extract('image.jpg', 20)

# rgb_color=[]
# # def color(colors):
# for _ in range(20):
#     rgb=colors[_].rgb
#     rgb_color.append((rgb[0],rgb[1],rgb[2]))

# print(rgb_color)
from turtle import Turtle, Screen,colormode, penup, right
import random
colormode(255)
color_list=[(199, 175, 117), (124, 36, 24), (210, 221, 213), (168, 106, 57), (222, 224, 227), (186, 158, 53), (6, 57, 83), (109, 67, 85), (113, 161, 175), (22, 122, 174), (64, 153, 138), (39, 36, 36), (76, 40, 48), (9, 67, 47), (90, 141, 53), (181, 96, 79), (132, 40, 42), (210, 200, 151)]

tim=Turtle()
tim.hideturtle()
tim.setheading(225)
tim.penup()
tim.forward(300)
tim.pendown()
tim.setheading(0)

for __ in range(10):
    for _ in range(10):
        tim.dot(10,random.choice(color_list))
        tim.penup()
        tim.forward(40)
        tim.pendown()

    tim.penup()
    tim.setheading(90)
    tim.forward(40)
    tim.setheading(180)
    tim.forward(400)
    tim.setheading(0)
    tim.pendown()

screen=Screen()
screen.exitonclick()


'''
.. module:: plot_itmes
   :synopsis: PyQtGraph extension classes for plot widget objects.
.. moduleauthor:: Yongkyun Shin <github.com/yongkyuns>

This module implements child classes of default PyQtGraph plot items for 2D graph visualization.

'''

from pyqtgraph.graphicsItems.PlotItem import PlotItem
from pyqtgraph.graphicsItems.PlotDataItem import PlotDataItem
import numpy as np
from pyqtgraph.functions import mkPen
from pyqtgraph.Qt import QtCore

class Plot(PlotItem):
    '''
    Plot is a child class of pyqtgraph.graphicsItems.PlotItem. This class
    can be used to draw 2D graph plots. This class is currently just a wrapper
    that renames PlotItem.

    ================  ==================================================
    **Arguments:**
    name              (string) name of the object
    data              (numpy array) 3-by-n array of (x,y,z) coordinates for plot. 2-by-n also works (assume 2D)
    ================  ==================================================
    '''

    def __init__(self, name, color='g', data=None, **kwargs):
        super().__init__(color=color, name=name, **kwargs)
        self._data = data

        self.pen = mkPen(color=color, width=1.5, style=QtCore.Qt.SolidLine)
        self.plotDataItem = PlotDataItem(pen=self.pen,antialias=False,name=name)
        self.addItem(self.plotDataItem)

    def setData(self, data=None, **kwargs):
        if data is not None:
            self.plotDataItem.setData(data)
            self._data = data
        else:
            self.plotDataItem.setData(**kwargs)
            # Update self._data here

        # if data is not None:
        #     dataType = dataType(data)
        #     if dataType == 'Nx2array':
        #         super().setData(data.tranpose(),**kwargs)
        #     elif dataType ==
        #     else:
        # else:
        #     print('Data is None!!')

class Signal(PlotDataItem):

    def __init__(self, name, color='g', data=None, **kwargs):
        self.pen = mkPen(color=color, width=1.5, style=QtCore.Qt.SolidLine)
        self._data = data
        super().__init__(pen=self.pen, antialias=False, name=name, **kwargs)

    def setData(self, data=None, **kwargs):
        if data is not None:
            super().setData(data)
            self._data = data
        else:
            super().setData(**kwargs)
            # Update self._data here