class Mother():
    def __init__(self, name:str) -> None:
        self.name : str = name
        self.eye_color : str = "blue"

    def speaking(self, words : str) -> str:
        return f"Mother Speaking function: {words}"

class Father():
    def __init__(self, name:str) -> None:
        self.name : str = name
        self.height : str = "6 Feet"

class Child(Mother, Father):
    def __init__(self, mother_name: str, father_name : str, child_name : str) -> None:
        Mother.__init__(self, mother_name)
        Father.__init__(self, father_name)
        self.child_name : str = child_name

qasim : Child = Child("Naseem Bano", "Muhammad Aslam", "Muhammad Qasim")

print(f"object height {qasim.height}")
print(f"object eye color {qasim.eye_color}")
print(qasim.speaking("Pakistan Zindabad"))

# print(dir(qasim))
from typing import Any, overload

class Addar():
    def add(self, x: int, y: int) -> int:
        return x + y

    def add(self, x: float, y: float) ->float:
        return x + y

obj: Addar = Addar()
print(obj.add(7.0,3.0))
print(obj.add(7,3))

###########

from typing import Union, overload
@overload
def add(x: int, y: int) -> int:
    ...

@overload
def add(x: float, y: float) -> float:
    ...

@overload
def add(x: str, y: str) -> str:
    ...

def add(x: Union[int, float, str], y: Union[int, float, str]) -> Union[int, float, str]:
    if isinstance(x, int) and isinstance(y, int):
        return x + y
    elif isinstance(x, float) and isinstance(y, float):
        return x + y
    elif isinstance(x, str) and isinstance(y, str):
        return x + y
    else:
        raise TypeError("Invalid argument types!")

# Usage examples
result1 = add(1, 2)
result2 = add(1.5, 2.5)
result3 = add("Hello", "World")

print(result1)
print(result2)
print(result3)

##########

# Overridding & polymorphism

class Animal():
    def eating(self, food : str ) ->None:
        print(f"Animal is eating {food}")

class Bird(Animal):
    def eating(self, food: str) -> None:
        print(f"Bird is eating {food}")

bird : Bird = Bird()
bird.eating("bread")

animal : Animal = Animal()
animal.eating("grass")

### Polymorphism

animal : Animal = Bird() # run time it will decide which object method it wil be run
animal.eating("grass")

############

# Static Method / static attribute

class MathOperations:

    counter : int = 100
    organization : str = "PIAIC"

    @staticmethod
    def add(x: int, y: int) -> int:
        """Add two numbers."""
        return x + y

    @staticmethod
    def multiply(x: int, y: int) -> int:
        """Multiply two numbers."""
        return x * y

# Using the static methods
result_add = MathOperations.add(10, 20)
result_multiply = MathOperations.multiply(10, 20)

print("Addition:", result_add)
print("Multiplication:", result_multiply)

print("Static variable or Class variable", MathOperations.organization)

###########

# Everything is object

class Human():
    def eating(self, food : str) -> None:
        print(f"Human is eating {food}")

obj1 : Human = Human()
obj1.eating("Biryani")

class Human1(object):
    def eating(self, food : str) -> None:
        print(f"Human is eating {food}")

obj2 : Human1 = Human1()
obj2.eating("Biryani1")

######

class Human1(object):
    def eating(self, food : str)->None:
        print(f"Human is eating {food}")

    def __call__(self) -> None:
        self.eating("Nihari!")

obj3 : Human1 = Human1()
obj3.eating("Biryani")

obj3.__call__()


import hashlib
import re
import subprocess

def checksum_string(s):
    return hashlib.md5(s.encode('utf-8')).hexdigest()

def checksum(fd):
    """ Calculate a md5 checksum of fd file handle

    Arguments:
      fd: A file descriptor return from open() call

    Returns:
      A md5 checksum of the file

    Raises:
      CalledProcessError if the file doesn't exist
    """

    md5sum_cmd = ["md5sum", fd.name]
    output = subprocess.check_output(md5sum_cmd, universal_newlines=True).strip()
    return output.split()[0]

class ArchiveChecksums(dict):
    @classmethod
    def from_file_desc(cls, fd):
        checksum_pattern = re.compile(r"(\S+)\s+(\S+)")
        checksums = dict()

        for line in (line.decode('utf-8').strip() for line in fd if line):

            # Skip comments
            if line.startswith('#'):
                continue

            # Skip lines that do not contain the pattern we are looking for
            result = checksum_pattern.search(line)
            if result is None:
                continue

            chksum, filepath = result.groups()
            checksums[filepath] = chksum

        return cls(checksums)


from django.conf import settings
from django.urls import include, path
from django.contrib import admin
from django.contrib.auth import views as auth_views

from wagtail.core import urls as wagtail_urls
from wagtail.admin import urls as wagtailadmin_urls

from .views import (
    HomeView,
    AvailabilityView,
    AvailabilityFormView,
    PlaysheetView,
    ContactView,
    AboutView,
)

urlpatterns = [
    path('confirmation/', include('confirm.urls', namespace='confirmation')),
    path('', auth_views.LoginView.as_view(
        template_name='login.html',
        redirect_authenticated_user=True),
         name='login'),
    path('availability/', include('availability.urls', namespace='availability')),
    path('playsheet/', PlaysheetView.as_view()),
    path('accounts/', include('accounts.urls')),
    path('contact/', ContactView.as_view(), name="contact"),
    path('season/', include('season.urls')),
    path('members/', include('members.urls')),
    path('schedule/', include('schedule.urls', namespace='schedule')),
    path('api/', include('api.urls')),
    path('django-admin/', admin.site.urls),
    path('chat/', include('tennis_channels.urls', namespace='chat')),

    path('admin/', include(wagtailadmin_urls)),
    path('', include(wagtail_urls)),
]

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        path('__debug__/', include(debug_toolbar.urls)),
    ] + urlpatterns


import os
from datetime import datetime, timedelta
import logging
import json
import shutil
from typing import List
import pandas as pd
from trader import Trader
from utils import tf_cron, NUM_KLINE_INIT, CANDLE_COLUMNS
from utils import get_pretty_table

bot_logger = logging.getLogger("bot_logger")

class BackTest:
    def __init__(self, exch, symbols_trading_cfg_file, data_dir):
        self.exch = exch
        self.data_dir = data_dir
        self.bot_traders: List[Trader] = []
        self.symbols_trading_cfg_file = symbols_trading_cfg_file
        self.debug_dir = os.environ["DEBUG_DIR"]

    def load_mt5_klines_monthly_data(self, symbol, interval, month, year):
        csv_data_path = os.path.join(self.data_dir, "{}-{}-{}-{:02d}.csv".format(symbol, interval, year, month))
        df = pd.read_csv(csv_data_path)
        df["Open time"] = pd.to_datetime(df["Open time"])
        return df

    def load_klines_monthly_data(self, symbol, interval, month, year):
        return self.load_mt5_klines_monthly_data(symbol, interval, month, year)

    def backtest_bot_trader(self, symbol_cfg):
        bot_trader = Trader(symbol_cfg)
        bot_trader.init_strategies()
        tfs_chart = {}
        # Load kline data for all required timeframes
        for tf in bot_trader.get_required_tfs():
            chart_df = pd.concat(
                [
                    self.load_klines_monthly_data(symbol_cfg["symbol"], tf, month, symbol_cfg["year"])
                    for month in sorted(symbol_cfg["months"])
                ],
                ignore_index=True,
            )
            tfs_chart[tf] = chart_df
        max_time = max([tf_chart.iloc[NUM_KLINE_INIT - 1]["Open time"] for tf_chart in tfs_chart.values()])
        end_time = max([tf_chart.iloc[-1]["Open time"] for tf_chart in tfs_chart.values()])
        tfs_chart_init = {}
        for tf, tf_chart in tfs_chart.items():
            tfs_chart_init[tf] = tf_chart[tf_chart["Open time"] <= max_time][-NUM_KLINE_INIT:]
            tfs_chart[tf] = tf_chart[tf_chart["Open time"] > max_time]
            start_index = tfs_chart_init[tf].index[0]
            tfs_chart_init[tf].index -= start_index
            tfs_chart[tf].index -= start_index
        bot_trader.init_chart(tfs_chart_init)
        bot_trader.attach_oms(None)  # for backtesting don't need oms

        timer = max_time
        end_time = end_time
        bot_logger.info("   [+] Start timer from: {} to {}".format(timer, end_time))
        required_tfs = [tf for tf in tf_cron.keys() if tf in bot_trader.get_required_tfs()]
        # c = 0
        while timer <= end_time:
            timer += timedelta(seconds=60)
            hour, minute = timer.hour, timer.minute
            for tf in required_tfs:
                cron_time = tf_cron[tf]
                if ("hour" not in cron_time or hour in cron_time["hour"]) and (
                    "minute" not in cron_time or minute in cron_time["minute"]
                ):
                    last_kline = tfs_chart[tf][:1]
                    tfs_chart[tf] = tfs_chart[tf][1:]
                    bot_trader.on_kline(tf, last_kline)
            #         c += 1
            # if c > 1000:
            #     break
        return bot_trader

    def start(self):
        with open(self.symbols_trading_cfg_file) as f:
            symbols_config = json.load(f)
        c = 0
        bot_logger.info("[*] Start backtesting ...")
        for symbol_cfg in symbols_config:
            bot_logger.info("[+] Backtest bot for symbol: {}".format(symbol_cfg["symbol"]))
            bot_trader = self.backtest_bot_trader(symbol_cfg)
            self.bot_traders.append(bot_trader)
            c += 1
            if c >= 2:
                break
        bot_logger.info("[*] Backtesting finished")

    def summary_trade_result(self):
        final_backtest_stats = []
        for bot_trader in self.bot_traders:
            bot_trader.close_opening_orders()
            backtest_stats = bot_trader.statistic_trade()
            bot_logger.info(get_pretty_table(backtest_stats, bot_trader.get_symbol_name(), transpose=True, tran_col="NAME"))
            backtest_stats.loc[len(backtest_stats) - 1, "NAME"] = bot_trader.get_symbol_name()
            final_backtest_stats.append(backtest_stats.loc[len(backtest_stats) - 1 :])

            bot_trader.log_orders()
            bot_trader.plot_strategy_orders()

        table_stats = pd.concat(final_backtest_stats, axis=0, ignore_index=True)
        s = table_stats.sum(axis=0)
        table_stats.loc[len(table_stats)] = s
        table_stats.loc[len(table_stats) - 1, "NAME"] = "TOTAL"
        bot_logger.info(get_pretty_table(table_stats, "SUMMARY", transpose=True, tran_col="NAME"))
        return table_stats

    def stop(self):
        pass


from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.

class User(AbstractUser):
    full_name = models.CharField(max_length=100)
    avatar = models.CharField(max_length=100, null=True)
    verified_email = models.BooleanField(default=False)
    created_at = models.DateTimeField(
        auto_now_add=True,
        null=True,
        blank=True
    )
    @classmethod
    def get_user(cls, username=None, email=None):
        query = {}
        if username:
            query['username'] = username
        if email:
            query['email'] = email
        user = User.objects.filter(**query).first()
        return user

    @classmethod
    def add_user(cls, username, full_name, email):
        user = User(
            username=username,
            full_name=full_name,
            email=email
        )
        user.save()
        return user

    @classmethod
    def update(cls, user, data):
        if 'username' in data:
            user.username = data['username']
        if 'email' in data:
            if user.email != data['email']:
                user.verified_email = False
            user.email = data['email']
        if 'fullname' in data:
            user.fullname = data['fullname']
        user.save()
        return user

class UserFollow(models.Model):
    follower = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='follower_user'
    )

    following = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='following_user'
    )

    created_at = models.DateTimeField(
        auto_now_add=True,
        null=True,
        blank=True
    )
    @classmethod
    def follow_user(cls, follower, following):
        user_follow = UserFollow.objects.filter(
            follower=follower,
            following=following
        ).first()
        if not user_follow:
            user_follow = UserFollow(
                follower=follower,
                following=following
            )
            user_follow.save()
        return user_follow

    @classmethod
    def unfollow_user(cls, follower, following):
        UserFollow.objects.filter(
            follower=follower,
            following=following
        ).delete()
        return True

