import argparse
import datetime
import glob
import hashlib
import http.server
import json
import logging
import os
import os.path
import shutil
import socketserver
import subprocess
import sys
import tempfile
import urllib.parse

import lxml.etree
import lxml.html

verbose = '--verbose' in sys.argv[1:] or '-v' in sys.argv[1:]
logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO, format="[%(levelname)s] %(message)s")

HTMLCOMPRESSOR_URL = "https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/htmlcompressor/htmlcompressor-1.5.3.jar"
YUICOMPRESSOR_URL = "https://github.com/yui/yuicompressor/releases/download/v2.4.8/yuicompressor-2.4.8.jar"

SCRIPTS_DIRECTORY = os.path.dirname(os.path.abspath(__file__))
ROOT_DIRECTORY = os.path.dirname(SCRIPTS_DIRECTORY)
SOURCE_DIRECTORY = os.path.join(ROOT_DIRECTORY, "src")
CHANGES_DIRECTORY = os.path.join(SCRIPTS_DIRECTORY, "changes")
BUILD_DIRECTORY = os.path.join(ROOT_DIRECTORY, "build")

CHANGES_PATH = os.path.join(CHANGES_DIRECTORY, "changes")

class Chdir():

  def __init__(self, path):
    self._path = os.path.abspath(path)

  def __enter__(self):
    self._previous = os.getcwd()
    os.chdir(self._path)

  def __exit__(self, exc_type, exc_val, exc_tb):
    os.chdir(self._previous)

def checksum(root):
  paths = find_files(root)
  sha = hashlib.sha1()
  for path in paths:
    sha.update(path.encode('utf-8'))
    with open(os.path.join(root, path), 'rb') as fh:
      sha.update(fh.read())
  return sha.hexdigest()

def extract_javascript(html, root):
  scripts = ""
  transactions = html.xpath("//script[@type='text/javascript']")
  for transaction in transactions:
    src = os.path.join(root, transaction.get("src"))
    with open(src) as script:
      scripts = scripts + "\n" + script.read()
    transaction.drop_tree()

  filtered = ""
  for line in scripts.split("\n"):
    if line.find('"use strict";') != 0:
      filtered = filtered + "\n" + line

  return filtered

def extract_tags(html, tag, key, root):
  scripts = ""
  transactions = html.xpath(tag)
  for transaction in transactions:
    src = os.path.join(root, transaction.get(key))
    with open(src) as script:
      scripts = scripts + "\n" + script.read()
    transaction.drop_tree()
  return scripts

def append_javascript(html, script):
  body = html.find('body')
  source = "<script type='text/javascript' type='text/css'>" + script + "</script>"
  link = lxml.html.fromstring(source).find('.//script')
  body.append(link)

def append_style(html, style):
  head = html.find('head')
  tag = "<style>" + style + "</style>"
  style = lxml.html.fromstring(tag).find('.//style')
  head.append(style)

def yuicompressor(contents, suffix):
  temp = tempfile.mktemp(suffix=suffix)
  with open(temp, 'w') as f:
    f.write(contents)
  yuicompressor_path = download(YUICOMPRESSOR_URL, SCRIPTS_DIRECTORY)
  command = ["java", "-jar", yuicompressor_path]
  output = subprocess.check_output(command + [temp]).decode('utf-8')
  os.unlink(temp)
  return output

def download(url, directory):
  basename = os.path.basename(urllib.parse.urlparse(url).path)
  path = os.path.join(directory, basename)
  if not os.path.exists(path):
    logging.info("Downloading '%s'...", basename)
    subprocess.check_call(["curl", "-L", "-o", path, url])
  return path

def htmlcompressor(contents):
  htmlcompressor_path = download(HTMLCOMPRESSOR_URL, SCRIPTS_DIRECTORY)
  command = ['java', '-jar', htmlcompressor_path]
  p = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
  output = p.communicate(input=contents.encode('utf-8'))[0].decode('utf-8')
  return output

def find_files(directory):
  result = []
  for root, subdirs, files in os.walk(directory):
    for file in files:
      if file.find('.') != 0:
        result.append(os.path.relpath(os.path.join(root, file), directory))
  return sorted(result)

def copy_diretory(source_dir, output_dir, task=shutil.copy):
  name = os.path.basename(os.path.abspath(source_dir))
  destination_dir = os.path.join(output_dir, name)
  os.mkdir(destination_dir)
  files = find_files(source_dir)
  for file in files:
    image_name = os.path.basename(os.path.abspath(file))
    destination_file = os.path.join(destination_dir, image_name)
    task(os.path.join(source_dir, file), destination_file)

def copy_files(source, destination, files):
  for file in files:
    source_file = os.path.join(source, file)
    destination_file = os.path.join(destination, file)
    shutil.copy(source_file, destination_file)

def load_settings(path, version):
  settings = None
  with open(path, 'r') as f:
    settings = json.load(f)
  settings["version"] = version
  return settings

def build(options):
  archives_dir = os.path.join(ROOT_DIRECTORY, "archives")
  input_file = os.path.join(SOURCE_DIRECTORY, "index.html")
  output_file = os.path.join(BUILD_DIRECTORY, "index.html")
  images_dir = os.path.join(SOURCE_DIRECTORY, "images")
  assets_dir = os.path.join(SOURCE_DIRECTORY, "assets")
  defaults_dir = os.path.join(SOURCE_DIRECTORY, "defaults")
  manifest_file = os.path.join(BUILD_DIRECTORY, "cache.manifest")

  logging.info("Getting version...")

  version = run([CHANGES_PATH, "version"]).strip()
  logging.info("Version %s", version)

  logging.info("Loading settings...")
  settings = load_settings(path=os.path.abspath(options.settings), version=version)

  # Create/empty the build directory.
  # We do not simply delete the directory so as not to break the development server which might be serving from here.
  if os.path.exists(BUILD_DIRECTORY):
    for path in os.listdir(BUILD_DIRECTORY):
      path = os.path.join(BUILD_DIRECTORY, path)
      if os.path.isfile(path):
        os.unlink(path)
      else:
        shutil.rmtree(path)
  else:
    os.mkdir(BUILD_DIRECTORY)

  # index.html

  contents = None
  with open(input_file) as f:
    contents = f.read()
  html = lxml.html.fromstring(contents)

  logging.info("Extracting JavaScript...")
  script = "window.config = %s;\n" % json.dumps(settings, sort_keys=True)
  script += extract_tags(html, "//script[@type='text/javascript']", "src", SOURCE_DIRECTORY)
  if not settings["debug"] and not options.debug:
    logging.info("Minifying JavaScript...")
    script = yuicompressor(script, '.js')
  append_javascript(html, script)

  logging.info("Exctracting CSS...")
  style = extract_tags(html, "//link[@type='text/css']", "href", SOURCE_DIRECTORY)
  if not settings["debug"] and not options.debug:
    logging.info("Minifying CSS...")
    style = yuicompressor(style, '.css')
  append_style(html, style)

  contents = lxml.html.tostring(html).decode('utf-8')
  if not settings["debug"] and not options.debug:
    logging.info("Compressing HTML...")
    contents = htmlcompressor(contents)

  logging.info("Writing HTML...")
  with open(output_file, 'w') as f:
    f.write("<!DOCTYPE html>\n")
    f.write(contents)

  # authorization.html
  logging.info("Copying authorization page...")
  os.makedirs(os.path.join(BUILD_DIRECTORY, "authorization"))
  shutil.copy(os.path.join(SOURCE_DIRECTORY, "authorization/index.html"),
              os.path.join(BUILD_DIRECTORY, "authorization/index.html"))

  # images
  logging.info("Copying images...")
  copy_diretory(images_dir, BUILD_DIRECTORY)

  # images
  logging.info("Copying assets...")
  copy_diretory(assets_dir, BUILD_DIRECTORY)

  # defaults
  logging.info("Copying defaults...")
  copy_diretory(defaults_dir, BUILD_DIRECTORY)

  # icon
  icon_file = os.path.join(ROOT_DIRECTORY, settings['icon'])
  shutil.copy(icon_file, os.path.join(BUILD_DIRECTORY, "images", "icon.png"))

  # Generate a sha for the build.
  logging.info("Generating a checksum...")
  build_checksum = checksum(BUILD_DIRECTORY)

  # Write the manifest.
  logging.info("Writing the manifest...")
  build_files = find_files(BUILD_DIRECTORY)
  with open(manifest_file, 'w') as f:
    f.write("CACHE MANIFEST\n")
    f.write("# %s\n" % build_checksum)
    f.write("CACHE:\n")
    f.write("\n".join(map(lambda x: x, build_files)))
    f.write("\n")
    f.write("NETWORK:\n")
    f.write("*\n")

  # We don't want the following files to be added to the manifest.
  copy_files(SOURCE_DIRECTORY, BUILD_DIRECTORY, ["sizes.html"])

  # Set the version number.
  logging.info("Writing version...")
  with open(os.path.join(BUILD_DIRECTORY, "version.txt"), "w") as fh:
    fh.write(version)
    fh.write("\n")

  # Get the release notes.
  logging.info("Getting release notes... ")
  notes = run([CHANGES_PATH, "notes"]).strip()
  logging.info("Writing release notes... ")
  with open(os.path.join(BUILD_DIRECTORY, "release.txt"), "w") as fh:
    fh.write(notes)
    fh.write("\n")

  # Archive the build.
  if not os.path.exists(archives_dir):
    os.makedirs(archives_dir)
  settings_name = os.path.splitext(os.path.basename(options.settings))[0]
  with Chdir(ROOT_DIRECTORY):
    archive_path = os.path.join(archives_dir, "build-%s-%s.tar.gz" % (build_checksum, settings_name))
    latest_archive_path = os.path.join(archives_dir, "build-latest-%s.tar.gz" % settings_name)
    release_path = os.path.join(archives_dir, f"Game-Play-Color-{version}.tar.gz")
    with Chdir(BUILD_DIRECTORY):
      subprocess.check_call(["tar", "-zcf", archive_path, "."])
    if os.path.exists(latest_archive_path):
      os.remove(latest_archive_path)
    os.symlink(archive_path, latest_archive_path)

    with Chdir(archives_dir):
      files = glob.glob("Game-Play-Color-*.tar.gz")
      for f in files:
        f_path = os.path.join(archives_dir, f)
        logging.info("Removing '%s'...", f_path)
        os.remove(f_path)
    logging.info("Creating '%s'...", release_path)
    shutil.copyfile(archive_path, release_path)

def run(command):
  result = subprocess.run(command, capture_output=True)
  try:
    result.check_returncode()
    return result.stdout.decode('utf-8')
  except subprocess.CalledProcessError as e:
    logging.error(e.stderr.decode("utf-8"))
    raise

def command_build(parser):
  parser.add_argument("settings", help="settings file")
  parser.add_argument("--debug", action="store_true", default=False, help="build without minification")
  return build

def command_serve(parser):
    parser.add_argument("--port", default=8000, type=int, help="Listening port.")

    def inner(options):
      httpd = socketserver.TCPServer(("", options.port), http.server.SimpleHTTPRequestHandler)
      logging.info("Serving on http://127.0.0.1:%d...", options.port)
      os.chdir(BUILD_DIRECTORY)
      httpd.serve_forever()

    return inner

def add_command(subparsers, name, command, help=""):
  parser = subparsers.add_parser(name, help=help)
  fn = command(parser)
  parser.set_defaults(fn=fn)

def main():
  parser = argparse.ArgumentParser(description="Build script for Game Play.")
  parser.add_argument('--verbose', '-v', action='store_true', default=False, help="show verbose output")
  subparsers = parser.add_subparsers(help="Command to run.")
  add_command(subparsers, name="build", command=command_build, help="Build the project.")
  add_command(subparsers, name="serve", command=command_serve, help="Run a local server.")
  options = parser.parse_args()
  options.fn(options)

if __name__ == '__main__':
  main()


from __future__ import absolute_import, division

import numpy as np
import cv2

