"""
Modifies a PDB file to be used for motif-scaffolding in order to make it monomeric.

1. Changes all chain-ids to be A (so that the protein is a monomer)
2. Aligns the axis of symmetry along the z-axis (requirement of RFDiffusion)
"""

from pathlib import Path
from shutil import copy as copy_file

import typer
import pandas as pd
from biotite.structure.io import load_structure, save_structure

from monomerizer import monomerizer, pdb

def main(
    input_pdb: Path = typer.Argument(..., help="PDB to be modified"),
    output_dir: Path = typer.Argument(..., help="Directory to hold outputs"),
    generator_steps: int = typer.Option(
        default=25, help="How many denoising steps to take."
    ),
    num_designs: int = typer.Option(
        default=3,
        help="How many structures RFDiffusion should generate per linker length",
    ),
    linker_lengths: str = typer.Option(
        default=None,
        help="List of lengths to use for linking, e.g. '10-20' or '12,15,17`, if not provided then choose automatically",
    ),
    trim_n: int = typer.Option(
        default=0, help="How many N-terminal residues to trim from each chain"
    ),
    trim_c: int = typer.Option(
        default=0, help="How many C-terminal residues to trim from each chain"
    ),
    num_selected: int = typer.Option(
        default=3, help="Top designs by symmetry to copy into the top output directory."
    ),
):
    """
    Change all chain-ids to A and align axis of cyclic symmetry to the z-axis for a given input PDB.

    Examples:
    make_monomer.py tests/pdbs/2XQS_short.pdb tmp/ --generator-steps=25 --linker-lengths=15 --num-designs=5
    make_monomer.py tests/pdbs/2XQS_short.pdb tmp/ --generator-steps=10 --linker-lengths=10-20 --num-designs=3
    make_monomer.py tests/pdbs/4JPP_short.pdb tmp/ --generator-steps=15 --linker-lengths=30 --num-designs=1
    """
    output_dir.mkdir(exist_ok=True, parents=True)

    # load, modify, and save the pdb structure
    unified_structure = load_structure(input_pdb)

    # perform structure modifications
    if (trim_n > 0) or (trim_c > 0):
        unified_structure = pdb.trim_termini(unified_structure, trim_n, trim_c)
    unified_structure = pdb.unify_chain_ids(unified_structure)

    # generate a template for what the contig map will look like
    base_contigs = monomerizer.generate_base_contigs(unified_structure)

    # add the pore
    pore_res_ids, pore_res_chain_id, unified_structure = pdb.fill_pore(
        unified_structure
    )
    # determine which residues the pore contacts or are buried, these should be fixed
    fixed_res_ids = monomerizer.get_fixed_res_ids(unified_structure, pore_res_ids)
    inpaint_contigs = monomerizer.generate_inpaint_contig(
        unified_structure, fixed_res_ids, pore_res_chain_id
    )

    unified_pdb = (output_dir / input_pdb.stem).with_suffix(".unified.pdb")
    save_structure(unified_pdb, unified_structure)

    # get the number of lengths/runs we need to complete
    if linker_lengths is None:
        res_lengths = monomerizer.get_res_range(unified_structure)
    else:
        res_lengths = monomerizer.parse_manual_res_range(linker_lengths)

    # scan over residue lengths and generate structures
    structures = monomerizer.generate_linked_structures(
        unified_pdb,
        pore_res_ids,
        pore_res_chain_id,
        output_dir,
        res_lengths,
        num_designs,
        base_contigs,
        inpaint_contigs,
        steps=generator_steps,
    )

    results = {
        "pdb": [structure.pdb_file for structure in structures],
        "linker_length": [structure.linker_length for structure in structures],
        "symmetry_rmsd": [structure.symmetry_rmsd for structure in structures],
    }
    results_df = pd.DataFrame().from_dict(results)
    results_df = results_df.sort_values(by="symmetry_rmsd")
    selected_dir = output_dir / "top"
    selected_dir.mkdir(exist_ok=True)
    for idx in range(min(num_selected, num_designs * len(res_lengths))):
        copy_file(
            results_df.iloc[idx].pdb,
            selected_dir / results_df.iloc[idx].pdb.name,
        )
    results_df.to_csv(output_dir / "results.csv")
    print(results_df)

if __name__ == "__main__":
    typer.run(main)


from art import logo
import random
from replit import clear

BEGINNER = 10
AMATEUR = 8
PROFFESIONAL = 6
SUPERSTAR = 4
number_range = []
lives = 0
for i in range(1, 101):
    number_range.append(i)
print(number_range)
number = 0

def choose_number():
    """returns a random number"""
    number = random.choice(number_range)
    return number

# def choose_level():
#   """asigns the number of lives with respect to the level the player choses"""
#   chose_level = input("choose a level of your choice\n biginner \n Amateur\n professional,\n superstar").lower()
#   if chose_level == "biginner":
#     lives = BEGINNER
#   elif chose_level == "amateur":
#     lives = AMATEUR
#   elif chose_level == "professional":
#     lives = PROFFESIONAL
#   elif chose_level == "superstar":
#     lives = SUPERSTAR
#   return lives

def play_again():
    """restarts or ends the game"""
    continue_playing = input("type 'p' too continue playing or 'q' to quit: ").lower()
    if continue_playing == "p":
        clear()
        game(lives)
    else:
        clear()

def game(lives):
    print(logo)
    print("Welcome to my guess a number game")
    print("i am thinking of a number between 1-100")
    number = choose_number()
    chose_level = input(
        "choose a level of difficulty. Type: 'beginner', 'Amateur', 'professional', 'superstar'\n\n"
    ).lower()
    if chose_level == "beginner":
        lives = BEGINNER
    elif chose_level == "amateur":
        lives = AMATEUR
    elif chose_level == "professional":
        lives = PROFFESIONAL
    elif chose_level == "superstar":
        lives = SUPERSTAR
    else:
        print("howdy you missed something ")

    while lives > 0:
        print(f"you have {lives} attempts remaining to guess the number")
        guess = int(input("make a guess:"))
        if guess > number:
            lives -= 1
            print(
                f"Too high.\nGuess again.\nYou have {lives} attempts remaining to guess the number"
            )
        elif guess < number:
            lives -= 1
            print(
                f"Too low.\nGuess again.\nYou have {lives} attempts remaining to guess the number."
            )
        elif guess == number:
            print(f"Yes! you won.The correct number is {number}")
            play_again()
    play_again()

game(lives)

# new one
from random import randint
from replit import clear
EASY_LEVEL_TURNS = 10
HARD_LEVEL_TURNS = 5
def game():
  answer = randint(1, 100)
  print(f"psst the answer is {answer}")
  print("welcome to my game of guess a number")
  print("I am thinking of a number between 1 - 100")
  def level():
    level = input("choose a level: type 'hard' or 'easy': ").lower()
    if level == "hard":
      return HARD_LEVEL_TURNS
    elif level == "easy":
      return EASY_LEVEL_TURNS

  def check():
    if guess > answer:
      return f"Too high\nGuess again: \nyou have {lives -1} attempts remaining to make a guess"
    elif guess < answer:
      return f"Too low\nGuess again: \nyou have {lives -1} attempts remaining to make a guess"
    else:
      return "You win"

  lives= level()
  while lives > 0:
    guess = int(input("Guess a number: "))
    compare = check()
    if compare == "You win":
      print(f"{compare} the right number is {answer}")
      play_again = input("type 'p' to play again or 'q' to quit: ").lower()
      if play_again == "p":
        clear()
        game()
      else:
        clear()
    else:
      lives -= 1
      print(compare)

  print("You lose but all hope os not lost")
  play_again = input("type 'p' to play again or 'q' to quit: ").lower()
  if play_again == "p":
    clear()
    game()
  else:
    clear()

game()

#TEACHERS'S CORRECTION

from random import randint
from art import logo

EASY_LEVEL_TURNS = 10
HARD_LEVEL_TURNS = 5

#Function to check user's guess against actual answer.
def check_answer(guess, answer, turns):
  """checks answer against guess. Returns the number of turns remaining."""
  if guess > answer:
    print("Too high.")
    return turns - 1
  elif guess < answer:
    print("Too low.")
    return turns - 1
  else:
    print(f"You got it! The answer was {answer}.")

#Make function to set difficulty.
def set_difficulty():
  level = input("Choose a difficulty. Type 'easy' or 'hard': ")
  if level == "easy":
    return EASY_LEVEL_TURNS
  else:
    return HARD_LEVEL_TURNS

def game():
  print(logo)
  #Choosing a random number between 1 and 100.
  print("Welcome to the Number Guessing Game!")
  print("I'm thinking of a number between 1 and 100.")
  answer = randint(1, 100)
  print(f"Pssst, the correct answer is {answer}")

  turns = set_difficulty()
  #Repeat the guessing functionality if they get it wrong.
  guess = 0
  while guess != answer:
    print(f"You have {turns} attempts remaining to guess the number.")

    #Let the user guess a number.
    guess = int(input("Make a guess: "))

    #Track the number of turns and reduce by 1 if they get it wrong.
    turns = check_answer(guess, answer, turns)
    if turns == 0:
      print("You've run out of guesses, you lose.")
      return
    elif guess != answer:
      print("Guess again.")

game()


import asyncio
import pkgutil
import sys

from werkzeug.wrappers import Response
from werkzeug.utils import cached_property
from werkzeug.urls import Href
from werkzeug.exceptions import MethodNotAllowed
from markupsafe import Markup

from galerka.util import asyncached, AsyncGetter