class UserBlock(models.Model):
    blocker = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='blocker_user'
    )

    blocked = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='blocked_user'
    )

    created_at = models.DateTimeField(
        auto_now_add=True,
        null=True,
        blank=True
    )
    @classmethod
    def block_user(cls, blocker, blocked):
        user_block = UserBlock.objects.filter(
            blocker=blocker,
            blocked=blocked
        ).first()
        if not user_block:
            user_block = UserBlock(
                blocker=blocker,
                blocked=blocked
            )
            user_block.save()
        return user_block

    @classmethod
    def unblock_user(cls, blocker, blocked):
        UserBlock.objects.filter(
            blocker=blocker,
            blocked=blocked
        ).delete()
        return True


#!/usr/bin/env python3
#
# file: circle.py
# package: lab2
# author: Travis Kessler (Travis_Kessler@student.uml.edu)
#
# Commands duckiebot to move in a 1m diameter circle
#

import rospy
from duckietown_msgs.msg import Twist2DStamped

def drive_in_circle():

    r = rospy.Rate(10)
    pub = rospy.Publisher(
        'vehicle_command',
        Twist2DStamped,
        queue_size=1
    )
    movement = Twist2DStamped()
    for _ in range(80):
        r.sleep()
        movement.v = 0.4
        movement.omega = 2
        pub.publish(movement)
    movement.v = 0.0
    movement.omega = 0
    pub.publish(movement)

if __name__ == '__main__':

    rospy.init_node('lab2_circle', anonymous=True)
    drive_in_circle()


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import argparse
from multiprocessing import Pool
from tqdm import tqdm
import functools
import warnings
import glob
warnings.filterwarnings('ignore')

def get_list_of_frags(df_region,i):

    frag_left_start = df_region.loc[i]['left_start']
    frag_right_end = df_region.loc[i]['right_end']

    Mcount = df_region.loc[i]['Fragment_number']
    Num_mid_frags = Mcount - 2

    Lst_of_frags = [[df_region.loc[i]['left_start'],df_region.loc[i]['left_end']]]
    if Num_mid_frags > 0:
        list_of_frag_coord = list(map(int, df_region.loc[i]['mid_frags'].split(',')))
        for k in range(Num_mid_frags):
            Lst_of_frags.append([list_of_frag_coord[2*k],list_of_frag_coord[2*k+1]])
    Lst_of_frags.append([df_region.loc[i]['right_start'],df_region.loc[i]['right_end']])

    # order the fragment by starting site.
    Lst_of_frags.sort(key = lambda x: int(x[0]))

    Lst_of_frags_array = np.array(Lst_of_frags)

    return Lst_of_frags_array

def plot_each_block(list_of_gems,fig,ax,total_length,Colorcode,sorted_by_len = False):
    if not sorted_by_len:
        if not isinstance(list_of_gems, list):
            sorted_list_of_gems = list_of_gems.tolist()
        sorted_list_of_gems.sort(key = lambda x: x[-1][-1] - x[0][0])
    else:
        if not isinstance(list_of_gems, list):
            sorted_list_of_gems = list_of_gems.tolist()

    y_idx = np.arange(len(list_of_gems))[::-1]
    num_frags = len(y_idx)
    height = len(y_idx) * 0.05

    for idx, line in enumerate(sorted_list_of_gems):
        left_end = line[0][0]
        right_end = line[-1][-1]
        x_thin = [left_end, right_end]
        y_thin = np.ones_like(x_thin) * y_idx[idx]
        ax.plot(x_thin, y_thin, c = 'grey', alpha = 0.8, lw = 0.4)
        for frag in line:
            x_thick = frag
            if (x_thick[-1] - x_thick[0]) < (0.001 * total_length):
                x_thick[-1] = x_thick[0] + 0.001 * total_length
            y_thick = np.ones_like(x_thick) * y_idx[idx]
            # If CTCF, c = #0000B2. If Cohesin, c = #005900.
            ax.plot(x_thick, y_thick, c = Colorcode, lw = 2)

    ax.tick_params(axis = 'y', which = 'both', left = False, top = False,labelleft = False)
    ax.set_ylabel('\n\n C#:'+str(num_frags),fontsize=6,rotation='horizontal', ha='right')
    ax.set_ylim(ymin=-1.25, ymax=len(y_idx)+0.75)
    return num_frags

def region_plot(region_boundary,bedfilepath,bedfiledir2, saveplotpath,title,Colorcode, silent = False):
    '''
    GEM file is large, avoid overloading it
    it contains a GEM and its fragments in each line.
    df_region_boundary also didn't change when switching region.
    Avoid overloading.
    '''
#     ipdb.set_trace()
    extension = 'bed'
    all_filenames = [i for i in glob.glob(bedfilepath+'*.{}'.format(extension))]
    all_filenames.sort(reverse=True)
    NumFiles = len(all_filenames)
    myorder = [1,0,2]
    Maxnum_pair = int((NumFiles-3)/2)
    if Maxnum_pair>0:
        for pair_idx in range(Maxnum_pair):
            myorder.extend([3+pair_idx*2+1,3+pair_idx*2])

    all_filenames[:] = [all_filenames[i] for i in myorder]

    total_length = region_boundary[-1]-region_boundary[0]

    region_idx = 0
    Mid_Idx = 0
    df_region = [[] for dummy in range(len(all_filenames))]
    df_region_2side = [[] for dummy in range(Maxnum_pair)]
    Heights = np.zeros(len(all_filenames))
    Heights_2side = np.zeros(Maxnum_pair)
    for df_region_path in all_filenames:
        df_region[region_idx] = pd.read_csv(df_region_path, sep = '\t',
                                            names = ['name', 'left_start', 'left_end', 'GEM_ID',
                                                    'Fragment_number','???','mid_frags', 'right_start',
                                                     'right_end'])

        df_region[region_idx]['frag_coord_filtered_array'] = None
        for i in range(len(df_region[region_idx])):
#             ipdb.set_trace()
            df_region[region_idx].at[i,'frag_coord_filtered_array'] = get_list_of_frags(df_region[region_idx],i)

        Heights[region_idx] = max(len(np.arange(len(df_region[region_idx]['frag_coord_filtered_array']))[::-1])* 0.05+0.1,0.25)

        if region_idx > 2 and np.mod(region_idx,2)==0:
            tempname = df_region_path.split('/')[-1].split('_')[0]+'_'+df_region_path.split('/')[-1].split('_')[1][:-1]
            df_region_2side_path = bedfiledir2+tempname+'.bed'
            df_region_2side[Mid_Idx] = pd.read_csv(df_region_2side_path, sep = '\t',
                                                    names = ['name', 'left_start', 'left_end', 'GEM_ID',
                                                            'Fragment_number','???','mid_frags', 'right_start',
                                                             'right_end'])
            df_region_2side[Mid_Idx]['frag_coord_filtered_array'] = None
            for i in range(len(df_region_2side[Mid_Idx])):
#             ipdb.set_trace()
                df_region_2side[Mid_Idx].at[i,'frag_coord_filtered_array'] = get_list_of_frags(df_region_2side[Mid_Idx],i)

            Heights_2side[Mid_Idx] = max(len(np.arange(len(df_region_2side[Mid_Idx]['frag_coord_filtered_array']))[::-1])* 0.05+0.1,0.25)
            Mid_Idx += 1

        region_idx += 1

# #     This is for single plot
#     fig, ax = plt.subplots(NumFiles, 1, sharex= True,
#                            figsize = (NumFiles, np.sum(Heights)),
#                            gridspec_kw={'height_ratios': Heights})

#     Num_frags = np.zeros(len(all_filenames))
#     for region_idx in range(len(all_filenames)):
#         Num_frags[region_idx] = plot_each_block(df_region[region_idx]['frag_coord_filtered_array'],fig,ax[region_idx],total_length,sorted_by_len = False)

#     ax[0].set_xticks([region_boundary[0],region_boundary[-1]])
#     ax[0].set_xticklabels([region_boundary[0],region_boundary[-1]],fontsize=4)

#     title = title+'_anchcomp_'+str(int(np.sum(Num_frags[0:3])))+'_M-'+str(int((len(Num_frags)-3)/2))+'_'+str(int(np.sum(Num_frags[3:])))
#     ax[0].set_title(title, fontsize = 10)
#     fig.subplots_adjust(hspace=0)
# #     plt.savefig('Minji_data/Cohesin_results/01ALL/4kbext_dm/Plots/{}.png'.format(title),
# #                 dpi = 600, bbox_inches='tight')
#     plt.savefig(saveplotpath+'{}.png'.format(title),dpi = 600, bbox_inches='tight')

#     if not silent:
#         plt.show()
#     plt.close()

# # # # This is for the split plots
    Num_frags = np.zeros(len(all_filenames))
    Num_frags_2side = np.zeros(Maxnum_pair)

    for figlistid in range(Maxnum_pair+1):
        if figlistid == 0:
            fig, ax = plt.subplots(3, 1, sharex= True,
                                   figsize = (3, np.sum(Heights[0:3])),
                                   gridspec_kw={'height_ratios': Heights[0:3]})
            for region_idx in range(3):
                Num_frags[region_idx] = plot_each_block(df_region[region_idx]['frag_coord_filtered_array'],fig,ax[region_idx],total_length,Colorcode,sorted_by_len = False)

            MetaX = ax[0].get_xlim()
            ax[0].set_xticks([region_boundary[0],region_boundary[-1]])
            ax[0].set_xticklabels([region_boundary[0],region_boundary[-1]],fontsize=4)
            Title = title+'_anchcomp_'+str(int(np.sum(Num_frags[0:3])))
            ax[0].set_title(Title, fontsize = 10)
            fig.subplots_adjust(hspace=0)
            try:
                plt.savefig(saveplotpath+'{}.pdf'.format(Title), bbox_inches='tight')
                if not silent:
                    plt.show()
                plt.close()
            except:
                plt.savefig(saveplotpath+'{}.pdf'.format(Title),dpi = 100, bbox_inches='tight')
                if not silent:
                    plt.show()
                plt.close()
        else:

            fig, ax = plt.subplots(3, 1, sharex= True,
                                   figsize = (3, np.sum(Heights[3+2*(figlistid-1):3+2*(figlistid)])+Heights_2side[figlistid-1]),
                                   gridspec_kw={'height_ratios': np.concatenate((Heights[3+2*(figlistid-1):3+2*(figlistid)],[Heights_2side[figlistid-1]]))})
            for region_idx in range(3+2*(figlistid-1),3+2*(figlistid)):
                Num_frags[region_idx] = plot_each_block(df_region[region_idx]['frag_coord_filtered_array'],fig,ax[np.mod(region_idx-3,2)],total_length,Colorcode,sorted_by_len = False)

            Num_frags_2side[figlistid-1] = plot_each_block(df_region_2side[figlistid-1]['frag_coord_filtered_array'],fig,ax[2],total_length,Colorcode,sorted_by_len = False)
#             ipdb.set_trace()
            MidName = all_filenames[3+2*(figlistid-1)].split('/')[-1].split('_')[1][2:-1]
            ax[0].set_xlim(xmin=MetaX[0], xmax=MetaX[-1])
            ax[0].set_xticks([region_boundary[0],region_boundary[-1]])
            ax[0].set_xticklabels([region_boundary[0],region_boundary[-1]],fontsize=4)
            Title = title+'_M-'+str(MidName)+'_1side:'+str(int(np.sum(Num_frags[3+2*(figlistid-1):3+2*(figlistid)])))+'_2side:'+str(int(Num_frags_2side[figlistid-1]))
            ax[0].set_title(Title, fontsize = 10)
            fig.subplots_adjust(hspace=0)
            try:
                plt.savefig(saveplotpath+'{}.pdf'.format(Title), bbox_inches='tight')
                if not silent:
                    plt.show()
                plt.close()
            except:
                print(Title,' : This plot use low dpi since too long.')
                plt.savefig(saveplotpath+'{}.pdf'.format(Title),dpi = 100, bbox_inches='tight')
                if not silent:
                    plt.show()
                plt.close()
    return None

def region_plot_2sides(region_boundary,bedfilepath, saveplotpath,title,Colorcode, silent = False):
    '''
    GEM file is large, avoid overloading it
    it contains a GEM and its fragments in each line.
    df_region_boundary also didn't change when switching region.
    Avoid overloading.
    '''
