from collections import Counter, defaultdict
import re

from article import Article

RELEVANT_ENT_LABELS = [
    "FAC",
    "GPE",
    "LOC",
    "NORP",
    "ORG",
    "PERSON",
    "PRODUCT",
    "EVENT",
    "WORK_OF_ART",
]

ENT_REPLACEMENTS = {
    "Adam Neumann": ["Neumann"],
    "Bill Ackman": ["Ackman"],
    "Bitcoin": ["Bitcoins"],
    "BlackRock": ["BlackRock Inc."],
    "China": ["Chinese"],
    "Citi": ["Citibank"],
    "Deutsche Bank": ["Deutsche Bank AG"],
    "Donald Trump": ["Trump"],
    "Elon Musk": ["Elon", "Musk"],
    "Facebook": ["Facebook Inc."],
    "Federal Reserve": ["Fed"],
    "GameStop": ["GameStop Corp."],
    "Goldman Sachs": ["Goldman", "Goldman Sachs Group Inc."],
    "Greensill": ["Greensill Capital"],
    "JPMorgan": ["JPMorgan Chase & Co."],
    "Jack Dorsey": ["Dorsey"],
    "Kodak": ["Eastman Kodak Co."],
    "SEC": [
        "Securities and Exchange Commission",
        "U.S. Securities and Exchange Commission",
    ],
    "Softbank": ["SoftBank Group Corp."],
    "Tesla": ["Tesla Inc."],
    "U.S.": ["US", "America", "American"],
    "U.S. Treasury": ["Treasury"],
    "Warren Buffet": ["Buffet"],
}

class EntityExtractor:
    def __init__(self):
        print("Loading NLP model... ", end='', flush=True)
        try:
            import en_core_web_sm as spacy_en_model
        except ImportError:
            raise Exception(
                "Failed to load spacy model, try installing with `python -m spacy download "
                "en_core_web_sm`."
            )
        self.nlp = spacy_en_model.load()
        print("Done.")

    def extract_entities(self, article: Article, clean: bool) -> Counter:
        doc = self.nlp(str(article))
        counter = Counter(
            (ent.text) for ent in doc.ents if ent.label_ in RELEVANT_ENT_LABELS
        )
        if clean:
            EntityExtractor.clean_entity_counter(counter)
        return counter

    @staticmethod
    def clean_entity_counter(counter):
        # Remove whitespace from outside of all keys.
        for key in list(counter.keys()):
            if key.strip() != key:
                root = key.strip()
                counter[root] += counter[key]
                del counter[key]

        # Replace possessive "'s" with root.
        for key in list(counter.keys()):
            if key[-2:] == "’s" or key[-2:] == "'s":
                root = key[:-2]
                counter[root] += counter[key]
                del counter[key]

        # Remove all unexpected special characters.
        for key in list(counter.keys()):
            root = re.sub('[^a-zA-Z0-9.& -]+', '', key)
            if key != root:
                counter[root] += counter[key]
                del counter[key]

        # Remove prefix "the" if there are spaces.
        for key in list(counter.keys()):
            if " " in key and key[:4].lower() == "the ":
                root = key[4:]
                counter[root] += counter[key]
                del counter[key]

        # Replace all "UPPER CASE" with "Title Case".
        for key in list(counter.keys()):
            if " " in key and key.isupper():
                title_key = key.title()
                counter[title_key] += counter[key]
                del counter[key]

        # Apply custom replacements.
        inverted_replacements = defaultdict(list)
        for correction in ENT_REPLACEMENTS:
            for bad in ENT_REPLACEMENTS[correction]:
                inverted_replacements[bad] = correction
        for bad in inverted_replacements:
            count = counter[bad]
            counter[inverted_replacements[bad]] += count
            del counter[bad]


# -*- coding: utf-8 -*-

def main():
    while True:
        x, y = map(int, input().split())
        soma = 0

        if x <= 0 or y <= 0:
            break

        temp = x
        temp2 = y

        x = max(temp, temp2)
        y = min(temp, temp2)

        for c in range(y, x+1):
            print('%i' %(c), end=' ')
            soma += c

        print('Sum=%i' %(soma))

main()


matriz1=[[ 1,2,3,4],[5,6,7,8]]
for i in range(len(matriz1)):
	print(matriz1[i])

matriz2=[[ 1,2,3,4],[5,6,7,8]]
for f in range(len(matriz2)):
	print(matriz2[f])


from database.pkgdb import writeDB
from database.config import openDB

def update(args):
    config = openDB()
    pkgdb = []
    for repo in config["repo"]:
        if len(args) > 0:
            if repo["src"] not in args:
                continue
        try:
            repoEnable = repo["enable"]
        except:
            repoEnable = True
        if repoEnable == False:
            continue
        if repo["type"] == "github":
            print("pkg: {}".format(repo["src"]))  # 打印软件包名称
            from repo.github import GithubRepo
            try:
                pkg = GithubRepo(repo["src"])
            except:
                # 跳过产生错误的软件包
                print("无法获取 Github 仓库信息")
                continue
            print("ver: {}\n".format(pkg.tag))  # 打印最新版本
            pkgdb.append(
                {"name": repo["src"],
                 "ver": pkg.tag,
                 "desc": pkg.body,
                 "url": pkg.url})

    print("正在写出数据")
    writeDB(pkgdb)
    print("更新完成")


START_STONES = 7
FINAL_STONES = 61
MAX_STONES = FINAL_STONES * 2 - 1

game = [
    [
        0 if i+j >= FINAL_STONES else -1
        for j in range(MAX_STONES)
    ]
    for i in range(MAX_STONES)
]

def can_win(moves):
    for move in moves:
        if move % 2 == 0:
            return True
    return False

def loses(moves):
    for move in moves:
        if move % 2 == 0 or move < 0:
            return False
    return True

def check_pos(i, j, moves_left):
    if game[i][j] == -1:
        moves = [
            game[i+1][j],
            game[i*2][j],
            game[i][j+1],
            game[i][j*2],
        ]
        if moves_left % 2 == 1:
            if can_win(moves):
                game[i][j] = moves_left
        else:
            if loses(moves):
                game[i][j] = moves_left

def solve_game():
    for moves_left in range(1, 5):
        for i in range(START_STONES, FINAL_STONES):
            for j in range(1, FINAL_STONES):
                check_pos(i, j, moves_left)

if __name__ == '__main__':
    solve_game()
    for j in range(1, FINAL_STONES):
        if game[START_STONES][j] == 4:
            print(j, game[START_STONES][j])

    print("Done")


#program to calculate avg of numbers in a give list

n=int(input("Enter number of elements :"))

lst1=[]

for i in range(0,n):
    elem=int(input("Enter element :"))
    lst1.append(elem)

avg=sum(lst1)/n

print("Avg of list elements :",avg)


#!/usr/bin/python3
# -*- coding: utf-8 -*-

'''
너비가 같은 N개의 나무 판자를 붙여 세운 울타리가 있고 각 판자의 높이가 주어질 때 잘라낼 수 있는
직사각형의 최대 크기를 계산하는 프로그램. 판자의 너비는 모두 1이라고 가정

입력:
첫 줄에 테스트 케이스 개수 C (C<=50), 각 테스트 케이스의 첫 줄에는 판자의 수 N(1<=N<=20000)
이 주어짐. 그 다음 줄에는 N개의 정수로부 왼쪽부터 각 판자의 높이가 순서대로 주어짐.
높이는 모두 10,000이하 자연수
'''

def divide_conquer(fence, left, right):
  max_rec = 0
  c = right - left
  if c == 1:
    return fence[left]

  mid = left + int(c / 2)
  left_max = divide_conquer(fence, left, mid)
  right_max = divide_conquer(fence, mid, right)

  min_height = min(fence[mid-1], fence[mid])

  lh = mid
  for i in range(mid, left - 1, -1):
    if fence[i] < min_height:
      break
    lh = i

  rh = mid + 2
  for i in range(mid+1, right):
    if fence[i] < min_height:
      break
    rh = i

  return max(left_max, right_max, (rh - lh) * min_height)

def brute_force2(fence):
  """책 예제
  left부터 min_height를 구하면서 최대 직사각형을 찾는 로직
  """
  ret = 0
  N = len(fence)
  for left, h in enumerate(fence):
    min_height = h
    for right in range(left, N):
      min_height = min(min_height, fence[right])
      ret = max(ret, (right - left + 1) * min_height)

  return ret

def brute_force(fence):
  """내가 만든 로직
  left부터 각 판자의 크기에서 가장 큰 직사각형을 찾는 로직
  """
  max_rectangle = -1

  for i, h in enumerate(fence):
    s = 0
    for j in range(i-1, -1, -1):
      if fence[j] < h:
        s = j + 1
        break;
    e = len(fence)
    for j in range(i+1, len(fence)):
      if fence[j] < h:
        e = j
        break;

    count = e - s
    max_rectangle = max(max_rectangle, count * h)

  return max_rectangle

def main():
  with open('fence.dat') as f:
    C = int(f.readline())
    for i in range(C):
      N = int(f.readline())
      fence = [int(h) for h in f.readline().split()]
      print('brute force 1:', brute_force(fence))
      print('brute force 2:', brute_force2(fence))
      max_rec = divide_conquer(fence, 0, len(fence))
      print('divide and conquer:', max_rec)

if __name__ == '__main__':
 main()


'''
Created on Apr 9, 2013

@author: francis.horsman:gmail.com
'''

from newer.solver.strategies.StrategyDifficulty import StrategyDifficulty
from sets import Set

class FixCellSingleVertexPossibles(object):
    r"""@author: francis.horsman@gmail.com
    """
    name = "FixCellSingleVertexPossibles"
    difficulty = StrategyDifficulty.EASY+4
    def __call__(self, model):
        for cell in model.cells:
            cellsR = model.getCellsForRow(cell)
            cellsC = model.getCellsForCol(cell)
            knowns = cell.knowns()
            for known in knowns:
                (row, col) = cell.coords(known)
                for c in cellsR:
                    for element in c.getRow(row):
                        possibles = element.getPossibles()
                        element.setPossibles(possibles-Set([known]))
                for c in cellsC:
                    for element in c.getCol(col):
                        possibles = element.getPossibles()
                        element.setPossibles(possibles-Set([known]))


"""
https://leetcode-cn.com/problems/find-all-duplicates-in-an-array/

给你一个长度为 n 的整数数组 nums ，其中 nums 的所有整数都在范围 [1, n] 内，且每个整数出现 一次 或 两次 。请你找出所有出现 两次 的整数，并以数组形式返回。

你必须设计并实现一个时间复杂度为 O(n) 且仅使用常量额外空间的算法解决此问题。

示例 1：
    输入：nums = [4,3,2,7,8,2,3,1]
    输出：[2,3]

示例 2：
    输入：nums = [1,1,2]
    输出：[1]

示例 3：
    输入：nums = [1]
    输出：[]

提示：
    n == nums.length
    1 <= n <= 10^5
    1 <= nums[i] <= n
    nums 中的每个元素出现 一次 或 两次

"""
from typing import List

"""方法一：将元素交换到对应的位置"""
class Solution:
    def findDuplicates(self, nums: List[int]) -> List[int]:
        for i in range(len(nums)):
            while nums[i] != nums[nums[i] - 1]:
                nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1]
        return [num for i, num in enumerate(nums) if num - 1 != i]

"""方法二：使用正负号作为标记"""
class Solution:
    def findDuplicates(self, nums: List[int]) -> List[int]:
        ans = []
        for x in nums:
            x = abs(x)
            if nums[x - 1] > 0:
                nums[x - 1] = -nums[x - 1]
            else:
                ans.append(x)
        return ans

if __name__ == "__main__":
    nums = [4,3,2,7,8,2,3,1]
    sol = Solution()
    result = sol.findDuplicates(nums)
    print (result)

0442_数组中重复的数据.py


from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
from . import views