from . import Tracker
from ..utils import dict2tuple
from ..utils.complex import real, fft2, ifft2, complex_add, complex_mul, complex_div, fftshift
from ..descriptors.fhog import fast_hog

class TrackerKCF(Tracker):

    def __init__(self, **kargs):
        super(TrackerKCF, self).__init__('KCF')
        self.parse_args(**kargs)
        self._correlation = self.setup_kernel(self.cfg.kernel_type)

    def parse_args(self, **kargs):
        self.cfg = {
            'lambda_': 1e-4,
            'padding': 1.5,
            'output_sigma_factor': 0.125,
            'interp_factor': 0.012,
            'sigma': 0.6,
            'poly_a': 1,
            'poly_b': 7,
            'cell_size': 4,
            'kernel_type': 'gaussian'}

        for key, val in kargs.items():
            self.cfg.update({key: val})
        self.cfg = dict2tuple(self.cfg)

    def setup_kernel(self, kernel_type):
        assert kernel_type in ['linear', 'polynomial', 'gaussian']
        if kernel_type == 'linear':
            return lambda x1, x2: self._linear_correlation(x1, x2)
        elif kernel_type == 'polynomial':
            return lambda x1, x2: self._polynomial_correlation(
                x1, x2, self.cfg.poly_a, self.cfg.poly_b)
        elif kernel_type == 'gaussian':
            return lambda x1, x2: self._gaussian_correlation(
                x1, x2, self.cfg.sigma)

    def init(self, image, init_rect):
        # initialize parameters
        self.resize_image = False
        if np.sqrt(init_rect[2:].prod()) > 100:
            self.resize_image = True
            init_rect = init_rect / 2
        self.t_center = init_rect[:2] + init_rect[2:] / 2
        self.t_sz = init_rect[2:]
        mod = self.cfg.cell_size * 2
        self.padded_sz = self.t_sz * (1 + self.cfg.padding)
        self.padded_sz = self.padded_sz.astype(int) // mod * mod + mod

        # get feature size and initialize hanning window
        if image.ndim == 2:
            image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
        if self.resize_image:
            size = (int(image.shape[1] / 2), int(image.shape[0] / 2))
            image = cv2.resize(image, size)
        self.z = self._crop(image, self.t_center, self.padded_sz)
        self.z = fast_hog(np.float32(self.z), self.cfg.cell_size)
        self.feat_sz = self.z.shape
        self.hann_window = np.outer(
            np.hanning(self.feat_sz[0]),
            np.hanning(self.feat_sz[1])).astype(np.float32)
        self.hann_window = self.hann_window[:, :, np.newaxis]
        self.z *= self.hann_window

        # create gaussian labels
        output_sigma = self.cfg.output_sigma_factor * \
            np.sqrt(np.prod(self.feat_sz[:2])) / (1 + self.cfg.padding)
        rs, cs = np.ogrid[:self.feat_sz[0], :self.feat_sz[1]]
        rs, cs = rs - self.feat_sz[0] // 2, cs - self.feat_sz[1] // 2
        y = np.exp(-0.5 / output_sigma ** 2 * (rs ** 2 + cs ** 2))
        self.yf = fft2(y)

        # train classifier
        k = self._correlation(self.z, self.z)
        self.alphaf = complex_div(self.yf, complex_add(fft2(k), self.cfg.lambda_))

    def update(self, image):
        if image.ndim == 2:
            image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
        if self.resize_image:
            size = (int(image.shape[1] / 2), int(image.shape[0] / 2))
            image = cv2.resize(image, size)

        # locate target
        x = self._crop(image, self.t_center, self.padded_sz)
        x = self.hann_window * fast_hog(np.float32(x), self.cfg.cell_size)
        k = self._correlation(x, self.z)
        score = real(ifft2(complex_mul(self.alphaf, fft2(k))))
        offset = self._locate_target(score)
        self.t_center += offset * self.cfg.cell_size
        # limit the estimated bounding box to be overlapped with the image
        self.t_center = np.clip(
            self.t_center, -self.t_sz / 2 + 2,
            image.shape[1::-1] + self.t_sz / 2 - 1)

        # update model
        new_z = self._crop(image, self.t_center, self.padded_sz)
        new_z = self.hann_window * fast_hog(np.float32(new_z), self.cfg.cell_size)
        k = self._correlation(new_z, new_z)
        new_alphaf = complex_div(self.yf, complex_add(fft2(k), self.cfg.lambda_))
        self.alphaf = (1 - self.cfg.interp_factor) * self.alphaf + \
            self.cfg.interp_factor * new_alphaf
        self.z = (1 - self.cfg.interp_factor) * self.z + \
            self.cfg.interp_factor * new_z

        bndbox = np.concatenate([
            self.t_center - self.t_sz / 2, self.t_sz])
        if self.resize_image:
            bndbox = bndbox * 2

        return bndbox

    def _crop(self, image, center, size):
        corners = np.zeros(4, dtype=int)
        corners[:2] = np.floor(center - size / 2).astype(int)
        corners[2:] = corners[:2] + size
        pads = np.concatenate(
            (-corners[:2], corners[2:] - image.shape[1::-1]))
        pads = np.maximum(0, pads)

        if np.any(pads > 0):
            corners = np.concatenate((
                corners[:2] + pads[:2],
                corners[2:] - pads[2:])).astype(int)

        patch = image[corners[1]:corners[3], corners[0]:corners[2]]

        if np.any(pads > 0):
            patch = cv2.copyMakeBorder(
                patch, pads[1], pads[3], pads[0], pads[2],
                borderType=cv2.BORDER_REPLICATE)

        return patch

    def _linear_correlation(self, x1, x2):
        xcorr = np.zeros((self.feat_sz[0], self.feat_sz[1]), np.float32)
        for i in range(self.feat_sz[2]):
            xcorr_ = cv2.mulSpectrums(
                fft2(x1[:, :, i]), fft2(x2[:, :, i]), 0, conjB=True)
            xcorr_ = real(ifft2(xcorr_))
            xcorr += xcorr_
        xcorr = fftshift(xcorr)

        return xcorr / x1.size

    def _polynomial_correlation(self, x1, x2, a, b):
        xcorr = np.zeros((self.feat_sz[0], self.feat_sz[1]), np.float32)
        for i in range(self.feat_sz[2]):
            xcorr_ = cv2.mulSpectrums(
                fft2(x1[:, :, i]), fft2(x2[:, :, i]), 0, conjB=True)
            xcorr_ = real(ifft2(xcorr_))
            xcorr += xcorr_
        xcorr = fftshift(xcorr)

        out = (xcorr / x1.size + a) ** b

        return out

    def _gaussian_correlation(self, x1, x2, sigma):
        xcorr = np.zeros((self.feat_sz[0], self.feat_sz[1]), np.float32)
        for i in range(self.feat_sz[2]):
            xcorr_ = cv2.mulSpectrums(
                fft2(x1[:, :, i]), fft2(x2[:, :, i]), 0, conjB=True)
            xcorr_ = real(ifft2(xcorr_))
            xcorr += xcorr_
        xcorr = fftshift(xcorr)

        out = (np.sum(x1 * x1) + np.sum(x2 * x2) - 2.0 * xcorr) / x1.size
        out[out < 0] = 0
        out = np.exp(-out / self.cfg.sigma ** 2)

        return out

    def _locate_target(self, score):
        def subpixel_peak(left, center, right):
            divisor = 2 * center - left - right
            if abs(divisor) < 1e-3:
                return 0
            return 0.5 * (right - left) / divisor

        _, _, _, max_loc = cv2.minMaxLoc(score)
        loc = np.float32(max_loc)

        if max_loc[0] in range(1, score.shape[1] - 1):
            loc[0] += subpixel_peak(
                score[max_loc[1], max_loc[0] - 1],
                score[max_loc[1], max_loc[0]],
                score[max_loc[1], max_loc[0] + 1])
        if max_loc[1] in range(1, score.shape[0] - 1):
            loc[1] += subpixel_peak(
                score[max_loc[1] - 1, max_loc[0]],
                score[max_loc[1], max_loc[0]],
                score[max_loc[1] + 1, max_loc[0]])
        offset = loc - np.float32(score.shape[1::-1]) / 2

        return offset

class TrackerDCF(TrackerKCF):

    def __init__(self, **kargs):
        kargs.update({'kernel_type': 'linear'})
        super(TrackerDCF, self).__init__(**kargs)


#Normal function / Named functions
#def Function_Name(Function_Parameters):

def Add(iNo1 ,iNo2):
    return iNo1+iNo2

#Lambda Functions /  Unnamed function
# lambda parameters : body

AddFunction = lambda A,B : A+B
def main():
    Ans1 = Add(10,11)
    Ans2 = AddFunction(11,22)

    print("Addition using normal function : ",Ans1)
    print("Addition using Lambda function : ",Ans2)
    print("Type of lambda function is : ",type(AddFunction))

if __name__ == "__main__":
    main()


import asyncio

import numpy as np
import matplotlib.pyplot as plt
from itertools import chain

async def test(idle: float):
    outfile = f'/tmp/res{idle}.tr'
    proc = await asyncio.create_subprocess_shell("ns ../sat-aloha.tcl poisson",
                                                 shell=True,
                                                 env={
                                                     'IDLE': str(idle),
                                                     'OUTFILE': outfile
                                                 })
    await proc.communicate()
    proc = await asyncio.create_subprocess_shell(f"perl loss.pl {outfile}",
                                                 shell=True,
                                                 stdout=asyncio.subprocess.PIPE)
    stdout, _ = await proc.communicate()
    rho_0, rho_s = stdout.decode().splitlines()[-1].split()[-2:]
    print(idle, rho_0, rho_s)
    return float(rho_0), float(rho_s)

async def main():
    res = await asyncio.gather(
        *(test(i)
          for i in chain(np.arange(0.01, 0.3, 0.01), np.arange(0.3, 5, 0.1))))
    with open('res.txt', 'w') as f:
        for rho_0, rho_s in res:
            print(rho_0, rho_s, file=f)
    rho_0s, rho_ss = zip(*res)
    plt.scatter(rho_0s, rho_ss)
    plt.grid()
    plt.xlabel(r'$\rho_0$')
    plt.ylabel(r'$\rho_s$')
    plt.xlim(right=1)
    plt.show()

asyncio.run(main())


from time import sleep
import keypad_4x4_lib_sumar

kp = keypad_4x4_lib_sumar.keypad()

digit_inputed = []

def digit():
	r = None
	while r == None:
		r = kp.getKey()
	return r

print ("Please enter a 4 digit code: ")

# Getting digit 1, printing it, then sleep to allow the next digit press.
d1 = digit()
print (d1)
sleep(1)

d2 = digit()
print (d2)
sleep(1)

d3 = digit()
print (d3)
sleep(1)

d4 = digit()
print (d4)

# printing out the assembled 4 digit code.
print ("You Entered %s%s%s%s "%(d1,d2,d3,d4))


# 외워 머신러닝 딥러닝 기본 프레임워크
import numpy as np
import tensorflow as tf

#1. 데이터
x = np.array([1,2,3])
y = np.array([1,2,3])

#2. 모델 구성 (순차모델 레이어 구성)
from tensorflow.keras.models import Sequential
#. DENSE => DNN MODEL
#. xNN 뉴럴 네크워크 (CNN,ANN,VNN,RNN... etc)
from tensorflow.keras.layers import Dense

model = Sequential()
model.add(Dense(5, input_dim=1, activation='linear'))
model.add(Dense(3, activation='linear'))
model.add(Dense(4))
model.add(Dense(1))

#3. 컴파일, 훈련
from tensorflow.keras.optimizers import Adam, SGD
# model.compile(loss='mse', optimizer=Adam(learning_rate=0.001))
model.compile(loss='mse', optimizer='adam')
# model.compile(loss='mse', optimizer=SGD(learning_rate=0.01, momentum=0.0, nesterov=False, name='SGD'))
model.fit(x, y, epochs=1000, batch_size=1)