#     ipdb.set_trace()
    extension = 'bed'
    all_filenames = [i for i in glob.glob(bedfilepath+'*.{}'.format(extension))]
    all_filenames.sort(reverse=True)
    NumFiles = len(all_filenames)

    total_length = region_boundary[-1]-region_boundary[0]

    region_idx = 0
    df_region = [[] for dummy in range(len(all_filenames))]
    Heights = np.zeros(NumFiles)
    for df_region_path in all_filenames:
        df_region[region_idx] = pd.read_csv(df_region_path, sep = '\t',
                                            names = ['name', 'left_start', 'left_end', 'GEM_ID',
                                                    'Fragment_number','???','mid_frags', 'right_start',
                                                     'right_end'])

        df_region[region_idx]['frag_coord_filtered_array'] = None
        for i in range(len(df_region[region_idx])):
#             ipdb.set_trace()
            df_region[region_idx].at[i,'frag_coord_filtered_array'] = get_list_of_frags(df_region[region_idx],i)

        Heights[region_idx] = max(len(np.arange(len(df_region[region_idx]['frag_coord_filtered_array']))[::-1])* 0.05+0.1,0.25)

        fig, ax = plt.subplots(1, 1,figsize = (1, Heights[region_idx]))
        Num_frags = plot_each_block(df_region[region_idx]['frag_coord_filtered_array'],fig,ax,total_length,Colorcode,sorted_by_len = False)
        ax.set_xlim(xmin=region_boundary[0], xmax=region_boundary[-1])
        ax.set_xticks([region_boundary[0],region_boundary[-1]])
        ax.set_xticklabels([region_boundary[0],region_boundary[-1]],fontsize=4)

        MidName = all_filenames[region_idx].split('/')[-1].split('_')[-1][2:-4]
        Title = title+'_M-'+str(MidName)+'_'+str(int(Num_frags))
        ax.set_title(Title, fontsize = 10)
        plt.savefig(saveplotpath+'{}.pdf'.format(Title), bbox_inches='tight')

        region_idx += 1
        try:
            plt.savefig(saveplotpath+'{}.pdf'.format(Title), bbox_inches='tight')
            if not silent:
                plt.show()
            plt.close()
        except:
            plt.savefig(saveplotpath+'{}.pdf'.format(Title), bbox_inches='tight')
            if not silent:
                plt.show()
            plt.close()
# #     This is for single plot
#     fig, ax = plt.subplots(NumFiles, 1, sharex= True,
#                            figsize = (NumFiles, np.sum(Heights)),
#                            gridspec_kw={'height_ratios': Heights})

#     Num_frags = np.zeros(len(all_filenames))
#     for region_idx in range(len(all_filenames)):
#         Num_frags[region_idx] = plot_each_block(df_region[region_idx]['frag_coord_filtered_array'],fig,ax[region_idx],total_length,sorted_by_len = False)

#     ax[0].set_xticks([region_boundary[0],region_boundary[-1]])
#     ax[0].set_xticklabels([region_boundary[0],region_boundary[-1]],fontsize=4)

#     title = title+'_anchcomp_'+str(int(np.sum(Num_frags[0:3])))+'_M-'+str(int((len(Num_frags)-3)/2))+'_'+str(int(np.sum(Num_frags[3:])))
#     ax[0].set_title(title, fontsize = 10)
#     fig.subplots_adjust(hspace=0)
# #     plt.savefig('Minji_data/Cohesin_results/01ALL/4kbext_dm/Plots/{}.png'.format(title),
# #                 dpi = 600, bbox_inches='tight')
#     plt.savefig(saveplotpath+'{}.png'.format(title),dpi = 600, bbox_inches='tight')

#     if not silent:
#         plt.show()
#     plt.close()

    return None

def fn(regionfilepath):
    regionfile = pd.read_csv(regionfilepath,sep = '\t',header=None)
    region_boundary = np.array(regionfile.iloc[0][1:3]).astype(int)
    cr_id = regionfile.iloc[0][3]
    cr_id = cr_id[:-3]
    title = cr_id
    bedfilepath = bedfiledir+cr_id+'_'
    region_plot(region_boundary,bedfilepath,bedfiledir2, saveplotpath,title, silent = True)
#     region_plot_2sides(region_boundary,bedfilepath, saveplotpath,title, silent = True)

    return None

def mainplotfunc(bedfiledir,bedfiledir2,saveplotpath,regionfiledir,Multithread=20,MaxCr=3015):
#     bedfiledir: path for 1 side sorted GEMs files. i.e. './bedfiles/'
#     bedfiledir: path for 2 side sorted GEMs files. i.e. './2sides_bedfiles/'
#     saveplotpath: path to save plots. i.e. './Plots/'
#     regionfiledir: path of processed region_cr files.
#     Multithread: number of multithreading
#     MaxCr: maximum number of cr_id

    regionfilelist = [i for i in glob.glob(regionfiledir+'Region_cr*')]
    with Pool(Multithread) as p:
        r = list(tqdm(p.imap(fn, regionfilelist), total = MaxCr-1))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--bedfiledir',type = str)
    parser.add_argument('--bedfiledir2',type = str)
    parser.add_argument('--saveplotpath',type = str)
    parser.add_argument('--regionfiledir',type = str)

    parser.add_argument('--Multithread',type = int)
    parser.add_argument('--MaxCr',type = int)
    args = parser.parse_args()

    bedfiledir = args.bedfiledir
    bedfiledir2 = args.bedfiledir2
    saveplotpath = args.saveplotpath
    regionfiledir = args.regionfiledir
    Multithread = args.Multithread
    MaxCr = args.MaxCr

    mainplotfunc(bedfiledir,bedfiledir2,saveplotpath,regionfiledir,Multithread,MaxCr)


#creating a contact book that connects to sqlite3 using the python sqlite API
#lets you see all contacts, see specific ones, update contacts, add new contacts, delete old contacts, delete all contacts
#everytime an action is done, user is returned to main 'screen' and is asked what to do next -- while loop
#when done, remember to close connection() object

import os
import sqlite3
from sqlite3 import Error

def create_connection(db_file):
    """creates sqlite Connection() object
    :param db_file: database file """

    conn = None

    try:
        conn = sqlite3.connect(db_file)
        print(sqlite3.version)

    except:
        print('something')

    return conn

def create_table(conn, new_table_sql):
    """ creates a new table using CREATE TABLE
    :param conn: Connection object
    :param new_table_sql: CREATE TABLE statement """

    cur = conn.cursor()
    cur.execute(new_table_sql)
    conn.commit()

def add_contact(conn, contact_info):
    """adds a row to the contacts table using INSERT INTO
    conn: Connection object
    contact_info: tuple of values """

    sql = """ INSERT INTO contacts (name, email, phone, address) VALUES (?, ?, ?, ?) """
    cur = conn.cursor()
    cur.execute(sql, contact_info)
    conn.commit()
    print("\nAdded new contact")

def update_contact_column(conn, row_id, column_id, contact_info):
    """updates a column value of a specific row
    conn: connection object
    row_id: row ID number
    column_id: column name string
    contact_info: new value to update with
    """

    sql = """ UPDATE contacts
              SET """ + column_id + """ = ?
              WHERE id = ? """
    cur = conn.cursor()
    cur.execute(sql, (contact_info, row_id))
    conn.commit()
    print("\nUpdated %s of row %d" % (column_id, row_id))

def update_entire_contact(conn, contact_info):
    """updates an entire row
    conn: connection object
    contact_info: tuple of new values - must also include row ID at the end """

    sql = """ UPDATE contacts
              SET name = ?, email = ?, phone = ?, address = ?
              WHERE id = ? """
    cur = conn.cursor()
    cur.execute(sql, contact_info)
    conn.commit()
    print("\nUpdated row")

def delete_contact(conn, row_id):
    """deletes a row using DELETE FROM
    conn: connection object
    row_id: row ID number """

    sql = """ DELETE FROM contacts WHERE id = ? """
    cur = conn.cursor()
    cur.execute(sql, (row_id,))
    conn.commit()
    print("\nDeleted row %d" % row_id)

def delete_all_contacts(conn):
    """deletes all rows using DELETE FROM
    conn: connection object """

    sql = """ DELETE FROM contacts """
    cur = conn.cursor()
    cur.execute(sql)
    conn.commit()
    print("\nDeleted all contacts")

def view_all_contacts(conn):
    """prints full contact list using SELECT
    conn: connection object """

    sql = """ SELECT * FROM contacts """
    cur = conn.cursor()
    cur.execute(sql)
    rows = cur.fetchall()

    print("\nPrinting all contacts: \n")
    for row in rows:
        print(row)

def view_contact(conn, row_id):
    """printing specific row using SELECT
    conn: connection object
    row_id: row ID number """

    sql = """ SELECT * FROM contacts WHERE id = ? """
    cur = conn.cursor()
    cur.execute(sql, (row_id,))
    rows = cur.fetchall()

    print("\nPrinting contact #%d" % row_id)
    for row in rows:
        print(row)

def main():

    db_path = os.path.join(os.path.expanduser('~'), 'Desktop', 'SQLite', 'demobase.db')
    new_table_sql = """ CREATE TABLE IF NOT EXISTS contacts (
                        id INTEGER PRIMARY KEY,
                        name TEXT NOT NULL,
                        email TEXT,
                        phone TEXT,
                        address TEXT ); """
    conn = create_connection(db_path)
    create_table(conn, new_table_sql)

    print("Welcome to your contact book! What would you like to do?\n")

    while True:
        print("\n---------------------------------------")
        print("\n1. View all contacts 2. View one contact 3. Add a contact 4. Update an entire contact 5. Update a value of a preexisting contact 6. Delete a contact 7. Delete all contacts\n")
        user_input = input("? ")

        if user_input == "1":
            view_all_contacts(conn)

            print("\nDone? (Y/N) ")
            user_done = input()

            if user_done == "Y" or user_done == "y":
               break
            else:
                continue

        if user_input == "2":
            print("\nWhich row would you like to see?")
            row_id = int(input("Row # "))
            view_contact(conn, row_id)

            print("\nDone? (Y/N) ")
            user_done = input()
            if user_done == "Y" or user_done == "y":
               break
            else:
                continue

        if user_input == "3":
            con_name = input("Name? ")
            con_email = input("Email? ")
            con_phone = input("Phone number? ")
            con_address = input("Address? ")

            contact_info = (con_name, con_email, con_phone, con_address)
            add_contact(conn, contact_info)

            print("\nDone? (Y/N) ")
            user_done = input()
            if user_done == 'Y' or user_done == 'y':
                break
            else:
                continue

        if user_input == "4":
            con_id = int(input("Contact ID? "))
            con_name = input("Name? ")
            con_email = input("Email? ")
            con_phone = input("Phone number? ")
            con_address = input("Address? ")

            contact_info = (con_name, con_email, con_phone, con_address, con_id)
            update_entire_contact(conn, contact_info)

            print("\nDone? (Y/N) ")
            user_done = input()
            if user_done == 'Y' or user_done == 'y':
                break
            else:
                continue

        if user_input == "5":
            con_id = int(input("Contact ID? "))
            column_name = input("Which column would you like to update? (name, phone, email, address) ")
            new_value = input("New value? ")

            update_contact_column(conn, con_id, column_name, new_value)

            print("\nDone? (Y/N) ")
            user_done = input()
            if user_done == 'Y' or user_done == 'y':
                break
            else:
                continue

        if user_input == "6":
            con_id = int(input("Contact ID? "))

            confirm = input("Are you sure you want to delete contact #%d? (Y/N)" % con_id)
            if confirm == "y" or confirm == "Y":
                delete_contact(conn, con_id)

            else:
                print("Backing out.")

            print("\nDone? (Y/N) ")
            user_done = input()
            if user_done == 'Y' or user_done == 'y':
                break
            else:
                continue

        if user_input == "7":
            confirm = input("Are you sure you want to delete ALL contacts? (Y/N)")
            if confirm == "y" or confirm == "Y":
                delete_all_contacts(conn)

            else:
                print("Backing out.")

            print("\nDone? (Y/N) ")
            user_done = input()
            if user_done == 'Y' or user_done == 'y':
                break
            else:
                continue

    conn.close()
if __name__ == "__main__":
    main()


import bs4
import json
import string
from urllib.request import urlopen,Request
from bs4 import BeautifulSoup as soup