urlpatterns = [
    path('register/', views.UserRegisterView.as_view(), name='register'),
    path('login/', views.UserLoginView.as_view(), name='login'),
    path('logout/', views.UserLogoutView.as_view(), name='logout'),
    path('profile-details/<int:pk>/', views.UserDetailsView.as_view(), name='profile-details'),
    path('profile-edit/<int:pk>/', views.UserEditView.as_view(), name='profile-edit'),
    path('profile-delete/<int:pk>/', views.UserDeleteView.as_view(), name='profile-delete'),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


from reportlab.lib.pagesizes import letter
from fpdf import FPDF
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import locale
import numpy as np
import folium

path_csv = "Data/ds_salaries.csv"
pdf = FPDF()

def get_date():
    locale.setlocale(locale.LC_ALL, '')
    fecha_actual = datetime.datetime.now()
    return(fecha_actual.strftime('%A, %-d de %B de %Y'))

def recopilar_datos():
    fuente_datos = input("Ingresa la ruta del archivo csv: ")
    fuente_datos = path_csv
    return pd.DataFrame(pd.read_csv(fuente_datos))

def preparar_datos(df):
    return df[['job_title','salary_in_usd', 'employee_residence']]

def modelo_analisis(df):
    data = {}
    df_mx = df.query("employee_residence == 'MX'")
    df_min = df_mx.query(f"salary_in_usd == {df_mx['salary_in_usd'].min()}")
    df_max = df_mx.query(f"salary_in_usd == {df_mx['salary_in_usd'].max()}")
    data['maximo'] = f"{df_max.iloc[0]['job_title']} --> {df_max.iloc[0]['salary_in_usd']}"
    data['minimo'] = f"{df_min.iloc[0]['job_title']} --> {df_min.iloc[0]['salary_in_usd']}"
    return data

def generar_mapa(data):
    map_crime = folium.Map(location = [23.634501, -102.552784], zoom_start=5)
    colors = ['red', 'black', 'blue', 'green', 'gray', 'purple', 'orange']
    icons = ['glyphicon-usd', 'glyphicon-folder-open', 'glyphicon-dashboard', 'glyphicon-thumbs-down', 'glyphicon-remove', 'glyphicon-remove-sign', 'glyphicon-remove-circle']
    folium.Marker([20.66682,-103.39182], popup=data["maximo"], icon=folium.Icon(icon=f'{icons[1]}', color=f'{colors[1]}')).add_to(map_crime)
    folium.Marker([25.67507,-100.31847], popup=data["minimo"], icon=folium.Icon(icon=f'{icons[2]}', color=f'{colors[2]}')).add_to(map_crime)
    folium.Marker([19.42847,-99.12766], popup="Data scient ingener", icon=folium.Icon(icon=f'{icons[3]}', color=f'{colors[3]}')).add_to(map_crime)
    map_crime.save('Data/HTML/ds_salaries_2".html')

if __name__ == '__main__':
    data = recopilar_datos()
    data_prepared = preparar_datos(data)
    data = modelo_analisis(data_prepared)
    generar_mapa(data)


from codecs import open
from os import path

from setuptools import setup

HERE = path.abspath(path.dirname(__file__))

with open(path.join(HERE, "README.md"), encoding="utf-8") as f:
    long_description = f.read()

extras = {
    "dev": [
        "pip-tools",
        "black",
        "isort",
        "mypy",
        "types-PyYAML",
        "types-aiofiles",
        "flake8",
        "flake8-pyproject",
        "pytest",
        "pytest-mock",
        "pytest-asyncio",
        "pytest-aiohttp",
        "pytest-xdist",
        "pytest-cov",
        "pytest-rerunfailures",
        "no_implicit_optional",
        "python-dotenv",
        "twine",
    ],
    "ha": [
        "homeassistant_api>=4",
    ],
    "cloud": [
        "pyjwt",
        "cryptography",
        "aioboto3",
    ],
}

setup(
    name="smarthouse",
    version="2.4.0",
    description="Smart House Scenarios",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://smarthouselib.readthedocs.io/",
    author="Ivan Kriuchkov",
    author_email="vivenchik@gmail.com",
    license="MIT",
    classifiers=[
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.12",
        "Operating System :: OS Independent",
    ],
    packages=["smarthouse"],
    include_package_data=True,
    install_requires=[
        "aiohttp[speedups]",
        "aiofiles",
        "pyyaml",
        "python-telegram-bot[all,ext]",
        "telegram",
        "pydantic",
        "pydantic-settings",
        "async_lru",
        "astral",
    ],
    extras_require=extras,
    setup_requires=["pytest-runner"],
    tests_require=[
        "pytest",
        "pytest-mock",
        "pytest-asyncio",
        "pytest-aiohttp",
        "python-dotenv",
        "pytest-runner",
    ],
    test_suite="tests",
)


import pygame, sys
from settings import *
from level import Level
from support import level_0
from ui import UI
from overworld import Overworld

class Game:
    def __init__(self):
        pygame.init()
        self.screen=pygame.display.set_mode((screen_width,screen_height))
        self.clock=pygame.time.Clock()
        pygame.display.set_caption('Runner')
        self.max_level=2
        self.max_unlocked_level=1
        self.status='overworld'
        self.overworld=Overworld(self.screen,self.max_unlocked_level,0,self.create_level,self.incr_max_unlocked_level)

        #Gui setup
        self.ui=UI(self.screen)
        self.coin_amount=0
        self.current_health=100

    def create_level(self,current_level,unlock_level):
        self.level=Level(current_level,self.screen,self.change_coin_amount,self.change_health,self.change_status,unlock_level)
        self.status='play'

    def incr_max_unlocked_level(self,current_level):
        if self.max_unlocked_level<self.max_level  and self.max_unlocked_level==current_level:

            self.max_unlocked_level+=1

            self.overworld.max_level=self.max_unlocked_level

            self.overworld.node_sprites.empty()

            self.overworld.create_node_sprites()

            print(self.max_unlocked_level)

    def change_coin_amount(self,amount):
        self.coin_amount+=amount

    def change_status(self):
        if self.status=='overworld':
            self.status='play'
        else:
            self.status='overworld'

    def change_health(self,amount):
        self.current_health+=amount

    def run(self):

        while True:
            for event in pygame.event.get():
                if event.type==pygame.QUIT:
                    pygame.quit()
                    sys.exit()

            if self.current_health < 10:
                pygame.quit()
                sys.exit()
            self.screen.fill('grey')

            if self.status=='overworld':
                self.overworld.run()
            elif self.status=='play':
                self.level.run()
                self.ui.show_health(self.current_health,100)
                self.ui.show_coins(self.coin_amount)

            pygame.display.update()

            self.clock.tick(fps)

if __name__=='__main__':
    game=Game()
    game.run()


import csv
import numpy as np
import matplotlib.pyplot as plt

def lookahead_moving_average(data, window):
    ma = []
    for i in range(len(data)):
        avg = 0
        if i + window > len(data):
            window -= 1
        for j in range(window):
            avg += data[i+j]
        ma.append(avg/float(window))
    return np.array(ma, dtype=float)

def single_exp_smoothing(data, alpha):
    S_t = data[0]
    ses = []
    for d in data:
        S_t = alpha * d + (1 - alpha) * S_t
        ses.append(S_t)
    return np.array(ses, dtype=float)

def double_exp_smoothing(data, alpha, gamma):
    S_t = data[0]
    b_t = data[1] - data[0]
    S_tt, b_tt = 0, 0
    des = []
    for d in data:
        S_tt = alpha * d + (1 - alpha) * S_t
        b_tt = gamma * (S_tt - S_t) + (1 - gamma) * b_t
        S_t = S_tt
        b_t = b_tt
        des.append(S_tt + b_tt)
    return np.array(des, dtype=float)

d = []
with open('data.csv', 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    for row in reader:
        d.append(row)
dataset = np.array(d, dtype=float)

time = dataset[:, 0]
data = dataset[:, 1]

plt.figure(1)
plt.subplot(511)
plt.title('look head moving average')
plt.plot(time, data, color='black', label='raw', lw=0.3)
ma = lookahead_moving_average(data, window=151)
plt.plot(time, data-ma, color='red', label='window=151', lw=1)
plt.ylabel('data')
plt.legend(bbox_to_anchor=(1.005, 1), loc=2, borderaxespad=0.)

plt.subplot(512)
plt.title('single exponential smoothing')
colours = ['red', 'blue', 'green', 'yellow']
alphas = [0.2, 0.3, 0.5, 0.8]
plt.plot(time, data, color='black', label='raw', lw=0.3)
for i in range(len(alphas)):
    ses = single_exp_smoothing(data, alpha=alphas[i])
    a_label = 'alpha={}'.format(alphas[i])
    plt.plot(time, data-ses, color=colours[i], label=a_label)
plt.legend(bbox_to_anchor=(1.005, 1), loc=2, borderaxespad=0.)

plt.subplot(513)
plt.title('double exponential smoothing for alpha = .2')
plt.plot(time, data, color='black', label='raw', lw=0.3)

des = double_exp_smoothing(data, 0.2, 0.2)
plt.plot(time, data-des, color='blue', label='.2, .2')
des = double_exp_smoothing(data, 0.2, 0.5)
plt.plot(time, data-des, color='green', label='.2, .5')
des = double_exp_smoothing(data, 0.2, 0.8)
plt.plot(time, data-des, color='red', label='.2, .8')
plt.legend(bbox_to_anchor=(1.005, 1), loc=2, borderaxespad=0.)

plt.subplot(514)
plt.title('double exponential smoothing for alpha = .5')
plt.plot(time, data, color='black', label='raw', lw=0.3)
des = double_exp_smoothing(data, 0.5, 0.2)
plt.plot(time, data-des, color='blue', label='.5, .2')
des = double_exp_smoothing(data, 0.5, 0.5)
plt.plot(time, data-des, color='green', label='.5, .5')
des = double_exp_smoothing(data, 0.5, 0.8)
plt.plot(time, data-des, color='red', label='.5, .8')
plt.legend(bbox_to_anchor=(1.005, 1), loc=2, borderaxespad=0.)

plt.subplot(515)
plt.title('double exponential smoothing for alpha = .8')
plt.plot(time, data, color='black', label='raw', lw=0.3)
des = double_exp_smoothing(data, 0.8, 0.2)
plt.plot(time, data-des, color='blue', label='.8, .2')
des = double_exp_smoothing(data, 0.8, 0.5)
plt.plot(time, data-des, color='green', label='.8, .5')
des = double_exp_smoothing(data, 0.8, 0.8)
plt.plot(time, data-des, color='red', label='.8, .5')
plt.legend(bbox_to_anchor=(1.005, 1), loc=2, borderaxespad=0.)

plt.show()


# -*- coding: utf-8 -*-
"""
Created on Sun Dec 27 17:27:58 2020

@author: hp
"""
"""ilk defa bu programda kod yazdım açıkçası problemi çözemedim.Kendime
özgü bir şey olmadığı içinde kopyala yapıştır yamak istemedim farklı bir kaynaktan
Top leaner programına katılmayı çok isterim ama şans"""
name = "Hilal"
surname = "ATAMAN"

counter=3
while True:

   if (counter>0):
       student_name= input("Write your student name: ")
       student_surname= input("Write your student surname: ")
       if student_name== name and  student_surname == surname:
           print("Welcome")
           break
       elif student_name== name and  student_surname != surname:
           print("Student_surname is false\n")
       elif student_name != name and  student_surname == surname:
           print("Student_name is false\n")
       elif not student_name.strip() and not student_surname .strip():
           print("You must write string value.")
       else:
           print("student_name and student_name are false=\n")

       counter -=1
   else :
       print("çok fazla denem yaptınız daha sonra tekrar deneyiniz")
       break

arasınav= input("Vize 1 notunuzu girin; ")
final= input("Vize 2 notunuzu girin; ")
proje= input("Final notunuzu girin; ")

derece =int(int(arasınav)*3/10 + int(proje)*2/10 +int(final)*5/10)

if (derece > 90):
    print ("Ders notunuz A")

elif (derece>=70 or derece<90):
    print ( "Ders notunuz B")

elif (derece>=50 or derece<70):
    print ("Ders notunuz C")

elif (derece>=30 or derece<50):
    print ("Ders notunuz D")

else:
    print ("Dersten kaldınız")


from sqlalchemy import func
from datetime import timedelta
import pandas as pd

from quotes.get_yahoo import add_yahoo
from database.db import db
from models.Quotes import Quotes

def get_quotes(tickers, start, end):
    """
    get_quotes() collects quotes for tickers: checks if quotes already exist in Quotes, adds missing quotes to Quotes from Yahoo Finance and returns pandas.DataFrame with all quotes.
    type: (str[], datetime, datetime) -> (pandas.DataFrame/None, str[])

    :param tickers: list of tickers type: str[] (e.g. ['MSFT', 'AAPL'])
    :param start: start date, type: datetime
    :param end: end date, type: datetime
    :return: pandas.DataFrame with quotes for tickers between start and end dates/None if no data collected, list of errors
    """

    bcal = pd.bdate_range(start = start, end = end - timedelta(days = 1)) # business day calendar
    quotes = pd.DataFrame(index = bcal) # return pandas.DataFrame
    errors = []

    # For every requested ticker
    for ticker in tickers:
        # Add missing data to Quotes (if any)
        status, error = add_missing(ticker = ticker, start = start, end = end)
        errors += error

        # If add_missing successful, try to collect all quotes from Quotes
        if status == True:
            try:
                # Execute query for the ticker
                subquery = db.select(Quotes.date, Quotes.quote).where((Quotes.ticker == ticker) & (Quotes.date >= start) & (Quotes.date <= end))
                query = db.session.execute(subquery).fetchall()

                # Create DataFrame with data from query
                quote = pd.DataFrame(query, columns = ['Date', ticker])
                quote['Date'] = pd.to_datetime(quote['Date'])
                quote.set_index('Date', inplace = True)

                # Concat quote with return DataFrame
                quotes = pd.concat([quotes, quote], axis=1)

            except:
                errors += [f"Failed to collect data from database for: {ticker}"]

    if len(quotes.columns) == 0: # if no data was collected, return None, errors
        return None, errors

    else:
        return quotes, errors # else return pandas.DataFrame, errors

def add_missing(ticker, start, end):
    """
    add_missing() adds missing quotes to Quotes using add_yahoo() module.
    type: (str, datetime, datetime) -> (Bool, str[])

    :param ticker: ticker type: str (e.g. 'MSFT')
    :param start: start date, type: datetime
    :param end: end date, type: datetime
    :return: True if successful (including when no data had to be added)/False otherwise, list of errors
    """

    # Get minimum and maximum dates in Quotes for the ticker
    min_date, max_date = get_dbdates(ticker = ticker)

    # If no min_date add all quotes
    if min_date == None or max_date == None:
        return add_yahoo(ticker = ticker, start = start, end = end)

    else:
        # Declare status and errors placeholders
        status_start, status_end = True, True
        errors_start, errors_end = [], []

        # If start is before min_date add missing quotes before min_date
        if start < min_date:
            status_start, errors_start = add_yahoo(ticker = ticker, start = start, end = min_date - timedelta(days = 1))

        # If end is after max_date add missing quotes after max_date
        if end > max_date + timedelta(days = 1):
            status_end, errors_end = add_yahoo(ticker = ticker, start = max_date + timedelta(days = 1), end = end)

        return all([status_start, status_end]), errors_start + errors_end

def get_dbdates(ticker):
    """
    get_dbdates() gets min and max date for quotes stored in Quotes for the ticker.
    type: (str) -> (str, str)/(None, None)

    :param ticker: ticker, type: str (e.g. 'MSFT')
    :return: minumum date / None, maximum date / None, type: str, str
    """

    try:
        subquery = db.select(db.func.min(Quotes.date), db.func.max(Quotes.date)).where(Quotes.ticker == ticker)
        query = db.session.execute(subquery)#.scalars()
        dates = list(query)[0]

    except:
        dates = [None, None]

    return dates[0], dates[1]


n=int(input())
l=list(map(int,input().split()))
i=1
sum1=0
sum2=0
while i<=n:
    sum1=sum1+i
    sum2=sum2+l[i-1]
    i=i+1
if(sum1==sum2):
    print ("YES")
else:
    print("NO")


import random
import numpy as np
import mathutils
import bpy
from bpy_extras.object_utils import world_to_camera_view

from src.utils import CAMERA_Z_UPPER_LIMIT, CAMERA_X_LIMIT

class CameraRandomizer(object):

    def __init__(self, camera, parent_cup, two_cups_env):
        self.camera = camera
        self.parent_cup = parent_cup
        self.two_cups_env = two_cups_env
        self.reset_camera_position()

    def north_coord_limit(self, cup_coords, camera_coord):

        max_idx = np.argmax([np.abs(coord[0] - camera_coord[0]) for coord in cup_coords])
        limit_coord = np.array(cup_coords[max_idx])
        limit_coord[2] = max([coord[2] for coord in cup_coords])
        return limit_coord

    def south_coord_limit(self, cup_coords, camera_coord):

        min_idx = np.argmin([np.abs(coord[0] - camera_coord[0]) for coord in cup_coords])
        limit_coord = np.array(cup_coords[min_idx])
        limit_coord[2] = min([coord[2] for coord in cup_coords])

        return limit_coord

    def sample_z_position(self, north_limit):
        return random.uniform(north_limit[2] + 1, CAMERA_Z_UPPER_LIMIT)

    def sample_x_position(self, view_angle, south_limit, z):

        # lower limit
        z_delta = np.abs(z - south_limit[2])
        x_low = south_limit[0] + z_delta / np.tan(view_angle / 2)
        return random.uniform(1.2 * x_low, CAMERA_X_LIMIT[1])

    def sample_x_rotation(self, view_angle, north_limit, south_limit, z, x):

        # low angle
        delta_x = np.abs(x - north_limit[0])
        delta_z = np.abs(z - north_limit[2])
        low_angle = np.arctan(delta_x / delta_z) - view_angle / 2
        low_angle = low_angle * 1.1

        # high angle
        delta_x = np.abs(x - south_limit[0])
        delta_z = np.abs(z - south_limit[2])
        high_angle = np.arctan(delta_x / delta_z) + view_angle / 2
        high_angle = high_angle * 0.95
        high_angle = min(np.pi/2 - 0.2, high_angle)

        return random.uniform(low_angle, high_angle)

    def west_and_east_limits(self, cup_coords, camera_y):
        side1_idx = np.argmax([np.abs(coord[1] - camera_y) for coord in cup_coords])
        side1 = np.array(cup_coords[side1_idx])
        side2_idx = np.argmax([np.abs(coord[1] - side1[1]) for coord in cup_coords])
        side2 = np.array(cup_coords[side2_idx])

        if side2[1] < side1[1]:
            west_limit = side2
            east_limit = side1
        else:
            west_limit = side1
            east_limit = side2

        return west_limit, east_limit

    def sample_y_position(self, west_limit, east_limit, sample_x):

        vertical_camera_angle = bpy.data.cameras['Camera'].angle_x

        # west limit
        x_delta = sample_x - west_limit[0]
        y_west = west_limit[1] + np.tan(vertical_camera_angle/2) * x_delta

        if y_west < 0:
            y_west = y_west * 1.1
        else:
            y_west = y_west * 0.9

        # west limit
        x_delta = sample_x - east_limit[0]
        y_east = east_limit[1] - np.tan(vertical_camera_angle/2) * x_delta

        if y_east < 0:
            y_east = y_east * 0.9
        else:
            y_east = y_east * 1.1

        return random.uniform(y_west, y_east)

    def random_z_rotation(self, view_angle, sample_y, sample_x, west_limit, east_limit):

        # highest angle
        delta_y = np.abs(sample_y - west_limit[1])
        delta_x = np.abs(sample_x - west_limit[0])
        theta = np.arctan(delta_y/ delta_x)

        if sample_y < west_limit[1]:
            west_angle = view_angle/2 + theta
        else:
            west_angle = view_angle/2 - theta

        # lowest angle
        delta_y = np.abs(sample_y - east_limit[1])
        delta_x = np.abs(sample_x - east_limit[0])
        theta = np.arctan(delta_y/ delta_x)

        if sample_y < east_limit[1]:
            east_angle = view_angle/2 - theta
        else:
            east_angle = view_angle/2 + theta

        return np.pi/2 + 0.95 * random.uniform(-west_angle, east_angle)

    def reset_camera_position(self):
        bpy.context.scene.update()
        self.camera = bpy.context.scene.objects['Camera']
        self.parent_cup = bpy.context.scene.objects['cup_1']
        self.camera.rotation_euler = mathutils.Vector([90, 0, 90]) * 2 * np.pi / 360
        self.camera.location = (4, 0, 6)

    def do_randomzation(self):

        self.reset_camera_position()
        cup = self.parent_cup
        mw = cup.matrix_world
        cup_coords = [np.array(mw * v.co) for v in cup.data.vertices] # Global coordinates of vertices

        # second cup
        if (self.two_cups_env):

            cup2 = bpy.context.scene.objects['cup_2']
            mw = cup2.matrix_world
            cup_coords2 = [np.array(mw * v.co) for v in cup2.data.vertices] # Global coordinates of vertices

            cup_coords = cup_coords + cup_coords2

        camera_coord = self.camera.location

        north_limit = self.north_coord_limit(cup_coords, camera_coord)
        south_limit = self.south_coord_limit(cup_coords, camera_coord)
        west_limit, east_limit = self.west_and_east_limits(cup_coords, camera_coord[1])

        sample_z = self.sample_z_position(north_limit)
        # rotation
        sample_x = self.sample_x_position(bpy.data.cameras['Camera'].angle_y, south_limit, sample_z)
        sample_x_rotation = self.sample_x_rotation(bpy.data.cameras['Camera'].angle_y, north_limit, south_limit, sample_z, sample_x)

        sample_y = self.sample_y_position(west_limit, east_limit, sample_x)
        sample_z_rotation = self.random_z_rotation(bpy.data.cameras['Camera'].angle_x, sample_y, sample_x, west_limit, east_limit)

        return sample_x, sample_y, sample_z, sample_x_rotation, sample_z_rotation, [north_limit, south_limit, west_limit, east_limit]

    def change_camera_position(self):

        x, y, z, sample_x_rotation, sample_z_rotation, limits = self.do_randomzation()
        self.camera.location = (x, y, z)
        self.camera.rotation_euler[0] = sample_x_rotation
        self.camera.rotation_euler[2] = sample_z_rotation
        success = self.coords_within_image(limits)
        return success

    def coords_within_image(self, coords):

        scene = bpy.context.scene
        scene.update()
        cs, ce = self.camera.data.clip_start, self.camera.data.clip_end

        object_names = [obj.name for obj in list(bpy.data.objects)]
        random_objects = []
        image_coords = []

        for name in object_names:

            if 'random' == name[:6]:
                obj = bpy.data.objects[name]
                mat_world = obj.matrix_world
                verts = (mat_world * vert.co for vert in obj.data.vertices)
                coords_2d = [world_to_camera_view(scene, self.camera, coord) for coord in verts]
                image_coords.append(coords_2d)
                random_objects.append(obj)

        def random_object_is_blocking(obj_coords, limit_coord):

            for co in obj_coords:
                if np.abs(co.x - limit_coord.x) < 0.01 and np.abs(co.y - limit_coord.y) < 0.01 and co.z < limit_coord.z:
                    return True
            return False

        for idx, coord in enumerate(coords):
            coord = mathutils.Vector(coord)
            co_ndc = world_to_camera_view(scene, self.camera, coord)

            if not((0.0 < co_ndc.x < 1.0 and
                0.0 < co_ndc.y < 1.0 and cs < co_ndc.z < ce)):

                return False

            update_objects = []
            update_image_coords = []
            for i in range(len(image_coords)):

                if random_object_is_blocking(image_coords[i], co_ndc):
                    obstacle = random_objects[i]
                    print('POP', obstacle.name)
                    bpy.data.objects.remove(obstacle)
                else:
                    update_objects.append(random_objects[i])
                    update_image_coords.append(image_coords[i])
            random_objects = update_objects
            image_coords = update_image_coords

        return True

def blender_run():
    cr = CameraRandomizer(bpy.data.objects['Camera'], bpy.data.objects['cup_1'])
    cr.change_camera_position()

if __name__== '__main__':
    import sys, os
    sys.path.append(os.getcwd())
    blender_run()


from tensorflow.keras.models import load_model
import matplotlib.pyplot as plt
import os
import cv2
import numpy as np
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.vgg16 import preprocess_input, decode_predictions
import sys
from PyQt5.QtWidgets import *
from PyQt5 import QtGui
    # QAction, QApplication,QMainWindow ,QWidget, QPushButton, QMessageBox, QLabel, QLineEdit, QTextEdit, QGridLayout, QListWidget, QTableWidget,QFileDialog
from PyQt5.QtGui import *

class Window(QWidget):

    def __init__(self):
        super().__init__()
        self.title = "고궁판별기"
        self.top = 200
        self.left = 500
        self.width = 400
        self.height = 300
        self.InitWindow()

    def InitWindow(self):
        self.setWindowIcon(QtGui.QIcon("icon.png"))
        self.setWindowTitle(self.title)
        self.text_edit = QTextEdit(self)
        self.text_edit.setGeometry(120, 200, 200, 50)
        self.setGeometry(self.left, self.top, self.width, self.height)
        vbox = QVBoxLayout()
        self.btn1 = QPushButton("Open Image")
        self.btn1.clicked.connect(self.getImage)
        vbox.addWidget(self.btn1)
        self.label = QLabel("result")
        vbox.addWidget(self.label)
        vbox.addWidget(self.text_edit)
        self.setLayout(vbox)
        self.show()

    def getImage(self):
        fname,_ = QFileDialog.getOpenFileName(self)
        imagePath = fname
        pixmap = QPixmap(imagePath).scaled(350,300)
        self.label.setPixmap(QPixmap(pixmap))
        self.resize(pixmap.width(), pixmap.height())
        if fname:
         data = fname
         print(data)
         #data500_VGG16_flatten_Dropout_model
         # model = load_model('projects_pretrained_change_setps_and_val_steps4(epoch50_and_data(each500)flatten_Dropout_)before_fine_tuning.h5')
         model = load_model('projects_pretrained_change_setps_and_val_steps4(256size)_add_class3(epoch50_and_data(each100)flatten_adam_softmax)before_fine_tuning.h5')
         # model =load_model('projects_pretrained_change_setps_and_val_steps4(128size)_add_class3(epoch50_and_data(each100)flatten_Dropout_adam_softmax)before_fine_tuning.h5')
         #data800_VGG16_flatten_Dropout_no_argumnet_model
         # model = load_model('projects_pretrained(Dropout_epoch50_and_data(each800)no_data_argu)before_fine_tuning.h5')projects_pretrained_change_setps_and_val_steps4(128size)_add_class3(epoch50_and_data(each100)flatten_Dropout_adam_softmax)before_fine_tuning

         #data100_VGG16_flatten
         # model =load_model('projects_pretrained_change_setps_and_val_steps4(epoch50_and_data(each100)flatten)before_fine_tuning.h5')
         img_path = data
         img = cv2.imread(data)
         img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
         img = image.load_img(img_path, target_size=(256, 256))
         img_tensor = image.img_to_array(img)
         img_tensor = np.expand_dims(img_tensor, axis=0)
         img_tensor = preprocess_input(img_tensor)
         pre = model.predict(img_tensor)
         merge = ('china:',round(pre[0][0]*100,2),'%','japan:',round(pre[0][1]*100,2),'%','korea:',round(pre[0][2]*100,2),'%')
         self.text_edit.setText(str(merge))

App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())


################################################
#                                              #
#     Implementation of Section 6.1 and 6.2    #
#        "Training the Feedforward Network"    #
#                                              #
################################################

import numpy as np
from keras.layers import Conv1D,MaxPooling1D,Dropout,Input,regularizers
from keras.models import Model,optimizers
from utils import Motion_Edit

#load data in the form of (None, 240, 73)
DataSet = ".\\data\\data_cmu2.npz"
Data = np.load(DataSet)['clips']

# make data Zero Mean - Unit Variance
preprocess = np.load('ZMUV_locomotion.npz')
Xmean = np.swapaxes(preprocess['Xmean'],1,2)
Xstd = np.swapaxes(preprocess['Xstd'],1,2)
Data = (Data - Xmean)/Xstd

# extract Trajectory and foot contact information / These are inputs for Our Deep net
X_decoded = Data
Upsilon_T = Data[:,:,-7:]  #[xvelocity,zvelocity,rvelocity, lh,lt,rh,rt]

# map data to motion manifold space | feature space -> hidden space
X_encoded = Motion_Edit(X_decoded,'.\\model\\autoencoder_ND')

#defining Network structure , input-shape: (None,240,7) / output-shape: (None,120,256)
input_shape = Input((240,7))
ConvLayer1 = Conv1D(filters=64,kernel_size=(45,),input_shape=(240,7),use_bias=True,activation='relu',padding='same')(input_shape)
ConvLayer2 = Conv1D(filters=128,kernel_size=(25,),use_bias=True,activation='relu',padding='same')(ConvLayer1)
ConvLayer3 = Conv1D(filters=256,kernel_size=(15,),use_bias=True,activation='relu',padding='same')(ConvLayer2)
Polling = MaxPooling1D(2,padding='same')(ConvLayer3)
Layer_Drop = Dropout(rate=0.2)(Polling)

Motion_Synthesis = Model(input_shape,Layer_Drop)

Motion_Synthesis.summary()
myadam = optimizers.adam(lr=0.00001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)
Motion_Synthesis.compile(optimizer=myadam,loss='mse')

#train model
Motion_Synthesis.fit(Upsilon_T,X_encoded,epochs=200,batch_size=1)

#save model for future use
model_json = Motion_Synthesis.to_json()
with open(".\\model\\motionsynthesis.json", "w") as json_file:
    json_file.write(model_json)
# serialize weights to HDF5
Motion_Synthesis.save_weights(".\\model\\motionsynthesis.h5")
print("Saved model to disk")


# -*- coding: utf-8 -*-
import time
def db_rename(name,port=5432):
    if __salt__['postgres.db_exists'](name,port=port):
        newname = '{0}_bak'.format(name)
        __salt__['postgres.db_exists'](newname) and __salt__['postgres.db_remove'](newname)
        cmd = "alter database {0} rename to {1}" .format(name,newname)
        psql = "psql -h db -U postgres -p {0} -c '{1}'".format(port,cmd)
        ret = __salt__['cmd.run_all'](psql)
        if ret['retcode'] == 0:
            return True
        else:
            return False
    else:
        return True
def db_back(name,port=5432):
    if __salt__['postgres.db_exists'](name):
        cmd = 'pg_dump -U postgres -h db {0} -f /var/lib/postgresql/{1}_{2}.bak'.format(name,name,time.strftime('%Y-%m-%d_%H:%M:%S'))
        ret = __salt__['cmd.run_all'](cmd)
        if ret['retcode'] == 0:
            return True
        else:
            return False
    else:
        return True


# -*- coding: utf-8 -*-

from plone.resource.interfaces import IResourceDirectory
from six import StringIO
from zope.component import getUtility
import logging

logger = logging.getLogger('cpskin.theme')

CUSTOM_FOLDER_NAME = 'cpskin'

def installTheme(context):
    if context.readDataFile('cpskin.theme-default.txt') is None:
        return
    addCustomLessFiles()

def addCustomLessFiles():
    added = False
    portal_resources = getUtility(IResourceDirectory, name='persistent')
    if CUSTOM_FOLDER_NAME not in portal_resources:
        portal_resources.makeDirectory(CUSTOM_FOLDER_NAME)
    folder = portal_resources[CUSTOM_FOLDER_NAME]
    if not 'variables.less' in folder:
        folder.writeFile(
            'variables.less',
            StringIO('/*\nPut your custom LESS variables here.\n*/\n\n'),
        )
        logger.info('Custom variables LESS files added to portal_resources')
    if not 'styles.less' in folder:
        folder.writeFile(
            'styles.less',
            StringIO('/*\nPut your custom LESS styles here.\n*/\n\n'),
        )
        logger.info('Custom styles LESS files added to portal_resources')
        added = True
    return added

def uninstallTheme(context):
    if context.readDataFile('cpskin.theme-uninstall.txt') is None:
        return
    removeCustomLessFiles()

def removeCustomLessFiles():
    portal_resources = getUtility(IResourceDirectory, name='persistent')
    if CUSTOM_FOLDER_NAME in portal_resources:
        del portal_resources[CUSTOM_FOLDER_NAME]
        logger.info('Custom LESS files removed from portal_resources')


import json
import os

class Storage:
    """
    The Storage class provides functionality to store and retrieve data in
    different storage formats.

    Attributes
    ----------
    file_name : str
        The name of the file to store the data.
    storage_type : str
        The type of storage format, such as "JSON" or "CSV".

    Methods
    -------
    store_in_json(data: dict) -> None:
        Stores the data in JSON format.

    retrieve_from_json() -> dict:
        Retrieves the data from JSON format.

    storage_config_mapper() -> dict:
        Returns a mapper dictionary that maps storage types to their respective
        read and write methods.

    read() -> dict:
        Reads the data from the specified storage format.

    write(data: dict) -> None:
        Writes the data to the specified storage format.
    """

    file_name = 'weather_data.json'
    storage_type = "JSON"

    @classmethod
    def store_in_json(cls, data: dict) -> None:
        """
        Stores the data in JSON format.

        Parameters
        ----------
        data : dict
            The data to be stored.

        Returns
        -------
        None

        """

        with open(cls.file_name, 'w') as file:
            json.dump(data, file)

    @classmethod
    def retrieve_from_json(cls) -> dict:
        """
        Retrieves the data from JSON format.

        Returns
        -------
        dict
            The retrieved data.

        """

        if os.path.exists(cls.file_name):
            with open(cls.file_name, 'r') as file:
                data = json.load(file)
            return data
        return {}

    @classmethod
    def storage_config_mapper(cls) -> dict:
        """
        Returns a mapper dictionary that maps storage types to their respective
        read and write methods.

        Returns
        -------
        dict
            The storage type mapper dictionary.

        """

        mapper = {
            "JSON": {
                "read": cls.retrieve_from_json,
                "write": cls.store_in_json
            }
        }
        return mapper

    @classmethod
    def read(cls) -> dict:
        """
        Reads the data from the specified storage format.

        Returns
        -------
        dict
            The retrieved data.

        """

        return cls.storage_config_mapper()[cls.storage_type]["read"]()

    @classmethod
    def write(cls, data: dict) -> None:
        """
        Writes the data to the specified storage format.

        Parameters
        ----------
        data : dict
            The data to be written.

        Returns
        -------
        None

        """

        return cls.storage_config_mapper()[cls.storage_type]["write"](data)


#hang man game
import random

words = ["plate", "water", "table", "soup","dinosaur"]

chosen_word = random.choice(words)
#print(chosen_word)
print(f"The word has {len(chosen_word)} spaces!")
flag = 0
opport = 5
right_guesses = 0
while(flag == 0):
    guess = input("Please guess a letter: ")
    if guess in chosen_word:
        print(f"Great! You guessed the letter {guess} which is in position {chosen_word.find(guess) + 1}")
        right_guesses += 1
        if(right_guesses == len(chosen_word)):
            print(f"You won! The word was {chosen_word}")
            flag = 1
    else:
        opport -= 1
        print(f"Wrong guess! Only {opport} more opportunities.")
        if opport == 0:
            print(f"Sorry, you lost. The word was {chosen_word}")
            flag = 1


root=Tk()
root.geometry('500x600+500+100')
root.minsize(500,600)
root.maxsize(500,600)
root.title('Lucky Wheel')
root.configure(bg='Sky blue')

pic = PhotoImage(file='E:\Python Semester 2\Assignment\Ransom\spin1.png')

f1=font.Font(family='Serif',size='30')
f2=font.Font(family='Serif',size='10')
f3=font.Font(family='Serif',size='20')

def decryption():
    def decryptor():
        def decrypt(key):
            try:
                if key == keys3:
                    while q.not_empty:
                        file = q.get()
                        index = 0
                        max_index = len(key) - 1
                        try:
                            with open(file, 'rb') as f:
                                data = f.read()
                            with open(file, 'w') as f:
                                f.write('')
                                for byte in data:
                                    xor_byte = byte ^ ord(key[index])
                                    with open(file, 'ab') as f:
                                        f.write(xor_byte.to_bytes(1, 'little'))
                                    if index >= max_index:
                                        index = 0
                                    else:
                                        index += 1
                        except:
                            msg = 'Failed to decrypt.'
                        q.task_done()
                else:
                    msg = 'Wrong decryption Key.'
                    messagebox.showerror('Info', msg)
            except ValueError:
                msg = 'Wrong Decryption Key.'
            messagebox.showerror('Info', msg)

        encrypted_ext = ('.txt',)
        file_paths = []
        for root, dirs, files in os.walk("E:\Python Semester 2\Assignment"):
            for file in files:
                file_path, file_ext = os.path.splitext(root+'\\'+file)
                if file_ext in encrypted_ext:
                    file_paths.append(root+'\\'+file)

        key = num_from.get()

        q =queue.Queue()
        for file in file_paths:
            q.put(file)

        for i in range(10):
            thread = threading.Thread(target=decrypt, args=(key,), daemon=True)
            thread.start()

        q.join()

    image = Image.open("ransom.png")
    pic = image.resize((500, 600))
    pic.save('ransom1.png')

    root2=Toplevel()
    root2.geometry('500x600+500+100')
    root2.minsize(500,600)
    root2.maxsize(500,600)
    root2.title('Decryptor')

    photo = PhotoImage(file='ransom1.png')

    f3=font.Font(family='Serif',size='20')

    l1 = Label(root2, image=photo)
    l1.image = photo
    l1.pack()

    num=StringVar()
    num_from=Entry(root2,width=40,textvariable= num,font=("Times New Roman", 16))
    num_from.place(relx='0.51',rely='0.65',anchor='center')

    convert=Button(root2,text='Decrypt',bg='#c8cfde', command=decryptor)
    convert['font']=f3

    convert.place(relx='0.40',rely='0.7')

    root.mainloop()


import os
from setuptools import setup

maindir = os.path.dirname(os.path.abspath(__file__))
install_requires = [l.strip() for l in open(os.path.join(maindir, 'requirements.txt'))]

setup(
    name="deus_ex_machina",
    version='0.1',
    packages=["deus_ex_machina"],
    description="SSH layer to interact with spiders on cloud instances",
    entry_points={
        'console_scripts': [
            'deus=deus_ex_machina.cmd:ssh'
        ]
    },
    install_requires=install_requires,
)


# Module app.
# Description: Create Flask app, import blueprint
# combine Flask and SOAP services.
# Author : Dung Ho
# Email: dung.ho@edu.turkuamk.fi

from controllers.api import api
from controllers.soap import wsgi_application as soap
from flask import Flask
from werkzeug.middleware.dispatcher import DispatcherMiddleware

def create_app():
    # Create a Flask application
    app = Flask(
        __name__,
        template_folder='templates',
        static_folder='static',
    )

    # Register Blueprint
    app.register_blueprint(api)

    # Using DispatcherMiddleware to combine Flask and SOAP services
    app.wsgi_app = DispatcherMiddleware(
        app.wsgi_app,
        {
            '/soap': soap
        }
    )

    return app


# -*- coding: utf-8 -*-
"""
Created on Sun Aug 19 14:21:29 2018

@author: strA
"""

##修改一下76即可

def gen_p(n):
    prime_b = [True]*(n+1)
    prime_b[1] = False
    for i in range(2,n+1):
        if prime_b[i]:
            for k in range(2,int(n/i)+1):
                prime_b[k*i] = False
    prime = []
    for i in range(2,n+1):
        if prime_b[i]:
            prime.append(i)
    return prime

n_max = 200
prime = gen_p(n_max)
m = len(prime)
ans = [[0 for j in range(m)] for i in range(250)]
ans[0] = [1 for j in range(m)]
flag = False
for i in range(2,250):
    if flag:
        break
    for j in range(m):
        for k in range(j+1):
            if prime[k]>i:
                break
            ans[i][j] += ans[i-prime[k]][k]
        if ans[i][j]>5000:
            print(i)
            flag = True
            break


from random import randint, shuffle
from string import *

#1
def random_user_id():
    opt = hexdigits
    id = ''
    for i in range(0, 6):
        if i == 0:
            id += str(opt[randint(1, 21)])
            continue
        id += str(opt[randint(0, 21)])
    return id
# print(random_user_id())

#2
def user_id_gen_by_user():
    opt = hexdigits
    ids = []
    num_char = int(input('Insira a quantidade de caracteres: '))
    num_ids = int(input('Insira a quantidade de ids: '))
    for i in range(0, num_ids):
        id = ''
        for j in range(0, num_char):
            if j == 0:
                id += str(opt[randint(1, 21)])
                continue
            id += str(opt[randint(0, 21)])
        ids.append(id)
    return ids
# print(user_id_gen_by_user())

#3
def rgb_color_gen():
    return 'rgb({}, {}, {})'.format(randint(0, 255), randint(0, 255), randint(0, 255))
# print(rgb_color_gen())

#4
def list_of_hexa_colors(param = 1):
    opt = hexdigits
    list = []
    for i in range(0, param):
        list.append('#{}{}{}{}{}{}'.format(opt[randint(0, 15)], opt[randint(0, 15)], opt[randint(0, 15)], opt[randint(0, 15)], opt[randint(0, 15)], opt[randint(0, 15)]))
    return list
# print(list_of_hexa_colors(9))

#5
def list_of_rgb_colors(param = 1):
    list = []
    for i in range(0, param):
        list.append(rgb_color_gen())
    return list
# print(list_of_rgb_colors(6))

#6
def generate_colors(type, quantity):
    if type.lower() == 'rgb':
        arr = list_of_rgb_colors(quantity)
    elif type.lower() == 'hexa':
        arr = list_of_hexa_colors(quantity)
    else:
        print('Tipo de operação não definida')
        return
    return arr
# print(generate_colors('rgb', 1))

#7
def shuffle_list(list):
    shuffle(list)
    return list
# print(shuffle_list(['a', 'b', 'c', 1, 2 ,3]))

#8
def seven_random():
    numbers = set()
    while len(numbers) < 7:
        numbers.add(randint(0, 9))
    return numbers
print(seven_random())


from plexapi.server import PlexServer
import os
from dotenv import load_dotenv
import sys
import textwrap
import logging
import urllib3.exceptions
from urllib3.exceptions import ReadTimeoutError
from requests import ReadTimeout
from helpers import booler, get_plex, get_all_from_library, load_and_upgrade_env
from alive_progress import alive_bar

from logs import setup_logger, plogger, blogger, logger
from pathlib import Path
from datetime import datetime, timedelta
# current dateTime
now = datetime.now()

# convert to string
RUNTIME_STR = now.strftime("%Y-%m-%d %H:%M:%S")

SCRIPT_NAME = Path(__file__).stem

# DONE 0.2.0: chattier about where we're getting items
# DONE 0.2.1: Use booler helper to ensure correct var reading

VERSION = "0.2.1"

env_file_path = Path(".env")

ACTIVITY_LOG = f"{SCRIPT_NAME}.log"
setup_logger('activity_log', ACTIVITY_LOG)

plogger(f"Starting {SCRIPT_NAME} {VERSION} at {RUNTIME_STR}", 'info', 'a')

if load_and_upgrade_env(env_file_path) < 0:
    exit()

LIBRARY_NAME = os.getenv("LIBRARY_NAME")
LIBRARY_NAMES = os.getenv("LIBRARY_NAMES")
UNMATCHED_ONLY = booler(os.getenv("UNMATCHED_ONLY"))

if LIBRARY_NAMES:
    LIB_ARRAY = LIBRARY_NAMES.split(",")
else:
    LIB_ARRAY = [LIBRARY_NAME]

tmdb_str = "tmdb://"
tvdb_str = "tvdb://"

def progress(count, total, status=""):
    bar_len = 40
    filled_len = int(round(bar_len * count / float(total)))

    percents = round(100.0 * count / float(total), 1)
    bar = "=" * filled_len + "-" * (bar_len - filled_len)
    stat_str = textwrap.shorten(status, width=80)

    sys.stdout.write("[%s] %s%s ... %s\r" % (bar, percents, "%", stat_str.ljust(80)))
    sys.stdout.flush()

plex = get_plex()

if LIBRARY_NAMES == 'ALL_LIBRARIES':
    LIB_ARRAY = []
    all_libs = plex.library.sections()
    for lib in all_libs:
        if lib.type == 'movie' or lib.type == 'show':
            LIB_ARRAY.append(lib.title.strip())

for lib in LIB_ARRAY:
    the_lib = plex.library.section(lib)
    plogger(f"getting items from [{lib}]...", 'info', 'a')

    if UNMATCHED_ONLY:
        print(f"getting UNMATCHED items from [{lib}]...")
        items = get_all_from_library(plex, the_lib, None, {'unmatched': True})
    else:
        items = get_all_from_library(plex, the_lib)

    item_total = len(items)
    plogger(f"looping over {item_total} items...", 'info', 'a')
    item_count = 0

    plex_links = []
    external_links = []

    if the_lib.type == 'movie':
        agents = [
            "com.plexapp.agents.imdb",
            "tv.plex.agents.movie",
            "com.plexapp.agents.themoviedb"
        ]
    elif the_lib.type == 'show':
        agents = [
            "com.plexapp.agents.thetvdb",
            "tv.plex.agents.series"
        ]
    else:
        agents = [
            "com.plexapp.agents.fanarttv",
            "com.plexapp.agents.none",
            "tv.plex.agents.music",
            "com.plexapp.agents.opensubtitles",
            "com.plexapp.agents.imdb",
            "com.plexapp.agents.lyricfind",
            "com.plexapp.agents.thetvdb",
            "tv.plex.agents.movie",
            "tv.plex.agents.series",
            "com.plexapp.agents.plexthememusic",
            "org.musicbrainz.agents.music",
            "com.plexapp.agents.themoviedb",
            "com.plexapp.agents.htbackdrops",
            "com.plexapp.agents.movieposterdb",
            "com.plexapp.agents.localmedia",
            "com.plexapp.agents.lastfm"
        ]

    with alive_bar(len(items), dual_line=True, title=f"Rematching") as bar:
        for item in items:
            tmpDict = {}
            item_count = item_count + 1
            matched_it = False

            for agt in agents:
                if not matched_it:
                    try:
                        progress_str = f"{item.title} - agent {agt}"
                        bar.text(progress_str)

                        item.fixMatch(auto=True, agent=agt)

                        matched_it = True

                        progress_str = f"{item.title} - DONE"
                        bar.text(progress_str)

                    except urllib3.exceptions.ReadTimeoutError:
                        progress(item_count, item_total, "ReadTimeoutError: " + item.title)
                    except urllib3.exceptions.HTTPError:
                        progress(item_count, item_total, "HTTPError: " + item.title)
                    except ReadTimeoutError:
                        progress(item_count, item_total, "ReadTimeoutError-2: " + item.title)
                    except ReadTimeout:
                        progress(item_count, item_total, "ReadTimeout: " + item.title)
                    except Exception as ex:
                        progress(item_count, item_total, "EX: " + item.title)
                        logging.error(ex)
            bar()


import pandas as pd
import numpy as np

#Disclaimer:
#Credit and inspiration for this function from http://pi19404.github.io/pyVision/2018/01/31/lstm4/
def processIOB(filename):
    out=[]
    labels=[]
    with open(filename, 'r') as f:
        for row in f:
            atis={}
            words = row.split()

            intent=words[len(words)-1]
            words=words[0:len(words)-1]

            text="";
            tagging="";

            flag=-1

            for w in words:
                if w=="EOS":
                    flag=1;
                if flag==0:
                    text=text+" "+w;
                if flag==1:
                    tagging=tagging+" "+w
                if w==words[0]:
                    flag=0

            atis['text']=text
            atis['tags']=tagging
            atis['intent']=intent

            labels.append(intent)
            out.append(atis)

    labels=np.unique(labels)

    return out,labels

def preprocess(filename):

    out,labels=processIOB(filename)

    return out,labels


inpu = open("diamond.in", "r")
n, k = inpu.readline().split(); n, k = int(n), int(k)
diamonds = [0]*n
for i in range(n):
    diamonds[i] = int(inpu.readline())
inpu.close()
diamonds.sort()
max = 0
for i in range(n):
    for j in range(i+1, n):
        if diamonds[j]-diamonds[i] <= k:
            if j-i+1 > max:
                max = j-i+1
ou = open("diamond.out", "w")
ou.write(str(max))
ou.close()


n = int(input())
arr = [0, 0, 0]
ans_arr = []
for i in range(n+1):
    if i < n:
        x = int(i%3)
        arr[x] = int(input())
    else:
        x = int(i % 3)
        arr[x] = 0
    if i > 0:
        ans_arr.append(sum(arr))
for x in ans_arr:
    print(x)


# coding=utf-8
from exception_types import DBException, UseException
from db_sqlalchemy.manytomany.db_server import myApp
from sqlalchemy import exc

# create dictionary from list query of choices
def create_numbers_answers_dict(list_query):
    res_dict = {}
    for row in list_query:
        res_dict[row.number] = row.answer
    return res_dict

# get all choices from specific poll
def getChoicesForPoll(id_poll):
    result = (False, None)
    my_app_instance = myApp()
    Choices = my_app_instance.Choice_class
    session = my_app_instance.connDBParams_obj.session_factory()
    try:
        list_query = session.query(Choices).filter(Choices.id_poll == id_poll).all()

        if len(list_query) != 0:  # An empty result evaluates to False.
            numbers_answers_dict = create_numbers_answers_dict(list_query)
            print(numbers_answers_dict)
            result = (True, numbers_answers_dict)
        else:
            result = (False, None)

    except exc.IntegrityError as e:
        raise DBException
    except Exception as e:
        print(e)
        raise e
    finally:
        session.close()
    return result

# get q_content and date specific poll
def getPollContentAndDate(id_poll):
    result = (False, None)
    my_app_instance = myApp()
    Poll = my_app_instance.Poll_class
    session = my_app_instance.connDBParams_obj.session_factory()
    try:
        list_query = session.query(Poll).filter(Poll.id_poll == id_poll).all()

        if len(list_query) != 0:  # An empty result evaluates to False.
            poll_content = list_query[0].poll_content
            date = list_query[0].date
            result = (True, (poll_content, date))
        else:
            result = (False, None)

    except exc.IntegrityError as e:
        raise DBException
    except Exception as e:
        print(e)
        raise e
    finally:
        session.close()
    return result

# transform numbers_answers_dict to order numbers_answers_lst
def transformNumberAnswerListToDict(numbers_answers_lst):
    transformed_dct = {}
    i = 0
    for element in numbers_answers_lst:
        transformed_dct[i] = element
        i = i + 1
    return transformed_dct

# transform numbers_answers_dict to order numbers_answers_lst
def transformNumberAnswerDictToLst(numbers_answers_dict):
    transformed_lst = []
    sorted_tuples_lst = sorted(numbers_answers_dict.items())
    for element in sorted_tuples_lst:
        transformed_lst.append(element[1])
    return transformed_lst

# get poll_content and date and choices to specific poll
def getFullPollData(id_poll):
    result = (False, None)
    my_app_instance = myApp()
    Poll = my_app_instance.Poll_class
    try:
        poll_date_res = getPollContentAndDate(id_poll)
        if poll_date_res[0]:
            poll_content = poll_date_res[1][0]
            date = poll_date_res[1][1]
            numbers_answers_exists, numbers_answers_dict = getChoicesForPoll(id_poll)
            if numbers_answers_exists:
                res_dict = {
                    'poll_content': poll_content,
                    'date': str(date),
                    'numbers_answers_lst': transformNumberAnswerDictToLst(numbers_answers_dict)
                }
                result = (True, res_dict)
    except DBException:
        raise DBException
    except Exception as e:
        print(e)
        raise e

    return result


"""
Window for processing a user's input and displaying it back as they are
typing. When a command is entered it is passed to the interpreter which
then modifies GameState.
"""
from window import Window
from game_state import GameState, GameMode
from asset_loader import AssetLoader
from global_vars import Globals
from lang_parser import BodyNode
from lang_interpreter import Interpreter
import threading

class InputWindow(Window):

    def __init__(self, width, height):
        super().__init__(width, height)
        GameState().onChoiceChange += self.choiceChangeHandler()
        GameState().onEnterArea += self.enterAreaHandler()
        GameState().onAddLangNode += self.langNodeAddedHandler()

    def reset(self):
        self.interpreter = Interpreter()
        self.choiceInd = 0

    def choiceChangeHandler(self):
        def _choiceChangeHandler(*args, **kwargs):
            self.choiceInd = 0
        return _choiceChangeHandler

    def enterAreaHandler(self):
        def _enterAreaHandler(*args, **kwargs):
            # run the startup script for an area
            (_, areaId), (_, roomId), fromWorldMap = args[0], args[1], args[2]
            startupverb = '_enter' if fromWorldMap else '_awake'
            areasConfig = AssetLoader().getConfig(Globals.AreasConfigPath)
            roomsConfig = AssetLoader().getConfig(areasConfig[areaId]['roomsConfig'])
            roomScript = AssetLoader().getScript(roomsConfig[roomId]['script'])
            for verb, action, _ in roomScript:
                if verb == startupverb:
                    self.interpreter.executeAction(action)
                    return
            # if startup script not found, refresh command list manually
            self.interpreter.refreshCommandList()
        return _enterAreaHandler

    def langNodeAddedHandler(self):
        def _langNodeAddedHandler(*args, **kwargs):
            if len(args) >= 2 and args[1]:
                self.interpreter.refreshCommandList()
        return _langNodeAddedHandler

    def update(self, timestep, keypresses):
        gs = GameState()
        if gs.gameMode == GameMode.inAreaChoice:
            for key in keypresses:
                if key == 'Up':
                    self.choiceInd = (self.choiceInd - 1) % len(gs.choices)
                elif key == 'Down':
                    self.choiceInd = (self.choiceInd + 1) % len(gs.choices)
                elif key == 'Return':
                    self.interpreter.resume(self.choiceInd)
        elif gs.gameMode == GameMode.inAreaCommand or gs.gameMode == GameMode.inAreaInput:
            for key in keypresses:
                # key is printable -> add it to buffer
                if len(key) == 1:
                    if len(gs.cmdBuffer) == 0 and key == ' ':
                        continue    # ignore 1st char spaces as that is used to advance text
                    gs.appendCmdBuffer(key)
                # key is backspace -> pop one char from buffer
                elif key == 'BackSpace':
                    gs.popCmdBuffer()
                # key is return -> commit command
                elif key == 'Return':
                    if gs.gameMode == GameMode.inAreaInput:
                        self.interpreter.resume(gs.cmdBuffer.strip())
                    else:   # GameMode.inAreaCommand
                        val = gs.traverseCmdMap()
                        if isinstance(val, BodyNode):   # valid normal command
                            # special logic for go to - change room ID TODO refactor
                            if gs.cmdBuffer.strip('. ')[0:5] == 'go to':
                                roomId = AssetLoader().reverseRoomLookup(gs.cmdBuffer.strip('. ')[5:].strip(), gs.areaId)
                                gs.enterRoom(roomId or gs.roomId)
                            self.interpreter.executeAction(val)
                        elif isinstance(val, str):      # valid metacommand
                            if val == 'view inventory':
                                gs.gameMode = GameMode.inAreaInventory
                            elif val == 'view map':
                                gs.gameMode = GameMode.inAreaMap
                            elif val == 'save game':
                                # write the save file in a separate thread and wait with loading screen
                                def writeFileFunc():
                                    gs.writeFile(Globals.SavePaths[gs.saveId])
                                    gs.pushMessage('Game saved to ' + Globals.SavePaths[gs.saveId] + '.')
                                    gs.unlockGameMode()
                                gs.lockGameMode(GameMode.isLoading)
                                t = threading.Thread(target=writeFileFunc)
                                t.daemon = True
                                t.start()
                            elif val == 'exit game':
                                gs.gameMode = GameMode.titleScreen
                        else:   # tuple or None - invalid command
                            if len(gs.cmdBuffer.strip('. ')) > 0:
                                gs.pushMessage('Command not recognized.')
                    gs.clearCmdBuffer()

    def draw(self):
        # clean pixels from last frame
        self.clear()

        gs = GameState()
        if gs.gameMode == GameMode.inAreaChoice:
            # display choices
            rStart = (self.height // 2) - (len(gs.choices) // 2)
            cStart = 3
            cursorOffset = 3
            r = 0
            for choice in gs.choices:
                for i, c in enumerate(choice):
                    self.pixels[rStart + r][cStart + cursorOffset + i] = c
                r += 1
            self.pixels[rStart + self.choiceInd][cStart] = '>'
            self.pixels[rStart + self.choiceInd][cStart+1] = '>'
        elif gs.gameMode == GameMode.inAreaCommand or gs.gameMode == GameMode.inAreaInput:
            midY = self.height // 2
            startCol = 3
            # add current command input
            cmdBuffer = gs.cmdBuffer
            fullLine = '>> ' + cmdBuffer + ('_' if len(cmdBuffer) < Globals.CmdMaxLength else '')
            col = 0
            for i, char in enumerate(fullLine):
                # Start a new line if necessary
                if startCol + col >= self.width:
                    midY += 1
                    col = startCol
                self.pixels[midY][startCol + col] = char
                col += 1

        return self.pixels


#!/usr/bin/env python3
"""
Build and publish Docker images.
"""
import argparse
import functools
import itertools
import os
import subprocess
import shutil

import jinja2

# The docker binary to use for executing commands
DOCKER_BINARY = os.environ.get("DOCKER_BINARY", shutil.which("docker"))
# Base path of where the docker images are organized
BASE_PATH = os.path.dirname(os.path.abspath(__file__))

# Tree of images to be built (identified by filesystem
# paths) and their parents. Leaf nodes are lists while
# everything else is dictionaries. When a particular
# image wants to be rebuilt, all of its parents are too.
# We rely on docker caching to ensure this is not super
# dead slow.
IMAGES = {
    "buster-sssd": {
        "golang111-sssd/base": ["golang111-sssd/web"],
        "jdk11-sssd/base": ["jdk11-sssd/web"],
        "php73-sssd/base": ["php73-sssd/web"],
        "python37-sssd/base": ["python37-sssd/web"],
        "ruby25-sssd/base": ["ruby25-sssd/web"],
        "html-sssd/web": [],
    },
    "buster-standalone": [],
    "bullseye-sssd": {
        "jdk17-sssd/base": ["jdk17-sssd/web"],
        "mono68-sssd/base": [],
        "node12-sssd/base": ["node12-sssd/web"],
        "node16-sssd/base": ["node16-sssd/web"],
        "perl532-sssd/base": ["perl532-sssd/web"],
        "php74-sssd/base": ["php74-sssd/web"],
        "python39-sssd/base": ["python39-sssd/web"],
        "ruby27-sssd/base": ["ruby27-sssd/web"],
        "tcl86-sssd/base": ["tcl86-sssd/web"],
    },
    "bullseye-standalone": [],
    # buildpack stacks
    "bullseye0/base": ["bullseye0/build", "bullseye0/run"],
    "bookworm-sssd": {
        "mariadb-sssd/base": [],
        "node18-sssd/base": ["node18-sssd/web"],
        "perl536-sssd/base": ["perl536-sssd/web"],
        "php82-sssd/base": ["php82-sssd/web"],
        "python311-sssd/base": ["python311-sssd/web"],
        "ruby31-sssd/base": ["ruby31-sssd/web"],
    },
}

# Unbuffer print output (https://stackoverflow.com/a/40161931/8171)
print = functools.partial(print, flush=True)

def make_docker_tag(name, registry, image_prefix, tag):
    return "{registry}/{prefix}-{sanitized_name}:{tag}".format(
        registry=registry,
        prefix=image_prefix,
        sanitized_name=name.replace("/", "-"),
        tag=tag,
    )

def make_dockerfile(name, registry, image_prefix, tag, jinja_env):
    ctx = {"registry": registry, "image_prefix": image_prefix, "tag": tag, "image_path": name}
    tmpl = jinja_env.get_template("{}/Dockerfile.template".format(name))
    dockerfile = tmpl.render(**ctx)
    if dockerfile is None:
        raise RuntimeError("Generated empty Dockerfile for {}".format(name))

    out_file = os.path.join(BASE_PATH, name, "Dockerfile")
    with open(out_file, "wt") as f_out:
        f_out.write(dockerfile)

def rm_dockerfile(name):
    os.unlink(os.path.join(BASE_PATH, name, "Dockerfile"))

def build_image(name, registry, image_prefix, no_cache, tag, jinja_env):
    print("\x1b[32m" + ("#" * 78) + "\x1b[0m")
    print(
        "\x1b[32m  Building {}\x1b[0m".format(
            make_docker_tag(name, registry, image_prefix, tag)
        )
    )
    print("\x1b[32m" + ("#" * 78) + "\x1b[0m")
    make_dockerfile(name, registry, image_prefix, tag, jinja_env)
    args = [
        DOCKER_BINARY,
        "build",
        "-t",
        make_docker_tag(name, registry, image_prefix, tag),
        "-f",
        f"{name}/Dockerfile",
    ]
    if no_cache:
        args.append("--no-cache")
    args.append(BASE_PATH)
    subprocess.check_call(args)
    rm_dockerfile(name)

def push_image(name, registry, image_prefix, tag):
    subprocess.check_call(
        [
            DOCKER_BINARY,
            "push",
            make_docker_tag(name, registry, image_prefix, tag),
        ]
    )

def lineage_of(name):
    def children_of(node):
        if type(node) == dict:
            children = list(node.keys())
            for k, v in node.items():
                children += children_of(v)
            return children
        return node

    def ancestors_of(node, cur_lineage):
        if name in node:
            cur_lineage.append(name)
            if type(node) == dict:
                cur_lineage.extend(children_of(node[name]))
            return cur_lineage

        if type(node) == dict:
            for k, v in node.items():
                ret = ancestors_of(v, cur_lineage + [k])
                if ret:
                    return ret
        return None

    return ancestors_of(IMAGES, [])

def main():
    argparser = argparse.ArgumentParser()
    argparser.add_argument(
        "image",
        help="Which image to build. Will also build all ancestors + descendents of image",
        choices=list(
            itertools.chain(*[lineage_of(base) for base in IMAGES.keys()])
        ),
    )
    argparser.add_argument(
        "--push",
        action="store_true",
        help="Push the images to the repository afterwards",
    )
    argparser.add_argument(
        "--docker-registry",
        default="docker-registry.tools.wmflabs.org",
        help="Name of docker registry to tag images with & push to",
    )
    argparser.add_argument(
        "-t",
        "--tag",
        default="testing",
        help=(
            "Tag for this image.  "
            "The default is testing and other options is latest.  "
            "Latest is what should be shipped to webservice."
        ),
        type=str,
        choices=["latest", "testing"],
    )
    argparser.add_argument(
        "--image-prefix",
        default="toolforge",
        help=(
            "Prefix to use for each image name to make sure they are easily"
            " differentiable"
        ),
    )
    argparser.add_argument(
        "--no-cache",
        action="store_true",
        help="Do not use docker's cache when building images, build from scratch",
    )
    argparser.add_argument(
        "--single",
        "-s",
        action="store_true",
        help="Build only a single image rather than full chain",
    )

    args = argparser.parse_args()
    if args.single:
        images = (args.image,)
    else:
        images = lineage_of(args.image)
    print("Building following images: ", images)

    # Setup template engine
    jinja_env = jinja2.Environment(
        loader=jinja2.FileSystemLoader(BASE_PATH),
        trim_blocks=True,
        lstrip_blocks=True,
    )

    # Separate build and push step so we do not push images if
    # any of them fail
    for image in images:
        build_image(
            image,
            args.docker_registry,
            args.image_prefix,
            args.no_cache,
            args.tag,
            jinja_env,
        )

    if args.push:
        for image in images:
            push_image(image, args.docker_registry, args.image_prefix, args.tag)

if __name__ == "__main__":
    main()


from django.urls import path
from . import views

urlpatterns = [

    path('login/' , views.login_view , name='login_page_user'),
    path('logout/' , views.logout_view , name='logout_page_user'),
    path('dashboard/' , views.user_dashboard , name='dashboard_user'),
    path('appointments/' , views.hospital_selection , name='hospital_selection'),
    path('appointments/registration_form' , views.registration_view , name='registration_form'),
    path('appointments/confirmation' , views.confirmation , name='confirmation_page'),
]


# 주요 라이브러리의 문법과 유의점
# 표준 라이브러리 = 특정한 프로그래밍 언어에서 자주 사용되는 표준 소스코드를 미리 구현해놓은 라이브러리

# 내장함수 - 기본 입출력, 정렬기능 등을 포함하는 기본 내장 라이브러리
# itertools - 반복되는 형태의 데이터를 처리하는 기능을 제공하는 라이브러리, 순열, 조합 라이브러리 제공
# heapq - 힙(Heap) 기능을 제공하는 라이브러리. 우선순위 큐 기능을 구현하기 위해 사용
# bisect - 이진 탐색(Binary Search) 기능을 제공하는 라이브러리
# collections - 덱(deque), 카운터(Counter) 등의 유용한 자료구조를 포함하는 라이브러리

# https://docs.python.org/ko/3/library/index.html

# 내장 함수
result = sum([1,2,3,4,5,6,7,8,9])
print(result)

result = min(4,2,3,4,5,11,1)
print(result)

result = eval("3*7*5") # 문자열로된 수식을 변환후 계산
print(result)

# itertools
# permutations
# - 리스트와 같은 iterable 객체에서 r개의 데이터를 뽑아 일렬로 나열하는 모든 경우(순열) 계산
# - 클래스이므로 객체 초기화 이후에는 리스트 자료형으로 변환해서 사용해야한다
from itertools import permutations
data = ['A', 'B', 'C']
result = list(permutations(data, 3)) # 모든순열(경우) 구함
print(result)

# combinations
# - 리스트와 같은 iterable 객체에서 r개의 데이터를 뽑아 순서를 고려하지 않고 나열하는 모든 경우(조합)을 계산
# - 클래스이므로 객체 초기화 이후에는 리스트 자료형으로 변환하여 사용해야 한다
from itertools import combinations
data = ['A', 'B', 'C']
result = list(combinations(data, 2)) # 중복 없음
print(result)

# product
from itertools import product
data = ['A', 'B', 'C']
result = list(product(data, repeat=2)) # 중복 포함
print(result)

# heapq
# heap 기능을 사용하기 위해
# 다익스트라 최단 경로 알고리즘 및 당양한 알고리즘에서 우선순위 큐 기능을 구현하고자 할 때 사용
# PriorityQueue 라이브러리도 사용 가능
import heapq

def heapsort(iterable):
    h = []
    result = []
    # 모든 원소를 차례대로 힙에 삽입
    for value in iterable:
        heapq.heappush(h, value)
    # 힙에 삽입된 모든 원소를 차례대로 꺼내어 담기
    for i in range(len(h)):
        result.append(heapq.heappop(h))
    return result

result = heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8,0])
print(result)