#4. 평가, 예측
loss = model.evaluate(x,y,batch_size=1)
print("loss : ", loss)

result = model.predict ([4])
print('result :', result)


import sys
import os
from PIL import Image

# grab first and second argument
src_folder = sys.argv[1]
des_folder = sys.argv[2]

# check if new/ exists, if not create it
if not os.path.exists(des_folder):
    os.makedirs(des_folder)

# loop through Pokedex,
# convert images to png
# save to the new folder.

for image in os.listdir(src_folder):
    Image.open(os.path.join(src_folder, image)).save(
        os.path.join(des_folder, f"{os.path.splitext(image)[0]}.png"), format="png"
    )


'''
Created on 21/01/2020
@author: B Akash
'''
'''
Problem statement:
Write a Python program to select the rows where the score is missing, i.e. is NaN.
'''

import pandas as pd
import numpy as np

exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

dataFrame= pd.DataFrame(exam_data,labels)

print(dataFrame[dataFrame['score'].isnull()])


from django.shortcuts import redirect, render
from . models import *
from .forms import JobDetailsForm
# Create your views here.

def home(request):
    jobs = job_details.objects.all()
    return render(request, 'job_list.html', {'jobs': jobs})

def add_job(request):
    if request.method == 'POST':
        # Extract data from the POST request.
        company_name = request.POST.get('company_name')
        job_title = request.POST.get('job_title')
        expiry_on = request.POST.get('expiry_on')
        job_description = request.POST.get('job_description')
        how_to_apply = request.POST.get('how_to_apply')
        cat_id = request.POST.get('cat')
        image = request.FILES.get('image')

        # Create a new job details instance and save it to the database.
        job_cat = job_category.objects.get(pk=cat_id)
        new_job = job_details(
            company_name=company_name,
            job_title=job_title,
            expiry_on=expiry_on,
            job_description=job_description,
            how_to_apply=how_to_apply,
            cat=job_cat,
            image=image
        )
        new_job.save()

        # Redirect to the job listing page or any other appropriate page.
        return redirect('job_list')

    # Fetch categories for populating the category dropdown.
    categories = job_category.objects.all()
    return render(request, 'add_job.html', {'cat': categories})

def add_job2(request):
    if request.method == 'POST':
        form = JobDetailsForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('job_list')
    else:
        form = JobDetailsForm()

    return render(request, 'add_job2.html', {'form': form})

def index(request):
    job_list = job_details.objects.all()
    context = {'job_list': job_list }
    return render(request, 'index.html', context)


import pandas as pd
import numpy as np
import os
import datetime
import argparse

if __name__ == "__main__":

    parser = argparse.ArgumentParser(description='arguments')
    parser.add_argument('data_folder', type=str, help='folder to save data')
    parser.add_argument('ticker_name', type=str, default='BTC-USD',
                        help='ticker name to collect data')
    parser.add_argument('window_size', type=int, help='folder to save data')
    args = parser.parse_args()

    ticker_name = args.ticker_name
    data_path = args.data_folder
    window_size = args.window_size
    averages_dir = os.path.join(data_path, ticker_name, "average")
    print(averages_dir)
    all_df = pd.DataFrame()

    for date in os.listdir(averages_dir):
        date_avg_dir = os.path.join(averages_dir, date)
        for h in os.listdir(date_avg_dir):
            hour_avg = pd.read_csv(os.path.join(date_avg_dir, h))
            hour_avg['time'] = [datetime.datetime.strptime(f"{str(date)} {h.split('.')[0]}", '%Y-%m-%d %H')]
            hour_avg.set_index('time', inplace=True, drop=True)
            all_df = all_df.append(hour_avg)
    all_df = all_df.drop("Unnamed: 0", axis=1)
    all_df = all_df.sort_index().reset_index()
    sma = all_df.iloc[:, 1:].rolling(window=window_size).mean()
    sma['time'] = all_df['time']

    moving_averages_dir  = averages_dir.replace('average', 'moving_averages')
    os.makedirs(moving_averages_dir, exist_ok=True)
    for i, row in sma.iterrows():
        if not pd.isna(row['Low_mean']):
            sma_date_dir = os.path.join(moving_averages_dir,str(row['time'].date()))
            os.makedirs(sma_date_dir, exist_ok=True)
            out_csv = os.path.join(moving_averages_dir,
                                   str(row['time'].date()),
                                   f'{window_size}SMA_'+str(row['time'].hour) + '.csv')
            print(out_csv)
            pd.DataFrame({f'Low_mean_{window_size}_sma': [row['Low_mean']],
                            f'High_mean_{window_size}_sma': [row['High_mean']],
                            'time': [row['time']]}).to_csv(out_csv, index=False)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('instance', '0003_add_name_and_email_match_config_option'),
    ]

    operations = [
        migrations.AddField(
            model_name='writeitinstanceconfig',
            name='real_name_for_site_emails',
            field=models.TextField(default=b'', help_text='The name that should appear in the From: line of emails sent from this site', blank=True),
            preserve_default=True,
        ),
    ]


"""
audioディレクトリに入っている `.flac` ファイルからファイル名を取り出し、
redisに存在するwordならaduio フラグをtrue にして audio_available リストに追加する。
すでにaudio_available な単語はスルーする。
"""
import redis
import subprocess
import time

rds = redis.StrictRedis(decode_responses=True)

def main():
    result = subprocess.run(
        ["ls", "-1", "/Users/makinoshunni/.ghq/github.com/macinjoke/study-typer-frontend/dist/assets/audio"],
        stdout=subprocess.PIPE
    )
    filenames = result.stdout.decode('utf-8').split('\n')
    en_words = [
        filename[:filename.rfind('.flac')] for filename in filenames
        if filename.rfind('.flac') != -1
    ]
    print(f'{len(en_words)} 個の単語についてredisを探索します')
    count = 0
    for en in en_words:
        for i in range(1, 31):
            if rds.zscore(f'words:{i}', en) is not None:
                count += 1
                print(f'{i}: {en} のaudioを有効化します。')
                set_audio(en, i)

# def get_existing_word(en):
#     """
#     ハイフン-やアンスコ_などを含むファイル名を、redisのword:{hoge} のkeyに存在する
#     英単語に直して返す。redisに存在しなければNone を返す。
#     :param en: 英単語の文字列
#     :return: redisのキーに存在する英単語文字列 or None
#     """
#     en = en.lower()
#     if rds.exists(f'word:{en}'):
#         return en
#     elif en.find('-') != -1:
#         replaced = en.replace("-", " ")
#         if rds.exists(f'word:{replaced}'):
#             return replaced
#     elif en.find('_') != -1:
#         replaced = en.replace("_", " ")
#         if rds.exists(f'word:{replaced}'):
#             return replaced
#         replaced = en.replace("_", "-")
#         if rds.exists(f'word:{replaced}'):
#             return replaced
#     else:
#         return None

def set_audio(word, rank):
    rds.hset(f'word:{word}', 'audio', 'true')
    rds.zrem(f'words:{rank}', word)
    rds.zadd(f'words:{rank}:audio_available', int(time.time()), word)

if __name__ == '__main__':
    main()


from functools import reduce
from pathlib import Path

inp = Path('input.txt').read_text().splitlines()

def chinese_remainder(n: [int], a: [int]) -> int:
    # x % n[0] == a[0]
    # x % n[1] == a[1]
    # x % n[2] == a[2]
    # ...
    sum_ = 0
    prod = reduce(lambda x1, x2: x1 * x2, n)
    for n_i, a_i in zip(n, a):
        p = prod // n_i
        sum_ += a_i * mul_inv(p, n_i) * p
    return sum_ % prod

def mul_inv(a: int, b: int) -> int:
    b0 = b
    x0, x1 = 0, 1
    if b == 1:
        return 1
    while a > 1:
        q = a // b
        a, b = b, a % b
        x0, x1 = x1 - q * x0, x0
    if x1 < 0:
        x1 += b0
    return x1

x = inp
now = int(x[0])
buses = [int(i) if i != 'x' else 0 for i in x[1].split(',')]

min_wait, bus_id = min([(b - now % b, b) for b in buses if b != 0])
part1 = min_wait * bus_id
print(part1)

buses = [int(i) if i != 'x' else 0 for i in x[1].split(',')]
buses = [(b, b - i) for i, b in enumerate(buses) if b != 0]
bus_ids, bus_offsets = zip(*buses)
part2 = chinese_remainder(bus_ids, bus_offsets)

print(part2)