# class untuk membuat tuple dalam bentuk json
class Result:
    def __init__(self, scr_id, product_id, name, label, category, subcategory,real_price,sale_price):
        self.id = scr_id
        self.product_id = product_id
        self.name = name
        self.label = label
        self.category = category
        self.subcategory = subcategory
        self.real_price = real_price
        self.sale_price = sale_price

    def getJson(self):
        return {
            "id": self.id,
            "product_id": self.product_id,
            "name": self.name,
            "label": self.label,
            "category": self.category,
            "subcategory": self.subcategory,
            "real_price": self.real_price,
            "sale_price":self.sale_price
        }

# fungsi untuk mengumpulkan link2 untuk setiap kategori koleksi
def getNav(cat_container):
    # barang-barang new in
    new_in = cat_container.find("li", {"class" : "_category-link-wrapper menu-item menu-item--level-2 menu-item--is-leaf"})
    newin_atag = new_in.find("a", {"class" : "_category-link menu-item__category-link"})
    newin_link = newin_atag.get("href")
    navigators.append(newin_link)

    collection = cat_container.find("li", {"class" : "_category-link-wrapper menu-item menu-item--level-2 menu-item--current _displayUnfolded"})

    # untuk koleksi tanpa subkategori
    links = collection.find_all("li", {"class": "_category-link-wrapper menu-item menu-item--level-3 menu-item--is-leaf"})
    for i in range(len(links)):
        atag = links[i].find("a", {"class" : "_category-link menu-item__category-link"})
        if(atag):
            navigator = atag.get("href")
        else:
            navigator = "None"
        if(navigator!="None" and navigator and navigator not in navigators):
            navigators.append(navigator)

    # untuk koleksi dengan subkategori
    links = collection.find_all("li", {"class": "_category-link-wrapper menu-item menu-item--level-3"})
    for i in range(len(links)):
        subcat_ultag = links[i].find("ul", {"class" : "_subcategories subcategory-menu subcategory-menu--level-3"})
        subcats = subcat_ultag.find_all("li", {"class" : "_category-link-wrapper menu-item menu-item--level-4 menu-item--is-leaf"})
        for j in range(len(subcats)):
            subcat_name = subcats[j].get("data-name")
            if(subcat_name!="Lihat Semua"):
                subcat_atag = subcats[j].find("a", {"class" : "_category-link menu-item__category-link"})
                subcat_navigator = subcat_atag.get("href")
                subcat_navigator_2 = subcat_atag.get("data-href")
                if(subcat_navigator):
                    navigators.append(subcat_navigator)
                elif(subcat_navigator_2):
                    navigators.append(subcat_navigator_2)

    return navigators

# fungsi untuk mendapatkan kategori dan subkategori
def getCategory(cat_container):
    # barang-barang new in
    new_in = cat_container.find("li", {"class" : "_category-link-wrapper menu-item menu-item--level-2 menu-item--is-leaf"})
    cat_name = new_in.get("data-name")
    cat_tuple = (cat_name, "None")
    categories.append(cat_tuple)

    collection = cat_container.find("li", {"class" : "_category-link-wrapper menu-item menu-item--level-2 menu-item--current _displayUnfolded"})
    # untuk koleksi tanpa subkategori
    links = collection.find_all("li", {"class": "_category-link-wrapper menu-item menu-item--level-3 menu-item--is-leaf"})
    for i in range(len(links)):
        cat_name = links[i].get("data-name")
        if(cat_name!="Lihat Semua"):
            cat_tuple = (cat_name,"None")
            categories.append(cat_tuple)

    # untuk koleksi dengan subkategori
    links = collection.find_all("li", {"class": "_category-link-wrapper menu-item menu-item--level-3"})
    for i in range(len(links)):
        cat_name = links[i].get("data-name")
        subcat_ultag = links[i].find("ul", {"class" : "_subcategories subcategory-menu subcategory-menu--level-3"})
        subcats = subcat_ultag.find_all("li", {"class" : "_category-link-wrapper menu-item menu-item--level-4 menu-item--is-leaf"})
        for j in range(len(subcats)):
            subcat_name = subcats[j].get("data-name")
            if(subcat_name!="Lihat Semua"):
                cat_tuple = (cat_name,subcat_name)
                categories.append(cat_tuple)

    return categories

# mendapatkan HTML body dari page myurl
def getBody(myurl):
    headers = {'User-Agent': 'Chrome/5.0'}
    uClient = Request(myurl, headers=headers)
    page_html = urlopen(uClient).read()
    page_soup = soup(page_html,"html.parser")
    body = page_soup.body
    return body

# mendapatkan data koleksi wanita
def getData(navigators, categories):
    #menyimpan seluruh data barang
    data = []
    # menandakan sekarang sedang memparsing page categori yang mana
    cat_now = 0
    # jumlah produk / ID pada tuple json
    num_product = 1;
    for page in navigators:
        # print(cat_now, page)
        container = getBody(page)
        wraps = container.find_all("div",{"class":"_groups-wrap"})
        ultag = wraps[0].find("ul")
        litags = ultag.find_all("li")
        i=0
        for i in range(len(litags)):
            # get kode produk
            id = litags[i].get("id")
            product_info = litags[i].find("div", {"class": "product-info _product-info"})
            if(product_info):
                product_label = product_info.find("div", {"class" : "product-info-item product-info-item-label"})
                # get label produk
                if(product_label):
                    label = product_label.text
                else:
                    label = "None"
                product_name = product_info.find("a", {"class" : "name _item"})
                # get nama produk
                if(product_name):
                    name_temp = product_name.text
                    name_clean = name_temp.replace('\'', '')
                    name = name_temp.replace('\xa0', '')
                product_main_price = product_info.find("span", {"class" : "main-price"})
                # get harga barang ada 2 kasus
                # kasus 1 : bukan barang sale
                if(product_main_price):
                    main_price = product_main_price.get("data-price")
                    main_price_2 = main_price.replace(' IDR', '')
                    new_main_price = main_price_2.replace('.','')
                    # harga diskon kosong
                    new_price_sale = -1
                    res = Result(num_product, id, name, label, categories[cat_now][0], categories[cat_now][1] , int(new_main_price),int(new_price_sale))
                    data.append(res.getJson())
                    num_product+=1
                # kasus 2 : barang sale
                else:
                    product_main_price = product_info.find("span", {"class" : "line-through"})
                    product_price_sale = product_info.find("span", {"class" : "sale"})
                    # harga asli
                    if(product_main_price):
                        main_price = product_main_price.get("data-price")
                        main_price_2 = main_price.replace(' IDR', '')
                        new_main_price = main_price_2.replace('.','')
                    # harga diskon
                    if(product_price_sale):
                        price_sale = product_price_sale.get("data-price")
                        price_sale_2 = price_sale.replace(' IDR', '')
                        new_price_sale = price_sale_2.replace('.','')
                    res = Result(num_product, id, name, label, categories[cat_now][0], categories[cat_now][1] ,int(new_main_price),int(new_price_sale))
                    data.append(res.getJson())
                    num_product+=1
            i+=1
        cat_now+=1
    with open('../data/zara_women.json', 'w') as fp:
        fp.write(json.dumps(data, indent = 2))

# ------------------ Main Program ---------------------
# menyimpan link navigator untuk menuju page yang sesuai kategori
navigators = []
# menyimpan kategori dan subkategori barang dengan format tuple(kategori, subkategori)
categories = []

myurl = 'https://www.zara.com/id/id/woman-special-prices-l1314.html?v1=1446216'
container = getBody(myurl)
women_container = container.find("div",{"class" : "_container-nav navigation-menu"})
cat_container = women_container.find("li", {"class": "_category-link-wrapper menu-item menu-item--level-1 menu-item--current"})
navigators = getNav(cat_container)
categories = getCategory(cat_container)
print("please wait...")
getData(navigators, categories)
print("done!")


f_open = open("num_4_1.txt", "r", encoding="utf-8")
z_open = open("num_4_2.txt", "w", encoding="utf-8")
lines = f_open.readlines()
numbs = ['Один', 'Два', 'Три', 'Четыре']
for idx in range(len(lines)):
    lines[idx] = lines[idx].split()
    lines[idx][0] = numbs[idx]
for idx_1 in range(len(lines)):
    lines[idx_1] = ' '.join(lines[idx_1]) + '\n'

print(lines)
z_open.writelines(lines)
f_open.close()
z_open.close()


import os
import pickle
from collections import OrderedDict
import random
import glob

import pandas as pd
from dgllife.utils import smiles_to_bigraph, CanonicalAtomFeaturizer
import dgl
import numpy as np
import torch
from rdkit import Chem
from rdkit.Chem.rdmolops import GetAdjacencyMatrix
import networkx as nx
from Bio.PDB import *
import deepchem
import pickle

random.seed(0)

pk = deepchem.dock.ConvexHullPocketFinder()

def one_of_k_encoding(x, allowable_set):
    if x not in allowable_set:
        raise Exception("input {0} not in allowable set{1}:".format(x, allowable_set))
    # print list((map(lambda s: x == s, allowable_set)))
    return list(map(lambda s: x == s, allowable_set))

def one_of_k_encoding_unk(x, allowable_set):
    """Maps inputs not in the allowable set to the last element."""
    if x not in allowable_set:
        x = allowable_set[-1]
    return list(map(lambda s: x == s, allowable_set))

def atom_feature(atom):
    return np.array(one_of_k_encoding_unk(atom.GetSymbol(),
                                          ['C', 'N', 'O', 'S', 'F', 'P', 'Cl', 'Br', 'B', 'H']) +
                    one_of_k_encoding(atom.GetDegree(), [0, 1, 2, 3, 4, 5, 6, 7, 8]) +
                    one_of_k_encoding_unk(atom.GetTotalNumHs(), [0, 1, 2, 3, 4]) +
                    one_of_k_encoding_unk(atom.GetImplicitValence(), [0, 1, 2, 3, 4, 5]) +
                    [atom.GetIsAromatic()])  # (10, 6, 5, 6, 1) --> total 28

def get_atom_feature(m):
    H = []
    for i in range(len(m)):
        H.append(atom_feature(m[i][0]))
    H = np.array(H)

    return H

def process_protein(pdb_file):
    m = Chem.MolFromPDBFile(pdb_file)
    am = GetAdjacencyMatrix(m)
    pockets = pk.find_pockets(pdb_file)
    n2 = m.GetNumAtoms()
    c2 = m.GetConformers()[0]
    d2 = np.array(c2.GetPositions())
    binding_parts = []
    not_in_binding = [i for i in range(0, n2)]
    constructed_graphs = []
    for bound_box in pockets:
        x_min = bound_box.x_range[0]
        x_max = bound_box.x_range[1]
        y_min = bound_box.y_range[0]
        y_max = bound_box.y_range[1]
        z_min = bound_box.z_range[0]
        z_max = bound_box.z_range[1]
        binding_parts_atoms = []
        idxs = []
        for idx, atom_cord in enumerate(d2):
            if x_min < atom_cord[0] < x_max and y_min < atom_cord[1] < y_max and z_min < atom_cord[2] < z_max:
                binding_parts_atoms.append((m.GetAtoms()[idx], atom_cord))
                idxs.append(idx)
                if idx in not_in_binding:
                    not_in_binding.remove(idx)

        ami = am[np.array(idxs)[:, None], np.array(idxs)]
        H = get_atom_feature(binding_parts_atoms)
        g = nx.convert_matrix.from_numpy_matrix(ami)
        graph = dgl.DGLGraph(g)
        graph.ndata['h'] = torch.Tensor(H)
        graph = dgl.add_self_loop(graph)
        constructed_graphs.append(graph)
        binding_parts.append(binding_parts_atoms)

    constructed_graphs = dgl.batch(constructed_graphs)

    return binding_parts, not_in_binding, constructed_graphs

node_featurizer = CanonicalAtomFeaturizer(atom_data_field='h')

zero = np.eye(2)[1]
one = np.eye(2)[0]

protein_to_pdb = {}
with open("InterpretableDTIP-master/IBM_BindingDBuniprotPdb.txt", 'r') as fp:
    raw = fp.read()

for item in raw.split("\n")[1:-1]:
    data = item.split(",")
    protein_to_pdb[data[0].strip()] = data[1].strip()[0:4]

ligand_id_to_smile_train = {}
with open("InterpretableDTIP-master/data/train/chem.repr", 'r') as fp:
    raw = fp.read().split('\n')

with open("InterpretableDTIP-master/data/train/chem", 'r') as fp:
    raw_id = fp.read().split('\n')

for idx, smile in zip(raw_id, raw):
    ligand_id_to_smile_train[idx] = smile