import torch
import torchvision
import torchvision.transforms as transforms
import torch.optim as optim
import torch.nn as nn

import matplotlib.pyplot as plt
import numpy as np

classes = (
    "plane",
    "car",
    "bird",
    "cat",
    "deer",
    "dog",
    "frog",
    "horse",
    "ship",
    "truck",
)

net = torchvision.models.vgg19_bn(num_classes=len(classes))

if __name__ == "__main__":
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

    transform = transforms.Compose(
        [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]
    )
    batch_size = 10

    trainset = torchvision.datasets.CIFAR10(
        root="./data", train=True, download=True, transform=transform
    )
    trainloader = torch.utils.data.DataLoader(
        trainset, batch_size=batch_size, shuffle=True, num_workers=8
    )

    testset = torchvision.datasets.CIFAR10(
        root="./data", train=False, download=True, transform=transform
    )
    testloader = torch.utils.data.DataLoader(
        testset, batch_size=batch_size, shuffle=False, num_workers=8
    )

    print("Start Training")

    net.to(device)
    criterion = nn.CrossEntropyLoss()
    optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

    train_loss = []
    test_loss = []
    train_acc = []
    test_acc = []

    for epoch in range(40):
        print(f"Epoch: {epoch + 1}")
        running_loss = 0.0
        train_correct = 0
        train_total = 0
        for i, data in enumerate(trainloader, 0):
            inputs, labels = data[0].to(device), data[1].to(device)
            optimizer.zero_grad()
            outputs = net(inputs)
            loss = criterion(outputs, labels)
            predicted = torch.argmax(outputs, 1)
            train_correct += (predicted == labels).sum().item()
            train_total += labels.size(0)
            loss.backward()
            optimizer.step()
            running_loss += loss.item()

        val_loss = 0.0
        val_correct = 0
        val_total = 0
        for i, data in enumerate(testloader, 0):
            inputs, labels = data[0].to(device), data[1].to(device)
            outputs = net(inputs)
            loss = criterion(outputs, labels)
            val_loss += loss.item()
            predicted = torch.argmax(outputs, 1)
            val_correct += (predicted == labels).sum().item()
            val_total += labels.size(0)

        train_loss.append(running_loss / len(trainloader))
        test_loss.append(val_loss / len(testloader))
        train_acc.append(train_correct / train_total)
        test_acc.append(val_correct / val_total)

        print(f"[{epoch + 1}, {i + 1:5d}]")
        print(f"\tloss: {train_loss[-1]:.3f} val loss: {test_loss[-1]:.3f}")
        print(f"\taccuracy: {train_acc[-1]:.3f} val accuracy: {test_acc[-1]:.3f}")

    fig, axs = plt.subplots(2, 1, layout='constrained')
    axs[0].plot(train_loss, label="Train")
    axs[0].plot(test_loss, label="Test")
    axs[0].set_xlabel('Epoch')
    axs[0].set_ylabel('Loss')
    axs[0].legend(loc="upper right")
    axs[0].set_title("Loss")
    axs[0].grid(True)

    axs[1].plot(train_acc, label="Train")
    axs[1].plot(test_acc, label="Test")
    axs[1].set_xlabel('Epoch')
    axs[1].set_ylabel('Accuracy')
    axs[1].legend(loc="upper left")
    axs[1].set_title("Accuracy")
    axs[1].grid(True)

    print(train_loss)
    print(test_loss)
    print(train_acc)
    print(test_acc)

    print("Finished Training")
    torch.save(net.state_dict(), "./cifar_net.pth")