class View:
    def __init__(self, parent, url_fragment, *, request=None):
        self.parent = parent
        self.request = request or parent.request
        if getattr(self, 'url_fragment', None) is None:
            assert isinstance(url_fragment, str)
            self.url_fragment = url_fragment

    @asyncio.coroutine
    def traverse(self, pathinfo):
        if not pathinfo:
            return self
        url_fragment = pathinfo[0]
        if url_fragment == '..':
            if self.parent:
                child = self.parent
            else:
                child = self
        elif url_fragment == '.' or not url_fragment:
            child = self
        elif url_fragment in getattr(self, 'child_classes', {}):
            child = self.child_classes[url_fragment](self, url_fragment)
        else:
            child = (yield from self.get_child(url_fragment))
        return (yield from child.traverse(pathinfo[1:]))

    def __getitem__(self, *path):
        pathinfo = []
        for fragment in path:
            if isinstance(fragment, str):
                pathinfo.extend(fragment.split('/'))
            else:
                pathinfo.append(fragment)
        return self.traverse(pathinfo)

    @cached_property
    def redis_key(self):
        return self.request.redis_prefix + self.path

    @asyncio.coroutine
    def get_child(self, url_fragment):
        raise LookupError(url_fragment)

    @cached_property
    def path(self):
        path = '/'.join(parent.url_fragment for parent in self.lineage)
        if not path:
            return '/'
        else:
            return path

    @cached_property
    def lineage(self):
        parent = self.parent
        if parent:
            parent_lineage = parent.lineage
        else:
            parent_lineage = ()
        return parent_lineage + (self, )

    @cached_property
    def url(self):
        return self.root.href(self.path)

    @cached_property
    def href(self):
        if self.parent:
            return getattr(self.parent.href, self.url_fragment)
        else:
            return Href(self.request.url_root)

    def static_url(self, path):
        static_files = self.request.environ['galerka.static_files']
        item = static_files[path]
        try:
            sha = item.sha
        except AttributeError:
            return self.root.href.static(path)
        else:
            return '%s?%s' % (self.root.href.static(path), sha)

    @cached_property
    def root(self):
        return self.lineage[0]

    @classmethod
    def child(cls, name):
        def decorator(child):
            try:
                child_classes = cls.child_classes
            except AttributeError:
                child_classes = cls.child_classes = {}
            child_classes[name] = child
            return child
        return decorator

    @cached_property
    def allowed_methods(self):
        methods = ('GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'TRACE', 'OPTIONS')
        return [m for m in methods if getattr(self, m, None)]

    def get_response(self, method):
        method = method.upper()
        if method in self.allowed_methods:
            return getattr(self, method)
        else:
            return AsyncGetter(MethodNotAllowed(self.allowed_methods))

    @cached_property
    def HEAD(self):
        return self.GET

    @asyncached
    def OPTIONS(self):
        return Response('', headers={'Allow': ', '.join(self.allowed_methods)})

    @classmethod
    def _load_all_views(cls):
        for pkg in cls.view_packages:
            walk = pkgutil.walk_packages(pkg.__path__, pkg.__name__ + '.')
            for loader, name, is_pkg in walk:
                if name not in sys.modules:
                    module = loader.find_module(name).load_module(name)
                    yield module

class GalerkaView(View):
    extra_javascripts = ['main']
    styles = ['style.css']

    @cached_property
    def GET(self):
        try:
            rendered_page = self.rendered_page
        except AttributeError:
            return None
        else:
            @asyncio.coroutine
            def get():
                rendered = yield from rendered_page
                return Response(rendered, mimetype='text/html')
            return get()

    @property
    def POST(self):
        try:
            do_post = self.do_post
        except AttributeError:
            return None
        else:
            return self.handle_post()

    @asyncio.coroutine
    def handle_post(self):
        status, data, url = yield from self.do_post()
        if self.request.headers['accept'] == 'application/json':
            return Response(data,
                            status=status,
                            headers={'Content-Type':
                                     'application/json'})
        else:
            content = Markup('''

                    <title>OK</title>

OK

→ {}

({})

            ''').format(Markup(url), url, status)
            return Response(content, 303, mimetype='text/html',
                            headers={'Location': url})

    @asyncached
    def rendered_page(self):
        return (yield from self.render_template('base.mako'))

    @asyncached
    def rendered_hierarchy(self):
        result = []
        for page in self.lineage:
            result.append(Markup('
{}
').format(
                page.url,
                (yield from page.title),
            ))
        return Markup('').join(result)

    def get_template(self, name):
        return self.request.environ['galerka.mako'].get_template(name)

    @asyncio.coroutine
    def render_template(self, name):
        template = self.get_template(name)
        result = yield from template.render_async(
            this=self,
            request=self.request,
            static_url=self.static_url,
            redis=self.request.redis,
        )
        return Markup(result)

    @cached_property
    def javascripts(self):
        result = set(self.extra_javascripts)
        for cls in type(self).mro():
            result.update(getattr(cls, 'extra_javascripts', ()))
        return result


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : redis.py
# @Author: Fred Yangxiaofei
# @Date  : 2019/9/4
# @Role  : 获取Aliyun Redis实例信息

import json
from aliyunsdkcore.client import AcsClient
from aliyunsdkr_kvstore.request.v20150101.DescribeInstancesRequest import DescribeInstancesRequest
from libs.db_context import DBContext
from libs.web_logs import ins_log
from models.db import DB
from models.server import AssetConfigs, model_to_dict
from opssdk.operate import MyCryptV2
import fire

class RedisApi():
    def __init__(self, access_id, access_key, region):
        self.idc = '阿里云'
        self.region = region
        self.access_id = access_id
        self.access_key = access_key

    def get_region_redis(self, page_number=1, page_size=50):
        try:
            clt = AcsClient(self.access_id, self.access_key, self.region)
            request = DescribeInstancesRequest()
            request.set_accept_format('json')
            request.set_PageNumber(page_number)
            request.set_PageSize(page_size)
            response = clt.do_action_with_exception(request)
            return json.loads(str(response, encoding="utf8"))
        except Exception as err:
            print(err)

        return {}

    def get_redis_all(self):
        page_num = 1
        while True:
            data = self.get_region_redis(page_num)
            if not data and 'Instances' not in data: break
            page_num += 1
            row = data['Instances']['KVStoreInstance']
            if not row: break
            # print的时候将yield去掉
            # print(list(map(self.format_redis, row)))
            res = list(map(self.format_redis, row))
            yield res

    def format_redis(self, redis_info):
        """
        处理下我们要入库的信息
        :return:
        """
        if not isinstance(redis_info, dict):
            raise TypeError

        asset_data = dict()

        asset_data['db_instance_id'] = redis_info.get('InstanceId')
        asset_data['db_code'] = redis_info.get('InstanceName')
        asset_data['db_region'] = redis_info.get('RegionId')
        asset_data['db_version'] = redis_info.get('EngineVersion')
        asset_data['db_port'] = redis_info.get('Port')
        asset_data['db_public_ip'] = redis_info.get('ConnectionDomain')
        asset_data['db_type'] = redis_info.get('InstanceType')
        asset_data['db_class'] = redis_info.get('ArchitectureType')
        asset_data['state'] = redis_info.get('InstanceStatus')
        asset_data['db_user'] = 'root'  # 没看到user的接口信息，但是我是必填项
        asset_data['db_host'] = redis_info.get('PrivateIp')
        if not asset_data['db_host']: asset_data['db_host'] = asset_data['db_public_ip']

        return asset_data

    def sync_cmdb(self):
        """
        入库
        :return:
        """
        redis_info_list = self.get_redis_all()
        if not redis_info_list: return False
        with DBContext('w') as session:
            for data in redis_info_list:
                for redis in data:
                    ins_log.read_log('info', 'redis信息：{}'.format(redis))
                    db_code = redis.get('db_code')

                    exist_redis = session.query(DB).filter(DB.db_code == db_code).first()

                    if exist_redis:
                        session.query(DB).filter(DB.db_code == db_code).update({
                            DB.idc: self.idc, DB.db_class: redis.get('db_class'), DB.db_host: redis.get('db_host'),
                            DB.db_port: redis.get('db_port'), DB.db_user: redis.get('db_user'),
                            DB.db_disk: redis.get('db_disk'), DB.db_region: redis.get('db_region'),
                            DB.db_type: redis.get('db_type'), DB.db_version: redis.get('db_version'),
                            DB.state: redis.get('state'), DB.db_mark: redis.get('db_mark'),
                            DB.db_public_ip: redis.get('db_public_ip'),
                            DB.db_instance_id: redis.get('db_instance_id')})
                    else:
                        new_db = DB(idc=self.idc, db_code=db_code, db_class=redis.get('db_class'),
                                    db_host=redis.get('db_host'), db_port=redis.get('db_port'),
                                    db_user=redis.get('db_user'), db_region=redis.get('db_region'),
                                    db_type=redis.get('db_type'),
                                    db_disk=redis.get('db_disk'), db_version=redis.get('db_version'),
                                    state=redis.get('state'), db_public_ip=redis.get('db_public_ip'),
                                    db_instance_id=redis.get('db_instance_id'))
                        session.add(new_db)
            session.commit()

    @staticmethod
    def permission_auth(access_id, access_key, region, page_number=1, page_size=1):
        """
        没有异常正常获取到1-1数据就是权限认证通过
        :param access_id: AccessID
        :param access_key:  AccessKey
        :param region:  RegionID
        :param page_number: 第几页
        :param page_size:  一页多少数量
        :return:
        """
        clt = AcsClient(access_id, access_key, region, timeout=5)
        request = DescribeInstancesRequest()
        request.set_accept_format('json')
        request.set_PageNumber(page_number)
        request.set_PageSize(page_size)
        response = clt.do_action_with_exception(request)
        # print('Permission_auth_res-->',response)
        return json.loads(str(response, encoding="utf8"))

def get_configs():
    """
    get id / key / region info
    :return:
    """

    aliyun_configs_list = []
    with DBContext('r') as session:
        aliyun_configs_info = session.query(AssetConfigs).filter(AssetConfigs.account == '阿里云',
                                                                 AssetConfigs.state == 'true').all()
        for data in aliyun_configs_info:
            data_dict = model_to_dict(data)
            data_dict['create_time'] = str(data_dict['create_time'])
            data_dict['update_time'] = str(data_dict['update_time'])
            aliyun_configs_list.append(data_dict)
    return aliyun_configs_list

def main():
    """
    从接口获取已经启用的配置
    :return:
    """
    mc = MyCryptV2()
    aliyun_configs_list = get_configs()
    if not aliyun_configs_list:
        ins_log.read_log('error', '没有获取到阿里云资产配置信息，跳过')
        return False
    for config in aliyun_configs_list:
        access_id = config.get('access_id')
        access_key = mc.my_decrypt(config.get('access_key'))  # 解密后使用
        region = config.get('region')
        obj = RedisApi(access_id, access_key, region)
        obj.sync_cmdb()

if __name__ == '__main__':
    fire.Fire(main)


from django.urls import include, path
from rest_framework.routers import DefaultRouter

from . import views

app_name = 'game'

router = DefaultRouter()
router.register(r'user', views.UserViewSet)
router.register(r'pilot', views.PilotViewSet)

urlpatterns = [
    path('pilot/<int:pk>', views.PilotUpdate.as_view(), name='pilot'),
    path('rulebook/<int:pk>', views.RulebookView.as_view(), name='rulebook'),

    path('campaign/<int:pk>', views.CampaignView.as_view(), name='campaign'),
    #path('campaign/<int:pk>/plan', views.CampaignUpdate.as_view(), name='campaign-plan'),

    path('campaign/<int:pk>/plan', views.SessionPlan.as_view(), name='next-mission'),

    path('session/<int:session_id>', views.session_summary, name='session'),
    path('session/<int:pk>/debrief', views.SessionDebrief.as_view(), name='session-debrief'),

    path('profile/', views.player_page, name='player_profile'),
    path('player/<int:player_id>', views.player_page, name="player_update"),

    path('api/', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]


import configparser as cp
import pathlib
import sys
from os import path, mkdir

class Config(cp.ConfigParser):
    def __init__(self, program_name, default_template):
        super().__init__(self)
        if getattr(sys, 'frozen', False):
            exec_path = path.dirname(path.abspath(str(sys.executable)))
        else:
            exec_path = ".\\"
        self.program_name = program_name
        self.path = str(pathlib.Path.home()) + f"\\.config\\{program_name}\\config.ini"
        if not path.isdir(str(pathlib.Path.home()) + "\\.config\\"):
            mkdir(str(pathlib.Path.home()) + "\\.config\\")
        if not path.isdir(str(pathlib.Path.home()) + f"\\.config\\{program_name}\\"):
            mkdir(str(pathlib.Path.home()) + f"\\.config\\{program_name}\\")
        if not path.exists(str(pathlib.Path.home()) + f"\\.config\\{program_name}\\config.ini"):
            self._generate_default_config_file(default_template)
        self.read(self.path)

    def _generate_default_config_file(self, default_template):
        self['DEFAULT'] = {
            "Program": self.program_name}
        self.update(default_template)
        with open(self.path, 'w') as configfile:
            self.write(configfile)

    def save(self):
        with open(self.path, 'w') as configfile:
            self.write(configfile)


import os
from nextcord.ext import commands
from dotenv import load_dotenv
from cogs.buttons.sr_view import SRView
import nextcord, datetime

load_dotenv()

client = commands.Bot(command_prefix='!')
client.persistent_views_added = False

@client.event
async def on_ready():
    print("Bot is ready!")
    client.load_extension("cogs.buttons.sr_message")
    if not client.persistent_views_added:
        client.add_view(SRView())
    client.persistent_views_added = True
    print('loading persistent views')

# for loop that loads all the commands
for filename in os.listdir("./cogs"):
    if filename.endswith(".py"):
        client.load_extension(f"cogs.{filename[:-3]}")

client.run(os.getenv("TOKEN"))


from twisted.internet.defer import inlineCallbacks
from twisted.internet.task import Clock
from twisted.internet.error import ConnectionLost
from twisted.web.xmlrpc import Proxy

from vumi.message import TransportUserMessage
from vumi.tests.helpers import VumiTestCase
from vumi.tests.utils import LogCatcher
from vumi.transports.tests.helpers import TransportHelper
from vumi.transports.trueafrican.transport import TrueAfricanUssdTransport

class TestTrueAfricanUssdTransport(VumiTestCase):

    SESSION_INIT_BODY = {
        'session': '1',
        'msisdn': '+27724385170',
        'shortcode': '*23#'
    }

    @inlineCallbacks
    def setUp(self):
        self.tx_helper = self.add_helper(
            TransportHelper(TrueAfricanUssdTransport))
        self.clock = Clock()
        self.patch(TrueAfricanUssdTransport, 'get_clock', lambda _: self.clock)
        self.transport = yield self.tx_helper.get_transport({
            'interface': '127.0.0.1',
            'port': 0,
            'request_timeout': 10,
        })
        self.service_url = self.get_service_url(self.transport)

    def get_service_url(self, transport):
        """
        Get the URL for the HTTP resource. Requires the worker to be started.
        """
        addr = transport.web_resource.getHost()
        return "http://%s:%s/" % (addr.host, addr.port)

    def web_client(self):
        return Proxy(self.service_url)

    @inlineCallbacks
    def test_session_new(self):
        client = self.web_client()
        resp_d = client.callRemote('USSD.INIT', self.SESSION_INIT_BODY)

        [msg] = yield self.tx_helper.wait_for_dispatched_inbound(1)
        self.tx_helper.make_dispatch_reply(msg, "Oh Hai!")

        # verify the transport -> application message
        self.assertEqual(msg['transport_name'], self.tx_helper.transport_name)
        self.assertEqual(msg['transport_type'], "ussd")
        self.assertEqual(msg['session_event'],
                         TransportUserMessage.SESSION_NEW)
        self.assertEqual(msg['from_addr'], '+27724385170')
        self.assertEqual(msg['to_addr'], '*23#')
        self.assertEqual(msg['content'], None)

        resp = yield resp_d
        self.assertEqual(
            resp,
            {
                'message': 'Oh Hai!',
                'session': '1',
                'type': 'cont'
            }
        )

    @inlineCallbacks
    def test_session_resume(self):
        client = self.web_client()

        # initiate session
        resp_d = client.callRemote('USSD.INIT', self.SESSION_INIT_BODY)

        [msg] = yield self.tx_helper.wait_for_dispatched_inbound(1)
        self.tx_helper.make_dispatch_reply(msg, "pong")

        yield resp_d
        yield self.tx_helper.clear_dispatched_inbound()

        # resume session
        resp_d = client.callRemote(
            'USSD.CONT',
            {'session': '1',
             'response': 'pong'}
        )

        [msg] = yield self.tx_helper.wait_for_dispatched_inbound(1)
        self.tx_helper.make_dispatch_reply(msg, "ping")

        # verify the dispatched inbound message
        self.assertEqual(msg['transport_name'], self.tx_helper.transport_name)
        self.assertEqual(msg['transport_type'], "ussd")
        self.assertEqual(msg['session_event'],
                         TransportUserMessage.SESSION_RESUME)
        self.assertEqual(msg['from_addr'], '+27724385170')
        self.assertEqual(msg['to_addr'], '*23#')
        self.assertEqual(msg['content'], 'pong')

        resp = yield resp_d
        self.assertEqual(
            resp,
            {
                'message': 'ping',
                'session': '1',
                'type': 'cont'
            }
        )

    @inlineCallbacks
    def test_session_end_user_initiated(self):
        client = self.web_client()

        # initiate session
        resp_d = client.callRemote('USSD.INIT', self.SESSION_INIT_BODY)

        [msg] = yield self.tx_helper.wait_for_dispatched_inbound(1)
        self.tx_helper.make_dispatch_reply(msg, "ping")

        yield resp_d
        yield self.tx_helper.clear_dispatched_inbound()

        # user initiated session termination
        resp_d = client.callRemote(
            'USSD.END',
            {'session': '1'}
        )

        [msg] = yield self.tx_helper.wait_for_dispatched_inbound(1)
        self.assertEqual(msg['transport_name'], self.tx_helper.transport_name)
        self.assertEqual(msg['transport_type'], "ussd")
        self.assertEqual(msg['session_event'],
                         TransportUserMessage.SESSION_CLOSE)
        self.assertEqual(msg['from_addr'], '+27724385170')
        self.assertEqual(msg['to_addr'], '*23#')
        self.assertEqual(msg['content'], None)

        resp = yield resp_d
        self.assertEqual(resp, {})

    @inlineCallbacks
    def test_session_end_application_initiated(self):
        client = self.web_client()

        # initiate session
        resp_d = client.callRemote('USSD.INIT', self.SESSION_INIT_BODY)
        [msg] = yield self.tx_helper.wait_for_dispatched_inbound(1)

        self.tx_helper.make_dispatch_reply(msg, "ping")
        yield resp_d
        yield self.tx_helper.clear_dispatched_inbound()

        # end session
        resp_d = client.callRemote(
            'USSD.CONT',
            {'session': '1',
             'response': 'o rly?'}
        )

        [msg] = yield self.tx_helper.wait_for_dispatched_inbound(1)
        self.tx_helper.make_dispatch_reply(
            msg, "kthxbye", continue_session=False)

        resp = yield resp_d
        self.assertEqual(
            resp,
            {
                'message': 'kthxbye',
                'session': '1',
                'type': 'end'
            }
        )

    @inlineCallbacks
    def test_ack_for_outbound_message(self):
        client = self.web_client()

        # initiate session
        resp_d = client.callRemote('USSD.INIT', self.SESSION_INIT_BODY)

        # send response
        [msg] = yield self.tx_helper.wait_for_dispatched_inbound(1)
        rep = yield self.tx_helper.make_dispatch_reply(msg, "ping")
        yield resp_d

        [ack] = yield self.tx_helper.wait_for_dispatched_events(1)
        self.assertEqual(ack['event_type'], 'ack')
        self.assertEqual(ack['user_message_id'], rep['message_id'])
        self.assertEqual(ack['sent_message_id'], rep['message_id'])

    @inlineCallbacks
    def test_nack_for_outbound_message(self):
        client = self.web_client()

        # initiate session
        resp_d = client.callRemote('USSD.INIT', self.SESSION_INIT_BODY)

        [msg] = yield self.tx_helper.wait_for_dispatched_inbound(1)

        # cancel the request and mute the resulting error.
        request = self.transport._requests[msg['message_id']]
        request.http_request.connectionLost(ConnectionLost())
        resp_d.cancel()
        resp_d.addErrback(lambda f: None)

        # send response
        rep = yield self.tx_helper.make_dispatch_reply(msg, "ping")
        [nack] = yield self.tx_helper.wait_for_dispatched_events(1)

        self.assertEqual(nack['event_type'], 'nack')
        self.assertEqual(nack['user_message_id'], rep['message_id'])
        self.assertEqual(nack['sent_message_id'], rep['message_id'])
        self.assertTrue('HTTP client closed connection' in nack['nack_reason'])

    @inlineCallbacks
    def test_nack_for_request_timeout(self):
        client = self.web_client()

        # initiate session
        resp_d = client.callRemote('USSD.INIT', self.SESSION_INIT_BODY)

        [msg] = yield self.tx_helper.wait_for_dispatched_inbound(1)

        self.clock.advance(10.1)  # .1 second after timeout

        rep = yield self.tx_helper.make_dispatch_reply(msg, "ping")
        yield resp_d

        [nack] = yield self.tx_helper.wait_for_dispatched_events(1)
        self.assertEqual(nack['event_type'], 'nack')
        self.assertEqual(nack['user_message_id'], rep['message_id'])
        self.assertEqual(nack['sent_message_id'], rep['message_id'])
        self.assertEqual(nack['nack_reason'], 'Exceeded request timeout')

    @inlineCallbacks
    def test_nack_for_invalid_outbound_message(self):
        msg = yield self.tx_helper.make_dispatch_outbound("outbound")
        [nack] = yield self.tx_helper.wait_for_dispatched_events(1)
        self.assertEqual(nack['user_message_id'], msg['message_id'])
        self.assertEqual(nack['sent_message_id'], msg['message_id'])
        self.assertEqual(nack['nack_reason'],
                         'Missing in_reply_to, content or session_id fields')

    @inlineCallbacks
    def test_timeout(self):
        client = self.web_client()

        # initiate session
        resp_d = client.callRemote('USSD.INIT', self.SESSION_INIT_BODY)

        [msg] = yield self.tx_helper.wait_for_dispatched_inbound(1)
        with LogCatcher(message='Timing out') as lc:
            self.assertTrue(msg['message_id'] in self.transport._requests)
            self.clock.advance(10.1)  # .1 second after timeout
            self.assertFalse(msg['message_id'] in self.transport._requests)
            [warning] = lc.messages()
            self.assertEqual(warning,
                             'Timing out on response for +27724385170')
            resp = yield resp_d
            self.assertEqual(
                resp,
                {
                    'message': ('We encountered an error while processing'
                                ' your message'),
                    'type': 'end'
                }
            )

    @inlineCallbacks
    def test_request_tracking(self):
        """
        Verify that the transport cleans up after finishing a request
        """
        client = self.web_client()
        resp_d = client.callRemote('USSD.INIT', self.SESSION_INIT_BODY)

        [msg] = yield self.tx_helper.wait_for_dispatched_inbound(1)
        self.tx_helper.make_dispatch_reply(msg, "pong")
        self.assertTrue(msg['message_id'] in self.transport._requests)
        yield resp_d
        self.assertFalse(msg['message_id'] in self.transport._requests)

    @inlineCallbacks
    def test_missing_session(self):
        """
        Verify that the transport handles missing session data in a
        graceful manner
        """
        client = self.web_client()
        resp_d = client.callRemote('USSD.INIT', self.SESSION_INIT_BODY)

        [msg] = yield self.tx_helper.wait_for_dispatched_inbound(1)
        self.tx_helper.make_dispatch_reply(msg, "pong")
        yield resp_d
        yield self.tx_helper.clear_dispatched_inbound()

        # simulate Redis falling over
        yield self.transport.session_manager.redis._purge_all()

        # resume
        resp_d = client.callRemote(
            'USSD.CONT',
            {'session': '1',
             'response': 'o rly?'}
        )

        resp = yield resp_d
        self.assertEqual(
            resp,
            {
                'message': ('We encountered an error while processing'
                            ' your message'),
                'type': 'end'
            }
        )


from svg.path import parse_path
from svg.path import Path, Line, Arc, CubicBezier, QuadraticBezier
from xml.dom import minidom
# from magenta.models.sketch_rnn import utils
from rdp import rdp
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as grdspc
import numpy as np
import os
import re
import sys
import ipdb

folder_p = '/home/kelvin/OgataLab/parse_svg/parse_svg/Sketchy_data_valid/airplane/'
dest_p = '/home/kelvin/OgataLab/magenta/magenta/models/sketch_rnn/sketchy_data/'
# f_name = 'n02139199_15837-7.svg'

def adjust_axes(axis):
    """ equalize the scales of x-axis and y-axis """
    x_lim = axis.get_xlim()
    y_lim = axis.get_ylim()
    new_lim = (min(x_lim[0], y_lim[0]), max(x_lim[1], y_lim[1]))
    axis.set_xlim(new_lim)
    axis.set_ylim(new_lim)
    axis.set_aspect('equal')

def rsvg_in_folderxy(f_path, no_of_files):
    '''reads all the svg files in from folder path, equal to the number of files specified. Then all path data in the svg files are converted into stroke-3 data and stored in a list'''
    c=0
    svg_data = []

    for file in os.listdir(f_path):

        if file.endswith(".svg"):
            # data = to_stroke3(svg2xyList(f_path + file))
            data = svg2xyList(f_path + file)
            if c<no_of_files:
                svg_data.append(data)
                c+=1
            else:
                break
    return svg_data

def rsvg_in_folders3(f_path, no_of_files):
    '''reads all the svg files in from folder path, equal to the number of files specified. Then all path data in the svg files are converted into stroke-3 data and stored in a list'''
    c=0
    svg_data = []

    for file in os.listdir(f_path):

        if file.endswith(".svg"):
            data = to_stroke3(svg2xyList(f_path + file))
            # data = arr_reduce(data,100)
            # data = svg2xyList(f_path + file)
            # ipdb.set_trace()
            if c<no_of_files:
                svg_data.append(data)
                c+=1
            else:
                break
    return svg_data

def check_max_seq(f_path):

    seq_len = []
    for file in os.listdir(f_path):
        if file.endswith(".svg"):
            N = to_stroke3(svg2xyList(f_path+file))
            seq_len.append((len(N),file))
    # ipdb.set_trace()
    return sorted(seq_len,key=lambda k:k[0])
    # print("Maximum sequence length is:",max[])

def svg2xyList(file, eps=3.0):
    '''converts path component "d" from svg file into xy-coordinate list'''
    line = []
    strt_pts = []
    ed_pts = []
    strt_pts1 = []
    ed_pts1 = []
    # print(file)
    all_path = minidom.parse(file).getElementsByTagName('path')
    # ipdb.set_trace()
    for i in range(len(all_path)):
        clr = all_path[i].getAttribute('stroke')
        clr1 = all_path[i].getAttribute('STROKE')
        if clr == '#000' or clr1 == '#000':
            d = all_path[i].getAttribute('d')
            P = parse_path(d)
            points = []

            if len(P)<1:
                pass
            else:
                for j in range(len(P)):
                    abs_ed = P[len(P)-1].end.real, P[len(P)-1].end.imag

                    if isinstance(P[j], CubicBezier) or isinstance(P[j], Line):
                        strt = P[j].start.real, P[j].start.imag
                        ed = P[j].end.real, P[j].end.imag

                        if j == 0:
                            abs_strt = strt
                            points.append(strt)
                            points.append(ed)
                        else:
                            points.append(ed)
                    else:
                        print("What?! th is "+P[j])

                points = rdp(points, epsilon=eps)
                line.append(points)
        else:
            pass
    return line

def to_stroke3(data, dtype=np.int16, vmax=500):
    '''converts xy-coordinate list into stroke-3 format numpy array'''

    buf = []

    init_d = np.array(data[0][0])
    l_d = np.array((0, 0))

    for d in data:
        # move to (0, 0)
        d_arr = np.array(d) - init_d

        # convert to relative points
        tmp = d_arr[1:, :] - d_arr[:-1, :]
        tmp = np.concatenate((
            np.expand_dims(d_arr[0, :] - l_d, 0),
            tmp
        ))

        # probability of the pen status
        p = np.zeros((tmp.shape[0], 1))
        p[-1, 0] = 1.0

        tmp = tmp
        buf.append(np.concatenate((tmp, p), axis=1))

        # for the next line
        l_d = d_arr[-1, :]

    buf = np.vstack(buf)

    # normalization to avoid lose of data in casting
    buf[:, :2] = buf[:, :2] / np.absolute(buf[:, :2]).max() * abs(vmax)
    buf = buf.astype(dtype)
    return buf

def get_colors(n, cmap='cool'):
    cmap = matplotlib.cm.get_cmap(cmap)
    idx = np.linspace(0.0, 1.0, n)
    return cmap(idx)

def view_stroke3(data, axis):
    '''view stroke-3 data as an image'''

    line = []
    x, y = 0, 0

    colors = get_colors(len(data))

    for point, color in zip(data, colors):
        _x, _y, v = point
        x += _x
        y += _y
        line.append([x, y])
        if v != 0:
            line = np.array(line)
            axis.plot(line[:,0],line[:,1]*-1.0, color=color)
            line = []
    adjust_axes(axis)

def svg_to_npz_ex(f_path, t, v, tst, max_seq):
    '''converts a number of svg files into npz format. npz file will contain 3 sections, train, validation and test. test, validation, and test parameters should be input as integers, and total shouldn't be greater than existing files.'''
    category = re.search('valid/(.+?)/', f_path).group(1)
    train_data = []
    validation_data = []
    test_data = []
    data1 = []
    c=0
    # print(category)
    for file in os.listdir(f_path):

        if file.endswith(".svg"):
            # print(file)
            data0 = svg2xyList(f_path + file)
            try:
                check = to_stroke3(data0)  # 2d matrix of stroke-3 format pic.
            except:
                print('This freakin file-->'+file)

            seq_len = len(check)
            if seq_len>max_seq:
                pass
            else:
                data1 = exp_w_order(data0)
                # ipdb.set_trace()
                for x in range(len(data1)):
                    data2 = to_stroke3(data1[x])
                    if c<t:
                        train_data.append(data2)
                        c += 1
                    elif c >=t and c<(t+v):
                        validation_data.append(data2)
                        c += 1
                    elif c>=(t+v) and c<(t+v+tst):
                        test_data.append(data2)
                        c += 1
                    else:
                        break
    # ipdb.set_trace()
    filename = os.path.join(dest_p, 'sketchy_'+category+'_exep2.npz')
    np.savez_compressed(filename, train=train_data, valid=validation_data, test=test_data)
    print('conversion succeeded.')

def svg_to_npz(f_path, t, v, tst, max_seq):
    '''converts a number of svg files into npz format. npz file will contain 3 sections, train, validation and test. test, validation, and test parameters should be input as integers, and total shouldn't be greater than existing files.'''
    category = re.search('valid/(.+?)/', f_path).group(1)
    train_data = []
    validation_data = []
    test_data = []
    c=0
    # print(category)
    for file in os.listdir(f_path):

        if file.endswith(".svg"):
            # print(file)
            data0 = svg2xyList(f_path + file)
            try:
                data1 = to_stroke3(data0)  # 2d matrix of stroke-3 format pic.
            except:
                print('This freakin file-->'+file)
            data1 = arr_reduce(data1,100)
            seq_len = len(data1)
            if seq_len>max_seq:
                pass
            else:
                if c<t:
                    train_data.append(data1)
                    c += 1
                elif c >=t and c<(t+v):
                    validation_data.append(data1)
                    c += 1
                elif c>=(t+v) and c<(t+v+tst):
                    test_data.append(data1)
                    c += 1
                else:
                    break
    # ipdb.set_trace()
    filename = os.path.join(dest_p, 'sketchy_'+category+'_ep3.npz')
    np.savez_compressed(filename, train=train_data, valid=validation_data, test=test_data)
    print('conversion succeeded.')

def view_xylist(data, axis):
    line = []
    # data = np.concatenate(np.array(data)).astype(np.float16)
    for point in data:
        # ipdb.set_trace()
        line = np.array(point)
        axis.plot(line[:,0],line[:,1]*-1.0)
        line = []
    axis.set_aspect('equal')

def svg_mix(data):
    '''recursively changes the starting stroke of the sketch sequence'''
    fin_lis = []
    for i in range(len(data)):
        tmp_lis = data
        tmp = [tmp_lis[x] for x in range(1,len(tmp_lis))]
        tmp.append(tmp_lis[0])
        data=tmp
        fin_lis.append(tmp)
        tmp=[]
    return fin_lis

def svg_reverse(data):
    '''reverses direction of stroke'''
    fin_lis = []
    for i in reversed(range(len(data))):
        fin_lis.append(data[i])
    return fin_lis

def exp_w_order(data):
    '''expands xy-coordinate data. Data produced from svg2xyList.'''
    data1 = svg_mix(data)
    reverse_lis = []
    for i in range(len(data)):
        inter =svg_reverse(data[i])
        reverse_lis.append(inter)
    data2 = svg_mix(reverse_lis)
    data_ex = data1+data2
    return data_ex

def arr_reduce(data, lim):
    '''used to reduce length of sequence. 'lim' refers to preferred sequence length.'''
    if len(data)>lim:
        a = [x for x in range(lim,len(data))]
        b = np.delete(data,a,0)
    else:
        b = data
    return b

# data0 = rsvg_in_folderxy(folder_p,500,250)

# data1 = exp_w_order(data0)

# svg_to_npz_ex(folder_p, 15000, 500, 500, 250)
# svg_to_npz(folder_p, 400, 50, 50, 100) #dataset less than 500

# svg2xyList(folder_p+f_name)
# svg_list = rsvg_in_folder(folder_p, 36)
# # ipdb.set_trace()
# c = 0
# row, col = 5, 4
# gs = grdspc.GridSpec(row, col)

# for i in range(row):
#     for j in range(col):
#         ax = plt.subplot(gs[i,j])
#         view_xylist(data1[c], ax)
#         ax.set_title(str(c+1))
#         c+=1

# for i in range(row):
#     for j in range(col):
#         ax = plt.subplot(gs[i,j])
#         view_stroke3(svg_list[c], ax)
#         ax.set_title(str(c+1))
#         c+=1

# plt.show()
# print(P)


from collections.abc import Mapping, Sequence

def npu(o, id=0):
    """
    Applies npu recursively to modules and tensors.
    """
    if isinstance(o, Mapping):
        return type(o)((k, npu(v,id=id)) for (k, v) in o.items())
    if isinstance(o, Sequence):
        return type(o)(npu(v) for v in o)
    if hasattr(o, 'npu'):
        return o.npu(id)
    return o


import torch
import numpy as np
import random

from torch.utils.data import Dataset, DataLoader
from torchvision import datasets
from torchvision import transforms
from torch.utils.data.sampler import SubsetRandomSampler
import torchvision.transforms.functional as TF

import datasets.data_util as data_util
import constants

def get_mnist_train_valid_loader(data_dir,
                           batch_size,
                           random_seed,
                           valid_size=0.1,
                           shuffle=True,
                           num_workers=4,
                           pin_memory=False):
    """
    Utility function for loading and returning train and valid
    multi-process iterators over the MNIST dataset.
    If using CUDA, num_workers should be set to 1 and pin_memory to True.

    Parameters
    ------
    - data_dir (str): path directory to the dataset.
    - batch_size (int): how many samples per batch to load.
    - augment (bool): whether to apply the data augmentation scheme
      mentioned in the paper. Only applied on the train split.
    - random_seed (int): fix seed for reproducibility.
    - valid_size (float): fraction of the training set used for
      the validation set. Should be in the range [0, 1].
    - shuffle (bool): whether to shuffle the train/validation indices.
    - num_workers (int): number of subprocesses to use when loading the dataset.
    - pin_memory (bool): whether to copy tensors into CUDA pinned memory. Set it to
      True if using GPU

    Returns
    -------
    - train_loader: training set iterator.
    - valid_loader: validation set iterator.
    """

    normalize = transforms.Normalize(constants.MNIST_MEAN, constants.MNIST_STD )

    # define transforms
    valid_transform = transforms.Compose([
            transforms.ToTensor(),
            normalize,
    ])

    train_transform = valid_transform

    train_loader, valid_loader = data_util.get_train_valid_loader(data_dir, batch_size,
                                    random_seed, train_transform, valid_transform, datasets.MNIST,
                                    valid_size, shuffle, num_workers, pin_memory)

    return (train_loader, valid_loader)

def get_test_loader(data_dir,
                    batch_size,
                    shuffle=True,
                    num_workers=4,
                    pin_memory=False,
                    corrupted=False,
                    intensity=10,
                    corruption='rotation'):
    """
    Utility function for loading and returning a multi-process
    test iterator over the MNIST dataset.
    If using CUDA, num_workers should be set to 1 and pin_memory to True.

    Parameters
    ------
    - data_dir (str): path directory to the dataset.
    - batch_size (int): how many samples per batch to load.
    - shuffle (bool): whether to shuffle the dataset after every epoch.
    - num_workers (int): number of subprocesses to use when loading the dataset.
    - pin_memory (bool): whether to copy tensors into CUDA pinned memory. Set it to
      True if using GPU.
    - corrupted (bool): whether to return original test images or rotate them.
    - intensity (int): rotation angle in degrees or shift in pixels.
    - corruption (str): type of corruption, rotation or translation

    Returns
    -------
    - data_loader: test set iterator.
    """
    normalize = transforms.Normalize(constants.MNIST_MEAN, constants.MNIST_STD)

    # define transform
    transform = transforms.Compose([
        transforms.ToTensor(),
        normalize,
    ])

    if corrupted:
        if corruption == 'rotation':
            dataset = RotatedMNISTTest(f'{data_dir}/MNIST/raw', intensity, transform=transform)
        else:
            dataset = TranslatedMNISTTest(f'{data_dir}/MNIST/raw', intensity, transform=transform)
    else:
        dataset = datasets.MNIST(
            root=data_dir, train=False,
            download=False, transform=transform,
        )

    data_loader = torch.utils.data.DataLoader(
        dataset, batch_size=batch_size, shuffle=shuffle,
        num_workers=num_workers, pin_memory=pin_memory,
    )

    return data_loader

class RotatedMNISTTest(Dataset):
    """Class to wrap the MNIST test set with applied rotations"""

    def __init__(self, data_dir, rotation, transform=None):
        """
        Initialise the dataset and load data

        Parameters
        ------
        - data_dir (str): path to the dataset directory.
        - rotation (int): rotation angle in degrees.
        - transform (torchvision.transform): transformation
        to apply to images prior to rotation.
        """
        self.images, self.labels = data_util.load_mnist(data_dir, 't10k')
        self.transform=transform
        self.rotation=rotation

    def __len__(self):
        return(self.images.shape[0])

    def __getitem__(self, idx):

        img = self.images[idx].reshape((28, 28, 1)).copy()

        if self.transform:
            img = self.transform(img)

        img = TF.rotate(img, float(random.choice([-1, 1])*self.rotation))

        return img, int(self.labels[idx])

class TranslatedMNISTTest(Dataset):
    """Class to wrap the MNIST test set with applied cyclic translation"""

    def __init__(self, data_dir, translation, transform=None):
        """
        Initialise the dataset and load data

        Parameters
        ------
        - data_dir (str): path to the dataset directory.
        - translation (int): translation shift in pixels.
        - transform (torchvision.transform): transformation
        to apply to images prior to translaiton.
        """
        self.images, self.labels = data_util.load_mnist(data_dir, 't10k')
        self.transform=transform
        self.translation=translation

    def __len__(self):
        return(self.images.shape[0])

    def __getitem__(self, idx):

        img = self.images[idx].reshape((28, 28, 1)).copy()

        if self.translation > 0:
            translated_img = np.zeros_like(img)
            translated_img[:, :-1*self.translation, :] = img[:, self.translation:, :]
            translated_img[:, -1*self.translation:, :] = img[:, :self.translation, :]
        else:
            translated_img = img

        if self.transform:
            translated_img = self.transform(translated_img)

        return translated_img, int(self.labels[idx])

def get_MNIST_loaders(data_dir,
                        batch_size,
                        random_seed,
                        valid_size=0.1,
                        shuffle=True,
                        num_workers=4,
                        pin_memory=False,
                        corrupted_test=False,
                        intensity=10,
                        corruption='rotation'):

    """
    Utility function for loading and returning training, validation and testing
    multi-process iterators over the MNIST dataset.
    If using CUDA, num_workers should be set to 1 and pin_memory to True.

    Parameters
    ------
    - data_dir (str): path directory to the dataset.
    - batch_size (int): how many samples per batch to load.
    - shuffle (bool): whether to shuffle the dataset after every epoch.
    - num_workers (int): number of subprocesses to use when loading the dataset.
    - pin_memory (bool): whether to copy tensors into CUDA pinned memory. Set it to
      True if using GPU.
    - corrupted_test (bool): whether to return original test images or rotate them.
    - intensity (int): rotation angle in degrees or shift in pixels.
    - corruption (str): type of corruption, rotation or translation

    Returns
    -------
    - train_loader: training set iterator.
    - valid_loader: validation set iterator.
    - test_loader: test set iterator.
    """

    train_loader, valid_loader = get_mnist_train_valid_loader(data_dir, batch_size,
                                    random_seed, valid_size, shuffle, num_workers, pin_memory)
    test_loader = get_test_loader(data_dir, batch_size, shuffle, num_workers, pin_memory,
                                    corrupted_test, intensity, corruption)

    return train_loader, valid_loader, test_loader


from . import views
from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
    path('become-staff/', views.become_staff,name="become_staff"),
    path('staff-admin/', views.staff_admin,name="staff_admin"),
    path('logout/', views.logoutUser, name="logout" ),
    path('login/', views.loginUser, name='login'),
    path('add-product/', views.add_product,name="add_product"),
    path('edit-staff/', views.edit_staff, name='edit_staff'),
    path('', views.staffs, name='staffs'),
    path('<int:staff_id>/', views.staff, name='staff'),
    path('edit-product/<str:pk>/', views.edit_product,name="edit_product"),
    path('delete-product/<str:pk>/', views.delete_product, name="delete_product"),

]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


from aocd import data
import re
import numpy as np
import pandas as pd
from datetime import datetime

dl = data.split('\n')

def create_timeseries(data):
    # Create the Dataframe
    pattern = re.compile(r'\[(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2}) (?P<hour>\d{2}):(?P<minute>\d{2})\] (?P<action>.+)')
    actions = pd.Series(data)   # load into series
    df = actions.str.extract(pattern, expand=True)  # Expand via regex pattern

    # Create the timeseries index
    df[['year','month','day','hour','minute']] = df[['year','month','day','hour','minute']].apply(pd.to_numeric)  # Convert to int
    df[['year']] = 2018  # Forcing in-bounds year https://pandas-docs.github.io/pandas-docs-travis/timeseries.html#timeseries-oob
    df['ts'] = df.apply(lambda r: datetime(r.year, r.month, r.day, r.hour, r.minute, 0, 0), axis=1)  # Create timestamp field
    df['ts'] = pd.to_datetime(df.ts)  # Cast to pandas datetime
    df.drop(columns=['year','month','day', 'hour', 'minute'], inplace=True)  # Don't need these anymore
    df.set_index('ts', inplace=True)

    # Pull out guard id and set asleep flag
    guard_regex_pattern = re.compile(r'Guard #(?P<guard_id>\d+) begins shift')
    df['guard_id'] = df['action'].str.extract(guard_regex_pattern, expand=True)  # Pull out guard id
    df['asleep'] = np.where(df['action'] == 'falls asleep', 1, 0)

    # Fill empty timeslots so we have every minute to work with and filldown
    idx = pd.date_range(start=min(df.index), end=max(df.index), freq='min')
    idx = idx[(idx.hour == 0) | (idx.hour == 23)]  # Add entries for each minute during the midnight hour and before when they click in
    df = df.reindex(idx)
    df.sort_index(inplace=True)

    df['asleep'].ffill(inplace=True)  # filldown asleep flag
    df['guard_id'].ffill(inplace=True)  # Fill down guard id
    df['minute'] = df.index.minute
    return df

def part_a(data):
    df = create_timeseries(data)

    # Group by guard and minute and add them
    guard_sum = df.groupby(['guard_id']).sum()
    guard_num = guard_sum.idxmax().asleep # Sleepiest guard

    # Get guard schedule
    minute_sum = df[df['guard_id'] == guard_num].groupby('minute').sum()
    min_num = minute_sum.idxmax().asleep  # Sleepiest minute

    return int(guard_num) * int(min_num)

def part_b(data):
    df = create_timeseries(data)

    # Group by guard_id and minute
    sleepiest_guard_min = df.groupby(['guard_id','minute']).sum()
    i = sleepiest_guard_min.idxmax()
    return int(i.asleep[0]) * int(i.asleep[1])

ex1 = [
    '[1518-11-01 00:00] Guard #10 begins shift',
    '[1518-11-01 00:05] falls asleep',
    '[1518-11-01 00:25] wakes up',
    '[1518-11-01 00:30] falls asleep',
    '[1518-11-01 00:55] wakes up',
    '[1518-11-01 23:58] Guard #99 begins shift',
    '[1518-11-02 00:40] falls asleep',
    '[1518-11-02 00:50] wakes up',
    '[1518-11-03 00:05] Guard #10 begins shift',
    '[1518-11-03 00:24] falls asleep',
    '[1518-11-03 00:29] wakes up',
    '[1518-11-04 00:02] Guard #99 begins shift',
    '[1518-11-04 00:36] falls asleep',
    '[1518-11-04 00:46] wakes up',
    '[1518-11-05 00:03] Guard #99 begins shift',
    '[1518-11-05 00:45] falls asleep',
    '[1518-11-05 00:55] wakes up']

assert part_a(ex1) == 240
print("A: {}".format(part_a(dl)))

assert part_b(ex1) == 4455
print("B: {}".format(part_b(dl)))


import streamlit as st
import pandas as pd
import altair as alt

from urllib.error import URLError

@st.cache
def get_vaccination_data():
    """
    Data from Covid19India.org

    """
    COVID_INDIA_URL = "http://api.covid19india.org/csv/latest/cowin_vaccine_data_statewise.csv"
    df = pd.read_csv(COVID_INDIA_URL)
    return df

try:

    df = get_vaccination_data()
    pivot_table = df.pivot(index = 'State', columns = 'Updated On',values='Total Individuals Vaccinated')
    new_cols = dict(zip(pivot_table.columns, [pd.to_datetime(x,format="%d/%m/%Y").date() for x in pivot_table.columns]))
    df_formatted = pivot_table.rename(columns= new_cols, inplace=False)
    states = st.multiselect(
        "Choose states", list(df_formatted.index), ["Andhra Pradesh", "Goa"]
    )

    if not states:
        st.error("Please select at least one state.")
    else:
        data =  df_formatted.loc[states]
        st.write("### Vaccinations", data.sort_index())
        data = data.T.reset_index()
        data = pd.melt(data, id_vars=["Updated On"]).rename(
            columns={"Updated On": "date", "value": "Total Individuals Vaccinated"}
        )
        chart = (
            alt.Chart(data)
            .mark_line()
            .encode(
                x="date:T",
                y=alt.Y("Total Individuals Vaccinated:Q", stack=None),
                color="State:N",
            )
        )
    st.altair_chart(chart, use_container_width=True)
except URLError as e:
    st.error(
        """
        **This demo requires internet access.**

        Connection error: %s
    """
        % e.reason
    )


from datetime import datetime

from example.v1.example_protodc import Example, ExampleWatOneof as Oneof

dc = Example(
    life_the_universe_and_everything=42,
    examples=[
        Example(life_the_universe_and_everything=43),
    ],
    time=datetime.now()
)

dc.javascript = "eval('while(true){}')"

# Round trip to JSON and back.
txt = dc.to_protojson()
dc2 = Example.from_protojson(txt)

# Round trip to a python protobuf and back.
pb = dc.to_protobuf()
dc3 = Example.from_protobuf(pb)

# Check that nothing was lost in translation...
print(dc == dc2 == dc3)


import itertools

n, d = map(int, input().split())

arr = list(map(int, input().rstrip().split()))

counter = 0

for i in range(0, n - 2):
    subsequence = list(itertools.takewhile(lambda x: x - arr[i] <= 2 * d, arr[i:]))

    if len(subsequence) > 2:
        # set, otherwise: 3x(7 10 13) in 1 6 7 7 8 10 12 13 14 19 sequence
        for ai, aj, ak in set(itertools.combinations(subsequence, 3)):
            if aj - ai == d and ak - aj == d:
                counter += 1

print(counter)


import torch
from torch.autograd import Function

class GuidedBackpropReLU(Function):
    @staticmethod
    def forward(ctx, input):
        positive_mask = (input > 0).type_as(input)
        output = torch.addcmul(
            torch.zeros(input.size()).type_as(input), input, positive_mask
        )
        ctx.save_for_backward(input, output)
        return output

    @staticmethod
    def backward(ctx, grad_output):
        input, output = ctx.saved_variables

        positive_mask_1 = (input > 0).type_as(grad_output)
        positive_mask_2 = (grad_output > 0).type_as(grad_output)
        grad_input = torch.addcmul(
            torch.zeros(input.size()).type_as(input),
            torch.addcmul(
                torch.zeros(input.size()).type_as(input), grad_output, positive_mask_1
            ),
            positive_mask_2,
        )

        return grad_input

def guide_relu(self, input):
    output = GuidedBackpropReLU.apply(input)
    return output


import math
from collections import deque
def divisors(n):
	d1 = deque()
	d2 = deque()
	for i in range(1, math.ceil(math.sqrt(n))):
		if n % i == 0:
			d1.append(i)
			d2.appendleft(int(n/i))
	s = math.sqrt(n)
	if n % s == 0:
		return list(d1) + [int(math.sqrt(n))] + list(d2)
	else:
		return list(d1) + list(d2)

user = int(input())
print(len(divisors(user)))


import cv2
from LabFiles import *
from lib.utils.Timer import *
from lib.Homography import *

Timer.start('program')

# read file
imGreen = cv2.imread(LabFiles.input(3, 2, 'green'))
imPoster = cv2.imread(LabFiles.input(3, 2, 'poster'))

H = np.array([[0.8346, -0.0058, -141.3292],
              [0.0116, 0.8025, -78.2148],
              [-0.0002, -0.0006, 1.]])
homography = Homography(H)

result = homography.applyInterpolated(imPoster, imGreen)

# print result

cv2.imwrite(LabFiles.output(3, 2, 'homographied-interpolated'), result)

# stoper
Timer.stop('program')

# show
LabFiles.show(3, 2, 'homographied-interpolated')


from django.contrib import messages
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views import View
from django.db import connection
from pymysql import IntegrityError
import datetime
from .forms import CarPlate, MakeReservationForm, VehicleRate, CreateRequestForm, BranchRate, ReservationNo, Pay
from datetime import date

class PayVehicle(View):
    def post(self, request, resno):
        form = Pay(request.POST)

        if form.is_valid():
            branch_id = form.cleaned_data['branch']
            money = form.cleaned_data['money']
            plate = form.cleaned_data['plate']
            required_payment = form.cleaned_data['required_payment']
            res_no = form.cleaned_data['res_no']
            required_payment = float(required_payment)

            if required_payment != money:
                messages.error(request, 'Please enter correct amount.')
                return self.get(request, res_no)
            else:
                cursor = connection.cursor()
                sql = "UPDATE branch SET budget = budget + {} where branch_id = {};".format(money, branch_id)
                cursor.execute(sql)

                sql = "update vehicle set status = 'available', branch_id = {} where license_plate =  '{}';".format(
                    branch_id, plate)
                cursor.execute(sql)

                sql = "UPDATE reservation set status = 'paid' where reservation_number = {}".format(res_no)
                cursor.execute(sql)
                messages.success(request, 'Payment is taken. Thank you :)')
                return self.get(request, res_no)

        return redirect('/customer/error')

    def get(self, request, resno) -> 'html':
        user_id = request.session['logged_in_user']
        cursor = connection.cursor()
        sql = "SELECT discount_rate, user_id,customer_status FROM customer_discount NATURAL JOIN user WHERE user_id ={}".format(
            user_id)
        cursor.execute(sql)
        user_data = cursor.fetchall()
        discount_rate = user_data[0][0]

        sql = "SELECT reservation_number, license_plate, end_date, cost FROM reservation WHERE reservation_number = {}".format(
            resno)
        cursor.execute(sql)
        reservation = cursor.fetchall()

        res_no = reservation[0][0]
        license_plate = reservation[0][1]
        end_date = reservation[0][2]
        cost = reservation[0][3]

        today = date.today()
        if (((today - end_date).days) >= 0):
            fee_time = ((today - end_date).days)
        else:
            fee_time = 0

        if fee_time > 0:
            penalty = fee_time * 100
        else:
            penalty = 0
        total = cost + penalty

        discount = (total * int(discount_rate)) / 100

        form = Pay()
        context = {
            'res_no': res_no,
            'license_plate': license_plate,
            'discount_rate': discount_rate,
            'cost': cost,
            'penalty': penalty,
            'total': total,
            'discount': discount,
            'required_payment': total - discount,
            'form': form
        }
        return render(request, 'payVehicle.html', context)

class ReturnVehicle(View):

    def post(self, request):
        form = ReservationNo(request.POST)

        if form.is_valid():
            return redirect('customer:customer_pay_vehicle', resno=form.cleaned_data['ReservationNo'])

        return self.get(request)

    def get(self, request) -> 'html':
        user_id = request.session['logged_in_user']
        cursor = connection.cursor()
        sql = "SELECT reservation_number, license_plate, start_date,end_date,cost, status FROM `reservation` WHERE reserver = {} and status = 'accepted';".format(
            user_id)
        cursor.execute(sql)
        active_res = cursor.fetchall()

        sql = "SELECT discount_rate, user_id, customer_status FROM customer_discount NATURAL JOIN user WHERE user_id ={}".format(
            user_id)
        cursor.execute(sql)
        user_data = cursor.fetchall()

        discount_rate = user_data[0][0]
        user_status = user_data[0][2]

        form = ReservationNo()
        context = {
            'old_res': active_res,
            'form': form,
            'discount_rate': discount_rate,
            'user_status': user_status
        }
        return render(request, 'returnvehicles.html', context)

class RateBranch(View):

    def post(self, request):
        form = BranchRate(request.POST)

        if form.is_valid():
            customer_id = request.session['logged_in_user']
            branch_id = form.cleaned_data['branch']
            comment = form.cleaned_data['comment']
            score = form.cleaned_data['score']

            try:
                print("asdjkgnkjadfnhkadf")
                cursor = connection.cursor()
                sql = "INSERT INTO branch_rate (customer_id, branch_id, comment, score) VALUES ({}, {}, '{}', {});".format(
                    customer_id, branch_id, comment, score)
                cursor.execute(sql)
            except:
                messages.error(request, 'You already evaluated this branch.')
                return self.get(request)

            messages.success(request, 'You evaluation is saved.')
            return self.get(request)

        return redirect('/customer/error')

    def get(self, request):
        form = BranchRate()
        context = {
            'form': form,
            'message': ''
        }
        return render(request, 'ratebranch.html', context)

class CreateRequest(View):

    def post(self, request):
        form = CreateRequestForm(request.POST)
        user_id = request.session['logged_in_user']
        if form.is_valid():
            user_id = request.session['logged_in_user']
            license_plate = form.cleaned_data['license_plate']
            to_branch = form.cleaned_data['to_branch']
            reason = form.cleaned_data['reason']
            cursor = connection.cursor()

            sql = """SELECT branch_id FROM vehicle WHERE license_plate = "{}";""".format(license_plate)
            cursor.execute(sql)
            from_branch = cursor.fetchall()[0][0]
            if int(from_branch) == int(to_branch):
                cursor = connection.cursor()
                sql = "SELECT * FROM request, (SELECT branch_id, branch_name FROM branch) AS from_branch_name, " \
                      "(SELECT branch_id, branch_name FROM branch) AS to_branch_name " \
                      "WHERE from_branch = from_branch_name.branch_id and to_branch = to_branch_name.branch_id and made_by_customer = {};".format(user_id)
                cursor.execute(sql)
                old_req = cursor.fetchall()
                form = CreateRequestForm()
                context = {
                    'old_req': old_req,
                    'form': form,
                    'message': 'Error occured.'
                }
                return render(request, 'customerRequest.html', context)
            sql = "INSERT INTO request " \
                  "(req_id, made_by_customer, from_branch, to_branch, requested_vehicle, checked_by_employee, isApproved, reason) " \
                  "VALUES (NULL, {}, {}, {}, '{}', NULL, NULL, '{}');".format(user_id, from_branch, to_branch,
                                                                              license_plate, reason)
            cursor.execute(sql)
            sql = "SELECT * FROM request, (SELECT branch_id, branch_name FROM branch) AS from_branch_name, (SELECT branch_id, branch_name FROM branch) AS to_branch_name WHERE from_branch = from_branch_name.branch_id and to_branch = to_branch_name.branch_id and made_by_customer = {};".format(user_id)
            cursor.execute(sql)
            old_req = cursor.fetchall()
            form = CreateRequestForm()
            context = {
                'old_req': old_req,
                'form': form,
                'message': 'Request is taken.',
            }
            return render(request, 'customerRequest.html', context)

        cursor = connection.cursor()
        sql = "SELECT * FROM request, (SELECT branch_id, branch_name FROM branch) AS from_branch_name, (SELECT branch_id, branch_name FROM branch) AS to_branch_name WHERE from_branch = from_branch_name.branch_id and to_branch = to_branch_name.branch_id and made_by_customer = {};".format(user_id)
        cursor.execute(sql)
        old_req = cursor.fetchall()
        form = CreateRequestForm()
        context = {
            'old_req': old_req,
            'form': form,
            'message': 'Error occured.'
        }
        return render(request, 'customerRequest.html', context)

    def get(self, request) -> 'html':
        user_id = request.session['logged_in_user']
        cursor = connection.cursor()
        sql = "SELECT * FROM request, (SELECT branch_id, branch_name FROM branch) AS from_branch_name, (SELECT branch_id, branch_name FROM branch) AS to_branch_name WHERE from_branch = from_branch_name.branch_id and to_branch = to_branch_name.branch_id and made_by_customer = {};".format(user_id)
        cursor.execute(sql)
        old_req = cursor.fetchall()
        form = CreateRequestForm()
        context = {
            'old_req': old_req,
            'form': form,
            'message': ''
        }
        return render(request, 'customerRequest.html', context)

class RateCar(View):

    def post(self, request):
        form = VehicleRate(request.POST)

        if form.is_valid():
            license_plate = form.cleaned_data['license_plate']
            comment = form.cleaned_data['comment']
            rate = form.cleaned_data['rate']
            user_id = request.session['logged_in_user']
            cursor = connection.cursor()
            try:
                sql = "INSERT INTO vehicle_rate (customer_id, license_plate, comment, score) " \
                      "VALUES ({}, '{}', '{}', {});".format(user_id, license_plate, comment, rate)
                cursor.execute(sql)
            except:
                messages.error(request, 'You already evaluated this vehicle.')
                return self.get(request)

            messages.success(request, 'Your evaluation is saved.')
            return self.get(request)

    def get(self, request) -> 'html':
        user_id = request.session['logged_in_user']
        cursor = connection.cursor()
        sql = "SELECT * FROM `reservation` WHERE reserver = {} and status = 'paid';".format(user_id)
        cursor.execute(sql)
        old_res = cursor.fetchall()
        form = VehicleRate()
        context = {
            'old_res': old_res,
            'userid': user_id,
            'form': form
        }
        return render(request, 'ratevehicles.html', context)

class MakeReservation(View):

    def post(self, request):

        user_id = request.session['logged_in_user']
        error_message = ''

        form = MakeReservationForm(request.POST, user=user_id, license_plate=None, daily_cost=None)
        if form.is_valid():
            reserver_id = form.cleaned_data['reserver_id']
            reason = form.cleaned_data['reason']
            license_plate = form.cleaned_data['license_plate']
            daily_cost = form.cleaned_data['daily_cost']
            start_date = form.cleaned_data['start_date']
            end_date = form.cleaned_data['end_date']
            chauffeur_id = form.cleaned_data['chauffeur_id']
            insurance_type = form.cleaned_data['insurance_type']
            if start_date > end_date:
                return redirect('/customer/errorDate')

            rental_period_in_days = abs((end_date - start_date).days)
            if rental_period_in_days == 0:
                rental_period_in_days = 1

            cost = rental_period_in_days * daily_cost

            cursor = connection.cursor()
            print(insurance_type != 'NULL')
            if insurance_type != 'NULL':
                sql = "SELECT insurance_type FROM `insurance` WHERE insurance_price = {};".format(insurance_type)
                cursor.execute(sql)
                insurances = cursor.fetchall()
                insurance_type = insurances[0][0]

            # some assertions are needed before inserting a new reservation

            # assertion 1- if the car to be reserved is not available

            #assertion 2- if you already have an reservation that day

            #these two assertions are provided at triggers

            #assertion 3- if the user has not paid for a reservation before
            assertion_3_sql = " select * from reservation where reserver = " + str(user_id) + " and status = \'not_paid\'"
            cursor.execute(assertion_3_sql)
            result = cursor.fetchall()
            if len(result) != 0:
                print('hfjdfhdjfj')
                error_message = 'First pay your previous reservations'
                return render(request, 'error.html', {'message': error_message})

            #assertion 4- if user driving license info doesnt allow it to rent this car
            assertion_4_sql = "select car_type from vehicle natural join car where license_plate = \'" + str(license_plate) + '\';'
            cursor.execute(assertion_4_sql)
            result_car_type = cursor.fetchall()
            result_car_type = result_car_type[0]

            cursor.execute('select license_type from driving_license where user_id = \'' + str(user_id) + '\';')
            result_user_license = cursor.fetchall()
            result_user_license = result_user_license[0]
            if result_user_license[0][0:1] != result_car_type[0] and chauffeur_id == 'NULL':
                error_message = 'You cannot drive this car, you need a chaeffuer'
                return render(request, 'error.html', {'message': error_message})

            sql = """
            INSERT INTO `reservation`
            (`start_date`, `end_date`, `status`, `cost`, `reserver`,
            `checked_by`, `isApproved`, `reason`, `insurance_type`, `license_plate`, `reserved_chauf_id`, `isChaufAccepted`)
            VALUES ('{}', '{}', 'not_accepted', '{}', '{}', NULL, 'false', '{}', '{}', '{}', {}, NULL);
        """.format(start_date, end_date, cost, reserver_id, reason, insurance_type, license_plate,
                   chauffeur_id)

            print(sql)
            try:
                cursor.execute(sql)
            except Exception as ex:
                error_message = 'It is not available to make reservation'
                return render(request, 'error.html', {'message': error_message})

            return redirect('/customer/reservationsuccess')

        return render(request, 'error.html', {'message': error_message})

    def get(self, request, plate) -> 'html':
        cursor = connection.cursor()
        sql = "SELECT * FROM vehicle where license_plate = \'{}\';".format(plate)
        cursor.execute(sql)
        vehicle = cursor.fetchall()
        vehicleTuple = vehicle[0]

        user_id = request.session['logged_in_user']

        form = MakeReservationForm(user=user_id, license_plate=vehicleTuple[0], daily_cost=vehicleTuple[2])
        context = {
            'vehicle': vehicle[0],
            'userid': request.session['logged_in_user'],
            'form': form
        }
        return render(request, 'makeReservation.html', context)

class CustomerDashboard(View):

    def post(self, request):
        form = CarPlate(request.POST)

        if form.is_valid():
            return redirect('customer:customer_make_res', plate=form.cleaned_data['plate'])

        return render(request, 'customerDashboard.html')

    def get(self, request) -> 'html':
        user_id = request.session['logged_in_user']
        cursor = connection.cursor()
        cursor.execute(
            'SELECT * FROM vehicle NATURAL JOIN branch WHERE status = \'available\';'
        )
        desc = cursor.fetchall()

        # some statistics for the customer
        cursor.execute('SELECT (select branch_name from branch where branch_id = V.branch_id) as name, count(*) as number_of_reservations, (select score from branch_rate where branch_id = V.branch_id and customer_id = R.reserver) as your_score, avg(cost) as cost FROM reservation R, vehicle V where R.license_plate = V.license_plate and R.reserver = ' + str(user_id) + ' and R.status <> \'canceled\' group by V.branch_id;')
        result = cursor.fetchall()
        for res in result:
            print(res)

        context = {
            'vehicles': desc,
            'info': result,
        }
        return render(request, 'customerDashboard.html', context)

class Error(View):

    def get(self, request):
        return render(request, 'error.html')

class DateError(View):
    def get(self, request):
        return render(request, 'errorDate.html')

class ReservationComplate(View):
    def get(self, request):
        return render(request, 'reservationcomplate.html')

class ListReservations(View):
    def get(self, request):
        reserver = request.session['logged_in_user']

        cursor = connection.cursor()
        cursor.execute(
            'SELECT * FROM reservation WHERE reserver =' + str(reserver) + ';'
        )
        result = cursor.fetchall()
        context = {
            'reservations': result
        }
        return render(request, 'listReservations.html', context)

class OrderReservations(View):
    def post(self, request):
        order = request.POST['order-by']
        reserver = request.session['logged_in_user']
        cursor = connection.cursor()

        if int(order) == 1:
            cursor.execute(
                'SELECT * FROM reservation WHERE reserver =' + str(reserver) + ' order by start_date;'
            )
        elif int(order) == 2:
            cursor.execute(
                'SELECT * FROM reservation WHERE reserver =' + str(reserver) + ' order by cost;'
            )
        else:
            cursor.execute(
                'SELECT * FROM reservation WHERE reserver =' + str(reserver) + ' order by end_date;'
            )
        result = cursor.fetchall()
        context = {
            'reservations': result
        }
        return render(request, 'listReservations.html', context)

class PenaltiesView(View):
    def get(self, request):
        reserver = request.session['logged_in_user']
        sql = "SELECT issue_id, description, dr.cost, author_expertise_id, license_plate FROM damage_report dr, reservation r WHERE r.reservation_number = dr.issued_reservation and r.reserver = {}".format(reserver)
        cursor = connection.cursor()
        cursor.execute(sql)
        userPenalties = cursor.fetchall()
        context = {'penalties' : userPenalties, 'message' : ""}
        return render(request, 'listPenalties.html', context)
    def post(self, request):
        reserver = request.session['logged_in_user']
        issue = request.POST.get('issueId', "")
        sql = "DELETE FROM damage_report WHERE issue_id = {}".format(issue)
        cursor = connection.cursor()
        cursor.execute(sql)
        sql = "SELECT issue_id, description, dr.cost, author_expertise_id, license_plate FROM damage_report dr, reservation r WHERE r.reservation_number = dr.issued_reservation and r.reserver = {}".format(reserver)
        cursor = connection.cursor()
        cursor.execute(sql)
        userPenalties = cursor.fetchall()
        context = {'penalties' : userPenalties, 'message' : "Successfully paid penalty."}
        return render(request, 'listPenalties.html', context)

def cancelReservation( request):
    reservation = request.GET.get('reservation', None)
    customer = request.GET.get('customer', None)

    cursor = connection.cursor()
    cursor.execute('update reservation set status = \'canceled\' where reservation_number = ' + str(reservation) + ';')

    data = {}
    data['canceled'] = True
    return JsonResponse(data)


# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding("utf-8")

from project.database import db, Base
from marshmallow import Schema, fields
import datetime

class ShipmentMethod(Base):
    __tablename__ = 'shipment_methods'
    id = db.Column(db.BigInteger, primary_key=True)
    title = db.Column(db.String(length=100), nullable=False)
    description = db.Column(db.Text, nullable=False)
    price = db.Column(db.DECIMAL(precision=20, scale=4), default=0)

    created_at = db.Column(db.TIMESTAMP, default=datetime.datetime.now, nullable=False)
    updated_at = db.Column(db.TIMESTAMP, default=datetime.datetime.now, nullable=False, onupdate=datetime.datetime.now)

    def __str__(self):
        return self.title + " با هزینه ارسال : " + str(self.price)

class ShipmentMethodSchema(Schema):
    id = fields.Int()
    title = fields.Str()
    description = fields.Str()
    price = fields.Str()


from json.encoder import JSONEncoder
import datetime
import decimal
import uuid

class DefaultJsonEncoder(JSONEncoder):
    """
    An encoder specially created to encode datetime
    objects or other specific Python representations
    """
    def default(self, obj):
        # Date/Time string spcifications at ECMA 262
        # https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15

        if isinstance(obj, datetime.datetime):
            representation = obj.isoformat()
            if representation.endswith('+00:00'):
                representation = representation[:-6] + 'Z'
            return representation

        if isinstance(obj, datetime.time):
            if datetime.timezone and datetime.timezone.is_aware(obj):
                raise ValueError('Cannot represent timezon-aware times.')
            return obj.isoformat()

        if isinstance(obj, datetime.date):
            return str(obj)

        if isinstance(obj, datetime.timedelta):
            return str(obj.total_seconds())

        if isinstance(obj, decimal.Decimal):
            return float(obj)

        if isinstance(obj, uuid.UUID):
            return str(obj)

        if isinstance(obj, bytes):
            return obj.decode()

        if hasattr(obj, 'tolist'):
            return obj.tolist()

        # Conversion for lists and tuples
        if hasattr(obj, '__getitem__'):
            convert_to = list if isinstance(obj, (list, tuple)) else dict
            try:
                return convert_to(obj)
            except Exception:
                raise

        if hasattr(obj, '__iter__'):
            return tuple(item for item in obj)

        return super().default(obj)


import socket
import random
from collections import defaultdict

def encode_utf(message):
    """Encodes a given message to utf-8 encoding

    :param message: The message to be encoded to utf-8
    :type message: str
    :return: The utf-8 encoded message
    """
    return str(message).encode('utf-8')

def decode_utf(message):
    """Decodes a given message from utf-8 encoding

    :param message: The message to be decoded to utf-8
    :return: The utf-8 decoded message
    """
    return message.decode('utf-8')

def get_sentence():
    """Function that creates a random sentence based on th principle of Markov chains

    :return:
    """
    with open("dracula.txt") as f:
        words = f.read().split()

    word_dict = defaultdict(list)
    for word, next_word in zip(words, words[1:]):
        word_dict[word].append(next_word)

    word = "Dracula"
    word_list = []
    while not word.endswith("."):
        word_list.append(word)
        word = random.choice(word_dict[word])

    _sentence = " ".join(word_list)
    return _sentence

class TCPClient:
    def __init__(self, host, port):
        self.serverName = host
        self.serverPort = port
        self.clientSocket = None

    def create(self):
        """Class method to create a TCP socket object and instantiates the clientSocket
        class variable

        """
        try:
            self.clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except socket.error as e:
            print(f"Error creating socket: {e}")

    def connect(self):
        """Class method to connect the client socket to given server ip address (serverName)
        and server port (serverPort).

        """
        try:
            self.clientSocket.connect((self.serverName, self.serverPort))
        except socket.error as e:
            print(f"Error creating socket: {e}")

    def send_message(self, sentence):
        """Class method to send a message from client to server

        :param sentence: The message (the sentence from client) that needs to be transmitted
        """
        try:
            self.clientSocket.send(encode_utf(sentence))
        except socket.error as e:
            print(f"Error sending data: {e}")

    def receive_message(self):
        """Class method to receive a message from server

        :return: The message returned from server
        :rtype: bytes
        """
        try:
            message = self.clientSocket.recv(1024)
            return message
        except socket.error as e:
            print(f"Error receiving data: {e}")

    def close_socket(self):
        """Method to close the created socket

        """
        self.clientSocket.close()

    def get_word_and_char_count(self, sentence_to_send):
        """The main driver mechanics that sends sentence to the server
        and return results from the server.

        :param sentence_to_send: The sentence to be send
        :type sentence_to_send: str
        :returns:
            - word_count - The number of words returned
            - num_chars - the number of characters returned
        """
        print(f"The sentence is: {sentence_to_send}")
        self.send_message(sentence_to_send)
        word_count, num_chars = [int(i) for i in decode_utf(self.receive_message()).split('\n')]
        print(f"The number of words is {word_count} and the characters is {num_chars}")
        return word_count, num_chars

if __name__ == '__main__':
    print("Client fired up:")
    serverName = socket.gethostname()  # ‘hostname’
    serverPort = 12000
    ip_address = socket.gethostbyname(serverName)
    client = TCPClient(ip_address, serverPort)
    client.create()
    client.connect()
    sentence = get_sentence()
    client.get_word_and_char_count(sentence)
    client.close_socket()


import unittest2 as unittest

import ROOT

from monitoring_app import tasks

class TestPages(unittest.TestCase):
    def setUp(self):
        self.fextension = 'root'
        # The fname and keys match those of the data generated by
        # `generate_histograms.py`
        self.dummy_fname = 'histograms.root'
        self.dummy_keys = ['histogram_{0}'.format(i) for i in range(4)]
        self.dummy_th1 = ROOT.TH1F('dummy:xtitle:ytitle', 'dummy', 10, 0, 1)
        self.dummy_th1.FillRandom('gaus', 1000)

    def tearDown(self):
        # Delete TH1 so we don't create multiple instances with the same name
        del self.dummy_th1

    def test_add_file_extension(self):
        """Extension is added to a filename when not present."""
        fname = 'filename'
        fname_expected = '{0}.{1}'.format(fname, self.fextension)
        assert tasks.add_file_extension(fname) == fname_expected

    def test_dont_add_file_extension_again(self):
        """Extension is not added to a filename if already present."""
        fname = 'filename.{0}'.format(self.fextension)
        assert tasks.add_file_extension(fname) == fname

    def test_data_for_th1f(self):
        """Appropriate information is provided on TH1F ROOT objects."""
        data = tasks.data_for_object(self.dummy_th1)
        for key in ('binning', 'values', 'uncertainties', 'axis_titles'):
            assert key in data
        nbins = self.dummy_th1.GetNbinsX()
        assert len(data['binning']) == nbins
        assert len(data['values']) == nbins
        assert len(data['uncertainties']) == nbins
        assert len(data['axis_titles']) == 2
        assert data['axis_titles'][0] == self.dummy_th1.GetXaxis().GetTitle()
        assert data['axis_titles'][1] == self.dummy_th1.GetYaxis().GetTitle()

    def test_data_for_unknown_tobject(self):
        """No information should be returned for unsupported ROOT objects."""
        # Use a child of TObject that we don't support
        obj = ROOT.TH3D()
        data = tasks.data_for_object(obj)
        assert not data

    def test_get_key_from_file(self):
        """Dictionary describing key in file is returned."""
        data = tasks.get_key_from_file(self.dummy_fname, self.dummy_keys[0])
        for k in ('success', 'data'):
            assert k in data
        data_data = data['data']
        assert data['success'] == True
        assert data_data
        for k in ('filename', 'key_name', 'key_title', 'key_class', 'key_data'):
            assert k in data_data
        assert data_data['filename'].endswith(self.dummy_fname)
        assert data_data['key_name'] == self.dummy_keys[0]
        assert data_data['key_title'] == 'Gaussian'
        assert data_data['key_class'] == 'TH1F'

    def test_get_key_from_file_invalid_filename(self):
        """Error dictionary is returned with message."""
        # As this test intentionally tries to open a non-existent file, which
        # ROOT would by default print an error about, temporarily change the
        # logging level to suppress such a message
        originalErrorIgnoreLevel = ROOT.gErrorIgnoreLevel
        ROOT.gErrorIgnoreLevel = ROOT.kFatal
        data = tasks.get_key_from_file('fake_file.root', self.dummy_keys[0])
        ROOT.gErrorIgnoreLevel = originalErrorIgnoreLevel
        for k in ('success', 'message'):
            assert k in data
        assert 'data' not in data
        assert data['success'] == False
        assert data['message'].startswith('Could not open')

    def test_get_key_from_file_invalid_key_name(self):
        """Error dictionary is returned with message."""
        data = tasks.get_key_from_file(self.dummy_fname, 'fake_key')
        for k in ('success', 'message'):
            assert k in data
        assert 'data' not in data
        assert data['success'] == False
        assert data['message'].startswith('Could not find')

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


import pygame
from Exit_gate import *
from Platforms import *
from Enemy import *
from Coin import *

blob_group = pygame.sprite.Group()
platform_group = pygame.sprite.Group()
lava_group = pygame.sprite.Group()
exit_group = pygame.sprite.Group()
coin_group = pygame.sprite.Group()

#Dummy coin beside the score
score_coin = Coin(tile_size//2, tile_size//2)
coin_group.add(score_coin)

class World:
    def __init__(self, data):
        self.tile_list = []

        dirt_img = pygame.image.load('img/dirt.png')
        grass_img = pygame.image.load('img/grass.png')
        # lava_img = pygame.image.load('img/lava.png')

        row_count = 0
        for row in data:
            col_count = 0
            for tile in row:
                if tile == 1:
                    img = pygame.transform.scale(dirt_img, (tile_size, tile_size))
                    img_rect = img.get_rect()
                    img_rect.x = col_count*tile_size
                    img_rect.y = row_count*tile_size
                    tile = (img, img_rect)
                    self.tile_list.append(tile)
                if tile == 2:
                    img = pygame.transform.scale(grass_img, (tile_size, tile_size))
                    img_rect = img.get_rect()
                    img_rect.x = col_count*tile_size
                    img_rect.y = row_count*tile_size
                    tile = (img, img_rect)
                    self.tile_list.append(tile)
                if tile == 3:
                    blob = Enemy(col_count*tile_size, row_count*tile_size+15)
                    blob_group.add(blob)
                if tile == 4:   # Horizontol
                    platform = Platform(col_count*tile_size, row_count*tile_size, 1, 0)
                    platform_group.add(platform)
                if tile == 5:   # Vertical
                    platform = Platform(col_count*tile_size, row_count*tile_size, 0, 1)
                    platform_group.add(platform)
                if tile == 6:
                    lava = Lava(col_count*tile_size, row_count*tile_size+tile_size//2)
                    lava_group.add(lava)
                if tile == 7:
                    coin = Coin(col_count*tile_size + (tile_size // 2), row_count*tile_size + tile_size//2)
                    coin_group.add(coin)
                if tile == 8:
                    exi = Exit(col_count*tile_size, row_count*tile_size- (tile_size//2))
                    exit_group.add(exi)
                col_count += 1
            row_count += 1

    def draw(self, screen):
        for tile in self.tile_list:
            screen.blit(tile[0], tile[1])