with open("InterpretableDTIP-master/data/train/edges.neg", 'r') as fp:
    raw = fp.read().split('\n')

with open("InterpretableDTIP-master/data/train/edges.pos", 'r') as fp:
    raw2 = fp.read().split('\n')

raw = [(a, 0) for a in raw]
raw2 = [(a, 1) for a in raw2]
raw_all = raw + raw2
random.shuffle(raw_all)
previous_pdb = ''
#count = len(raw_all)
#raw_all_new = raw_all[int(8 * len(raw_all)/10):]
count = len(raw_all)
for j in range(10, 12):
    i = 1
    negative_train = []
    for item in raw_all[int(j * len(raw_all)/12):int((j+1) * len(raw_all)/12)]:
        print(f"{j}: {i}/{count/12}")
        try:
            a = item[0].split(',')
            smile = ligand_id_to_smile_train[a[1]]
            pdb_code = protein_to_pdb[a[3]]
            if pdb_code != '5veu':
                if previous_pdb != pdb_code:
                    pdbl = PDBList()
                    pdbl.retrieve_pdb_file(
                        pdb_code, pdir='./pdbs/', overwrite=True, file_format="pdb"
                    )
                    # Rename file to .pdb from .ent
                    os.rename(
                        './pdbs/' + "pdb" + pdb_code + ".ent", './pdbs/' + pdb_code + ".pdb"
                    )
                    # Assert file has been downloaded
                    assert any(pdb_code in s for s in os.listdir('./pdbs/'))
                    print(f"Downloaded PDB file for: {pdb_code}")
                    _, _, constructed_graphs = process_protein(f"./pdbs/{pdb_code}.pdb")

                    previous_pdb = pdb_code

                g = smiles_to_bigraph(smile, node_featurizer=node_featurizer)
                g = dgl.add_self_loop(g)
                negative_train.append(((constructed_graphs, g), item[1]))

        except Exception as e:
            print(e)
            continue
        i += 1
    with open(f"ibm_bindingdb_train_{j}.pkl", 'wb') as fp:
        pickle.dump(negative_train, fp)


import sqlite3

connection = sqlite3.connect('calenderApp.db', check_same_thread=False)
cursor = connection.cursor()
cursor.execute(
    """
  CREATE TABLE heures(id INTEGER PRIMARY KEY AUTOINCREMENT,
  matricule VARCHAR(6),
  date_publication TEXT,
  duree INTEGER
  );
  """
)
connection.commit()
cursor.close()
connection.close()


import tkinter as tk
#import center as ct