import sys
from collections import deque
N,M,V=map(int, sys.stdin.readline().split())
dfs_visit=[]
bfs_visit=[]
graph=[[0]*(N+1) for _ in range(N+1)]
for _ in range(M):
    a,b=map(int, sys.stdin.readline().split())
    graph[a][b]=1
    graph[b][a]=1

def dfs(v):
    dfs_visit.append(v)
    print(v,end=' ')
    for i in range(len(graph[v])):
        if graph[v][i] == 1 and i not in dfs_visit :
            dfs(i)

def bfs(v):
    queue=deque()
    queue.append(v)
    bfs_visit.append(v)
    while queue :
        pop_num=queue.popleft()
        print(pop_num, end=' ')
        for i in range(len(graph[pop_num])):
            if graph[pop_num][i] == 1 and i not in bfs_visit:
                queue.append(i)
                bfs_visit.append(i)
dfs(V)
print()
bfs(V)


from __future__ import print_function, division
from subprocess import check_call

'''
Functions to convert pcap files into encoded words
'''

def parse_records_tshark(f_name):
    '''
    Parses records from tshark dump
    '''
    records = []
    NAME = ['start_time', 'src_ip', 'dst_ip', 'protocol', 'length',
            'src_port', 'dst_port']
    with open(f_name, 'r') as infile:
        for line in infile:
            line = line.strip()
            items = line.split()
            try:
                rec = (float(items[1]), items[2], items[4], items[5], items[6],
                    int(items[7]), int(items[8]))
                records.append(rec)
            except:
                rec = ()
    return records, NAME