# Easier to understand CRT solution
# We are looking for the following relation to be satisfied:
# ex t st t + v % ids[k] == 0 for each k, v
n = 0
product_running = 1
for bus_id, offset in buses:

    offset = bus_id - offset
    c = 0
    while (n + offset) % bus_id != 0:
        n += product_running
        c += 1

    product_running *= bus_id
    prev_n = n - c * (product_running // bus_id)
    str1 = f"({prev_n} + {c} * {product_running // bus_id}) = "
    print(f"{str1:>50}"
          f"{n:>20} + {offset:>3} % {bus_id:>3} == 0 ")

print(f't = {n}')


#!/usr/bin/env python3

import argparse
import itertools
from pathlib import Path
import re
import sys
from typing import List, Iterable

class Image:
    def __init__(self, pbm: str):
        pbm = re.sub(r"#\n", "", pbm).split()
        assert(pbm[0] == "P1")
        self.width = int(pbm[1])
        self.height = int(pbm[2])
        pbm = pbm[3:]
        self.raster = [[bool(int(pixel)) for pixel in pbm[row:row + self.width]] for row in range(0, len(pbm), self.width)]

    def resize(self, width: int, height: int):
        assert(self.width <= width and self.height <= height)
        top_pad = [[False] * width for _ in range((height - self.height) // 2)]
        bottom_pad = [[False] * width for _ in range(-((self.height - height) // 2))]
        left_pad = [False] * ((width - self.width) // 2)
        right_pad = [False] * -((self.width - width) // 2)
        self.raster = top_pad + [left_pad + row + right_pad for row in self.raster] + bottom_pad
        self.width = width
        self.height = height
        assert(width * height == sum(map(len, self.raster)))

    @property
    def data(self) -> Iterable[int]:
        data = []
        for row in self.raster:
            for value in row:
                data.append(1 if value else -1)
        return data

    @staticmethod
    def data_to_pbm(data: List[int], width: int, height: int) -> str:
        pbm = "P1\n{} {}\n".format(width, height) + \
            "\n".join([" ".join(["1" if pixel == 1 else "0" for pixel in data[row:row + width]]) for row in range(0, len(data), width)])
        return pbm

def train(images: List[Image]) -> List[List[int]]:
    assert(images)
    image_height = images[0].height
    image_width = images[0].width
    neuron_count = image_width * image_height
    weights = [list(itertools.repeat(0, neuron_count))
               for _ in range(0, neuron_count)]
    img_nums = [list(image.data) for image in images]
    for i in range(0, neuron_count):
        for j in range(i + 1, neuron_count):
            weights[i][j] = weights[j][i] = (
                sum(img_data[i] * img_data[j] for img_data in img_nums))
    # print("Weights:")
    # for i in range(0, neuron_count):
    #     row = (str(weights[i][j]) for j in range(0, neuron_count))
    #     print(" ".join(row))
    return weights

def activation_rule(weights: List[List[int]], state: List[int], i: int) -> int:
    return sum(weights[i][j] * state[j] for j in
               range(0, len(weights)))

def update_state(weights: List[List[int]], state: List[int]) -> bool:
    """Updates the state, returning whether the state changed"""
    change_count = 0
    for i in range(0, len(state)):
        activation = activation_rule(weights, state, i)
        oldstate = state[i]
        state[i] = 1 if activation >= 0 else -1
        if state[i] != oldstate:
            change_count += 1
    return change_count > 0

def match(image_file: str, model_file: str):
    image = Image(Path(image_file).read_text())
    model = model_file.read().split("\n")
    (width, height) = map(int, model[0].split())
    model = model[1:]
    weights = [list(map(int, row.split())) for row in model][:width * height]
    assert(len(weights) == width * height)
    image.resize(width, height)

    state = image.data
    MAX_ITER = 10
    for cur_iter in range(MAX_ITER):
        print("State", cur_iter, file=sys.stderr)
        print(Image.data_to_pbm(state, width, height), file=sys.stderr)
        cur_iter += 1
        changed = update_state(weights, state)
        if not changed:
            break

    print("{} iterations".format(cur_iter), file=sys.stderr)
    print(Image.data_to_pbm(state, width, height))

def main(args: List[str]):
    cmd_parser = argparse.ArgumentParser(description="""
        Implementation of a Hopfield network.
        """)
    subparsers = cmd_parser.add_subparsers(dest="command")

    train_parser = subparsers.add_parser("train", help="""Train the
        Hopsfield network on the specified files, which are expected to be plain
        PBM files. The generated model is printed to standard output.""")
    train_parser.add_argument("training_files", nargs="+")

    match_parser = subparsers.add_parser("match", help="""
        Find the best match, as determined from the model taken from standard
        input, for the specified file (a plain PBM file). The match is printed
        to standard output.""")
    match_parser.add_argument("test_file")
    match_parser.add_argument("model_file", nargs="?", type=argparse.FileType("r"), default=sys.stdin)

    result = cmd_parser.parse_args()

    if result.command == "train":
        images = [Image(Path(f).read_text()) for f in result.training_files]
        pixels = [image.raster for image in images]
        width = max(map(len, itertools.chain(*pixels)))
        height = max(map(len, pixels))
        for image in images:
            image.resize(width, height)
        model = train(images)
        print("{} {}".format(width, height))
        print("\n".join(" ".join(map(str, row)) for row in model))
    elif result.command == "match":
        match(result.test_file, result.model_file)

if __name__ == "__main__":
    main(sys.argv)


#!/usr/bin/env python3

from abc import ABC, abstractmethod
import math

# Note Area doesn't define the type of coordinates; it happily works with Coord or tuples
class Area:
    def __init__(self, plane, id, coord):
        self.plane = plane
        self.id = id # 1-based
        self.anchor = coord # remember the anchor because we know it's a groundable point
        self.points = set()
        self.points.add(coord)
        self.min = list(coord)
        self.max = list(coord)

    def grow(self, coord):
        self.points.add(coord)
        for i in range(len(coord)):
            self.min[i] = min(self.min[i], coord[i])
            self.max[i] = max(self.max[i], coord[i])

    def closest(self, coord, grounded_fn):
        #return min((x for x in self.points if grounded_fn(x)), default=None, key=lambda p: abs(p[0] - coord[0]) + abs(p[1] - coord[1]))
        order = [x for x in self.points]
        order.sort(key=lambda p: abs(p[0] - coord[0]) + abs(p[1] - coord[1]))
        for x in order:
            if grounded_fn(x):
                return x
        return None

    def __repr__(self):
        return f"{len(self.points)} pt(s): {self.points}"

# grounded_fn returns true for a given plane coord if it is fillable while staying grounded
def scan(plane, grounded_fn, pts_limit=math.inf):
    areas = []
    for k in plane:
        if plane[k].is_void() and plane[k].is_model() and grounded_fn(k) and not any([k in a.points for a in areas]):
            area = Area(plane, len(areas) + 1, k)
            areas.append(area)
            flood_fill(plane, areas, area, k, pts_limit)
    return areas

def flood_fill(plane, areas, area, start, pts_limit):
    stack = [start]
    while len(stack) > 0 and len(area.points) < pts_limit:
        k = stack.pop()
        for n in plane.adjacent(k):
            if plane[n].is_void() and plane[n].is_model() and not any([n in a.points for a in areas]) and n not in stack:
                area.grow(n)
                stack.append(n)

# Partitioner is supposed to break large Areas up into smaller Areas suitable for one bot
# Might be useful later but I realised it's probably simpler to prevent scan/fill from creating
# large areas in the first place.
class Partitioner(ABC):
    @abstractmethod
    def partition_area(plane, area, subdivisions):
        pass

class PartitionSquares(Partitioner):
    def __init__(self, R):
        # arbitrary hueristic
        self.target_pts_per_bot = (R * R) / 20.0 / 2.0

    def partition(plane, areas):
        jobs = []
        total_pts = sum([len(a.points) for a in areas])
        split = min(int(total_pts / self.target_pts_per_bot), 20)
        pts_per_job = total_pts / split
        for area in areas:
            if len(area.points) / float(pts_per_job) < 1.25:
                # small area; queue it up and disregard
                jobs.add(area)
                split -= 1
                total_pts -= len(area.points)
                pts_per_job = total_pts / split

        for area in areas:
            if area not in jobs:
                sub_areas = partition_area(plane, area, math.ceil(len(area.points) / pts_per_job))
                jobs.extend(sub_areas)

        return jobs


import pygame as py
from random import randint
import salva_pontuacao as sp
import database as db
import menu

def perguntas(janela, font_perguntas, subfont, font_avisos, font, acerto_music, erro_music, click_music, derrota_music, vitoria_music):

    tela_jogo = True

    img_fundo = py.image.load('img/img_fundo.png')

    pontos = 0
    pergunta = 0
    respondido = True           #Olha se a pergunta foi respondida
    perguntas_feitas = 0
    lista_perguntas_feitas  = []
    vidas = 3

    img_vida = py.image.load('img/coracao.png')
    img_pontos = py.image.load('img/estrela.png')
    img_vidro = py.image.load('img/vidro.png')
    img_vidro_cabeca = py.image.load('img/cabeca.png')
    img_menu = py.image.load('img/menu.png')

    while tela_jogo:

        #Mudar para que numeros não se repita
        if respondido == True:

            j = 0
            while j < 1:
                pergunta = randint(1, 50)
                questao = db.select_questao(pergunta)

                if len(lista_perguntas_feitas) == 50:
                        perguntas_feitas += 1
                        respondido = True
                        j += 1

                if pergunta not in lista_perguntas_feitas:
                    lista_perguntas_feitas.append(pergunta)
                    respondido = False
                    j += 1
                    perguntas_feitas += 1

        #Verfica se todas as perguntas disponiveis foram feitas e chama a tela de fim de jogo
        if perguntas_feitas > 50:

            #verifica se o botão de fechar janela foi ativado
            returno = sp.fim_de_jogo(pontos, janela, font, subfont, font_avisos, click_music, acerto_music, derrota_music, vitoria_music)

            if returno == False:
                return False

            else:
                return True

        #vidas display
        if vidas >= 1:
            janela.blit(img_vida, (20, 15))

            if vidas >= 2:
                janela.blit(img_vida, (65, 15))

                if vidas >= 3:
                    janela.blit(img_vida, (110, 15))

        #Verifica se as vidas acabaram e chama a tela de fim de jogo
        if vidas == 0:
            retorno = sp.fim_de_jogo(pontos, janela, font, subfont, font_avisos, click_music, acerto_music, derrota_music, vitoria_music)

            #verifica se o botão de fechar janela foi ativado
            if retorno == False:
                return False
            else:
                return True

        #limpa e atualiza tela
        py.display.flip()

        #imagem de fundo e botão voltar
        janela.blit(img_fundo,(0, 0))

        #pontos display
        janela.blit(img_vidro_cabeca, (12, 10))
        janela.blit(img_menu, (380, 8))
        janela.blit(img_pontos, (630, 14))
        pontos_display = subfont.render("Pontos: "+str(pontos), True, (225,225,225))
        janela.blit(pontos_display, (675, 25))

        #fazer isto só uma vez
        perg = formata_texto(questao[0], font_perguntas)
        resp_a = formata_texto(questao[1], font_perguntas)
        resp_b = formata_texto(questao[2], font_perguntas)
        resp_c = formata_texto(questao[3], font_perguntas)
        resp_d = formata_texto(questao[4], font_perguntas)
        resp_e = formata_texto(questao[5], font_perguntas)
        correta = questao[6]

        k = 0
        tab = 0

        janela.blit(img_vidro, (12, 265))

        while k < int(len(perg)) or k <  int(len(perg)) or k <  int(len(resp_a)) or k <  int(len(resp_b)) or k <  int(len(resp_c)) or k <  int(len(resp_d)) or  k < int(len(resp_e)):

            if k <  int(len(perg)):
                janela.blit(perg[k], (25, 75 + tab))

            if k <  int(len(resp_a)):
                janela.blit(resp_a[k], (20, 275 + tab))

            if k <  int(len(resp_b)):
                janela.blit(resp_b[k], (20, 325 + tab))

            if k <  int(len(resp_c)):
                janela.blit(resp_c[k], (20, 375 + tab))

            if k <  int(len(resp_d)):
                janela.blit(resp_d[k], (20, 425 + tab))

            if k <  int(len(resp_e)):
                janela.blit(resp_e[k], (20, 475 + tab))

            k = k + 1
            tab = tab + 25

        for event in py.event.get():

            if event.type == py.QUIT:
                return False

            if event.type == py.MOUSEBUTTONDOWN:
                x, y = py.mouse.get_pos()

                if x > 25 and x < 37 and y > 275 and y < 287:
                    respondido = True
                    resposta = 'A'

                if x > 25 and x < 37 and y > 325 and y < 339:
                    respondido = True
                    resposta = 'B'

                if x > 25 and x < 37 and y > 375 and y < 386:
                    respondido = True
                    resposta = 'C'

                if x > 25 and x < 37 and y > 425 and y < 439:
                    respondido = True
                    resposta = 'D'

                if x > 25 and x < 37 and y > 475 and y < 486:
                    respondido = True
                    resposta = 'E'

                if x > 388 and x < 420 and y > 20 and y < 47:
                    ret = menu.menu(janela, font, subfont, acerto_music, click_music, vitoria_music, derrota_music, erro_music, img_vidro_cabeca, img_vida, img_pontos, img_menu, pontos, vidas)

                    if ret == 1:
                        tela_jogo = False
                        return True

        if respondido == True:

                if correta == resposta:
                    pontos += 1
                    acerto_music.play()

                else:
                    vidas -= 1
                    erro_music.play()

def formata_texto(texto, fonte):

    lista = []
    pergunta = []
    i = 0
    j = 95

    if len(texto) > i:

        while i < len(texto):

                if (i+j) >= len(texto):

                    if texto[i] == ' ':
                        pergunta.append(texto[i+1:len(texto)])
                    elif texto[i] != ' ':
                        pergunta.append(texto[i:len(texto)])
                    i+=j

                elif texto[i+j] == ' ':
                    pergunta.append(texto[i:i+j])
                    i = i + j

                elif texto[i+j] != ' ':
                    while texto[i+j] != ' ':
                        j-=1

                    if texto[i] == ' ':
                        pergunta.append(texto[i+1:i+j])
                    elif texto[i-1] != ' ':
                        pergunta.append(texto[i:i+j])
                    i = i + j
                    j = 95

    else:
        pergunta.append(texto)

    k = 0

    while k < len(pergunta):

        lista.append(fonte.render(pergunta[k], True, (225,225,225)))
        k = k + 1

    return lista


import json
import logging
from pathlib import Path
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np

def is_jsonable(obj):
    """
    判断对象obj是否可json序列化
    :param obj:
    :return:
    """
    try:
        json.dumps(obj)
        return True
    except (TypeError, OverflowError):  # OverflowError是对象太大导致的无法序列化
        return False

def init_logger(log_file=None, log_file_level=logging.NOTSET):
    '''
    Example:
        >>> init_logger(log_file)
        >>> logger.info("abc'")
    '''
    if isinstance(log_file,Path):
        log_file = str(log_file)
    # log_format = logging.Formatter("[%(asctime)s %(levelname)s] %(message)s")
    log_format = logging.Formatter("%(message)s")
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(log_format)
    logger.handlers = [console_handler]
    if log_file and log_file != '':
        file_handler = logging.FileHandler(log_file)
        file_handler.setLevel(log_file_level)
        file_handler.setFormatter(log_format)
        logger.addHandler(file_handler)
    return logger

def fig_confusion_matrix(confusion, categories_list):
    # 绘制混淆矩阵。对每类的分类情况做了归一化，防止有的类数量太多颜色太深，其他类数量少颜色太浅
    # Set up plot
    fig = plt.figure()
    ax = fig.add_subplot(111)
    normalize_confusion = confusion / confusion.sum(1).reshape((-1,1))
    cax = ax.matshow(normalize_confusion)
    fig.colorbar(cax)

    # Set up axes
    list_categories_and_num = [f"{num}  {c}" for num,c in zip(confusion.sum(1), categories_list)]
    ax.set_xticklabels([''] + categories_list, rotation=90)
    ax.set_yticklabels([''] + list_categories_and_num)

    # Force label at every tick
    ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
    ax.yaxis.set_major_locator(ticker.MultipleLocator(1))

    fig.tight_layout()  # 适应窗口大小，否则可能有东西在窗口里画不下
    return fig

def fig_images(img):
    fig, ax = plt.subplots()
    npimg = img.numpy()
    plt_img = ax.imshow(np.transpose(npimg, (1, 2, 0)))
    fig.tight_layout()
    return fig


# 가나다순(사전순)으로
#
# 따로 묶은 리스트가 출력되도록 리스트 내포를 이용한 프로그램을 작성하십시오.

# ord() <<-->> chr()

dicBase = (('가', '깋'), ('나', '닣'), ('다', '딯'), ('라', '맇'), ('마', '밓'), ('바', '빟'), ('사', '싷'),

           ('아', '잏'), ('자', '짛'), ('차', '칳'), ('카', '킿'), ('타', '팋'), ('파', '핗'), ('하', '힣'))

inputWord = ['막', '부모님', '비용', '비행기', '원래', '처리', '최초', '꼴', '좀', '들다', '싶다',

             '수출', '계시다', '다', '뒤', '듣다', '함께', '아이', '무척', '보이다', '가지다', '그',

             '자르다', '데리다', '마리', '개', '정도', '옳다', '놀이', '뜨겁다']

#
# print(len(dicBase))
# AscBase = ord(dicBase[0][0]), ord(dicBase[0][1])
# print(AscBase)
# AscBase = ord(dicBase[1][0]), ord(dicBase[1][1])
# print(AscBase)

lst=[]
for j in range(len(dicBase)):
    branch = []
    for i in range(len(inputWord)):
        ascnum = ord(inputWord[i][0])
        # if ascnum >= dicBase[j][0] and  ascnum <= dicBase:
        if ord(dicBase[j][0]) <= ascnum <= ord(dicBase[j][1]):
            branch.append(inputWord[i])
    lst.append(branch)

print(lst)


#!/usr/bin/env python3

from setuptools import find_packages, setup

with open("README.md") as readme_file:
    readme = readme_file.read()

with open("requirements.txt") as requirements_file:
    requirements = requirements_file.readlines()

setup(
    name="vmm-export",
    author="awk",
    author_email="awk@awk.space",
    version="1.0.0",
    description="Automatically export VMs from Synology VMM.",
    long_description=readme,
    long_description_content_type="text/markdown",
    license="MIT",
    url="https://github.com/awkspace/vmm-export",
    install_requires=requirements,
    packages=find_packages(),
    entry_points={"console_scripts": ["vmm-export = vmm_export.cli:main"]},
)


from graphics import *

def sidebar(point_one, point_two, text, win):
    box = Rectangle(point_one, point_two)
    box.setFill('cyan')
    point_oneX = point_one.getX()
    point_oneY= point_one.getY()
    point_twoX = point_two.getX()
    point_twoY = point_two.getY()
    y_dif = point_twoY - point_oneY
    x_dif = point_twoX - point_oneX
    what_to_do_text = Text(Point(point_oneX + x_dif/2, point_oneY+y_dif/2), text)
    outputfile = Entry(Point(point_oneX+x_dif/2, point_oneY+y_dif/4), 10)
    box.draw(win)
    outputfile.draw(win)
    what_to_do_text.draw(win)
    key = False
    while key != 'Return':
        key = win.getKey()
        print(key)
    return outputfile.getText()

def main():
    img = Image(Point(0, 0), 'img2.gif')
    img_width = img.getWidth()
    img_height = img.getHeight()
    win = GraphWin('Change color', img_width, img_height)
    win.setCoords(0, 0, img_width, img_height)
    img.move(img_width/2, img_height/2)
    img.draw(win)
    for each_row in range(200):
        for each_column in range(200):
            r, g, b = img.getPixel(each_row, each_column)
            brightness = int(round(.299*r + .587*g + .114*b))
            img.setPixel(each_row, each_column, color_rgb(brightness, brightness, brightness))
        update()
    filename = sidebar(Point(0, img_height-img_height/15), Point(img_width, img_height), 'Enter the filename save and press Enter', win)
    img.save(filename)
    win.getMouse()

main()


import json
from quart import Blueprint, Response, request
from shered.models.person_model import PersonModel

patch_person_blueprint = Blueprint('patch_person', __name__,)

def data_validation(data: dict, signature: dict) -> dict:
    errors = []

    for prop in signature.keys():
        if prop in data.keys():
            if type(data[prop]) != signature[prop]:
                errors.append('Bad type for ' + prop)
            elif type(data[prop]) == str and len(data[prop]) > 255:
                errors.append('Max len of ' + prop + ' is 255!')

    if len(data) > len(signature):
        errors.append('To much data!')

    return {'error'+str(i): error for i, error in enumerate(errors)}

@patch_person_blueprint.route('/api/v1/persons/<int:person_id>', methods=['PATCH'])
async def patch_person_person(person_id: int) -> Response:
    if request.is_json:
        person_data = await request.get_json()
        try:
            errors = data_validation(person_data, PersonModel.get_signature())
        except:
            errors = {
                'error': 'Bad JSON'
            }
    else:
        errors = {
            'error': 'Bad JSON'
        }

    if len(errors) == 0:
        try:
            person = PersonModel.select().where(PersonModel.person_id == person_id).get()
            if 'name' in person_data.keys():
                person.person_name = person_data['name']
            if 'age' in person_data.keys():
                person.person_age = person_data['age']
            if 'address' in person_data.keys():
                person.person_address = person_data['address']
            if 'work' in person_data.keys():
                person.person_work = person_data['work']
            person.save()
        except PersonModel.DoesNotExist:
            person = None

        if person is not None:
            return Response(
                status=200,
                content_type='application/json',
                response=json.dumps(person.as_dict())
            )
        else:
            return Response(
                status=404,
                content_type='application/json',
                response=json.dumps({
                    'message': 'Not found Person for ID'
                })
            )

    return Response(
        status=400,
        content_type='application/json',
        response=json.dumps({
            'message': 'Error',
            'errors': errors
        })
    )


"""
Author: Trevor Stalnaker
File: rectmanager.py

Manages more complicated collide rectangles for sprites
"""

import copy, pygame

def getRects(image):
    """This fucntion gets the rects for an image."""
    image = copy.copy(image)
    pxa = pygame.PixelArray(image)
    topCorner = pxa[0,0]
    scale = 1
    rects, flag, count = [], False, 0

    for w in range(pxa.shape[0]):
        for h in range(pxa.shape[1]):
            if pxa[w,h] != topCorner:
                if not flag:
                    leftBound, flag = (w,h), True
                else: count += 1
            elif pxa[w,h] == topCorner and flag:
                rects.append(pygame.Rect(leftBound[0],leftBound[1],
                                         scale,scale*count))
                flag, count = False, 0

    return rects

def moveRects(rects, pos):
    """This function moves the rects to a certain position."""
    return [rect.move(pos[0],pos[1]) for rect in rects]


# Prim's Algorithm applied to City Grid

INF = 999999
N = 7
#Adjacency Matrix for The City
City = [[0, 8, 0, 3, 0, 2, 4],
        [8, 0, 3, 2, 0, 0, 0],
        [0, 3, 0, 1, 2, 0, 0],
        [3, 2, 1, 0, 3, 5, 0],
        [0, 0, 2, 3, 0, 7, 0],
        [2, 0, 0, 5, 7, 0, 5],
        [4, 0, 0, 0, 0, 5, 0]]

House = [0, 0, 0, 0, 0, 0, 0]

Streets = 0

House[0] = True

print(" Streets : \n")
while (Streets < N - 1):

    minimum = INF
    a = 0
    b = 0
    for m in range(N):
        if House[m]:
            for n in range(N):
                if ((not House[n]) and City[m][n]):
                    if minimum > City[m][n]:
                        minimum = City[m][n]
                        a = m
                        b = n
    print(str(a) + "->" + str(b) + " with cost : " + str(City[a][b]))
    House[b] = True
    Streets += 1


# Created by yhwang on 2017/7/31.
import threading
import time
num = 1
# 互斥锁
Lock = threading.Lock()
# 信号量锁
# semaphore = threading.BoundedSemaphore(5)

def fun(count):
    Lock.acquire()
    global num
    print("thread %i" % count)
    time.sleep(2)
    num = num+1
    Lock.release()
    print("thread %i done" % count)

threads = list()
for n in range(500):
    thread = threading.Thread(target=fun, args=(n,))
    # thread.setDaemon(True)#主程序不会等待守护线程结束---->就是说无所谓了,主线程挂了,整个程序就挂了
    thread.start()
    threads.append(thread)

# 等待结果
for n in range(len(threads)):
    threads[n].join()

print("All finish")
print(num)


from django.db import migrations, transaction

@transaction.atomic()
def migrate_old_printer_data(apps, schema_editor):
    Printer = apps.get_model('shop', 'Printer')
    QrCode = apps.get_model('shop', 'QrCode')
    old_data = Printer.objects.all()
    if not old_data:
        return
    for printer in old_data:
        if printer.shop:
            QrCode.objects.create(
                shop=printer.shop,
                device=printer,
                qrcode_url=printer.qrcode_url,
            )

class Migration(migrations.Migration):

    dependencies = [
        ('shop', '0011_auto_20190527_1522'),
    ]

    operations = [
        migrations.RunPython(migrate_old_printer_data),
        migrations.RemoveField(
            model_name='printer',
            name='qrcode_url',
        ),
        migrations.RemoveField(
            model_name='printer',
            name='shop',
        ),
    ]


import boto3

def delete_message(queue_url, receipt_handle, region):
    sqs_client = boto3.client("sqs", region_name=region)
    response = sqs_client.delete_message(
        QueueUrl=queue_url,
        ReceiptHandle=receipt_handle,
    )
    return response


import datetime
import math
import pathlib
import time
import uuid

from typing import Optional

from .config import MailerConfig
from .connection import Database, SMTPSender, PersistentCommand, \
    CommandWorker, CommandQueue, SentryReporter
from .connection.database import DBAppConfig
from .consts import Queries, CMD_COMPONENT
from .context import Context
from .logging import prepare_logging
from .model import MessageRequest

class Mailer(CommandWorker):

    def __init__(self, cfg: MailerConfig, workdir: pathlib.Path, mode: str):
        self.cfg = cfg
        self.workdir = workdir
        self.rate_limiter = RateLimiter(
            window=cfg.mail.rate_limit_window,
            count=cfg.mail.rate_limit_count,
        )

        self._prepare_logging()
        self._init_context(workdir=workdir, mode=mode)
        self.ctx = Context.get()

    def _init_context(self, workdir: pathlib.Path, mode: str):
        Context.initialize(
            config=self.cfg,
            workdir=workdir,
            db=Database(cfg=self.cfg.db),
            sender=SMTPSender(cfg=self.cfg.mail),
            mode=mode,
        )
        if self.cfg.sentry.enabled and self.cfg.sentry.workers_dsn is not None:
            SentryReporter.initialize(
                dsn=self.cfg.sentry.workers_dsn,
                environment=self.cfg.general.environment,
                server_name=self.cfg.general.client_url,
            )

    def _prepare_logging(self):
        prepare_logging(cfg=self.cfg)
        Context.logger.set_level(self.cfg.log.level)

    def work(self) -> bool:
        Context.update_trace_id(str(uuid.uuid4()))
        ctx = Context.get()
        Context.logger.debug('Trying to fetch a new job')
        cursor = ctx.app.db.conn_query.new_cursor(use_dict=True)
        cursor.execute(Queries.SELECT_CMD, {'now': datetime.datetime.utcnow()})
        result = cursor.fetchall()
        if len(result) != 1:
            Context.logger.debug(f'Fetched {len(result)} jobs')
            return False

        command = result[0]
        try:
            cmd = PersistentCommand.deserialize(command)
            self._process_command(cmd)
        except Exception as e:
            Context.logger.warning(f'Errored with exception: {str(e)}')
            SentryReporter.capture_exception(e)
            ctx.app.db.execute_query(
                query=Queries.UPDATE_CMD_ERROR,
                attempts=command.get('attempts', 0) + 1,
                error_message=f'Failed with exception: {str(e)}',
                updated_at=datetime.datetime.utcnow(),
                uuid=command['uuid'],
            )

        Context.logger.info('Committing transaction')
        ctx.app.db.conn_query.connection.commit()
        cursor.close()
        Context.logger.info('Job processing finished')
        self.rate_limiter.hit()
        Context.update_trace_id('-')
        return True

    def _process_command(self, cmd: PersistentCommand):
        app_ctx = Context.get().app
        mc = load_mailer_command(cmd)
        mc.prepare(app_ctx.db)
        rq = mc.to_request(
            msg_id=cmd.uuid,
            trigger='PersistentComment',
        )
        self.send(rq)
        app_ctx.db.execute_query(
            query=Queries.UPDATE_CMD_DONE,
            attempts=cmd.attempts + 1,
            updated_at=datetime.datetime.utcnow(),
            uuid=cmd.uuid,
        )

    def run(self):
        Context.get().app.db.connect()
        Context.logger.info('Preparing command queue')
        queue = CommandQueue(
            worker=self,
            listen_query=Queries.LISTEN,
        )
        queue.run()

    def send(self, rq: MessageRequest):
        Context.logger.info(f'Sending request: {rq.template_name} ({rq.id})')
        # get template
        if not self.ctx.templates.has_template_for(rq):
            raise RuntimeError(f'Template not found: {rq.template_name}')
        # render
        Context.logger.info(f'Rendering message: {rq.template_name}')
        msg = self.ctx.templates.render(rq)
        # send
        Context.logger.info(f'Sending message: {rq.template_name}')
        self.ctx.app.sender.send(msg)
        Context.logger.info('Message sent successfully')

#########################################################################################
# Commands and their logic
#########################################################################################

class RateLimiter:

    def __init__(self, window: int, count: int):
        self.window = window
        self.count = count
        self.hits = []  # type: list[float]

    def hit(self):
        if self.window == 0:
            return
        Context.logger.debug('Hit for checking rate limit')
        now = datetime.datetime.now().timestamp()
        threshold = now - self.window
        while len(self.hits) > 0 and self.hits[0] < threshold:
            self.hits.pop()
        self.hits.append(now)

        if len(self.hits) >= self.count:
            Context.logger.info('Reached rate limit')
            sleep_time = math.ceil(self.window - now + self.hits[0])
            if sleep_time > 1:
                Context.logger.info(f'Will sleep now for {sleep_time} second')
                time.sleep(sleep_time)

def _app_config_to_context(app_config: Optional[DBAppConfig]) -> dict:
    if app_config is None:
        return {}
    return {
        'supportEmail': app_config.support_email,
        'appTitle': app_config.app_title,
    }

class MailerCommand:

    FUNCTION_NAME = 'unknown'
    TEMPLATE_NAME = ''

    def to_context(self) -> dict:
        pass

    def to_request(self, msg_id: str, trigger: str) -> MessageRequest:
        pass

    def prepare(self, db: Database):
        pass

    @classmethod
    def corresponds(cls, cmd: PersistentCommand) -> bool:
        return cls.FUNCTION_NAME == cmd.function

    @staticmethod
    def create_from(cmd: PersistentCommand) -> 'MailerCommand':
        pass

class CmdUser:

    def __init__(self, user_uuid: str, first_name: str, last_name: str,
                 email: str):
        self.uuid = user_uuid
        self.first_name = first_name
        self.last_name = last_name
        self.email = email

    def to_context(self) -> dict:
        return {
            'uuid': self.uuid,
            'firstName': self.first_name,
            'lastName': self.last_name,
            'email': self.email
        }

class CmdOrg:

    def __init__(self, org_id: str, name: str, email: str):
        self.id = org_id
        self.name = name
        self.email = email

    def to_context(self) -> dict:
        return {
            'id': self.id,
            'name': self.name,
            'email': self.email
        }

class MailerWizardCommand(MailerCommand):

    def __init__(self, app_uuid: str):
        self.app_uuid = app_uuid
        self.app_config = None  # type: Optional[DBAppConfig]

    def prepare(self, db: Database):
        self.app_config = db.get_app_config(
            app_uuid=self.app_uuid,
        )

class _MWRegistrationConfirmation(MailerWizardCommand):

    FUNCTION_NAME = 'sendRegistrationConfirmationMail'
    TEMPLATE_NAME = 'registrationConfirmation'

    def __init__(self, email: str, user: CmdUser, code: str,
                 client_url: str, app_uuid: str):
        super().__init__(app_uuid=app_uuid)
        self.email = email
        self.user = user
        self.code = code
        self.client_url = client_url

    @property
    def activation_link(self):
        return f'{self.client_url}/signup/{self.user.uuid}/{self.code}'

    def to_context(self) -> dict:
        ctx = {
            'user': self.user.to_context(),
            'activationLink': self.activation_link,
            'clientUrl': self.client_url,
            'hash': self.code,
        }
        ctx.update(_app_config_to_context(self.app_config))
        return ctx

    def to_request(self, msg_id: str, trigger: str) -> MessageRequest:
        return MessageRequest(
            message_id=msg_id,
            template_name=self.TEMPLATE_NAME,
            trigger=trigger,
            ctx=self.to_context(),
            recipients=[self.email],
        )

    @classmethod
    def corresponds(cls, cmd: PersistentCommand) -> bool:
        return cls.FUNCTION_NAME == cmd.function and 'userUuid' in cmd.body

    @staticmethod
    def create_from(cmd: PersistentCommand) -> MailerCommand:
        return _MWRegistrationConfirmation(
            email=cmd.body['email'],
            user=CmdUser(
                user_uuid=cmd.body['userUuid'],
                first_name=cmd.body['userFirstName'],
                last_name=cmd.body['userLastName'],
                email=cmd.body['userEmail'],
            ),
            code=cmd.body['hash'],
            client_url=cmd.body['clientUrl'],
            app_uuid=cmd.app_uuid,
        )

class _MWQuestionnaireInvitation(MailerWizardCommand):

    FUNCTION_NAME = 'sendQuestionnaireInvitationMail'
    TEMPLATE_NAME = 'questionnaireInvitation'

    def __init__(self, email: str, invitee: CmdUser, owner: CmdUser,
                 project_uuid: str, project_name: str,
                 client_url: str, app_uuid: str):
        super().__init__(app_uuid=app_uuid)
        self.email = email
        self.invitee = invitee
        self.owner = owner
        self.project_uuid = project_uuid
        self.project_name = project_name
        self.client_url = client_url

    @property
    def project_link(self):
        return f'{self.client_url}/projects/{self.project_uuid}'

    def to_context(self) -> dict:
        ctx = {
            'invitee': self.invitee.to_context(),
            'owner': self.owner.to_context(),
            'project': {
                'uuid': self.project_uuid,
                'name': self.project_name,
                'link': self.project_link,
            },
            'clientUrl': self.client_url,
        }
        ctx.update(_app_config_to_context(self.app_config))
        return ctx

    def to_request(self, msg_id: str, trigger: str) -> MessageRequest:
        return MessageRequest(
            message_id=msg_id,
            template_name=self.TEMPLATE_NAME,
            trigger=trigger,
            ctx=self.to_context(),
            recipients=[self.email],
        )

    @staticmethod
    def create_from(cmd: PersistentCommand) -> MailerCommand:
        return _MWQuestionnaireInvitation(
            email=cmd.body['email'],
            invitee=CmdUser(
                user_uuid=cmd.body['inviteeUuid'],
                first_name=cmd.body['inviteeFirstName'],
                last_name=cmd.body['inviteeLastName'],
                email=cmd.body['inviteeEmail'],
            ),
            owner=CmdUser(
                user_uuid=cmd.body['ownerUuid'],
                first_name=cmd.body['ownerFirstName'],
                last_name=cmd.body['ownerLastName'],
                email=cmd.body['ownerEmail'],
            ),
            project_uuid=cmd.body['questionnaireUuid'],
            project_name=cmd.body['questionnaireName'],
            client_url=cmd.body['clientUrl'],
            app_uuid=cmd.app_uuid,
        )

class _MWRegistrationCreatedAnalytics(MailerWizardCommand):

    FUNCTION_NAME = 'sendRegistrationCreatedAnalyticsMail'
    TEMPLATE_NAME = 'registrationCreatedAnalytics'

    def __init__(self, email: str, user: CmdUser, client_url: str, app_uuid: str):
        super().__init__(app_uuid=app_uuid)
        self.email = email
        self.user = user
        self.client_url = client_url

    def to_context(self) -> dict:
        ctx = {
            'user': self.user.to_context(),
            'clientUrl': self.client_url,
        }
        ctx.update(_app_config_to_context(self.app_config))
        return ctx

    def to_request(self, msg_id: str, trigger: str) -> MessageRequest:
        return MessageRequest(
            message_id=msg_id,
            template_name=self.TEMPLATE_NAME,
            trigger=trigger,
            ctx=self.to_context(),
            recipients=[self.email],
        )

    @classmethod
    def corresponds(cls, cmd: PersistentCommand) -> bool:
        return cls.FUNCTION_NAME == cmd.function and 'userUuid' in cmd.body

    @staticmethod
    def create_from(cmd: PersistentCommand) -> MailerCommand:
        return _MWRegistrationCreatedAnalytics(
            email=cmd.body['email'],
            user=CmdUser(
                user_uuid=cmd.body['userUuid'],
                first_name=cmd.body['userFirstName'],
                last_name=cmd.body['userLastName'],
                email=cmd.body['userEmail'],
            ),
            client_url=cmd.body['clientUrl'],
            app_uuid=cmd.app_uuid,
        )

class _MWResetPassword(MailerWizardCommand):

    FUNCTION_NAME = 'sendResetPasswordMail'
    TEMPLATE_NAME = 'resetPassword'

    def __init__(self, email: str, user: CmdUser, code: str,
                 client_url: str, app_uuid: str):
        super().__init__(app_uuid=app_uuid)
        self.email = email
        self.user = user
        self.code = code
        self.client_url = client_url

    @property
    def reset_link(self):
        return f'{self.client_url}/forgotten-password/{self.user.uuid}/{self.code}'

    def to_context(self) -> dict:
        ctx = {
            'user': self.user.to_context(),
            'resetLink': self.reset_link,
            'clientUrl': self.client_url,
            'hash': self.code,
        }
        ctx.update(_app_config_to_context(self.app_config))
        return ctx

    def to_request(self, msg_id: str, trigger: str) -> MessageRequest:
        return MessageRequest(
            message_id=msg_id,
            template_name=self.TEMPLATE_NAME,
            trigger=trigger,
            ctx=self.to_context(),
            recipients=[self.email],
        )

    @staticmethod
    def create_from(cmd: PersistentCommand) -> MailerCommand:
        return _MWResetPassword(
            email=cmd.body['email'],
            user=CmdUser(
                user_uuid=cmd.body['userUuid'],
                first_name=cmd.body['userFirstName'],
                last_name=cmd.body['userLastName'],
                email=cmd.body['userEmail'],
            ),
            code=cmd.body['hash'],
            client_url=cmd.body['clientUrl'],
            app_uuid=cmd.app_uuid,
        )

class _MRRegistrationConfirmation(MailerCommand):

    FUNCTION_NAME = 'sendRegistrationConfirmationMail'
    TEMPLATE_NAME = 'registrationConfirmation'

    def __init__(self, email: str, org: CmdOrg, code: str,
                 client_url: str, callback_url: Optional[str]):
        self.email = email
        self.org = org
        self.code = code
        self.client_url = client_url
        self.callback_url = callback_url

    @property
    def activation_link(self) -> str:
        return f'{self.client_url}/signup/{self.org.id}/{self.code}'

    @property
    def callback_link(self) -> Optional[str]:
        if self.callback_url is None:
            return None
        return f'{self.client_url}/registry/signup/{self.org.id}/{self.code}'

    def to_context(self) -> dict:
        return {
            'organization': self.org.to_context(),
            'hash': self.code,
            'activationLink': self.activation_link,
            'callbackLink': self.callback_link,
            'clientUrl': self.client_url,
        }

    def to_request(self, msg_id: str, trigger: str) -> MessageRequest:
        return MessageRequest(
            message_id=msg_id,
            template_name=self.TEMPLATE_NAME,
            trigger=trigger,
            ctx=self.to_context(),
            recipients=[self.email],
        )

    @classmethod
    def corresponds(cls, cmd: PersistentCommand) -> bool:
        return cls.FUNCTION_NAME == cmd.function and 'organizationId' in cmd.body

    @staticmethod
    def create_from(cmd: PersistentCommand) -> MailerCommand:
        return _MRRegistrationConfirmation(
            email=cmd.body['email'],
            org=CmdOrg(
                org_id=cmd.body['organizationId'],
                name=cmd.body['organizationName'],
                email=cmd.body['organizationEmail'],
            ),
            code=cmd.body['hash'],
            client_url=cmd.body['clientUrl'],
            callback_url=cmd.body.get('callbackUrl', None),
        )

class _MRRegistrationCreatedAnalytics(MailerCommand):

    FUNCTION_NAME = 'sendRegistrationCreatedAnalyticsMail'
    TEMPLATE_NAME = 'registrationCreatedAnalytics'

    def __init__(self, email: str, org: CmdOrg, client_url: str):
        self.email = email
        self.org = org
        self.client_url = client_url

    def to_context(self) -> dict:
        return {
            'organization': self.org.to_context(),
            'clientUrl': self.client_url,
        }

    def to_request(self, msg_id: str, trigger: str) -> MessageRequest:
        return MessageRequest(
            message_id=msg_id,
            template_name=self.TEMPLATE_NAME,
            trigger=trigger,
            ctx=self.to_context(),
            recipients=[self.email],
        )

    @classmethod
    def corresponds(cls, cmd: PersistentCommand) -> bool:
        return cls.FUNCTION_NAME == cmd.function and 'organizationId' in cmd.body

    @staticmethod
    def create_from(cmd: PersistentCommand) -> MailerCommand:
        return _MRRegistrationCreatedAnalytics(
            email=cmd.body['email'],
            org=CmdOrg(
                org_id=cmd.body['organizationId'],
                name=cmd.body['organizationName'],
                email=cmd.body['organizationEmail'],
            ),
            client_url=cmd.body['clientUrl'],
        )

class _MRResetToken(MailerCommand):

    FUNCTION_NAME = 'sendResetTokenMail'
    TEMPLATE_NAME = 'resetToken'

    def __init__(self, email: str, org: CmdOrg, code: str, client_url: str):
        self.email = email
        self.org = org
        self.code = code
        self.client_url = client_url

    @property
    def reset_link(self):
        return f'{self.client_url}/forgotten-token/{self.org.id}/{self.code}'

    def to_context(self) -> dict:
        return {
            'organization': self.org.to_context(),
            'resetLink': self.reset_link,
            'hash': self.code,
            'clientUrl': self.client_url,
        }

    def to_request(self, msg_id: str, trigger: str) -> MessageRequest:
        return MessageRequest(
            message_id=msg_id,
            template_name=self.TEMPLATE_NAME,
            trigger=trigger,
            ctx=self.to_context(),
            recipients=[self.email],
        )

    @staticmethod
    def create_from(cmd: PersistentCommand) -> MailerCommand:
        return _MRResetToken(
            email=cmd.body['email'],
            org=CmdOrg(
                org_id=cmd.body['organizationId'],
                name=cmd.body['organizationName'],
                email=cmd.body['organizationEmail'],
            ),
            code=cmd.body['hash'],
            client_url=cmd.body['clientUrl'],
        )

_MAILER_COMMANDS = [
    _MWRegistrationConfirmation,
    _MWResetPassword,
    _MWQuestionnaireInvitation,
    _MWRegistrationCreatedAnalytics,
    _MRRegistrationConfirmation,
    _MRResetToken,
    _MRRegistrationCreatedAnalytics,
]

def load_mailer_command(cmd: PersistentCommand) -> MailerCommand:
    if cmd.component != CMD_COMPONENT:
        raise RuntimeError('Tried to process non-mailer command')
    for CMD_TYPE in _MAILER_COMMANDS:
        if issubclass(CMD_TYPE, MailerCommand) and CMD_TYPE.corresponds(cmd):
            try:
                return CMD_TYPE.create_from(cmd)
            except KeyError as e:
                raise RuntimeError(f'Cannot parse command: {str(e)}')
    raise RuntimeError('Cannot process such command')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.4'
#       jupytext_version: 1.1.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # s_ens_two_scenarios [<img src="https://www.arpm.co/lab/icons/icon_permalink.png" width=30 height=30 style="display: inline;">](https://www.arpm.co/lab/redirect.php?code=s_ens_two_scenarios&codeLang=Python)
# For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=ExerENScont).

# +
import numpy as np
import matplotlib.pyplot as plt

from arpym.estimation import effective_num_scenarios
from arpym.tools import add_logo
# -

# ## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_ens_two_scenarios-parameters)

k_ = 100  # size of grid of probabilities
min_p_1 = 0  # minimum value for p_1
max_p_1 = 1  # maximum value for p_1

# ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_ens_two_scenarios-implementation-step01): Create flexible probabilities scenarios

# create flexible probabilities
p_1 = np.linspace(min_p_1, max_p_1, num=k_)
p_2 = np.ones(k_)-p_1
p = np.vstack((p_1, p_2))

# ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_ens_two_scenarios-implementation-step02): Calculate the effective number of scenarios

ens = np.zeros(k_)
for k in range(k_):
    ens[k] = effective_num_scenarios(p[:, k])

# ## Plots

# +
plt.style.use('arpm')

f = plt.figure(figsize=(1280.0/72.0, 720.0/72.0), dpi=72.0)
plt.plot(p_1, ens, lw=1.5)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.xlabel(r'$p_1$', fontsize=17)
plt.ylabel('$ens(\mathbf{p})$', fontsize=17)
plt.title('Effective number of scenarios as the flexible probabilities vary\n'
          r'$\bar{t}=2$', fontsize=20, fontweight='bold')
add_logo(f, location=1, set_fig_size=False)
plt.tight_layout()


# open('test.txt','w')
file_name="test.txt"

# f=open('test.txt','r')
# f.close()

# f=open(file_name,'w')
# f.write("hello world")
# f.close()

# f=open(file_name,'r')
# # ret = f.read(4)
# # print(ret)
# # ret = f.read(4)
# # print(ret)
# # f.close()

# f=open(file_name,'r')
# # ret = f.readlines()
# # print(ret)
#
# ret = f.readline()
# print(ret)
#
# f.close()

# f=open(file_name,'a')
# f.write('aaaa')
# f.close()

my_list=[1,3.14,"hello","what"]
a,pi,world,heihei=my_list
print(pi,heihei)


import logging
import json
import re

from flask import request, jsonify, Response
from codeitsuisse import app

logger = logging.getLogger(__name__)

@app.route('/tickerStreamPart1', methods=['POST'])
def evaluate():
    data = request.get_json()
    logging.info("data sent for evaluation {}".format(data))
    inputValue = data.get("stream")
    result = tickerFunc(inputValue)
    logging.info("My result :{}".format(result))
    result = {"output": result}
    return json.dumps(result)

def tickerFunc(stream):
    res_list = []
    time_dict = dict()  # Tickers based on timestamp (For handling different trades)

    for trade in stream:
        trade_list = trade.split(",")
        time_stamp = trade_list[0]

        if time_stamp not in time_dict:
            time_dict[time_stamp] = dict()

        # Tabulate quantity and notional price
        for i in range(1, len(trade_list), 3):
            quantity = int(trade_list[i + 1])
            price = float(trade_list[i + 2])
            notional = quantity * price

            if trade_list[i] in time_dict[time_stamp]:
                time_dict[time_stamp][trade_list[i]][0] += quantity
                time_dict[time_stamp][trade_list[i]][1] += notional

            else:
                time_dict[time_stamp][trade_list[i]] = [quantity, notional]

    # Convert dict to list
    ticker_list = []

    for timestamp, value in time_dict.items():
        for ticker, data in value.items():
            ticker_str = ",".join([ticker, str(data[0]), str(round(data[1], 1))])
            ticker_list.append(ticker_str)

        # Sort list
        ticker_list.sort()
        result = ",".join(ticker_list)
        res_list.append(f"{timestamp},{result}")

    res_list.sort()

    return res_list

def cumulate_ticker(trade_list):
    time_stamp = trade_list[0]
    ticker_dict = dict()

    # Tabulate quantity and notional price
    for i in range(1, len(trade_list), 3):
        quantity = int(trade_list[i + 1])
        price = float(trade_list[i + 2])
        notional = quantity * price

        if trade_list[i] in ticker_dict:
            ticker_dict[trade_list[i]][0] += quantity
            ticker_dict[trade_list[i]][1] += notional

        else:
            ticker_dict[trade_list[i]] = [quantity, notional]

    # Convert dict to list
    res_list = []

    for key, value in ticker_dict.items():
        ticker_str = ",".join([key, str(value[0]), str(round(value[1], 1))])
        res_list.append(ticker_str)

    # Sort list
    res_list.sort()

    result = ",".join(res_list)

    return time_stamp + "," + result

@app.route('/tickerStreamPart2', methods=['POST'])
def ticker2():
    data = request.get_json()
    logging.info("data sent for evaluation {}".format(data))
    stream = data.get("stream")
    quantityBlock = data.get("quantityBlock")
    result = to_cumulative_delayed(stream, quantityBlock)
    logging.info("My result :{}".format(result))
    result = {"output": result}
    return json.dumps(result)

def to_cumulative_delayed(stream, quantity_block):
    stream.sort()
    track_dict = {}
    result = []

    for trade in stream:
        order_list = trade.split(",")
        timestamp = order_list[0]
        block_list = (
            []
        )  # Store all ticker that hits the quantity blocks during this timestamp

        for i in range(1, len(order_list), 3):
            curr_qty = int(order_list[i + 1])
            price = float(order_list[i + 2])

            # Ticker and quantity exist
            if order_list[i] in track_dict:
                exist_qty, exist_notional = track_dict[order_list[i]]

                # Check quantity match the quantity block
                if quantity_block <= exist_qty + curr_qty:

                    required_qty = quantity_block - exist_qty
                    notional = required_qty * price

                    # Current trade and existing quantity exceeds quantity block (Splitting required)
                    if curr_qty > required_qty:
                        excess_qty = curr_qty - required_qty

                        block_list.append(
                            f"{order_list[i]},{quantity_block},{notional + exist_notional}"
                        )

                        # Store leftover quantity and notional back into tracking dictionary
                        track_dict[order_list[i]] = [excess_qty, excess_qty * price]

                    # Current trade quantity = required quantity
                    else:
                        block_list.append(
                            f"{order_list[i]},{quantity_block},{notional + exist_notional}"
                        )
                        track_dict[order_list[i]] = [0, 0]

                else:
                    track_dict[order_list[i]][0] += curr_qty
                    track_dict[order_list[i]][1] += curr_qty * price

            else:
                if curr_qty == quantity_block:
                    block_list.append(
                        f"{order_list[i]},{quantity_block},{curr_qty * price}"
                    )

                else:
                    track_dict[order_list[i]] = [curr_qty, curr_qty * price]

        # Check if any quantity blocks fulfilled in current timestamp
        if block_list:
            # Sort quantity blocks by ticker alphabetical order
            block_list.sort()
            result.append(f"{timestamp},{','.join(block_list)}")

    return result


import requests
from pathlib import Path
import re
import json
import os
from config import config as cfg

def parse_paper(file_path, parse_info=""):
    if parse_info == "":
        url = cfg["URL"]["PARSER_URL"]
        with open(file_path, 'rb') as file:
            files = {'file': file}
            response = requests.post(url, files=files)
        text_data = json.loads(response.text)
    else:
        text_data = json.loads(parse_info)
    text_paragraphs = text_data["pdf_parse"]["body_text"]
    return text_paragraphs

def extract_figure_info(paper_name: str, file_name: str, parse_info:str=""):
    url = cfg["URL"]["PARSER_URL"]  # replace with your URL
    # file_path = './single_example/example.pdf'  # replace with your file path
    folder_path = os.path.join(cfg["SYS"]["OUT"], paper_name)
    path = Path(folder_path)
    file_path = f"{folder_path}.pdf"
    figure_path = path / "figures"

    text_paragraphs = parse_paper(file_path, parse_info)

    for text_file in Path(figure_path).glob("*.txt"):
        with open(str(text_file), 'r+', encoding="utf-8") as f:
            cur_text = f.read()
            match = re.search(r'(\b\w+)\s*\.?\s*(\d+)(?=\D|$)', cur_text)

            if match:
                figure_type, figure_index = match.group(1), match.group(2)

                print(figure_type, figure_index)

                if figure_type.lower().startswith("fig"):
                    pattern = rf"(Figure|Fig\.?\s*)\s*\.?\s*({figure_index})(?=\D|$)"
                else:
                    pattern = rf"({figure_type}s?)\s*\.?\s*({figure_index})(?=\D|$)"

                for item in text_paragraphs:
                    text_match = re.search(pattern, item["text"], re.IGNORECASE)
                    if text_match:
                        f.write(f'\n{item["text"]}')


import smtplib,ssl
import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import os

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice',voices[0].id)

def speak(audio):
    engine.say(audio)
    engine.runAndWait()

def wishMe():
    hour=int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
     speak("good morning!")
    elif hour>=12 and hour<=18:
        speak("good afternoon!")
    else:
        speak("good evening!")

    speak("I am DAVID sir. Please tell me how can i help you !")

def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("listening...")
        r.pause_threshold=0.5
        r.adjust_for_ambient_noise(source,duration=1)
        audio=r.listen(source)

    try:
        print("recognizing...")
        query=r.recognize_google(audio)
        print(f"user said:{query}\n")

    except Exception as e:
        print("say that again please...")
        return "None"
    return query

def sendEmail(to,content):
    port=465
    context=ssl.create_default_context()
    with smtplib.SMTP_SSL("smtp.gmail.com",port,context=context) as server:
        server.sendmail(to,to,content)

if __name__ == "__main__":
    wishMe()
    while True:
     query=takeCommand().lower()

     if 'wikipedia' in query :
         speak('searching wikipedia...')
         query=query.replace("wikipedia","")
         results=wikipedia.summary(query,sentences=2)
         speak("according to wikipedia")
         print(results)
         speak(results)

     elif "open youtube" in query :
         webbrowser.open("youtube.com")

     elif "open google" in query :
         webbrowser.open("google.com")

     elif "open stack overflow" in query :
         webbrowser.open("stackoverflow.com")

     elif "time" in query:
         strtime=datetime.datetime.now().strftime("%H:%M:%S")
         speak(f"SIR,THE TIME IS {strtime}")

     elif "code" in query:
         codepath=r"C:\Users\shivansh uppal\AppData\Local\Programs\Microsoft VS Code\Code.exe"
         os.startfile(codepath)

     elif "mail" in query:
         #need to enable less secure apps till then not working
         try:
             speak("what should i say ?")
             content=takeCommand()
             to = "shivanshway@gmail.com"
             sendEmail(to,content)
             speak("email is sent")

         except Exception as e:
             print(e)
             speak("sorry sir, email is not sent ")

     elif "github" in query:
         webbrowser.open("github.com")

     elif "quit" in query:
            speak("good bye sir")
            break

     elif "play music" in query:
            music_dir=r"C:\Users\shivansh uppal\Music"
            songs=os.listdir(music_dir)
            os.startfile(os.path.join(music_dir,songs[0]))


def readInput(seperator):
    inPath = input('Please enter the path to the input file\n')
    input_raw = open(inPath).read()
    # obsolete end of lines
    noObseol = 0
    for c in input_raw[::-1]:
        if(c == '\n'):
            noObseol+=1
        else:
            break
    if noObseol != 0:
        input_clean = input_raw[:-noObseol]
    else:
        input_clean = input_raw
    input_sliced = input_clean.split(seperator)
    return input_sliced

def prepare_data(input_sliced):

    bagMap = [b.split("contain") for b in input_sliced]
    # bagenanigans will contain all combinations of one inner and one outer bag including cardinality
    bagenanigans = []
    for b in bagMap:
        # remove unneccessary markup
        outerBag = b[0].replace("bags","").replace(" ","")
        innerBags = b[1].split(",")
        innerBags = [b.replace("bags","").replace("bag","").replace(" ","").replace(".","") for b in innerBags]

        # add entry in bagenanigans for each inner bag
        bagenanigans += [[outerBag, b[1:], b[0]] for b in innerBags]

        # some bags don't contain other bags, those can be discarded for our purpose
        bagenanigans = [b for b in bagenanigans if "n" not in b[2]]

    return bagenanigans

seperator = "\n"
input_sliced = readInput(seperator)
bagenanigans = prepare_data(input_sliced)

## Task 1 ##

shinyBags = ['shinygold']
numBags = 0
# at each recursion, shinyBags contains another layer of "parent bags"
# stop when no new possibilities are found
while(numBags < len(shinyBags)):
    numBags = len(shinyBags)
    shinyBags += [b[0] for b in bagenanigans if (b[1] in shinyBags and b[0] not in shinyBags)]

# shinygold is not counted, remove duplicates
print(len(set(shinyBags))-1, 'colors of bags can eventually contain at least one shiny gold bag.')

## Task 2 ##

# for each occurrence of
def getInnerBagCount(bagColor, bagAttributeMap):
    bagCount = 1
    for b in bagAttributeMap:
        if (b[0]==bagColor):
            bagCount += int(b[2])*getInnerBagCount(b[1], bagAttributeMap)
    return bagCount

# shinygold is not counted
print('There are',getInnerBagCount('shinygold',bagAttributeMap)-1,'individual bags required inside my single shiny gold bag.')


#Crear un script que pasando un número como argumento lo descomponga en sus dígitos. Es decir: 642 debería ser descompuesto en:
6, 4, 2

numero = int (input("Coloca un número: "))

if(numero >= 100):
	if(numero <= 999):
		a = numero /100
		b = (numero % 100)/10
		c = (numero % 100) %10 /10
		print(a, b, c)
	else:
		print("Ese no es el número")
else:
	print("Ese no es el número")


from apscheduler.executors.asyncio import AsyncIOExecutor
from apscheduler.jobstores.redis import RedisJobStore
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from pytz import utc

from sophie_bot.config import get_str_key, get_int_key
from sophie_bot.utils.logger import log

DEFAULT = "default"

jobstores = {
    DEFAULT: RedisJobStore(
        host=get_str_key("REDIS_HOST"),
        port=get_str_key("REDIS_PORT"),
        db=get_int_key("REDIS_DB_FSM")
    )
}
executors = {DEFAULT: AsyncIOExecutor()}
job_defaults = {"coalesce": False, "max_instances": 3}

scheduler = AsyncIOScheduler(
    jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc
)

log.info("Starting apscheduller...")
scheduler.start()


import numpy as np
import time
from datetime import datetime
from faker import Faker
import pandas as pd
import boto3
import sys
import json
import base64

fake = Faker()

start_time = int(time.time())
end_time = time.time() + 600

number_of_devices = 3
areas = ['N', 'S', 'E', 'W']
desired_device_ids = ['ABC123', 'DEF456', 'GHI789']
# def get_device_ids_areas(number_of_devices):
#     # Universal Unique Identifier
#     return [(fake.uuid4(), areas[np.random.randint(0,4)]) for x in range(number_of_devices)]
def get_device_ids_areas(desired_device_ids):
    return [(device_id, areas[np.random.randint(0, 4)]) for device_id in desired_device_ids]

def convert_date_to_human_readable(unix_time):
    return datetime.fromtimestamp(unix_time).strftime('%Y-%m-%d %H:%M:%S')

def get_temperature(previous_temperature = 22):
    # if previous_temperature % 2 == 0:
    #     return previous_temperature + np.random.randint(-2,5)
    # else:
    #     return previous_temperature + np.random.randint(-3,3)
    threshold = 50  # Threshold value for generating temperature above 50
    return np.random.randint(threshold, 101)
    # return np.random.randint(1, 101)

kinesis_client = boto3.client('kinesis', region_name='us-east-1')  # Replace with your AWS region

def send_temperature_to_stream(device_id, area, timestamp, temperature):
    stream_name = 'Abdul-Temperature-Stream'  # Replace with your Kinesis Data Stream name
    partition_key = device_id

    # Prepare the temperature data to be sent
    temperature_data = {
        'device_id': device_id,
        'area': area,
        'timestamp': timestamp,
        'temperature': temperature
    }

    # Convert the data to a JSON string
    json_data = json.dumps(temperature_data)

    # Base64 encode the JSON string
    encoded_data = base64.b64encode(json_data.encode('utf-8')).decode('utf-8')

    # Send the data to the Kinesis Data Stream
    response = kinesis_client.put_record(
        StreamName=stream_name,
        Data=json_data,
        PartitionKey=partition_key
    )

    # Print the response (useful for debugging)
    print(f"Data sent to Kinesis. ShardId: {response['ShardId']}, SequenceNumber: {response['SequenceNumber']}, Data: {json_data}")

def main():

    ids_areas = get_device_ids_areas(desired_device_ids )
    print(ids_areas)
    while True:
        for each_id, area in ids_areas:
            timestamp = convert_date_to_human_readable(int(time.time()))
            default_temperature = get_temperature()
            send_temperature_to_stream(each_id, area, timestamp, default_temperature)

        # Wait for 1 second before sending data for the next round
        time.sleep(5)

def lambda_handler(event, context):
    main()


from transformers import (
    GPT2LMHeadModel,
    GPT2Tokenizer
)

class EmailExtractorModel():

    def __init__(
            self,
            model_args
        ):
        self.model_name_or_path = model_args.model_name_or_path
        self.load_finetuned_model = model_args.load_finetuned_model

    def load_tokenizer(
            self
        ):
        self.tokenizer = GPT2Tokenizer.from_pretrained(self.model_name_or_path)
        self.tokenizer.truncation_side = "left"
        if not self.load_finetuned_model:
            self.tokenizer.add_special_tokens({"pad_token": "<pad>"})

        return self.tokenizer

    def load_model(
            self
        ):
        self.model = GPT2LMHeadModel.from_pretrained(self.model_name_or_path)
        self.model.to("cuda")
        if not self.load_finetuned_model:
            self.model.resize_token_embeddings(len(self.tokenizer))

        return self.model