class opening:
    def __init__(self, windows):
        self.windows = windows
        self.windows.title("opening")
        self.windows.overrideredirect(1)
        self.windows.geometry("1000x200")
        self.windows.resizable(False, False)
        self.windows.configure(bg = "black")
        #self.windows

        #insertion du texte d ' opening dans la fenetre
        self.frame1 = tk.Frame(self.windows, bd=0, relief=tk.SUNKEN,  width=100, height=100)
        self.label1 = tk.Label(self.frame1, fg="red", text="Welcome To The Reservation App")
        self.label1.config(font = ('times new roman', 40),bg = "black")
        self.frame1.pack(expand=True)
        self.label1.pack(expand=True)

    def center(self):
        w = 1000
        h = 200

        # Gets both half the screen width/height and window width/height
        x = (self.windows.winfo_screenwidth() // 2) - (w // 2)
        y = (self.windows.winfo_screenheight() // 2) - (h // 2)

            # Positions the window at the desired location
        self.windows.geometry(f'{w}x{h}+{x}+{y}')


#!Python 3

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import bs4 as bs

#create webdriver
#driver = webdriver.Chrome(r"C:\Users\CommandCenter\AppData\Local\Programs\Python\Python36-32\chromedriver.exe")
driver = webdriver.Chrome(r"C:\Program Files\Python\Python36\chromedriver.exe")

#navigate to careers webpage
driver.get('https://www.amazon.com/s/page=1&keywords=cashews')

pageHTML = driver.find_element_by_tag_name('html')
pageHTML = pageHTML.get_attribute('innerHTML')
soup = bs.BeautifulSoup(pageHTML, 'lxml')
container = soup.find("ul", {"id": "s-results-list-atf"})
i = 1
for row in container.findAll("div", {"class": "a-fixed-left-grid-inner"}):
    itemName = row.find("h2").text
    try:
        itemWholePrice = row.find("span", {"class": "sx-price-whole"}).text
        itemFractionalPrice = row.find("sup", {"class": "sx-price-fractional"}).text
    except:
        itemWholePrice = "Missing"
        itemFractionalPrice = "Missing"

    print(itemName)
    print(str(itemWholePrice) + "." + str(itemFractionalPrice))

driver.quit()


#!/usr/bin/python3
"""Using and API and work in Json
"""
import json
import requests
import sys

if __name__ == "__main__":
    """working on an API
    """
    dict_to_json = {}
    new_list = []
    # get user and extrac his/her username
    response = requests.get('https://jsonplaceholder.typicode.com/users/{}'
                            .format(sys.argv[1]))
    get_user = response.json()
    username = get_user.get('username')

    # get Completed and title
    new_reponse = requests.get('https://jsonplaceholder.typicode.com/todos/\
?userId={}'.format(sys.argv[1]))
    get_task = new_reponse.json()

    with open('{}.json'.format(sys.argv[1]), mode="w") as File_json:
        for item in get_task:
            new_dict = {}
            new_dict['task'] = item.get('title')
            new_dict['completed'] = item.get('completed')
            new_dict['username'] = username
            new_list.append(new_dict)

        dict_to_json["{}".format(sys.argv[1])] = new_list
        json.dump(dict_to_json, File_json)


dic = {
    "ZRO" : 0,
    "ONE" : 1,
    "TWO" : 2,
    "THR" : 3,
    "FOR" : 4,
    "FIV" : 5,
    "SIX" : 6,
    "SVN" : 7,
    "EGT" : 8,
    "NIN" : 9,
}
T = int(input())
for tc in range(1, T + 1):
    input()
    words = input().split()
    words.sort(key=lambda x:dic[x])
    print(f'#{tc}\n{" ".join(words)}')


# 1차 셔틀 버스
import datetime

def solution(n, t, m, timetable):
    for miniute in range(1, 60*24 + 1):
        bus_tickets = []
        r = []
        for _t in timetable:
            r.append((datetime.time.fromisoformat(_t), 0))

        con_time = (datetime.datetime.min + datetime.timedelta(hours=24, minutes= -miniute)).time()
        r.append((con_time, 1))
        r = sorted(r)

        for i in range(n):
            a = datetime.timedelta(hours=9, minutes=t * i)
            for j in range(m):
                bus_tickets.append((datetime.datetime.min + a).time())

        for ticket in bus_tickets:
            if ticket >= r[0][0]:
                temp = r.pop(0)
                if temp[1] == 1:
                    return temp[0].isoformat(timespec='minutes')

n = 1
t = 1
m = 5
timetable = ["08:00", "08:01", "08:02", "08:03"]
answer = "09:00"
result = solution(n, t, m, timetable)
print(result)

n = 2
t = 10
m = 2
timetable = ["09:10", "09:09", "08:00"]
answer = "09:09"
result = solution(n, t, m, timetable)
print(result)

n = 2
t = 1
m = 2
timetable = ["09:00", "09:00", "09:00", "09:00"]
answer = "08:59"
result = solution(n, t, m, timetable)
print(result)

n = 1
t = 1
m = 5
timetable = ["00:01", "00:01", "00:01", "00:01", "00:01"]
answer = "00:00"
result = solution(n, t, m, timetable)
print(result)

n = 1
t = 1
m = 1
timetable = ["23:59"]
answer = "09:00"
result = solution(n, t, m, timetable)
print(result)

n = 10
t = 60
m = 45
timetable = ["23:59","23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59"]
answer = "18:00"
result = solution(n, t, m, timetable)
print(result)


import cv2
import numpy as np

cam = cv2.VideoCapture(0)

EVT=0
start_point=(0,0)
RDown=0
LDown=0

def draw_rectangle(event,x,y,flags,param):
    global EVT
    global PNT
    if event == cv2.EVENT_LBUTTONDOWN:
        EVT = cv2.EVENT_LBUTTONDOWN
        PNT = (x, y)
    if event == cv2.EVENT_LBUTTONUP:
        EVT = cv2.EVENT_LBUTTONUP
        PNT = (x, y)
    if event == cv2.EVENT_RBUTTONDOWN:
        EVT = cv2.EVENT_RBUTTONDOWN
    if event == cv2.EVENT_RBUTTONUP:
        EVT = cv2.EVENT_RBUTTONUP
        cv2.destroyWindow('image_ROI')

while True:
    _, img=cam.read()
    imgOriginal = img
    cv2.imshow('MBS3523',img)
    cv2.setMouseCallback('MBS3523', draw_rectangle)

    if EVT == cv2.EVENT_LBUTTONDOWN:
        start_point=PNT

    if EVT == cv2.EVENT_LBUTTONUP:
        cv2.rectangle(img, start_point, PNT, (255, 0, 0), 3)
        imgBound = img[start_point[1]:PNT[1], start_point[0]:PNT[0]]
        cv2.imshow('image_ROI', imgBound)
        LDown=1

    if EVT == cv2.EVENT_RBUTTONDOWN:
        RDown=1

    if EVT == cv2.EVENT_RBUTTONUP & RDown==1:
        if LDown==1:
            LDown=0
        img = imgOriginal
        RDown=0

    cv2.imshow('MBS3523', img)

    if cv2.waitKey(20) & 0xff == 27:
            break

capture.release()
cv2.destroyAllWindows()


from scene import Scene

import numpy as np
import torch
import _pickle as pickle
import copy
import cv2
import os
import time

start_time = time.time()
all_data = []

def cache_frames(ann,output_directory):

    # for each frame idx
    for f_idx in range (2700):

        if len(ann.data[f_idx]) == 0: # past last frame
            break

        # for each camera

        for c_idx in range(len(ann.cameras)):
            cam_frame_annotations = []

            camera = ann.cameras[c_idx]
            cam_name = ann.cameras[c_idx].name

            # get set of objects labeled within that camera
            ts_data = list(ann.data[ann.frame_idx].values())
            ts_data = list(filter(lambda x: x["camera"] == camera.name,ts_data))

            if len(ts_data) == 0:
                continue
            ids = [item["id"] for item in ts_data]
            if len(ts_data) > 0:
                boxes = torch.stack([torch.tensor([obj["x"],obj["y"],obj["l"],obj["w"],obj["h"],obj["direction"]]).float() for obj in ts_data])

                # convert into image space
                im_boxes = ann.hg.state_to_im(boxes,name = camera.name)

            for i in range (len(ts_data)):
                # for each object, append the image-space box to the ts_data annotation
                ts_data[i]["im_box"] = im_boxes[i]
                ts_data[i]["box"] = boxes[i]
                ts_data[i]["frame_idx"] = f_idx
                if "gen" not in ts_data[i].keys(): ts_data[i]["gen"] = "Manual"
                cam_frame_annotations.append(ts_data[i])

            # generate image path
            im_directory = "{}/im".format(output_directory)
            if not os.path.exists(im_directory):
                    os.mkdir(im_directory)
            scene_directory = "{}/im/scene_{}".format(output_directory,ann.scene_id)
            if not os.path.exists(scene_directory):
                    os.mkdir(scene_directory)
            cam_directory   = "{}/im/scene_{}/{}".format(output_directory,ann.scene_id,cam_name)
            if not os.path.exists(cam_directory):
                    os.mkdir(cam_directory)

            im_path = "{}/{}.png".format(cam_directory,str(f_idx).zfill(4))
            if not os.path.exists(im_path):
                frame = ann.buffer[ann.buffer_frame_idx][c_idx].copy() # second item is timestamp or dummy value
                frame = cv2.resize(frame,(1920,1080))
                cv2.imwrite(im_path,frame)

            # generate label path
            lab_directory = "{}/label".format(output_directory)
            if not os.path.exists(lab_directory):
                    os.mkdir(lab_directory)
            scene_directory = "{}/label/scene_{}".format(output_directory,ann.scene_id)
            if not os.path.exists(scene_directory):
                    os.mkdir(scene_directory)
            cam_directory   = "{}/label/scene_{}/{}".format(output_directory,ann.scene_id,cam_name)
            if not os.path.exists(cam_directory):
                    os.mkdir(cam_directory)

            label_directory = "{}/label/scene_{}/{}".format(output_directory,scene_id,cam_name)
            if not os.path.exists(label_directory):
                os.mkdir(label_directory)
            lab_path = "{}/{}.cpkl".format(label_directory,str(f_idx).zfill(4))

            with open(lab_path,"wb") as f:
                pickle.dump(cam_frame_annotations,f)

            # after all objects have been  added
            all_data.append([im_path,lab_path])

        # advance cameras
        ann.next()
        if f_idx % 100 == 0:
            t_est = time.time() - start_time
            print("Cached scene {} frame {}, {} fps cache rate".format(scene_id,f_idx,f_idx/t_est))

        if f_idx > 10:
            break

    save_label_path = "{}/data_summary.cpkl".format(output_directory)
    with open(save_label_path,"wb") as f:
        pickle.dump(all_data,f)

if __name__ == "__main__":

    video_dir = "/home/worklab/Documents/I24-3D/video"
    data_dir  = "/home/worklab/Documents/I24-3D/data"
    out_dir = "/home/worklab/Documents/I24-3D/cache"

    for scene_id in [1,2,3]:
        ann = Scene(video_dir,data_dir,scene_id = scene_id)
        cache_frames(ann,output_directory = out_dir)


import torch
import numpy as np

def predict(model, dataloader, device):
    """
    :param model:
    :param dataloader:
    :param device:
    :param get_x_fun:
    :return:
    """
    model = model.to(device)

    num_elements = len(dataloader.dataset)
    num_batches = len(dataloader)

    batch_size = dataloader.batch_size

    predictions = torch.zeros(num_elements)
    true_labels = torch.zeros(num_elements)

    for i, batch in enumerate(dataloader):
        start = i * batch_size
        end = start + batch_size
        if i == num_batches - 1:
            end = num_elements

        x, y = batch
        logits = model.forward(x.to(device))
        pred = torch.argmax(logits, dim=1)
        predictions[start:end] = pred.detach()
        true_labels[start:end] = y.detach()

    return predictions, true_labels


"""add consumed column to media

Revision ID: 96d7aa4b4895
Revises: 7e43b75b7a9b
Create Date: 2017-12-21 19:54:28.613492

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '96d7aa4b4895'
down_revision = '7e43b75b7a9b'
branch_labels = None
depends_on = None

def upgrade():
    op.add_column('media', sa.Column('consumed', sa.Boolean, default=False))
    op.execute(
        """
        UPDATE media
        SET consumed = 'f';
        """
    )

def downgrade():
    op.drop_column('media', 'consumed')


from __future__ import annotations

import os
import palinka
import re
import shutil

import pkg_resources

import os, shutil

def copytree(src, dst, symlinks=False, ignore=None):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if os.path.isdir(s):
            shutil.copytree(s, d, symlinks, ignore)
        else:
            shutil.copy2(s, d)

def rec_copy(src, dest):
    if not pkg_resources.resource_isdir(__name__, src):
        src_stream = pkg_resources.resource_string(__name__, src)
        with open(dest, "wb") as dest_file:
            dest_file.write(src_stream)
    else:
        os.makedirs(dest, exist_ok=True)
        for resource in pkg_resources.resource_listdir(__name__, src):
            rec_copy(src + "/" + resource, os.path.join(dest, resource))

class ProjectGenerator:
    def __init__(self, dir_path: str):
        self.path = os.path.join(dir_path, 'palinka')
        self.libs = []

    def add_library(self, dir_path: str, name: str):
        self.libs.append((dir_path, name))
        return self

    def generate(self, raw_code: str, symbol_table: palinka.model.symbol_table.SymbolTable, plant: palinka.model.automation.Plant):
        path = self.path

        if os.path.exists(path):
            shutil.rmtree(path)

        try:
            os.makedirs(path, exist_ok=True)
            rec_copy("assets/palinka", os.path.join(path))

            for lib, libname in self.libs:
                shutil.copytree(lib, os.path.join(self.path, "libs", libname))

        except Exception as e:
            print(e)

        CodeWriter(os.path.join(path, 'src/codegen')).write(raw_code)

        with open(os.path.join(path, "symbols.xml"), "wb") as file:
            file.write(palinka.model.symbol_table.serialize(symbol_table))

        with open(os.path.join(path, "plant.xml"), "wb") as file:
            file.write(palinka.model.automation.serialize(plant))

class CodeWriter:
    BEGIN_RE = r"\/\/\/ BEGIN (FILE|DIRECTORY) (\S+([.]\s)?) \/\/\/"
    END_RE = r"\/\/\/ END (FILE|DIRECTORY) \/\/\/"

    def __init__(self, root_dir):
        self.path = [root_dir]
        self.files = []
        self.acc = []

        if os.path.exists(os.path.join(*self.path)):
            shutil.rmtree(os.path.join(*self.path))
        os.makedirs(os.path.join(*self.path))

    def begin_dir(self, dir):
        self.path.append(dir)

    def end_dir(self):
        self.path.pop(-1)

    def write(self, txt):
        for line in txt.split('\n'):
            m_begin = re.search(CodeWriter.BEGIN_RE, line)
            m_end = re.search(CodeWriter.END_RE, line)

            if m_begin:
                t_file_or_dir = m_begin.group(1)
                arg = m_begin.group(2)
                if t_file_or_dir == "FILE":
                    self.begin_file(arg)
                else:
                    self.begin_dir(arg)
            elif m_end:
                t_file_or_dir = m_end.group(1)
                if t_file_or_dir == "FILE":
                    self.end_file()
                else:
                    self.end_dir()
            else:
                self.acc.append(line)

    def begin_file(self, file):
        self.files.append(file)

    def end_file(self):
        file = self.files.pop(-1)
        path = os.path.join(*self.path, file)

        # Make directry if not
        os.makedirs(os.path.join(*self.path), exist_ok=True)

        with open(path, "w") as file:
            file.write("\n".join(self.acc))

        self.acc = []

def write(root_dir: str, code: str):
    w = CodeWriter(root_dir)

    for line in code.split('\n'):
        w.write(line)

def create_project(dest, code: str, symbol_table: palinka.model.symbol_table.SymbolTable):
    ProjectGenerator(dest).generate(code, symbol_table)


import xlrd
import matplotlib.pyplot as plt
# 打开excel表格
data_excel = xlrd.open_workbook('2.xlsx')
table = data_excel.sheets()[0]
#划定饼状图区域
b_row=11  #开始行
e_row=17  #结束行
b_col=9   #开始列
e_col=14  #结束列

#读取饼状图标签
list_values=[]
for i in range(b_row, e_row):
    row = table.row_values(i)[1]
    list_values.append(row)
# print(list_values)

#提取单元格内容
for x in range(b_col,e_col):
    values = []
    col = table.col_values(x)
    col1=table.col_values(x)[1]
    for i in range(b_row, e_row):
        values.append(col[i])
    # print(values)
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 正常显示中文标签
    labels = values
    sizes = values
    # explode = (0, 0.1, 0, 0)
    fig1, ax1 = plt.subplots()
    ax1.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=False, startangle=90)
    ax1.axis('equal')
    plt.legend(list_values,loc="upper left",bbox_to_anchor=(-0.168,0.95))
    plt.title(col1+"任务分配与经费占比情况")
    plt.savefig("C:/Users/LLLLL/Desktop/作图任务/{}任务分配与经费占比情况.png".format(col1))
    plt.show()


from data_refinery_common.models import (
    DownloaderJob,
    DownloaderJobOriginalFileAssociation,
    OriginalFile,
    ProcessorJob,
    ProcessorJobOriginalFileAssociation,
    SurveyJob,
    SurveyJobKeyValue,
)

def create_downloader_job():
    job = DownloaderJob(
        downloader_task="SRA",
        batch_job_id="DEFAULT",
        num_retries=0,
        accession_code="NUNYA",
        success=None,
    )
    job.save()

    og_file = OriginalFile()
    og_file.source_filename = "doesn't matter"
    og_file.filename = "this either"
    og_file.absolute_file_path = "nor this"
    og_file.save()

    assoc1 = DownloaderJobOriginalFileAssociation()
    assoc1.original_file = og_file
    assoc1.downloader_job = job
    assoc1.save()

    og_file = OriginalFile()
    og_file.source_filename = "doesn't matter"
    og_file.filename = "this either"
    og_file.absolute_file_path = "nor this"
    og_file.save()

    assoc = DownloaderJobOriginalFileAssociation()
    assoc.original_file = og_file
    assoc.downloader_job = job
    assoc.save()

    return job

def create_processor_job(pipeline="AFFY_TO_PCL", ram_amount=2048, start_time=None):
    og_file_1 = OriginalFile()
    og_file_1.source_filename = "doesn't matter"
    og_file_1.filename = "this either"
    og_file_1.absolute_file_path = "nor this"
    og_file_1.save()

    og_file_2 = OriginalFile()
    og_file_2.source_filename = "doesn't matter"
    og_file_2.filename = "this either"
    og_file_2.absolute_file_path = "nor this"
    og_file_2.save()

    downloader_job = None
    if pipeline == "AFFY_TO_PCL":
        downloader_job = DownloaderJob(
            downloader_task="SRA",
            batch_job_id="DEFAULT",
            num_retries=0,
            accession_code="NUNYA",
            success=None,
        )
        downloader_job.save()

        assoc = DownloaderJobOriginalFileAssociation()
        assoc.original_file = og_file_2
        assoc.downloader_job = downloader_job
        assoc.save()

        assoc1 = DownloaderJobOriginalFileAssociation()
        assoc1.original_file = og_file_1
        assoc1.downloader_job = downloader_job
        assoc1.save()

    processor_job = ProcessorJob(
        downloader_job=downloader_job,
        pipeline_applied=pipeline,
        batch_job_id="PROCESSOR/dispatch-1528945054-e8eaf540",
        ram_amount=ram_amount,
        num_retries=0,
        success=None,
        start_time=start_time,
    )
    processor_job.save()

    assoc1 = ProcessorJobOriginalFileAssociation()
    assoc1.original_file = og_file_1
    assoc1.processor_job = processor_job
    assoc1.save()

    assoc = ProcessorJobOriginalFileAssociation()
    assoc.original_file = og_file_2
    assoc.processor_job = processor_job
    assoc.save()

    return processor_job

def create_survey_job():
    job = SurveyJob(
        source_type="SRA",
        batch_job_id="SURVEYOR/dispatch-1528945054-e8eaf540",
        num_retries=0,
        success=None,
    )

    job.save()

    sjkv = SurveyJobKeyValue()
    sjkv.key = "experiment_accession_code"
    sjkv.value = "RJ-1234-XYZ"
    sjkv.survey_job = job
    sjkv.save()

    return job


import os
os.chdir('d:\\PythonLab')

panda = open('panda.txt')  # open panda.txt file
pandaContent = panda.read() # read file
panda.close()
t = pandaContent.split('. A ')
wordlist = ['ADJECTIVE', 'NOUN', 'ADVERB', 'VERB']

for i in range(len(t)):
    word = t[i].split()
    for w in word:
        if w in wordlist:
            print('Enter ' + w.lower())
            temp = input()
            word[word.index(w)] = temp
        else:
            continue
    t[i] = ' '.join(word)
t = '. A '.join(t)
print(t)

pandaNew = open('pandaNew.txt', 'w')
pandaNew.write(t)
pandaNew.close()

# =====================================================================================================================
# regular expression method
import os, re
os.chdir('d:\\PythonLab')

panda = open('panda.txt')  # open panda.txt file
pandaContent = panda.read() # read file
panda.close()

uRegex = re.compile(r'[A-Z]{2,}')
wordlist = uRegex.findall(pandaContent)
pandaContent = re.sub('[A-Z]{2,}', '%s', pandaContent)

for w in wordlist:
    if w[0].lower() in 'aeiou':
        c = 'an'
    else:
        c = 'a'
    print('Enter ' + c + ' ' + w.lower())
    temp = input()
    wordlist[wordlist.index(w)] = temp

pandaContentNew = pandaContent % tuple(wordlist)
print(pandaContentNew)

pandaNew = open('pandaNew.txt', 'w')
pandaNew.write(pandaContentNew)
pandaNew.close()


from collections import defaultdict
from sqlalchemy import delete
from sqlalchemy.sql import select

from src.main.controller.view.curricula import Curricula, Curriculas
from src.main.repository.model.curricula import CurriculaDB
from src.main.repository.config import commit_rollback, db

class CurriculaRepository:
    @staticmethod
    async def create(create_from: Curriculas):
        """create Lead data"""
        for curricula in create_from:
            for subject_id in curricula.subjects_ids:
                db.add(
                    CurriculaDB(carrer_id=curricula.carrer_id, subject_id=subject_id)
                )
        await commit_rollback()

    @staticmethod
    async def delete(carrer_id: int):
        """delete curricula data by carrer id"""

        query = delete(CurriculaDB).where(CurriculaDB.carrer_id == carrer_id)
        await db.execute(query)
        await commit_rollback()

    @staticmethod
    async def get_all() -> Curriculas:
        query = select(CurriculaDB)
        result = (await db.scalars(query)).fetchall()

        curriculas = defaultdict(list)
        for curricula in result:
            curriculas[curricula.carrer_id].append(curricula.subject_id)

        curriculas = Curriculas(
            [Curricula(carrer_id=k, subjects_ids=v) for k, v in curriculas.items()]
        )
        return curriculas


"""Dictionary are used to store collection of data with their key:value pairs.
Dictionary is ordered, changable and not allow duplicates. Dictionaries are written with
curly brackets {} and have its keys and values. we can print item value by using key ex"""

dict1={'id':101,'name':'Rajeev Kumar','salary':40000}
print(dict1)

dict1={'id':101,'name':'Rajeev Kumar','salary':40000}
print(dict1['name'])
print(len(dict1))

#get the value of dictionary using key and using get() function
dict1={'id':101,'name':'Rajeev Kumar','salary':40000}
x=dict1['name']
print(x)
y=dict1.get('id')
print(y)

#keys() method returns all the keys of a dictionary
print(dict1.keys())

#Adding items into dictionary
dict1={'id':101,'name':'Rajeev Kumar','salary':40000}
dict1['address']='Delhi'
print(dict1)

#update dictionary
dict1.update({'name':'Rakesh','pin':843323})
print(dict1)

#remove items from dictionary
dict1.pop('pin')
del(dict1['id'])
print(dict1)
dict1.clear()
print(dict1)

#Loop in dictionary

#This will show all key name of a dictionary
dict1={'id':101,'name':'Rajeev Kumar','salary':40000}
for x in dict1:
    print(x)
#OR
for x in dict1.keys():
    print(x)

#print all value of a dictionary
for x in dict1:
    print(dict1[x])
#OR
for x in dict1.values():
    print(x)

#Print all keys and values of a dictionary using items() method
for x,y in dict1.items():
    print(x,y)

#Copy a dictionary: this can be done using copy() and dict() function
dict1={'id':101,'name':'Rajeev Kumar','salary':40000}
dict2=dict1.copy()
dict3={}
print(dict2)
dict3=dict2.copy()
print(dict3)
dict4=dict(dict3)
print(dict4)

#Nested Dictionary
employee={
    'employee1':{
        'eid': 101, 'name':'Rajeev Kumar','age':32
    },
    'employee2':{
        'eid':102, 'name': 'Prakash Kumar','age':35
    },
    'employe3':{
        'eid':103,'name':'Vyom Sharma','age':45
     }
}

print(employee)

#OR we can create 3 dictionary separately and create another one dictionary which hold 3
employee1={
        'eid': 101, 'name':'Rajeev Kumar','age':32
        }
employee2={
        'eid':102, 'name': 'Prakash Kumar','age':35
        }
employe3={
        'eid':103,'name':'Vyom Sharma','age':45
        }
employee={'employee1':employee1,'employee2':employee2,'employee3':employe3}
print(employee)


from django.utils.translation import gettext_lazy as _
from rest_framework.exceptions import ValidationError

from qt_utils.model_loaders import get_outstanding_token_model, get_user_model

def user_email_not_taken_validator(email):
    User = get_user_model()
    if User.is_email_taken(email):
        raise ValidationError(
            _("An account for the email already exists."),
        )

def user_email_exists_validator(email):
    User = get_user_model()
    if not User.is_email_taken(email):
        raise ValidationError(_("No user found with this email."))

def outstanding_token_exists(refresh_token):
    OutstandingToken = get_outstanding_token_model()
    if not OutstandingToken.objects.filter(token=refresh_token).exists():
        raise ValidationError(
            _("Oustanding token not found."),
        )


from __future__ import unicode_literals
#noinspection PyUnresolvedReferences
from stat_sender.endpoint.http_endpoint_factory import HttpEndpointFactory
#noinspection PyUnresolvedReferences
from stat_sender.endpoint.https_endpoint_factory import HttpsEndpointFactory

# storage
DB_FILE = '/tmp/usagestat_test/data/usage_stat_db/usage_stat.db'

# user_identity source
USER_IDENTITY_SOURCE = '/tmp/usagestat_test/data/user.id'

# endpoint
USED_ENDPOINT = 'https'
# endpoint defs
ENDPOINTS_DEF = {'http':  {'endpoint_factory': HttpEndpointFactory,
                           'remote_host': 'http://localhost:8000/statserver/api/v1/collect/',
                           'params': {}},
                 'https': {'endpoint_factory': HttpsEndpointFactory,
                           'remote_host': 'https://localhost:8000/statserver/api/v1/collect/',
                           'params': {'cert_dest_dir': '/tmp/usagestat_test/persist_data/', 'cert_name': 'test.client.ideco.usagestat', 'lifetime_days':10, 'expiration_days':8}}}

# task execution
SEND_ATTEMPT_COUNT = 2

# logs
LOG_CONF = {
    'version': 1,
    'formatters': {'default': {'format': '%(asctime)s %(levelname)-8s %(name)-15s %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S'}},
    'filters': {},
    'handlers': {'console': {'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'default'}},
    'loggers': {'stat_sender.entry_point': {'handlers': ['console'], 'level': 'INFO', 'propagate': True}}
}

__author__ = 'andrey.ushakov'


import os
import subprocess
import sys
import argparse

import numpy as np
import mxnet as mx
import scipy.io as sio
from utils.evaluation import eval_feature

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("gpu", default=0, type=int)
    parser.add_argument("model_path", type=str)
    parser.add_argument("--distractor", action="store_true")
    args = parser.parse_args()

    model_path = args.model_path
    basename = os.path.splitext(os.path.basename(model_path))[0]
    prefix = "-".join(basename.split("-")[:-1])
    epoch_idx = int(basename.split("-")[-1])
    gpu = args.gpu
    dataset = model_path.split("/")[1]

    assert dataset in ["market", "cuhk", "duke", "msmt"]

    print("%s/%s-%d" % (dataset, prefix, epoch_idx))

    # extract feature
    cmd = "python%c -m utils.extract --prefix %s --gpu-id %d --epoch-idx %d --dataset %s" % (
        sys.version[0], prefix, gpu, epoch_idx, dataset)

    if args.distractor and dataset == "market":
        cmd += " --distractor"

    subprocess.check_call(cmd.split(" "))

    # load extracted feature
    query_features_path = 'features/%s/query-%s.mat' % (dataset, prefix)
    gallery_features_path = "features/%s/gallery-%s.mat" % (dataset, prefix)
    assert os.path.exists(query_features_path) and os.path.exists(gallery_features_path)

    query_mat = sio.loadmat(query_features_path)
    gallery_mat = sio.loadmat(gallery_features_path)

    query_features = query_mat["feat"]
    query_ids = query_mat["ids"].squeeze()
    query_cam_ids = query_mat["cam_ids"].squeeze()

    gallery_features = gallery_mat["feat"]
    gallery_ids = gallery_mat["ids"].squeeze()
    gallery_cam_ids = gallery_mat["cam_ids"].squeeze()

    eval_feature(query_features, gallery_features, query_ids, query_cam_ids, gallery_ids, gallery_cam_ids,
                 ctx=mx.gpu(args.gpu), metric="cosine")

    if args.distractor:
        for i in range(3):
            distractor_features_path = 'features/%s/distractor%d-%s.mat' % (dataset, i + 1, prefix)
            distractor_mat = sio.loadmat(distractor_features_path)

            distractor_features = distractor_mat["feat"]
            distractor_ids = distractor_mat["ids"].squeeze()
            distractor_cam_ids = distractor_mat["cam_ids"].squeeze()

            gallery_features = np.concatenate([gallery_features, distractor_features], axis=0)
            gallery_ids = np.concatenate([gallery_ids, distractor_ids], axis=0)
            gallery_cam_ids = np.concatenate([gallery_cam_ids, distractor_cam_ids], axis=0)

            eval_feature(query_features, gallery_features, query_ids, query_cam_ids, gallery_ids, gallery_cam_ids,
                         ctx=mx.gpu(i) if i < 2 else mx.cpu(), metric="cosine")

            del distractor_features
            del distractor_cam_ids
            del distractor_ids

    print("\n")

    cmd = "python%c -m post_processing.post_clustering %s %s" % (sys.version[0], dataset, prefix)
    subprocess.check_call(cmd.split(" "))


TEMPLATE = "FNFPPNKPPHSOKFFHOFOC"
INPUT = """VS -> B
SV -> C
PP -> N
NS -> N
BC -> N
PB -> F
BK -> P
NV -> V
KF -> C
KS -> C
PV -> N
NF -> S
PK -> F
SC -> F
KN -> K
PN -> K
OH -> F
PS -> P
FN -> O
OP -> B
FO -> C
HS -> F
VO -> C
OS -> B
PF -> V
SB -> V
KO -> O
SK -> N
KB -> F
KH -> C
CC -> B
CS -> C
OF -> C
FS -> B
FP -> H
VN -> O
NB -> N
BS -> H
PC -> H
OO -> F
BF -> O
HC -> P
BH -> S
NP -> P
FB -> C
CB -> H
BO -> C
NN -> V
SF -> N
FC -> F
KK -> C
CN -> N
BV -> F
FK -> C
CF -> F
VV -> B
VF -> S
CK -> C
OV -> P
NC -> N
SS -> F
NK -> V
HN -> O
ON -> P
FH -> O
OB -> H
SH -> H
NH -> V
FF -> B
HP -> B
PO -> P
HB -> H
CH -> N
SN -> P
HK -> P
FV -> H
SO -> O
VH -> V
BP -> V
CV -> P
KP -> K
VB -> N
HV -> K
SP -> N
HO -> P
CP -> H
VC -> N
CO -> S
BN -> H
NO -> B
HF -> O
VP -> K
KV -> H
KC -> F
HH -> C
BB -> K
VK -> P
OK -> C
OC -> C
PH -> H
"""
from collections import defaultdict, Counter
from tqdm import tqdm

d = defaultdict(str)
for line in INPUT.splitlines():
    pair, inserted = line.split(' -> ')
    d[pair.strip()] = inserted.strip()

def step(template: str, rules: dict) -> str:
    """performs one insertion step as described here: https://adventofcode.com/2021/day/14"""
    split = [template[i:i+2] for i in range(len(template)-1)]
    new_template = [item[0] + d[item] + item[1] for item in split]
    nt = new_template[0]
    for item in new_template[1:]:
        nt += item[1:]
    return nt

# template = TEMPLATE
# for i in tqdm(range(10)):
#     template = step(template, d)

# c = {}
# for letter in set(template):
#     c[letter] = template.count(letter)
# print(max(c.values()) - min(c.values()))

# part 2 (kudos to Flo Reichel)

# Find count of AB pairs in initial string
first_element = 'F'
c = Counter()
for idx in range(len(TEMPLATE[:-1])):
    c[TEMPLATE[idx:idx+2]] += 1

# Loop steps
for i in range(40):
    # Copy and re-initialise counter
    cc = c
    c = Counter()
    for el in cc.keys():
        # Increment counter for AX and XB
        c[el[0] + d[el]] += cc[el]
        c[d[el] + el[1]] += cc[el]

# Now count the actual elements
l = Counter()
# Add back the very first element, since the loop below will only consider the second half of each pair
l[first_element] = 1
for el, ct in c.items():
    l[el[1]] += ct

print(l.most_common()[0][1] - l.most_common()[-1][1])


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

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('system', '0012_auto_20161114_1922'),
    ]

    operations = [
        migrations.AlterField(
            model_name='condominiumfloor',
            name='name',
            field=models.CharField(max_length=32, blank=True, verbose_name='floor name'),
        ),
        migrations.AlterField(
            model_name='condominiumporch',
            name='name',
            field=models.CharField(max_length=64, default='', blank=True, verbose_name='porch name'),
            preserve_default=False,
        ),
    ]


# coding: utf-8

# In[ ]:

import rospy
from std_msgs.msg import Bool,Float32
from ackermann_msgs.msg import AckermannDriveStamped
from geometry_msgs.msg import PointStamped, Point
import numpy as np
import serial

class ServoNode(Node):
    target_theta = Param(float, default=-np.pi/2)
    target_dist = Param(float, default=.3)
    gain_theta = Param(float, default=.8)
    gain_dist = Param(float, default=-.4)

    def __init__(self):
        super(ServoNode, self).__init__()
        self.object_close = False
        self.wall_theta = None
        self.wall_dist = None
        rospy.Timer(rospy.Duration(.1), self.timer_callback)

    pub = rospy.Publisher('/racecar/ackermann_cmd_mux/input/navigation', AckermannDriveStamped, queue_size=10)
    pubServo=rospy.Publisher('/arduino/servo/steering_angle',Float32,queue_size=10)

    @Subscriber('/racecar/ackermann_cmd_mux/input/navigation', AckermannDriveStamped)
    def aduino_servo_callback(self, msg):
        self.data = msg.drive.steering_angle

    def timer_callback(self, event):
        cmd = AckermannDriveStamped()
        cmd.drive.steering_angle = 1.0
        cmd.drive.speed=0.1
        self.pubServo.publish(cmd)
        self.pub.publish(cmd)

    def on_shutdown(self):
        # Send a stop command before exiting.
        self.pub.publish(AckermannDriveStamped())

if __name__ == '__main__':
    rospy.init_node("driver_node")
    node = ServoNode()
    rospy.on_shutdown(lambda: node.on_shutdown())
    rospy.spin()


def union(nums, num):
    past = nums[num]
    while past != 0:
        num = past
        past = nums[past]
    return num

n, m = map(int, input().strip().split(" "))
edges = []
vertices = []
sum_of_weight = 0
for i in range(0, m):
    x, y, weight = map(int, input().strip().split(" "))
    edges.append([x, y, weight])
    sum_of_weight += weight
    if x not in vertices:
        vertices.append(x)
    if y not in vertices:
        vertices.append(y)

edges = sorted(edges, key=lambda x: x[2])

num_of_edge = 0
past = [0 for i in range(0, n + 1)]
tree_weight = 0
while num_of_edge != n - 1:
    edge = edges[0]
    if union(past, edge[0]) != union(past, edge[1]):
        past[max(edge[0], edge[1])] = min(edge[0], edge[1])
        tree_weight += edge[2]
        num_of_edge += 1
    del edges[0]
print(sum_of_weight - tree_weight, end="")


from datetime import datetime
from service.booking import is_room_available

def define_room(room_number:int, capacity:str, floor_number:str):
    """
    Define a room with the provided room number, capacity, and floor number.

    Args:
        room_number (int): The unique room number.
        capacity (int): The capacity of the room.
        floor_number (int): The floor number where the room is located.

    Returns:
        dict: A dictionary representing the room with room_number, capacity, and floor_number.
    """
    room = {
        "room_number" : room_number,
        "capacity" : capacity,
        "floor_number" : floor_number,
    }
    return room

def list_rooms_with_availability(all_floors, all_bookings, start_time=None, end_time=None):
    """
    List all rooms with their availability status for a specified time slot.

    Args:
        all_floors (dict): A dictionary containing information about all floors and their rooms.
        all_bookings (dict): A dictionary containing all booking information.
        start_time (datetime, optional): The start time of the time slot. Defaults to current time.
        end_time (datetime, optional): The end time of the time slot. Defaults to current time.

    Returns:
        list: A list of dictionaries representing rooms with their availability status.
    """
    if start_time is None:
        start_time = datetime.now()
    if end_time is None:
        end_time = start_time

    rooms_with_availability = []

    for floor_number, floor_info in all_floors.items():
        rooms_on_floor = floor_info.get("rooms", {})

        for room_number, room_info in rooms_on_floor.items():
            availability = is_room_available(all_bookings, floor_number, room_number, start_time, end_time)
            room_info["currently_available"] = availability
            rooms_with_availability.append({"floor_number": floor_number, "room_info": room_info})

    return rooms_with_availability


from typing import List
import collections

class Solution:
  def countCharacters(self, words: List[str], chars: str) -> int:
    result, charsCounter = 0, collections.Counter(chars)
    for word in words:
      wordCounter = collections.Counter(word)
      isValidWord = True
      for c in wordCounter:
        if c not in charsCounter or wordCounter[c] > charsCounter[c]:
          isValidWord = False
          break
      if isValidWord:
        result += len(word)
    return result

words = ["cat","bt","hat","tree"]
chars = "atach"
s = Solution()
result = s.countCharacters(words, chars)
print(result)


import pdb

def add():
    i = 3
    j = 4
    print( i + j)
x = 5
y = 5
z = 9
result_2 = x + y
result_1 = y + z
print("starts from here : ")
# pdb.set_trace()
print(result_1)
# breakpoint()
print(result_2)
# breakpoint()
add()
print("done")


"""empty message

Revision ID: 18c83d14c83e
Revises: 541363c9cc7f
Create Date: 2022-03-31 10:16:37.723462

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql

# revision identifiers, used by Alembic.
revision = '18c83d14c83e'
down_revision = '541363c9cc7f'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('exe_case_record_detail', 'consume',
               existing_type=mysql.VARCHAR(length=10),
               nullable=True,
               existing_comment='请求耗时')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('exe_case_record_detail', 'consume',
               existing_type=mysql.VARCHAR(length=10),
               nullable=False,
               existing_comment='请求耗时')
    # ### end Alembic commands ###


import datetime as dt
import json

import pytest
from channels.db import database_sync_to_async
from channels.layers import channel_layers, get_channel_layer
from django.conf import settings
from django.utils.timezone import now

from venueless.core.models import (
    Announcement,
    BBBServer,
    Channel,
    ChatEvent,
    Exhibitor,
    Room,
    User,
    World,
)
from venueless.core.models.world import PlannedUsage
from venueless.core.utils.redis import flush_aredis_pool

@pytest.fixture(autouse=True)
async def clear_redis():
    from venueless.core.utils.redis import aredis

    if settings.REDIS_USE_PUBSUB:
        try:
            await get_channel_layer().flush()
        except:  # noqa
            channel_layers._reset_backends("CHANNEL_LAYERS")

    async with aredis() as redis:
        await redis.flushall()

    await flush_aredis_pool()

@pytest.fixture(autouse=True)
async def bbb_server():
    await database_sync_to_async(BBBServer.objects.create)(
        url="https://video1.pretix.eu/bigbluebutton/", secret="bogussecret", active=True
    )

@pytest.fixture(scope="session")
def world_data():
    with open("sample/worlds/sample.json") as f:
        world_data = json.load(f)
    return world_data

@database_sync_to_async
def _import_world(world_data):
    from venueless.core.utils.config import import_config

    import_config(world_data)
    world = World.objects.all().get()
    world.domain = "localhost"
    world.save()
    return world

@pytest.fixture(autouse=True)
async def world(world_data):
    world = await _import_world(world_data)
    return world

@database_sync_to_async
def _get_rooms(world):
    return list(world.rooms.all().prefetch_related("channel"))

@pytest.fixture
async def rooms(world):
    rooms = await _get_rooms(world)
    return rooms

@pytest.fixture
def bbb_room(rooms, bbb_server):  # pragma: no cover
    for room in rooms:
        if any("call.bigbluebutton" == module["type"] for module in room.module_config):
            return room

@pytest.fixture
def volatile_chat_room(rooms):
    for room in rooms:  # pragma: no cover
        if any(
            "chat.native" == module["type"] and module["config"]["volatile"] is True
            for module in room.module_config
        ):
            return room

@pytest.fixture
def chat_room(rooms):
    for room in rooms:  # pragma: no cover
        if any(
            "chat.native" == module["type"] and module["config"]["volatile"] is False
            for module in room.module_config
        ):
            return room

@pytest.fixture
def questions_room(rooms):
    for room in rooms:  # pragma: no cover
        if any(
            "question" == module["type"] and module["config"]["active"]
            for module in room.module_config
        ):
            return room

@pytest.fixture
def inactive_questions_room(rooms):
    for room in rooms:  # pragma: no cover
        if any(
            "question" == module["type"] and not module["config"].get("active")
            for module in room.module_config
        ):
            return room

@pytest.fixture
def unmoderated_questions_room(rooms):
    for room in rooms:  # pragma: no cover
        if any(
            "question" == module["type"]
            and not module["config"].get("requires_moderation", True)
            for module in room.module_config
        ):
            return room

@pytest.fixture
def stream_room(rooms):
    for room in rooms:  # pragma: no cover
        if any("livestream.native" == module["type"] for module in room.module_config):
            return room

@pytest.fixture
def exhibition_room(rooms):
    for room in rooms:  # pragma: no cover
        if any("exhibition.native" == module["type"] for module in room.module_config):
            return room

@database_sync_to_async
def _clear_db():
    ChatEvent.objects.all().delete()
    Channel.objects.all().delete()
    User.objects.all().delete()
    Room.objects.all().delete()
    Exhibitor.objects.all().delete()
    World.objects.all().delete()

@pytest.fixture(autouse=True)
@pytest.mark.django_db
async def clear_database(request):
    if "django_db" not in request.keywords:  # pragma: no cover
        return
    await _clear_db()

@pytest.fixture
def staff_user():
    from django.contrib.auth.models import User

    return User.objects.create(is_staff=True)

@pytest.fixture
def event_user(world):
    return User.objects.create(world=world, profile={"test": True}, traits=["test"])

@pytest.fixture
def staff_client(client, staff_user):
    client.force_login(staff_user)
    return client

@pytest.fixture
def planned_usage(world_data):
    from venueless.core.utils.config import import_config

    import_config(world_data)
    world = World.objects.all().get()
    world.domain = "localhost"
    world.save()
    return PlannedUsage.objects.create(
        world=world,
        start=now() + dt.timedelta(days=10),
        end=now() + dt.timedelta(days=13),
        attendees=200,
    )

@database_sync_to_async
def create_announcement(active):
    world = World.objects.all().get()
    announcement = Announcement.objects.create(
        world=world,
        state=Announcement.States.ACTIVE if active else Announcement.States.ARCHIVED,
        text="Test announcement",
    )
    return announcement

@pytest.fixture
async def announcement():
    announcement = await create_announcement(True)
    return announcement

@pytest.fixture
async def inactive_announcement():
    announcement = await create_announcement(False)
    return announcement


class Solution(object):
    def shortestDistance(self, words, word1, word2):
        """
        :type words: List[str]
        :type word1: str
        :type word2: str
        :rtype: int
        """
        assert word1!=word2

        lastWord1Index = float('-inf')
        lastWord2Index = float('-inf')
        ret = float('inf')

        for i,w in enumerate(words):
            if w==word1:
                lastWord1Index = i
            elif w==word2:
                lastWord2Index = i

            ret = min( ret, abs(lastWord1Index-lastWord2Index) )
            if ret==1:
                break

        return ret


import time
import requests
from pathlib import Path
from mognet_demo.models import Job, UploadJobResult
from mognet.model.result_state import READY_STATES, SUCCESS_STATES

_cwd = Path(__file__).parent

def test_full_a_to_z():
    """
    Test the "full A-Z", i.e., upload a file through the API, wait for the task,
    and get the result.
    """

    # 1. Upload the file.
    with (_cwd / "files.zip").open("rb") as files:
        submit_response = requests.post(
            "http://localhost:8000/jobs", files={"file": files}
        )

    assert submit_response.ok

    # 2. Get the job to wait for...
    job = Job.parse_obj(submit_response.json())

    # 3. Wait for it, through polling...
    while True:
        result_response = requests.get(
            f"http://localhost:8000/jobs/{job.job_id}/result?wait=10"
        )

        assert result_response.ok

        result = UploadJobResult.parse_obj(result_response.json())

        if result.job_status not in READY_STATES:
            time.sleep(1)

        break

    # 4 .And assert that it succeeds.
    assert result.job_status in SUCCESS_STATES

    assert result.result is not None

    assert len(result.result.documents) == 30