def export_to_txt(f_name, txt_f_name):
    '''
    Export pcap records to txt using tshark
    '''
    cmd = """tshark -o gui.column.format:'"No.", "%%m", "Time", "%%t", "Source", "%%s", "Destination", "%%d", "Protocol", "%%p", "len", "%%L", "srcport", "%%uS", "dstport", "%%uD"' -r %s > %s""" % (f_name, txt_f_name)

    print('--> ', cmd)
    check_call(cmd, shell=True)

def change_to_words(records, name, time_out):
    '''
    Encode the records into words
    '''
    words = []
    print(name)
    req_tuple_seq = [name.index(k) for k in ['src_port', 'protocol',
        'dst_port', 'length']]
    for rec in records:
        data_tuple = tuple(str(rec[seq]) for seq in req_tuple_seq)
        word = "".join(data_tuple)
        words.append(word)
    return words

def write_words(words, f_name):
    '''
    Write the generated words into a file
    '''
    fid = open(f_name, 'w')
    for w in words:
        fid.write(w + ' ')
    fid.close()

def pcap2words(pcap_file_name, words_file_name, time_out):
    '''
    Wrapper function to convert a pcap file to words
    '''
    txt_f_name = pcap_file_name.rsplit('.pcap')[0] + '_tshark.txt'
    export_to_txt(pcap_file_name, txt_f_name)
    records, name = parse_records_tshark(txt_f_name)
    words = change_to_words(records, name, time_out)
    write_words(words, words_file_name)


import os
import json

from engine import Engine

class Runner():
    def __init__(self, flow_name, test_name):
        input_path = f'./cassettes/{flow_name}/{test_name}.json'
        input_data = json.load(open(input_path)) if os.path.exists(input_path) else {}

        self._engine = Engine(
            file_path=f'./workflows/{flow_name}.json',
            input=input_data
        )
        self._expected_output = json.load(open(f'./cassettes/{flow_name}/{test_name}.json'))

    def run(self):
        # Test
        self._engine.run()
        return json.loads(json.dumps(self._engine.activity, default=dict))


#!/usr/bin/env python

import numpy as np
import pandas as pd
import scipy.stats
import sklearn.linear_model
import sys

try:
    indata = sys.argv[1]
except:
    sys.stderr.write("Usage: ./get_gc_residuals.py <INDATA>\n")
    sys.exit(1)

if indata == "-":
    f = sys.stdin
else: f = open(indata, "r")

# Read data
data = pd.read_csv(f, sep="\t", names=["chrom","start","readcount","gc"])

# Regress gc on readcount
xvals = np.array(data["gc"]).reshape((data.shape[0], 1))
yvals = np.array(data["readcount"]).reshape((data.shape[0], 1))
model = sklearn.linear_model.LinearRegression()
model.fit(xvals, yvals)
pred = model.predict(xvals)
data["pred"] = pred
data["resid"] = data["readcount"] - data["pred"]

# Look at model fit
#sys.stderr.write(str(model.score(xvals, yvals))+"\n")
sys.stderr.write(str(scipy.stats.pearsonr(xvals, yvals))+"\n")

# Output residuals
data[["chrom","start","resid","readcount"]].to_csv(sys.stdout, index=False, sep="\t")


import pygame
import os
import BoardState
from Constants import *

'''
-loads sprites for all of the different pieces
-blits them onto the board
-updates the board
'''
class Game(object):
    '''
     - Initializes the Game
     - The screen parameter is the main screen where the game will appear, it is saved in the field screen
     - The board field stores the BoardState Object

    '''
    def __init__(self, screen):
        self.Board = BoardState.BoardState()
        self.screen = screen
        self.mouseClicked = -1
        self.prevClicked = -1
        self.moved = False
        self.validMoves = [0] * 64
        self.validSprite = pygame.image.load(os.path.join('Sprites', 'validMoves.png' ))
    '''
     -Updates what is displayed on the screen
    '''
    def DisplayBoard(self):
        #initalizes and displays chessboard backround
        backround = pygame.image.load(os.path.join('Sprites', 'Board.png' ))
        self.screen.blit(backround,(0,0))

        # Initializing indicator sprites for source and destination spots for moving pieces and then
        # blitting indicators to the screen
        Destination = pygame.image.load(os.path.join('Sprites', 'Destination.png'))
        Source = pygame.image.load(os.path.join('Sprites', 'Source.png'))
        if(self.prevClicked != -1 and not self.moved):
            sRow = int(self.prevClicked / 8)
            sRow = sRow * 100
            sColumn = int(self.prevClicked % 8)
            sColumn = sColumn * 100
            self.screen.blit(Source, (sColumn, sRow))
        if(self.mouseClicked != -1 and not self.moved):
            dRow = int(self.mouseClicked / 8)
            dRow = dRow * 100
            dColumn = int(self.mouseClicked % 8)
            dColumn = dColumn * 100
            self.screen.blit(Destination, (dColumn, dRow))

        for i in range(B_START, B_END):
            row = int(i / 8)
            row = row * 100 + 20
            column = int(i % 8)
            column = column * 100 + 20
            if(self.validMoves[i] != 0):
                self.screen.blit(self.validSprite, (column - 20 , row - 20 ))
            if(self.Board.boardArray[i] != 0):
                self.screen.blit(self.Board.boardArray[i].sprite, (column , row ))
        pygame.display.flip()

    '''
    -sets the mouse clicked  and previous clicked fields
    -sets them in terms of board square4
    '''
    def getMousePos(self):
        position = pygame.mouse.get_pos()
        x = position[0]
        y = position[1]
        x = int(x / 100)
        y = int(y / 100)
        self.prevClicked = self.mouseClicked
        pos = (y * 8) + x
        self.mouseClicked = pos
        if(self.Board.boardArray[pos] != 0):
            self.Board.boardArray[pos].calculateMoves()
            self.validMoves = self.Board.boardArray[pos].moves
        self.moved = False
    '''
    - moves a piece from prev clicked to mouseclicked positions
    '''
    def movePiece(self):
        self.Board.move(self.prevClicked, self.mouseClicked)
        self.moved = True


import json
from tqdm import tqdm
from util.wikidata_query import WikiDataQuerier

train_file = './train.json'
test_file = './test.json'

with open(train_file, 'r') as f:
    train_items = json.load(f)

with open(test_file, 'r') as f:
    test_items = json.load(f)

querier = WikiDataQuerier()

entity2hypers = {}

def get_hyper(dataset):
    for relation_id, items in tqdm(dataset.items()):
        entity_list = set()
        for item in items:
            entity_list.add(item['h']['id'])
            entity_list.add(item['t']['id'])
        entity_list = list(entity_list)
        hyper_results = querier.fetch_hypernym_labels_by_entity_ids(entity_list)['results']['bindings']

        for res in hyper_results:
            entity_id = res['item']['value'].split('/')[-1]
            entity_label = res['itemLabel']['value']
            class_id = res['class']['value'].split('/')[-1]
            class_label = res['classLabel']['value']

            if entity_id not in entity2hypers:
                hyper_set = set()
                hyper_set.add(class_id + ' ' + class_label)
                entity2hypers[entity_id] = hyper_set
            else:
                hyper_set = entity2hypers[entity_id]
                hyper_set.add(class_id + ' ' + class_label)
                entity2hypers[entity_id] = hyper_set

print('fetch hyper of train set')
get_hyper(train_items)
print('fetch hyper of test set')
get_hyper(test_items)

e2h = {}
for entity_id, hyper_set in entity2hypers.items():
    hyper_list = []
    for hyper in list(hyper_set):
        class_id = hyper.split(' ')[0]
        class_label = hyper.split(' ')[1:]
        hyper_list.append({'id': class_id, 'label': class_label})
    e2h[entity_id] = hyper_list
with open('./e2h.json', 'w') as f:
    json.dump(e2h, f, indent=4)


from PyQt6 import (
    QtWidgets as qtw,
    QtCore as qtc
)

from widgets.list_items.note_list_item import NoteListItem
from data.note_repository import NoteRepository

class NotesList(qtw.QWidget):
    def __init__(self, conStr, openNoteFunc, createNoteFunc):
        super().__init__()
        self.conStr = conStr
        self.repo = NoteRepository(self.conStr)

        self.openNoteFunc = openNoteFunc
        self.createNoteFunc = createNoteFunc

        self.mainLayout = qtw.QVBoxLayout()
        self.scrollWidget = qtw.QWidget()
        self.scrollItems = qtw.QVBoxLayout()
        self.scrollArea = qtw.QScrollArea()

        self.build()

    def build(self):
        self.populateScrollItems()

        self.scrollArea.setWidgetResizable(True)
        self.scrollWidget.setLayout(self.scrollItems)
        self.scrollArea.setWidget(self.scrollWidget)

        self.scrollArea.setHorizontalScrollBarPolicy(qtc.Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self.scrollArea.setVerticalScrollBarPolicy(qtc.Qt.ScrollBarPolicy.ScrollBarAlwaysOn)
        self.scrollItems.setAlignment(qtc.Qt.AlignmentFlag.AlignTop)

        self.mainLayout.addWidget(self.scrollArea)

        newNoteButton = qtw.QPushButton("New Note")
        newNoteButton.clicked.connect(self.newNoteClicked)
        self.mainLayout.addWidget(newNoteButton)

        self.setLayout(self.mainLayout)

    def populateScrollItems(self):
        for i in reversed(range(self.scrollItems.count())):
            self.scrollItems.itemAt(i).widget().setParent(None)

        for note in self.repo.getAllNotes():
            noteWidget = NoteListItem(note, self.conStr, self.openNoteFunc, self.populateScrollItems)
            self.scrollItems.addWidget(noteWidget)

    def newNoteClicked(self):
        self.createNoteFunc()
        self.populateScrollItems()


from gensim.models import Word2Vec
from sklearn.decomposition import PCA
from matplotlib import pyplot

#define training data
sentences = [['this', 'is', 'my', 'first', 'sentence', 'for', 'this', 'test', 'on', 'word2vec'],
['this', 'is', 'the', 'second', 'sentence'],
['all', 'comedy', 'comes', 'in', 'threes'],
['i', 'am', 'all', 'four', 'female', 'politicians', 'and', 'all', 'that', 'jazz'],
['and', 'the', 'deed', 'was', 'done', 'i', 'had', 'gotten', 'to', 'five']]

#train model
model = Word2Vec(sentences, min_count=1) #Word2Vec(vocab=31, size=100, alpha=0.025)

#fit 2D Principal Component for Analysis model to vectors
X = model[model.wv.vocab]
pca = PCA(n_components=2)
result = pca.fit_transform(X)

#create scatter plot of projection
pyplot.scatter(result[:,0], result[:,1])
words = list(model.wv.vocab)
for i, word in enumerate(words):
    pyplot.annotate(word, xy=(result[i,0], result[i, 1]))
pyplot.show()


from astropy import time
from datetime import datetime
from asdf.exceptions import ValidationError
import pytest

from stdatamodels.jwst.datamodels import JwstDataModel

def test_strict_validation_enum():
    with JwstDataModel(strict_validation=True) as dm:
        assert dm.meta.instrument.name is None
        with pytest.raises(ValidationError):
            # FOO is not in the allowed enumerated values
            dm.meta.instrument.name = 'FOO'

def test_strict_validation_type():
    with JwstDataModel(strict_validation=True) as dm:
        with pytest.raises(ValidationError):
            # Schema requires a float
            dm.meta.target.ra = "FOO"

def test_strict_validation_date():
    with JwstDataModel(strict_validation=True) as dm:
        time_obj = time.Time(dm.meta.date)
        assert isinstance(time_obj, time.Time)
        date_obj = datetime.strptime(dm.meta.date, '%Y-%m-%dT%H:%M:%S.%f')
        assert isinstance(date_obj, datetime)


"""
Serial tests for tar
"""

import pytest
from pathlib import Path
import numpy as np
import lyncs_io as io
from lyncs_io.testing import (
    dtype_loop,
    shape_loop,
    ext_loop,
    tar_mode_loop,
    tempdir,
    generate_rand_arr,
)

@tar_mode_loop
@ext_loop
@dtype_loop
@shape_loop
def test_serial_tar(tempdir, dtype, shape, mode, ext):
    """
    Test all the basic functionality of saving, loading
    and getting the header of a file in a tarball
    """
    arr = generate_rand_arr(shape, dtype)

    ftmp = tempdir + f"tarball{mode}/foo{ext}"
    io.save(arr, ftmp)

    assert (arr == io.load(ftmp)).all()
    assert (arr == io.load(ftmp, format="Tar")).all()
    assert io.load(ftmp).shape == io.head(ftmp)["shape"]
    assert io.load(ftmp).dtype == io.head(ftmp)["dtype"]

    path = Path(ftmp)
    assert (arr == io.load(path.parent)[path.name]).all()

    # Test that an exception is raised when
    # trying to append to a compressed tarball
    with pytest.raises(ValueError):
        io.save(arr, tempdir + f"tarball.tar.gz/foo{ext}")
        io.save(arr, tempdir + f"tarball.tar.gz/foo{ext}")

    # Testing Head
    ftmp = tempdir + f"tarball{mode}/"
    assert list(io.head(ftmp).keys()) == list(io.load(ftmp).keys())
    assert io.load(ftmp)["foo.npy"].shape == io.head(ftmp)["foo.npy"]["shape"]

    ftmp = tempdir + "map_tar.tar"
    mydict = {
        "random": {
            "arr0.npy": generate_rand_arr(shape, dtype),
            "arr1.npy": generate_rand_arr(shape, dtype),
        },
        "zeros.npy": np.zeros((4, 4, 4, 4)),
    }
    io.save(mydict, ftmp)

    loaded_dict = io.load(ftmp, all_data=True)

    assert (mydict["random"]["arr0.npy"] == loaded_dict["random"]["arr0.npy"]).all()
    assert (mydict["random"]["arr1.npy"] == loaded_dict["random"]["arr1.npy"]).all()
    assert (mydict["zeros.npy"] == loaded_dict["zeros.npy"]).all()