from SPLT_tracker_new import MobileTracker
import argparse
import os
import cv2
os.environ['CUDA_VISIBLE_DEVICES'] = '1'
from toolkit.datasets import DatasetFactory
from common_path import *
parser = argparse.ArgumentParser(description='tracking')
parser.add_argument('--dataset', default= dataset_name_, type=str,
        help='eval one special dataset')
parser.add_argument('--video', default= video_name_, type=str,
        help='eval one special video')
parser.add_argument('--vis', default=False, help='whether visualzie result')
args = parser.parse_args()

def main():
    use_vot = False
    display = False
    save_results = True

    # load config
    model_name = 'SPLT36_haojie'
    dataset_root = '/media/masterbin-iiau/WIN_SSD/VOT2018_LT35'
    # create model
    tracker = MobileTracker(vot=use_vot, dis=display)
    # create dataset
    dataset = DatasetFactory.create_dataset(name=args.dataset,
                                            dataset_root=dataset_root,
                                            load_img=False)
    # OPE tracking
    for v_idx, video in enumerate(dataset):
        print(video.name)
        if args.video != '':
            # test one special video
            if video.name != args.video:
                continue
        toc = 0
        pred_bboxes = []
        scores = []
        track_times = []
        for idx, (img, gt_bbox) in enumerate(video):
            tic = cv2.getTickCount()
            if idx == 0:
                tracker.init_first(img, gt_bbox)
                pred_bbox = gt_bbox
                scores.append(None)
                if 'VOT2018-LT' == args.dataset:
                    pred_bboxes.append([1])
                else:
                    pred_bboxes.append(pred_bbox)
            else:
                print('processing %d'%idx)
                outputs = tracker.track(img)
                pred_bbox = outputs[0]
                pred_bboxes.append(pred_bbox)
                scores.append(outputs[1])
            toc += cv2.getTickCount() - tic
            track_times.append((cv2.getTickCount() - tic)/cv2.getTickFrequency())
            if idx == 0:
                cv2.destroyAllWindows()
            if args.vis and idx > 0:
                gt_bbox = list(map(int, gt_bbox))
                pred_bbox = list(map(int, pred_bbox))
                cv2.rectangle(img, (gt_bbox[0], gt_bbox[1]),
                              (gt_bbox[0]+gt_bbox[2], gt_bbox[1]+gt_bbox[3]), (0, 255, 0), 3)
                cv2.rectangle(img, (pred_bbox[0], pred_bbox[1]),
                              (pred_bbox[0]+pred_bbox[2], pred_bbox[1]+pred_bbox[3]), (0, 255, 255), 3)
                cv2.putText(img, str(idx), (40, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2)
                cv2.imshow(video.name, img)
                cv2.waitKey(1)
        toc /= cv2.getTickFrequency()
        if save_results:
            # save results
            if 'VOT2018-LT' == args.dataset:
                video_path = os.path.join('results', args.dataset, model_name,
                        'longterm', video.name)
                if not os.path.isdir(video_path):
                    os.makedirs(video_path)
                result_path = os.path.join(video_path,
                        '{}_001.txt'.format(video.name))
                with open(result_path, 'w') as f:
                    for x in pred_bboxes:
                        f.write(','.join([str(i) for i in x])+'\n')
                result_path = os.path.join(video_path,
                        '{}_001_confidence.value'.format(video.name))
                with open(result_path, 'w') as f:
                    for x in scores:
                        f.write('\n') if x is None else f.write("{:.6f}\n".format(x))
                result_path = os.path.join(video_path,
                        '{}_time.txt'.format(video.name))
                with open(result_path, 'w') as f:
                    for x in track_times:
                        f.write("{:.6f}\n".format(x))

if __name__ == '__main__':
    main()


import typing as typ
import logging
import datetime as dt

import lexid

from . import version
from . import v1patterns

logger = logging.getLogger("bumpver.v1version")

CalInfo = typ.Union[version.V1CalendarInfo, version.V1VersionInfo]

def _is_cal_gt(left: CalInfo, right: CalInfo) -> bool:
    """Is left > right for non-None fields."""

    lvals = []
    rvals = []
    for field in version.V1CalendarInfo._fields:
        lval = getattr(left , field)
        rval = getattr(right, field)
        if not (lval is None or rval is None):
            lvals.append(lval)
            rvals.append(rval)

    return lvals > rvals

def _ver_to_cal_info(vnfo: version.V1VersionInfo) -> version.V1CalendarInfo:
    return version.V1CalendarInfo(
        vnfo.year,
        vnfo.quarter,
        vnfo.month,
        vnfo.dom,
        vnfo.doy,
        vnfo.iso_week,
        vnfo.us_week,
    )

def cal_info(date: typ.Optional[dt.date] = None) -> version.V1CalendarInfo:
    """Generate calendar components for current date.

    >>> from datetime import date

    >>> c = cal_info(date(2019, 1, 5))
    >>> (c.year, c.quarter, c.month, c.dom, c.doy, c.iso_week, c.us_week)
    (2019, 1, 1, 5, 5, 0, 0)

    >>> c = cal_info(date(2019, 1, 6))
    >>> (c.year, c.quarter, c.month, c.dom, c.doy, c.iso_week, c.us_week)
    (2019, 1, 1, 6, 6, 0, 1)

    >>> c = cal_info(date(2019, 1, 7))
    >>> (c.year, c.quarter, c.month, c.dom, c.doy, c.iso_week, c.us_week)
    (2019, 1, 1, 7, 7, 1, 1)

    >>> c = cal_info(date(2019, 4, 7))
    >>> (c.year, c.quarter, c.month, c.dom, c.doy, c.iso_week, c.us_week)
    (2019, 2, 4, 7, 97, 13, 14)
    """
    if date is None:
        date = version.TODAY

    kwargs = {
        'year'    : date.year,
        'quarter' : version.quarter_from_month(date.month),
        'month'   : date.month,
        'dom'     : date.day,
        'doy'     : int(date.strftime("%j"), base=10),
        'iso_week': int(date.strftime("%W"), base=10),
        'us_week' : int(date.strftime("%U"), base=10),
    }

    return version.V1CalendarInfo(**kwargs)

FieldKey      = str
MatchGroupKey = str
MatchGroupStr = str

PatternGroups = typ.Dict[MatchGroupKey, MatchGroupStr]
FieldValues   = typ.Dict[FieldKey     , MatchGroupStr]

def _parse_field_values(field_values: FieldValues) -> version.V1VersionInfo:
    fvals = field_values
    tag   = fvals.get('tag')
    if tag is None:
        tag = "final"
    tag = version.TAG_BY_PEP440_TAG.get(tag, tag)
    assert tag is not None

    bid = fvals['bid'] if 'bid' in fvals else "0001"

    year = int(fvals['year']) if 'year' in fvals else None
    if year is not None and year < 100:
        year += 2000

    doy = int(fvals['doy']) if 'doy' in fvals else None

    month: typ.Optional[int]
    dom  : typ.Optional[int]

    if year and doy:
        date  = version.date_from_doy(year, doy)
        month = date.month
        dom   = date.day
    else:
        month = int(fvals['month']) if 'month' in fvals else None
        dom   = int(fvals['dom'  ]) if 'dom' in fvals else None

    iso_week: typ.Optional[int]
    us_week : typ.Optional[int]

    if year and month and dom:
        date     = dt.date(year, month, dom)
        doy      = int(date.strftime("%j"), base=10)
        iso_week = int(date.strftime("%W"), base=10)
        us_week  = int(date.strftime("%U"), base=10)
    else:
        iso_week = None
        us_week  = None

    quarter = int(fvals['quarter']) if 'quarter' in fvals else None
    if quarter is None and month:
        quarter = version.quarter_from_month(month)

    major = int(fvals['major']) if 'major' in fvals else 0
    minor = int(fvals['minor']) if 'minor' in fvals else 0
    patch = int(fvals['patch']) if 'patch' in fvals else 0

    return version.V1VersionInfo(
        year=year,
        quarter=quarter,
        month=month,
        dom=dom,
        doy=doy,
        iso_week=iso_week,
        us_week=us_week,
        major=major,
        minor=minor,
        patch=patch,
        bid=bid,
        tag=tag,
    )

def _is_calver(cinfo: CalInfo) -> bool:
    """Check pattern for any calendar based parts.

    >>> _is_calver(cal_info())
    True

    >>> vnfo = _parse_version_info({'year': "2018", 'month': "11", 'bid': "0018"})
    >>> _is_calver(vnfo)
    True

    >>> vnfo = _parse_version_info({'MAJOR': "1", 'MINOR': "023", 'PATCH': "45"})
    >>> _is_calver(vnfo)
    False
    """
    for field in version.V1CalendarInfo._fields:
        maybe_val: typ.Any = getattr(cinfo, field, None)
        if isinstance(maybe_val, int):
            return True

    return False

VersionInfoKW = typ.Dict[str, typ.Union[str, int, None]]

def _parse_pattern_groups(pattern_groups: PatternGroups) -> FieldValues:
    for part_name in pattern_groups.keys():
        is_valid_part_name = (
            part_name    in v1patterns.COMPOSITE_PART_PATTERNS
            or part_name in v1patterns.PATTERN_PART_FIELDS
        )
        if not is_valid_part_name:
            err_msg = f"Invalid part '{part_name}'"
            raise version.PatternError(err_msg)

    field_value_items = [
        (field_name, pattern_groups[part_name])
        for part_name, field_name in v1patterns.PATTERN_PART_FIELDS.items()
        if part_name in pattern_groups.keys()
    ]

    all_fields       = [field_name for field_name, _ in field_value_items]
    unique_fields    = set(all_fields)
    duplicate_fields = [f for f in unique_fields if all_fields.count(f) > 1]

    if any(duplicate_fields):
        err_msg = f"Multiple parts for same field {duplicate_fields}."
        raise version.PatternError(err_msg)
    else:
        return dict(field_value_items)

def _parse_version_info(pattern_groups: PatternGroups) -> version.V1VersionInfo:
    """Parse normalized V1VersionInfo from groups of a matched pattern.

    >>> vnfo = _parse_version_info({'year': "2018", 'month': "11", 'bid': "0099"})
    >>> (vnfo.year, vnfo.month, vnfo.quarter, vnfo.bid, vnfo.tag)
    (2018, 11, 4, '0099', 'final')

    >>> vnfo = _parse_version_info({'year': "18", 'month': "11"})
    >>> (vnfo.year, vnfo.month, vnfo.quarter)
    (2018, 11, 4)

    >>> vnfo = _parse_version_info({'year': "2018", 'doy': "11", 'bid': "099", 'tag': "b"})
    >>> (vnfo.year, vnfo.month, vnfo.dom, vnfo.bid, vnfo.tag)
    (2018, 1, 11, '099', 'beta')

    >>> vnfo = _parse_version_info({'MAJOR': "1", 'MINOR': "23", 'PATCH': "45"})
    >>> (vnfo.major, vnfo.minor, vnfo.patch)
    (1, 23, 45)

    >>> vnfo = _parse_version_info({'MAJOR': "1", 'MMM': "023", 'PPPP': "0045"})
    >>> (vnfo.major, vnfo.minor, vnfo.patch)
    (1, 23, 45)
    """
    field_values = _parse_pattern_groups(pattern_groups)
    return _parse_field_values(field_values)

def parse_version_info(version_str: str, raw_pattern: str = "{pycalver}") -> version.V1VersionInfo:
    """Parse normalized V1VersionInfo.

    >>> vnfo = parse_version_info("v201712.0033-beta", raw_pattern="{pycalver}")
    >>> assert vnfo == _parse_version_info({'year': 2017, 'month': 12, 'bid': "0033", 'tag': "beta"})

    >>> vnfo = parse_version_info("1.23.456", raw_pattern="{semver}")
    >>> assert vnfo == _parse_version_info({'MAJOR': "1", 'MINOR': "23", 'PATCH': "456"})
    """
    pattern = v1patterns.compile_pattern(raw_pattern)
    match   = pattern.regexp.match(version_str)
    if match is None:
        err_msg = (
            f"Invalid version string '{version_str}' "
            f"for pattern '{raw_pattern}'/'{pattern.regexp.pattern}'"
        )
        raise version.PatternError(err_msg)
    else:
        return _parse_version_info(match.groupdict())

def is_valid(version_str: str, raw_pattern: str = "{pycalver}") -> bool:
    """Check if a version matches a pattern.

    >>> is_valid("v201712.0033-beta", raw_pattern="{pycalver}")
    True
    >>> is_valid("v201712.0033-beta", raw_pattern="{semver}")
    False
    >>> is_valid("1.2.3", raw_pattern="{semver}")
    True
    >>> is_valid("v201712.0033-beta", raw_pattern="{semver}")
    False
    """
    try:
        parse_version_info(version_str, raw_pattern)
        return True
    except version.PatternError:
        return False

ID_FIELDS_BY_PART = {
    'MAJOR'  : 'major',
    'MINOR'  : 'minor',
    'MM'     : 'minor',
    'MMM'    : 'minor',
    'MMMM'   : 'minor',
    'MMMMM'  : 'minor',
    'MMMMMM' : 'minor',
    'MMMMMMM': 'minor',
    'PATCH'  : 'patch',
    'PP'     : 'patch',
    'PPP'    : 'patch',
    'PPPP'   : 'patch',
    'PPPPP'  : 'patch',
    'PPPPPP' : 'patch',
    'PPPPPPP': 'patch',
    'BID'    : 'bid',
    'BB'     : 'bid',
    'BBB'    : 'bid',
    'BBBB'   : 'bid',
    'BBBBB'  : 'bid',
    'BBBBBB' : 'bid',
    'BBBBBBB': 'bid',
}

def format_version(vinfo: version.V1VersionInfo, raw_pattern: str) -> str:
    """Generate version string.

    >>> import datetime as dt
    >>> vinfo = parse_version_info("v201712.0033-beta", raw_pattern="{pycalver}")
    >>> vinfo_a = vinfo._replace(**cal_info(date=dt.date(2017, 1, 1))._asdict())
    >>> vinfo_b = vinfo._replace(**cal_info(date=dt.date(2017, 12, 31))._asdict())
    >>> vinfo_c = vinfo_b._replace(major=1, minor=2, patch=34, tag='final')

    >>> format_version(vinfo_a, raw_pattern="v{yy}.{BID}{release}")
    'v17.33-beta'
    >>> format_version(vinfo_a, raw_pattern="{pep440_version}")
    '201701.33b0'

    >>> format_version(vinfo_a, raw_pattern="{pycalver}")
    'v201701.0033-beta'
    >>> format_version(vinfo_b, raw_pattern="{pycalver}")
    'v201712.0033-beta'

    >>> format_version(vinfo_a, raw_pattern="v{year}w{iso_week}.{BID}{release}")
    'v2017w00.33-beta'
    >>> format_version(vinfo_b, raw_pattern="v{year}w{iso_week}.{BID}{release}")
    'v2017w52.33-beta'

    >>> format_version(vinfo_a, raw_pattern="v{year}d{doy}.{bid}{release}")
    'v2017d001.0033-beta'
    >>> format_version(vinfo_b, raw_pattern="v{year}d{doy}.{bid}{release}")
    'v2017d365.0033-beta'

    >>> format_version(vinfo_c, raw_pattern="v{year}w{iso_week}.{BID}-{tag}")
    'v2017w52.33-final'
    >>> format_version(vinfo_c, raw_pattern="v{year}w{iso_week}.{BID}{release}")
    'v2017w52.33'

    >>> format_version(vinfo_c, raw_pattern="v{MAJOR}.{MINOR}.{PATCH}")
    'v1.2.34'
    >>> format_version(vinfo_c, raw_pattern="v{MAJOR}.{MM}.{PPP}")
    'v1.02.034'
    """
    full_pattern = raw_pattern
    for part_name, full_part_format in v1patterns.FULL_PART_FORMATS.items():
        full_pattern = full_pattern.replace("{" + part_name + "}", full_part_format)

    kwargs: typ.Dict[str, typ.Union[str, int, None]] = vinfo._asdict()

    release_tag = vinfo.tag
    if release_tag == 'final':
        kwargs['release'   ] = ""
        kwargs['pep440_tag'] = ""
    else:
        kwargs['release'   ] = "-" + release_tag
        kwargs['pep440_tag'] = version.PEP440_TAG_BY_TAG[release_tag] + "0"

    kwargs['release_tag'] = release_tag

    year = vinfo.year
    if year:
        kwargs['yy'  ] = str(year)[-2:]
        kwargs['yyyy'] = year

    kwargs['BID'] = int(vinfo.bid, 10)

    for part_name, field in ID_FIELDS_BY_PART.items():
        val = kwargs[field]
        if part_name.lower() == field.lower():
            if isinstance(val, str):
                kwargs[part_name] = int(val, base=10)
            else:
                kwargs[part_name] = val
        else:
            assert len(set(part_name)) == 1
            padded_len = len(part_name)
            kwargs[part_name] = str(val).zfill(padded_len)

    return full_pattern.format(**kwargs)

def incr(
    old_version: str,
    raw_pattern: str = "{pycalver}",
    *,
    major     : bool = False,
    minor     : bool = False,
    patch     : bool = False,
    tag       : typ.Optional[str] = None,
    tag_num   : bool = False,
    pin_date  : bool = False,
    maybe_date: typ.Optional[dt.date] = None,
) -> typ.Optional[str]:
    """Increment version string.

    'old_version' is assumed to be a string that matches 'pattern'
    """
    try:
        old_vinfo = parse_version_info(old_version, raw_pattern)
    except version.PatternError as ex:
        logger.error(str(ex))
        return None

    date = version.TODAY if maybe_date is None else maybe_date

    cur_cinfo = _ver_to_cal_info(old_vinfo) if pin_date else cal_info(date)

    if _is_cal_gt(old_vinfo, cur_cinfo):
        logger.warning(f"Old version appears to be from the future '{old_version}'")
        cur_vinfo = old_vinfo
    else:
        cur_vinfo = old_vinfo._replace(**cur_cinfo._asdict())

    cur_vinfo = cur_vinfo._replace(bid=lexid.next_id(cur_vinfo.bid))

    if major:
        cur_vinfo = cur_vinfo._replace(major=cur_vinfo.major + 1, minor=0, patch=0)
    if minor:
        cur_vinfo = cur_vinfo._replace(minor=cur_vinfo.minor + 1, patch=0)
    if patch:
        cur_vinfo = cur_vinfo._replace(patch=cur_vinfo.patch + 1)
    if tag_num:
        raise NotImplementedError("--tag-num not supported for old style patterns")
    if tag:
        cur_vinfo = cur_vinfo._replace(tag=tag)

    new_version = format_version(cur_vinfo, raw_pattern)
    if new_version == old_version:
        logger.error("Invalid arguments or pattern, version did not change.")
        return None
    else:
        return new_version


import math
import random
import sys

import glob
import time
from datetime import datetime

import pydash

from string import ascii_lowercase
from queue import Queue, PriorityQueue
import re
import sys

import util

from pprint import pprint

sys.setrecursionlimit(15000)
input_name = 'input/day25'

def main():
    files = glob.glob(f"{input_name}*")
    for file in sorted(files, reverse=True):
        print("Running file", file)
        problem1(file)
        problem2(file)

@util.timing
def problem1(filename):
    points = util.parse_ints(filename)

    umap = {}
    for i in range(len(points)):
        for j in range(i+1, len(points)):
            if dist(points[i], points[j]) <= 3:
                union(umap, i, j)

    constelations = set()
    for i in range(len(points)):
        group = find(umap, i)
        constelations.add(group)

    print(len(constelations), constelations)
    # 0, 1, 3, 6, 7
    # 7-8
    # 2-9

def union(umap, i1, i2):
    iv = find(umap, i1)
    i2v = find(umap, i2)
    value = min(iv, i2v)
    umap[iv] = value
    umap[i2v] = value

def find(umap, i):
    group = umap.get(i)
    if group is None or group == i:
        return i
    f = find(umap, group)
    if f != group:
        umap[i] = f
    return f

def dist(pos1, pos2):
    dist = 0
    for i in range(len(pos1)):
        dist += abs(pos1[i] - pos2[i])
    return dist

@util.timing
def problem2(filename):
    pass

if __name__ == '__main__':
    main()


import graph_generator
import sys
import os

def main():
    least_nodes = int(sys.argv[1])
    most_nodes = int(sys.argv[2])
    density = float(sys.argv[3])
    card_alphabet = int(sys.argv[4])
    leap = int(sys.argv[5])
    algorithm = sys.argv[6]

    no_max_edges = least_nodes*card_alphabet
    no_edges = int(density*no_max_edges)

    nodes = []

    for i in range(least_nodes, most_nodes+least_nodes, leap):
        nodes.append(i)

    print(nodes)

    no = ''

    for node in nodes:

        for i in range(5):

            no = str(i+1)
            graph_generator.main(node, density , card_alphabet, algorithm, no)
            print("DONE")
            os.wait

if __name__ == '__main__':
    main()


from bothub.api.v2.repository.validators import (
    ExampleTextHasLettersValidator,
    ChatGPTTokenLimitValidator
)
from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from bothub.common import languages
from bothub.common.models import Repository, QAKnowledgeBase, QAtext
from bothub.common.helpers import ChatGPTTokenText

from django.conf import settings
from django.utils.translation import ugettext_lazy as _

class QAKnowledgeBaseSerializer(serializers.ModelSerializer):
    class Meta:
        model = QAKnowledgeBase
        fields = [
            "id",
            "repository",
            "title",
            "description",
            "language_count",
            "user_name",
            "user",
            "last_update",
            "created_at",
        ]
        read_only_fields = ["created_at", "last_update"]

    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    user_name = serializers.SerializerMethodField("get_user_name")
    repository = serializers.PrimaryKeyRelatedField(queryset=Repository.objects)
    description = serializers.SerializerMethodField("get_description")
    language_count = serializers.SerializerMethodField("get_languages_count")

    def get_user_name(self, obj):
        return None if obj.user is None else obj.user.nickname

    def get_description(self, obj):
        return obj.get_text_description()

    def get_languages_count(self, obj):
        return obj.get_languages_count()

class QAtextSerializer(serializers.ModelSerializer):
    class Meta:
        model = QAtext
        fields = [
            "id",
            "text",
            "language",
            "knowledge_base",
            "created_at",
            "last_update",
            "title",
        ]
        read_only_fields = ["created_at", "last_update"]

    text = serializers.CharField(
        required=False, validators=[ExampleTextHasLettersValidator(), ChatGPTTokenLimitValidator()]
    )
    knowledge_base = serializers.PrimaryKeyRelatedField(
        queryset=QAKnowledgeBase.objects
    )
    language = serializers.ChoiceField(languages.LANGUAGE_CHOICES, required=True)
    title = serializers.SerializerMethodField("get_title")

    def get_title(self, obj):
        return obj.get_title()

    def validate_gpt_tokens(self):
        value = self.instance.text
        validator = ChatGPTTokenText()
        count, chunks = validator.count_tokens(value)
        if count > settings.GPT_MAX_TOKENS:
            raise ValidationError({
                "message": _(
                    f"Enter a valid value that is in the range of {settings.GPT_MAX_TOKENS} tokens"
                ),
                "chunks": "".join(chunks)
                }
            )


from os import *
import time

num = 100

ret = fork()

if (0 == ret):
    num += 1
    print('I\'m child pid[%d], ppid[%d]'%(getpid(), getppid()))
    print(num)
    time.sleep(1)
else:
    time.sleep(2)
    print('I\'m Parent pid[%d]'% getpid())
    print(num)


# Chapter 4: Containers and Advanced Controls
# Recipe 9: Surfing the web in your app
#
import wx
import wx.html2 as html2

class NaviBar(wx.Panel):
    def __init__(self, parent, browser):
        super(NaviBar, self).__init__(parent)

        self._url = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER)
        self._url.SetHint("Enter URL here and press enter...")

        back = wx.Button(self, style=wx.BU_EXACTFIT)
        back.Bitmap = wx.ArtProvider.GetBitmap(wx.ART_GO_BACK,
                                               wx.ART_TOOLBAR)
        fw = wx.Button(self, style=wx.BU_EXACTFIT)
        fw.Bitmap = wx.ArtProvider.GetBitmap(wx.ART_GO_FORWARD,
                                             wx.ART_TOOLBAR)

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(back, 0, wx.ALL, 5)
        sizer.Add(fw, 0, wx.ALL, 5)
        sizer.Add(self._url, 1, wx.EXPAND)
        self.SetSizer(sizer)

        b = browser
        self.Bind(wx.EVT_TEXT_ENTER,
                  lambda event: b.LoadURL(self._url.Value))
        self.Bind(wx.EVT_BUTTON, lambda event: b.GoBack(), back)
        self.Bind(wx.EVT_BUTTON, lambda event: b.GoForward(), fw)
        self.Bind(wx.EVT_UPDATE_UI,
                  lambda event: event.Enable(b.CanGoBack()),
                  back)
        self.Bind(wx.EVT_UPDATE_UI,
                  lambda event: event.Enable(b.CanGoForward()),
                  fw)

class WebFrame(wx.Frame):
    def __init__(self, parent, title):
        super(WebFrame, self).__init__(parent, title=title)

        self._browser = html2.WebView_New(self)
        self._bar = NaviBar(self, self._browser)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self._bar, 0, wx.EXPAND)
        sizer.Add(self._browser, 1, wx.EXPAND)
        self.SetSizer(sizer)

        self.Bind(html2.EVT_WEBVIEW_TITLE_CHANGED, self.OnTitle)

    def OnTitle(self, event):
        self.Title = event.GetString()

class MyApp(wx.App):
    def OnInit(self):
        WebFrame(None, "Surfing the Web").Show()
        return True

if __name__ == "__main__":
    app = MyApp(False)
    app.MainLoop()


import numpy as np
import cv2

nameimage = str(input("Enter image name:"))
image = cv2.imread(nameimage,0)
kernel =cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 5))
image = cv2.dilate(image,kernel) #we dilate image to remove pepper noise
gray = cv2.cvtColor(image, cv2.COLOR_BayerRG2GRAY)
blurred = cv2.GaussianBlur(image, (5, 5), 0) #blurring the image to have smooth edged using cannyy
cv2.imwrite("GaussianBlur.jpg",blurred)
edged = cv2.Canny(blurred, 75, 200) #output of canny edges
cv2.imwrite("edgesOfCanny.jpg",edged)
Result = ["0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0"]
Result1 = ["0","0","0"]
gray1 = cv2.bitwise_not(gray)

thresh1 = cv2.threshold(gray1, 0, 255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] #thresholding the image to use it while rotating.
######rotating the imgage#######
coords = np.column_stack(np.where(thresh1 > 0))
angle = cv2.minAreaRect(coords)[-1]
if angle < -45:
    angle = -(90 + angle)
else:
    angle = -angle
(h, w) = image.shape[:2]
center = tuple(np.array(image.shape[1::-1]) / 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
image = cv2.warpAffine(image, M,image.shape[1::-1],flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
gray = cv2.warpAffine(gray, M,image.shape[1::-1],flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
##################################
cv2.imwrite("Rotatedimage.png",image) #the result of rotating the original image
cv2.imwrite("Rotatedgrayimage.png",gray) #the resultof rotating  after converting to gray scale

gray_blurred = cv2.blur(gray, (3, 3)) #make blur by filter 3*3
#hought detection circle#
detected_circles = cv2.HoughCircles(gray_blurred,cv2.HOUGH_GRADIENT, 1, 20, param1=50,param2=30, minRadius=1, maxRadius=25)
f=open("Resultfile.txt","w+")
i=0
y=0
if detected_circles is not None:
    detected_circles = np.uint16(np.around(detected_circles))
    for pt in detected_circles[0, :]:
        a, b, r = pt[0], pt[1], pt[2]
        cv2.circle(image, (a, b), r, (255, 255, 255), 2)
        cv2.circle(image, (a, b), 1, (0, 0, 255), 3)
        # print x coorinateof detected circle
        cv2.putText(image,str(a), (a+30, b), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (80,170, 89), 2,1)
        # print y coorinateof detected circle
        cv2.putText(image, str(b), (a, b+30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (80,170, 89), 2, 1)
        if (a > 380 and b>580):
            ##ranges to detect from 1 to 5
                if(a>1100 and a<1200):
                    if (b > 950 and b < 999):
                        Result[0] = "Question 1.1:Strongly agree"
                    if (b > 999 and b < 1030):
                        Result[1] = "Question 1.2:Strongly agree"
                    if (b > 1030 and b < 1075):
                        Result[2] = "Question 1.3:Strongly agree"
                    if (b > 1075 and b < 1110):
                        Result[3] = "Question 1.4:Strongly agree"
                    if (b > 1110 and b < 1150):
                        Result[4] = "Question 1.5:Strongly agree"
                    if (b > 1150 and b < 1265):
                        Result[5] = "Question 2.1:Strongly agree"
                    if (b > 1265 and b < 1315):
                        Result[6] = "Question 2.2:Strongly agree"
                    if (b > 1315 and b < 1355):
                        Result[7] = "Question 2.3:Strongly agree"
                    if (b > 1355 and b < 1385):
                        Result[8] = "Question 2.4:Strongly agree"
                    if (b > 1385 and b < 1430):
                        Result[9] = "Question 2.5:Strongly agree"
                    if (b > 1430 and b < 1480):
                        Result[10] = "Question 2.6:Strongly agree"
                    if (b > 1480 and b < 1585):
                        Result[11] = "Question 3.1:Strongly agree"
                    if (b > 1585 and b < 1625):
                        Result[12] = "Question 3.2:Strongly agree"
                    if (b > 1625 and b < 1670):
                        Result[13] = "Question 3.3:Strongly agree"
                    if (b > 1670 and b < 1790):
                        Result[14] = "Question 4.1:Strongly agree"
                    if (b > 1790 and b < 1830):
                        Result[15] = "Question 4.2:Strongly agree"
                    if (b > 1830 and b < 1910):
                        Result[16] = "Question 4.3:Strongly agree"
                    if (b > 1910 and b < 2022):
                        Result[17] = "Question 5.1:Strongly agree"
                    if (b > 2022):
                        Result[18] = "Question 5.2:Strongly agree"
                if(a>1200 and a<1300):
                    if (b > 950 and b < 999):
                        Result[0] = "Question 1.1:agree"
                    if (b > 999 and b < 1030):
                        Result[1] = "Question 1.2:agree"
                    if (b > 1030 and b < 1075):
                        Result[2] = "Question 1.3:agree"
                    if (b > 1075 and b < 1110):
                        Result[3] = "Question 1.4:agree"
                    if (b > 1110 and b < 1150):
                        Result[4] = "Question 1.5:agree"
                    if (b > 1150 and b < 1265):
                        Result[5] = "Question 2.1:agree"
                    if (b > 1265 and b < 1315):
                        Result[6] = "Question 2.2:agree"
                    if (b > 1315 and b < 1355):
                        Result[7] = "Question 2.3:agree"
                    if (b > 1355 and b < 1385):
                        Result[8] = "Question 2.4:agree"
                    if (b > 1385 and b < 1430):
                        Result[9] = "Question 2.5:agree"
                    if (b > 1430 and b < 1480):
                        Result[10] = "Question 2.6:agree"
                    if (b > 1480 and b < 1585):
                        Result[11] = "Question 3.1:agree"
                    if (b > 1585 and b < 1625):
                        Result[12] = "Question 3.2:agree"
                    if (b > 1625 and b < 1670):
                        Result[13] = "Question 3.3:agree"
                    if (b > 1670 and b < 1790):
                        Result[14] = "Question 4.1:agree"
                    if (b > 1790 and b < 1830):
                        Result[15] = "Question 4.2:agree"
                    if (b > 1830 and b < 1910):
                        Result[16] = "Question 4.3:agree"
                    if (b > 1910 and b < 2022):
                        Result[17] = "Question 5.1:agree"
                    if (b > 2022):
                        Result[18] = "Question 5.2:agree"
                if (a > 1300 and a < 1400):
                    if (b > 950 and b < 999):
                        Result[0] = "Question 1.1:Neutral"
                    if (b > 999 and b < 1030):
                        Result[1] = "Question 1.2:Neutral"
                    if (b > 1030 and b < 1075):
                        Result[2] = "Question 1.3:Neutral"
                    if (b > 1075 and b < 1110):
                        Result[3] = "Question 1.4:Neutral"
                    if (b > 1110 and b < 1150):
                        Result[4] = "Question 1.5:Neutral"
                    if (b > 1150 and b < 1265):
                        Result[5] = "Question 2.1:Neutral"
                    if (b > 1265 and b < 1315):
                        Result[6] = "Question 2.2:Neutral"
                    if (b > 1315 and b < 1355):
                        Result[7] = "Question 2.3:Neutral"
                    if (b > 1355 and b < 1385):
                        Result[8] = "Question 2.4:Neutral"
                    if (b > 1385 and b < 1430):
                        Result[9] = "Question 2.5:Neutral"
                    if (b > 1430 and b < 1480):
                        Result[10] = "Question 2.6:Neutral"
                    if (b > 1480 and b < 1585):
                        Result[11] = "Question 3.1:Neutral"
                    if (b > 1585 and b < 1625):
                        Result[12] = "Question 3.2 :Neutral"
                    if (b > 1625 and b < 1670):
                        Result[13] = "Question 3.3:Neutral"
                    if (b > 1670 and b < 1790):
                        Result[14] = "Question 4.1:Neutral"
                    if (b > 1790 and b < 1830):
                        Result[15] = "Question 4.2:Neutral"
                    if (b > 1830 and b < 1910):
                        Result[16] = "Question 4.3:Neutral"
                    if (b > 1910 and b < 2022):
                        Result[17] = "Question 5.1:Neutral"
                    if (b > 2022):
                        Result[18] = "Question 5.2:Neutral"
                if (a > 1400 and a < 1500):
                    if (b > 950 and b < 999):
                        Result[0] = "Question 1.1: disagree"
                    if (b > 999 and b < 1030):
                        Result[1] = "Question 1.2:disagree"
                    if (b > 1030 and b < 1075):
                        Result[2] = "Question 1.3:disagree"
                    if (b > 1075 and b < 1110):
                        Result[3] = "Question 1.4: disagree"
                    if (b > 1110 and b < 1150):
                        Result[4] = "Question 1.5:disagree"
                    if (b > 1150 and b < 1265):
                        Result[5] = "Question 2.1:disagree"
                    if (b > 1265 and b < 1315):
                        Result[6] = "Question 2.2:disagree"
                    if (b > 1315 and b < 1355):
                        Result[7] = "Question 2.3:disagree"
                    if (b > 1355 and b < 1385):
                        Result[8] = "Question 2.4:disagree"
                    if (b > 1385 and b < 1430):
                        Result[9] = "Question 2.5:disagree"
                    if (b > 1430 and b < 1480):
                        Result[10] = "Question 2.6:disagree"
                    if (b > 1480 and b < 1585):
                        Result[11] = "Question 3.1:disagree"
                    if (b > 1585 and b < 1625):
                        Result[12] = "Question 3.2:disagree"
                    if (b > 1625 and b < 1670):
                        Result[13] = "Question 3.3:disagree"
                    if (b > 1670 and b < 1790):
                        Result[14] = "Question 4.1:disagree"
                    if (b > 1790 and b < 1830):
                        Result[15] = "Question 4.2:disagree"
                    if (b > 1830 and b < 1910):
                        Result[16] = "Question 4.3:disagree"
                    if (b > 1910 and b < 2022):
                        Result[17] = "Question 5.1:disagree"
                    if (b > 2022):
                        Result[18] = "Question 5.2:Disagree"
                if(a > 1500):
                    if (b > 950 and b < 999):
                        Result[0] = "Question 1.1:Strongly disagree"
                    if (b > 999 and b < 1030):
                        Result[1] = "Question 1.2:Strongly disagree"
                    if (b > 1030 and b < 1075):
                        Result[2] = "Question 1.3:Strongly disagree"
                    if (b > 1075 and b < 1110):
                        Result[3] = "Question 1.4:Strongly disagree"
                    if (b > 1110 and b < 1150):
                        Result[4] = "Question 1.5:Strongly disagree"
                    if (b > 1150 and b < 1265):
                        Result[5] = "Question 2.1:Strongly disagree"
                    if (b > 1265 and b < 1315):
                        Result[6] = "Question 2.2:Stronglydisagree"
                    if (b > 1315 and b < 1355):
                        Result[7] = "Question 2.3:Stronglydisagree"
                    if (b > 1355 and b < 1385):
                        Result[8] = "Question 2.4:Stronglydisagree"
                    if (b > 1385 and b < 1430):
                        Result[9] = "Question 2.5:Stronglydisagree"
                    if (b > 1430 and b < 1480):
                        Result[10] = "Question 2.6:Stronglydisagree"
                    if (b > 1480 and b < 1585):
                        Result[11] = "Question 3.1:Stronglydisagree"
                    if (b > 1585 and b < 1625):
                        Result[12] = "Question 3.2 :Stronglydisagree"
                    if (b > 1625 and b < 1670):
                        Result[13] = "Question 3.3:Strongly disagree"
                    if (b > 1670 and b < 1790):
                        Result[14] = "Question 4.1:Strongly disagree"
                    if (b > 1790 and b < 1830):
                        Result[15] = "Question 4.2:Strongly disagree"
                    if (b > 1830 and b < 1910):
                        Result[16] = "Question 4.3:Strongly disagree"
                    if (b > 1910 and b < 2022):
                        Result[17] = "Question 5.1:Strongly disagree"
                    if (b > 2022 ):
                        Result[18] = "Question 5.2:Strongly Disagree"
            ##ranges to detect above Question
        if(a>380 and b>260 and b<530):
                if(b>260 and b<350):
                    ##ranges to detect geneder Question
                    if(a>1200and a<1370):
                        Result1[0]="Gender:Male"
                    if(a>1370):
                        Result1[0] = "Gender:Female"
                if(b>355 and b<400):
                    ##ranges to detect semester Question
                    if(a>530 and a<600):
                        Result1[1] = "Semester:Fall"
                    elif(a>1070):
                        Result1[1] = "Semester:Summer"
                    else:
                        Result1[1] = "Semester:Spring"
                if (b > 440 and b < 475):
                    ##ranges to detect department Question
                    if (a>390 and a<560):
                        Result1[2] = "Department: MCTA"
                    if (a>560 and a<610):
                        Result1[2] = "Department: ENVER"
                    if (a>700 and a<740):
                        Result1[2] = "Department: BLDG"
                    if (a>740 and a<870):
                        Result1[2] = "Department: CESS"
                    if (a>870 and a<1000):
                        Result1[2] = "Department: ENRG"
                    if (a>1000 and a<1130):
                        Result1[2] = "Department: COMM"
                    if (a>1130):
                        Result1[2] = "Department: MANF"
                if (b > 475 and b < 520):
                    if (a > 390 and a < 560):
                        Result1[2] = "Department: LAAR"
                    if (a > 560 and a < 610):
                        Result1[2] = "Department: MATL"
                    if (a > 700 and a < 740):
                        Result1[2] = "Department: CISE"
                    if (a>740 and a<870):
                        Result1[2] = "Department: HAUD"

        cv2.imwrite("Hough answers.png", image)
        #putting result of array in the file
for x in Result1:
  f.write (Result1[y]+"\n")
  y=y+1
for x in Result:
  f.write (Result[i]+"\n")
  i=i+1
f.close()
kernel3 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9,9))
img = cv2.dilate(image, kernel3)
kernel2 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7,7))
img = cv2.erode(image, kernel2)
cv2.imwrite("hough answers.png", image)
cv2.waitKey()


from hashlib import sha256
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union

import cv2
import jpeg4py
import numpy as np
from PIL import Image
from PIL.ExifTags import TAGS

REFERENCE_FACIAL_POINTS = (
    (38.29459953, 51.69630051),
    (73.53179932, 51.50139999),
    (56.02519989, 71.73660278),
    (41.54930115, 92.3655014),
    (70.72990036, 92.20410156),
)

DEFAULT_CROP_SIZE = (112, 112)

def load_rgb(image_path: Union[Path, str], lib: str = "cv2") -> np.array:
    """Load RGB image from path.

    Args:
        image_path: path to image
        lib: library used to read an image.
            currently supported `cv2` and `jpeg4py`

    Returns: 3 channel array with RGB image

    """
    if Path(image_path).is_file():
        if lib == "cv2":
            image = cv2.imread(str(image_path))
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        elif lib == "jpeg4py":
            image = jpeg4py.JPEG(str(image_path)).decode()
        else:
            raise NotImplementedError("Only cv2 and jpeg4py are supported.")
        return image

    raise FileNotFoundError(f"File not found {image_path}")

def load_grayscale(mask_path: Union[Path, str]) -> np.array:
    """Load grayscale mask from path

    Args:
        mask_path: Path to mask

    Returns: 1 channel grayscale mask

    """
    if Path(mask_path).is_file():
        return cv2.imread(str(mask_path), cv2.IMREAD_GRAYSCALE)
    raise FileNotFoundError(f"File not found {mask_path}")

def pad(image: np.array, factor: int = 32, border: int = cv2.BORDER_REFLECT_101) -> tuple:
    """Pads the image on the sides, so that it will be divisible by factor.
    Common use case: UNet type architectures.

    Args:
        image:
        factor:
        border: cv2 type border.

    Returns: padded_image

    """
    height, width = image.shape[:2]

    if height % factor == 0:
        y_min_pad = 0
        y_max_pad = 0
    else:
        y_pad = factor - height % factor
        y_min_pad = y_pad // 2
        y_max_pad = y_pad - y_min_pad

    if width % factor == 0:
        x_min_pad = 0
        x_max_pad = 0
    else:
        x_pad = factor - width % factor
        x_min_pad = x_pad // 2
        x_max_pad = x_pad - x_min_pad

    padded_image = cv2.copyMakeBorder(image, y_min_pad, y_max_pad, x_min_pad, x_max_pad, border)

    return padded_image, (x_min_pad, y_min_pad, x_max_pad, y_max_pad)

def unpad(image: np.array, pads: Tuple[int, int, int, int]) -> np.ndarray:
    """Crops patch from the center so that sides are equal to pads.

    Args:
        image:
        pads: (x_min_pad, y_min_pad, x_max_pad, y_max_pad)

    Returns: cropped image

    """
    x_min_pad, y_min_pad, x_max_pad, y_max_pad = pads
    height, width = image.shape[:2]

    return image[y_min_pad : height - y_max_pad, x_min_pad : width - x_max_pad]

def pad_to_size(
    target_size: Tuple[int, int],
    image: np.array,
    bboxes: Optional[np.ndarray] = None,
    keypoints: Optional[np.ndarray] = None,
) -> Dict[str, Union[np.ndarray, Tuple[int, int, int, int]]]:
    """Pads the image on the sides to the target_size

    Args:
        target_size: (target_height, target_width)
        image:
        bboxes: np.array with shape (num_boxes, 4). Each row: [x_min, y_min, x_max, y_max]
        keypoints: np.array with shape (num_keypoints, 2), each row: [x, y]

    Returns:
        {
            "image": padded_image,
            "pads": (x_min_pad, y_min_pad, x_max_pad, y_max_pad),
            "bboxes": shifted_boxes,
            "keypoints": shifted_keypoints
        }

    """
    target_height, target_width = target_size

    image_height, image_width = image.shape[:2]

    if target_width < image_width:
        raise ValueError(f"Target width should bigger than image_width" f"We got {target_width} {image_width}")

    if target_height < image_height:
        raise ValueError(f"Target height should bigger than image_height" f"We got {target_height} {image_height}")

    if image_height == target_height:
        y_min_pad = 0
        y_max_pad = 0
    else:
        y_pad = target_height - image_height
        y_min_pad = y_pad // 2
        y_max_pad = y_pad - y_min_pad

    if image_width == target_width:
        x_min_pad = 0
        x_max_pad = 0
    else:
        x_pad = target_width - image_width
        x_min_pad = x_pad // 2
        x_max_pad = x_pad - x_min_pad

    result = {
        "pads": (x_min_pad, y_min_pad, x_max_pad, y_max_pad),
        "image": cv2.copyMakeBorder(image, y_min_pad, y_max_pad, x_min_pad, x_max_pad, cv2.BORDER_CONSTANT),
    }

    if bboxes is not None:
        bboxes[:, 0] += x_min_pad
        bboxes[:, 1] += y_min_pad
        bboxes[:, 2] += x_min_pad
        bboxes[:, 3] += y_min_pad

        result["bboxes"] = bboxes

    if keypoints is not None:
        keypoints[:, 0] += x_min_pad
        keypoints[:, 1] += y_min_pad

        result["keypoints"] = keypoints

    return result

def unpad_from_size(
    pads: Tuple[int, int, int, int],
    image: Optional[np.array] = None,
    bboxes: Optional[np.ndarray] = None,
    keypoints: Optional[np.ndarray] = None,
) -> Dict[str, np.ndarray]:
    """Crops patch from the center so that sides are equal to pads.

    Args:
        image:
        pads: (x_min_pad, y_min_pad, x_max_pad, y_max_pad)
        bboxes: np.array with shape (num_boxes, 4). Each row: [x_min, y_min, x_max, y_max]
        keypoints: np.array with shape (num_keypoints, 2), each row: [x, y]

    Returns: cropped image

    {
            "image": cropped_image,
            "bboxes": shifted_boxes,
            "keypoints": shifted_keypoints
        }

    """
    x_min_pad, y_min_pad, x_max_pad, y_max_pad = pads

    result = {}

    if image is not None:
        height, width = image.shape[:2]
        result["image"] = image[y_min_pad : height - y_max_pad, x_min_pad : width - x_max_pad]

    if bboxes is not None:
        bboxes[:, 0] -= x_min_pad
        bboxes[:, 1] -= y_min_pad
        bboxes[:, 2] -= x_min_pad
        bboxes[:, 3] -= y_min_pad

        result["bboxes"] = bboxes

    if keypoints is not None:
        keypoints[:, 0] -= x_min_pad
        keypoints[:, 1] -= y_min_pad

        result["keypoints"] = keypoints

    return result

def get_size(file_path: Union[str, Path]) -> Tuple[int, int]:
    """Gets size of the image in a lazy way.

    Args:
        file_path: Path to the target image.

    Returns: (width, height)

    """
    image = Image.open(file_path)
    labeled_exif = get_labeled_exif(get_exif(image))
    if labeled_exif["Orientation"] in [6, 8]:
        cv2_height, cv2_width = cv2.imread((str(file_path))).shape[:2]
        height, width = image.size
        if cv2_height != height or cv2_width != width:
            raise ValueError(
                f"PIL and cv2 image shapes do not match. " f"PIL {width, height}. CV2 {cv2_width, cv2_height}."
            )
    else:
        width, height = image.size

    return width, height

def get_exif(image: Image) -> dict:
    image.verify()
    return image._getexif()

def get_labeled_exif(exif: dict) -> dict:
    labeled = {}
    for (key, val) in exif.items():
        labeled[TAGS.get(key)] = val
    return labeled

def bgr2rgb(image: np.array) -> np.array:
    """Convert image from bgr to rgb format

    Args:
        image:

    Returns:

    """
    return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

def stretch_8bit(
    bands: np.ndarray, lower_percent: int = 1, higher_percent: int = 99, exclude_zero: bool = True
) -> np.ndarray:
    out = np.zeros_like(bands).astype(np.float32)
    for i in range(bands.shape[-1]):
        a = 0
        b = 1
        band = bands[:, :, i].flatten()
        if exclude_zero:
            filtered = band[band > 0]
        if len(filtered) == 0:
            continue
        c = np.percentile(filtered, lower_percent)
        d = np.percentile(filtered, higher_percent)
        t = a + (bands[:, :, i] - c) * (b - a) / (d - c)
        t[t < a] = a
        t[t > b] = b
        out[:, :, i] = t
    return out.astype(np.float32)

def get_sha256(image: np.ndarray, file_type: str = ".jpg") -> str:
    _, buffer = cv2.imencode(file_type, image)
    return sha256(buffer).hexdigest()

def align_face(
    image: np.ndarray,
    source_landmarks: Union[np.ndarray, list, tuple],
    target_landmarks: Union[np.ndarray, Tuple[Tuple[float, float], ...]] = REFERENCE_FACIAL_POINTS,
    crop_size: Union[List[int], np.ndarray, Tuple[int, int]] = DEFAULT_CROP_SIZE,
    interpolation: int = cv2.INTER_CUBIC,
    align_method: str = "similarity",
) -> np.ndarray:
    """Perform Affine transform and crop face.

    Args:
        image:
        source_landmarks:
        target_landmarks:
        crop_size:
        interpolation:
        align_method: Type of the method used for aligning
            similarity: only rotation and shift. Uses first two points
            cv2_affine: full affine transform. Uses first three points

    Returns: Aligned and cropped image.
    """

    if align_method == "cv2_affine":
        transformation_matrix = cv2.getAffineTransform(
            np.float32(source_landmarks[:3]), np.float32(target_landmarks[:3])
        )
    elif align_method == "similarity":
        transformation_matrix, _ = cv2.estimateAffinePartial2D(
            np.float32(source_landmarks), np.float32(target_landmarks)
        )
    else:
        raise NotImplementedError(f"Only cv2_affine and similarity methods are supported got {align_method}")

    return cv2.warpAffine(image, transformation_matrix, (crop_size[0], crop_size[1]), flags=interpolation)


#!/usr/bin/env python

import os,sys
import ogg.vorbis

"""
Wrote this script with help from /usr/share/doc/python-pyvorbis/README.

./change_info.py "./ripped/Orchestral Manoeuvres In The Dark/Crush" ARTIST OMD
Sets every ARTIST tag in the Crush album to 'OMD'

./change_info.py "./ripped/Orchestral Manoeuvres In The Dark/Crush" GENRE Synthpop
Sets every GENRE tag in the Crush album to 'Synthpop'
"""

def updateTag(filename, key, value):
   f = ogg.vorbis.VorbisFile(fullname)
   commdict = f.comment().as_dict()
   commdict[key] = [value]
   comments = ogg.vorbis.VorbisComment(commdict)
   try:
      comments.write_to()
   except TypeError:
      pass
   comments.write_to(fullname)

if __name__ == "__main__":
   if len(sys.argv) == 3:
      mdir = "."
      tagKey = sys.argv[1]
      tagValue = sys.argv[2]
   else:
      mdir = sys.argv[1]
      tagKey = sys.argv[2]
      tagValue = sys.argv[3]

   for filename in os.listdir(mdir):
      fullname = os.path.abspath(os.path.join(mdir, filename))
      updateTag(fullname, tagKey, tagValue)


n = int(input("Enter the number: "))
count_p = 0
count_c = 0
for i in range(2,n+1):
  count=0
  for x in range(2, i):
    if i % x == 0:
      count += 1
  if count == 0:
    print(f"{i} is a prime number.")
    count_p += 1
  else:
    print(f"{i} is a composite number.")
    count_c += 1
print(f"There are {count_p} prime and {count_c} composite number in the range.")


import h5py
import numpy as np
import matplotlib.pylab as plt
import os
import matplotlib
from scipy.stats import mode
import scipy
from scripts.plotting_helpers import placeAxesOnGrid
from matplotlib.patches import Rectangle
from pyitlib import discrete_random_variable as drv
import pathlib
import random

from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Arial']})
matplotlib.rcParams['pdf.fonttype'] = 42

class Figure:
    def __init__(self, output_file):
        self.output_file = output_file
        self.path_to_comp = os.path.join(
            os.path.dirname(os.path.abspath(__file__)
                            ), "..", "data", "local_large_data"
        )
        self.path_to_sample_movie = lambda local_id: f"comp_{local_id}.h5"
        self.list_movies = [637998955, 505811062, 509904120, 657391625]
        self.path_to_mutual_info_anal = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            "..",
            "data",
            "sup_fig4_intermediate.npy",
        )

        local_path = pathlib.Path(__file__).parent.absolute()

        self.path_schematic = os.path.join(
            local_path, "Supp Fig 5 - diagram.png")

    def load_data(self):

        self.list_id_obj = []

        # We first gather needed data

        self.list_movies_data = {}

        for index, local_id in enumerate(self.list_movies):
            local_path = self.path_to_sample_movie(local_id)
            [raw_sample, denoised_sample] = self.load_sample_movies(
                os.path.join(self.path_to_comp, local_path)
            )

            self.list_movies_data[local_id] = [raw_sample, denoised_sample]

    def load_sample_movies(self, local_path):
        with h5py.File(local_path, "r") as file_handle:
            denoised_sample = file_handle["data_proc"][:, :, :]
            raw_sample = file_handle["data_raw"][:, :, :]

        return [raw_sample, denoised_sample]

    def get_corr(self, array, list_pixel):
        array_dim = array.shape
        reshape_array = np.transpose(
            np.reshape(array, [array_dim[0], array_dim[1] * array_dim[2]])
        )
        corr_array = np.corrcoef(reshape_array[list_pixel, :])

        return corr_array

    def get_temporal_relationship_array(
        self,
        raw_data,
        proc_data,
        list_deltas=[-50, -10, -5, -2, -1, 0, 1, 2, 5, 10, 50],
        computation_frames=1000000,
        min_intensity=200,
    ):

        original_size = raw_data.shape

        full_range = np.max(np.abs(list_deltas))

        init_trace = raw_data[full_range:-full_range, 0, 0]
        length_trace = len(init_trace)

        average_frame = np.mean(raw_data, axis=2)
        [x_list, y_list] = np.where(average_frame > min_intensity)

        den_input_to_mutual = np.zeros(
            (len(list_deltas), length_trace * len(x_list)), dtype="uint16"
        )

        raw_input_to_mutual = np.zeros(
            (len(list_deltas), length_trace * len(x_list)), dtype="uint16"
        )

        for index_delta, delta in enumerate(list_deltas):
            start_index = 0
            print(index_delta)
            for index_list, dim1 in enumerate(x_list):
                dim2 = y_list[index_list]

                if -full_range + delta == 0:
                    local_trace_to_compare_den = proc_data[
                        full_range + delta:, dim1, dim2
                    ]
                    local_trace_to_compare_raw = raw_data[
                        full_range + delta:, dim1, dim2
                    ]
                else:
                    local_trace_to_compare_den = proc_data[
                        full_range + delta: -full_range + delta, dim1, dim2
                    ]
                    local_trace_to_compare_raw = raw_data[
                        full_range + delta: -full_range + delta, dim1, dim2
                    ]

                den_input_to_mutual[
                    index_delta, start_index: start_index + length_trace
                ] = local_trace_to_compare_den.astype("uint16")
                raw_input_to_mutual[
                    index_delta, start_index: start_index + length_trace
                ] = local_trace_to_compare_raw.astype("uint16")

                start_index = start_index + length_trace

        local_input_den = den_input_to_mutual[:,
                                              0:computation_frames].astype("uint16")
        local_input_raw = raw_input_to_mutual[:,
                                              0:computation_frames].astype("uint16")

        return [local_input_raw, local_input_den]

    def get_spatial_relationship_array(
        self,
        raw_data,
        proc_data,
        list_deltas=np.arange(-10, 10, 1),
        computation_frames=1000000,
    ):
        original_size = raw_data.shape

        average_frame = np.mean(raw_data, axis=2)
        [x_list, y_list] = np.where(average_frame > 200)

        to_keep = np.where(y_list < original_size[2] - np.max(list_deltas))[0]
        x_list = x_list[to_keep]
        y_list = y_list[to_keep]

        to_keep = np.where(y_list > -np.min(list_deltas))[0]
        x_list = x_list[to_keep]
        y_list = y_list[to_keep]

        den_input_to_mutual = np.zeros(
            (len(list_deltas), original_size[0] * len(x_list)), dtype="uint16"
        )

        raw_input_to_mutual = np.zeros(
            (len(list_deltas), original_size[0] * len(x_list)), dtype="uint16"
        )

        for index_delta, delta in enumerate(list_deltas):
            start_index = 0
            print(index_delta)
            for index_list, dim1 in enumerate(x_list):
                dim2 = y_list[index_list]
                if dim2 + delta < original_size[2]:
                    local_trace_to_compare_den = proc_data[:,
                                                           dim1, dim2 + delta]
                    local_trace_to_compare_raw = raw_data[:,
                                                          dim1, dim2 + delta]

                den_input_to_mutual[
                    index_delta, start_index: start_index + original_size[0]
                ] = local_trace_to_compare_den.astype("uint16")
                raw_input_to_mutual[
                    index_delta, start_index: start_index + original_size[0]
                ] = local_trace_to_compare_raw.astype("uint16")

                start_index = start_index + original_size[0]

        local_input_den = den_input_to_mutual[:,
                                              0:computation_frames].astype("uint16")
        local_input_raw = raw_input_to_mutual[:,
                                              0:computation_frames].astype("uint16")

        return [local_input_raw, local_input_den]

    def plot_corr_distrib(self, ax, list_corr_den, list_corr_raw):

        bins_on = np.arange(-1, 1, 0.01)
        [den_bins, final_bins] = np.histogram(
            np.array(list_corr_den), bins=bins_on)
        [raw_bins, final_bins] = np.histogram(
            np.array(list_corr_raw), bins=bins_on)

        plt.plot(bins_on[:-1], raw_bins, "#4A484A", label="Raw", linewidth=1)
        plt.fill_between(
            bins_on[:-1], raw_bins, color=(209 /
                                           255.0, 209 / 255.0, 209 / 255.0)
        )
        plt.plot(
            bins_on[:-1], den_bins, "#8A181A", label="Deep interpolation", linewidth=1
        )
        plt.fill_between(
            bins_on[:-1], den_bins, color=(231 /
                                           255.0, 209 / 255.0, 210 / 255.0)
        )

        plt.xlabel("Pearson correlation of individual pixels")
        plt.gca().spines["right"].set_visible(False)
        plt.gca().spines["top"].set_visible(False)
        plt.gca().spines["left"].set_visible(False)
        plt.gca().axes.yaxis.set_ticks([])
        plt.gca().axes.yaxis.set_ticklabels([])
        plt.legend(frameon=False, prop={"size": 8})

    def make_figure(self):
        self.fig = plt.figure(figsize=(18, 16))

        local_label = placeAxesOnGrid(
            self.fig, xspan=(0.01, 0.02), yspan=(0.01, 0.02))
        local_label.text(0, 0, "A", fontsize=15, weight="bold")
        local_label.axis("off")
        local_label.set_xlim(0, 0.01)
        local_label.set_ylim(0, 0.01)

        ax = placeAxesOnGrid(
            self.fig, dim=[2, 2], xspan=[0.05, 0.45], yspan=[0.05, 0.45]
        )

        [raw_sample, denoised_sample] = self.list_movies_data[637998955]

        list_pixel = np.random.randint(0, 512 * 512, size=10000)
        local_corr_raw = self.get_corr(raw_sample, list_pixel)
        local_corr_den = self.get_corr(denoised_sample, list_pixel)

        plt.sca(ax[0][0])
        plt.imshow(raw_sample[100, :, :], cmap="gray", clim=[100, 350])
        plt.title("Raw")
        vmin, vmax = plt.gci().get_clim()
        local_shape_raw = [512, 512]
        rectangle_length = 100 * local_shape_raw[0] / 400
        rect = matplotlib.patches.Rectangle(
            [30, local_shape_raw[0] - 60], rectangle_length, 30, angle=0.0, color="w"
        )
        ax[0][0].add_patch(rect)
        plt.axis("off")

        plt.sca(ax[0][1])
        plt.title("DeepInterpolation")
        plt.imshow(denoised_sample[100, :, :], cmap="gray", clim=[100, 350])
        plt.axis("off")

        plt.sca(ax[1][0])
        im_ax = plt.imshow(local_corr_raw, clim=[-0.5, 0.5])
        plt.xlabel("Random selection\nof 10,000 pixels")
        plt.ylabel("Random selection\nof 10,000 pixels")

        plt.sca(ax[1][1])
        plt.imshow(local_corr_den, clim=[-0.5, 0.5])
        plt.xlabel("Random selection\nof 10,000 pixels")
        plt.gca().get_yaxis().set_visible(False)
        plt.gca().get_yaxis().set_ticks([])

        ax = placeAxesOnGrid(
            self.fig, dim=[1, 1], xspan=[0.455, 0.46], yspan=[0.27, 0.48]
        )

        cb = plt.colorbar(im_ax, cax=ax)
        cb.set_label("Pearson correlation")

        local_label = placeAxesOnGrid(
            self.fig, xspan=(0.515, 0.525), yspan=(0.01, 0.02)
        )
        local_label.text(0, 0, "B", fontsize=15, weight="bold")
        local_label.axis("off")
        local_label.set_xlim(0, 0.01)
        local_label.set_ylim(0, 0.01)
        ax = placeAxesOnGrid(
            self.fig, dim=[1, 1], xspan=[0.505, 0.795], yspan=[0.05, 0.23]
        )

        for index, indiv_id in enumerate(self.list_movies):
            [raw_sample, denoised_sample] = self.list_movies_data[indiv_id]
            list_pixel = np.random.randint(0, 512 * 512, size=10000)
            local_corr_raw = self.get_corr(raw_sample, list_pixel)
            local_corr_den = self.get_corr(denoised_sample, list_pixel)

            if index == 0:
                full_corr_raw = local_corr_raw
                full_corr_den = local_corr_den
            else:
                full_corr_raw = np.append(full_corr_raw, local_corr_raw)
                full_corr_den = np.append(full_corr_den, local_corr_den)

        result = scipy.stats.ks_2samp(
            full_corr_den[random.sample(range(0, 40000), 1000)],
            full_corr_raw[random.sample(range(0, 40000), 1000)],
        )
        print("Comparison of pixel correlation using KS two-sided test")
        print(result)
        print(
            "rawpixel corr, mean:{}, sem:{}, N={}".format(
                np.mean(full_corr_raw),
                scipy.stats.sem(full_corr_raw),
                len(full_corr_raw),
            )
        )
        print(
            "denoised pixel corr, mean:{}, sem:{}, N={}".format(
                np.mean(full_corr_den),
                scipy.stats.sem(full_corr_den),
                len(full_corr_den),
            )
        )

        self.plot_corr_distrib(ax, full_corr_den, full_corr_raw)
        plt.text(
            0.8,
            0.5,
            "N=40,000 pixels\n4 experiments",
            fontsize=8,
            transform=ax.transAxes,
        )

        local_label = placeAxesOnGrid(
            self.fig, xspan=(0.515, 0.525), yspan=(0.3, 0.31))
        local_label.text(0, 0, "C", fontsize=15, weight="bold")
        local_label.axis("off")
        local_label.set_xlim(0, 0.01)
        local_label.set_ylim(0, 0.01)

        ax = placeAxesOnGrid(
            self.fig, dim=[1, 1], xspan=[0.505, 0.795], yspan=[0.3, 0.45]
        )

        local_img = plt.imread(self.path_schematic)
        plt.imshow(local_img)
        plt.axis("off")

        local_label = placeAxesOnGrid(
            self.fig, xspan=(0.01, 0.02), yspan=(0.5, 0.51))
        local_label.text(0, 0, "D", fontsize=15, weight="bold")
        local_label.axis("off")
        local_label.set_xlim(0, 0.01)
        local_label.set_ylim(0, 0.01)

        ax = placeAxesOnGrid(
            self.fig, dim=[2, 2], xspan=[0.05, 0.795], yspan=[0.55, 0.95]
        )

        [raw_sample, denoised_sample] = self.list_movies_data[637998955]

        delta_space = [0, 1, 2, 3, 4, 5, 6, 8, 10, 15, 20]
        delta_time = [0, 1, 2, 3, 4, 5, 10, 25, 50]

        if os.path.isfile(self.path_to_mutual_info_anal):
            with open(self.path_to_mutual_info_anal, "rb") as f:
                mi_den_space = np.load(f)
                mi_raw_space = np.load(f)
                mi_den_time = np.load(f)
                mi_raw_time = np.load(f)
                corr_den_space = np.load(f)
                corr_raw_space = np.load(f)
                corr_den_time = np.load(f)
                corr_raw_time = np.load(f)
        else:
            [
                data_relation_raw_space,
                data_relation_den_space,
            ] = self.get_spatial_relationship_array(
                raw_sample, denoised_sample, list_deltas=delta_space
            )
            [
                data_relation_raw_time,
                data_relation_den_time,
            ] = self.get_temporal_relationship_array(
                raw_sample, denoised_sample, list_deltas=delta_time
            )

            print("Computing mutual information")
            print(data_relation_den_space.shape)
            mi_den_space = drv.information_mutual(data_relation_den_space)
            mi_raw_space = drv.information_mutual(data_relation_raw_space)
            mi_den_time = drv.information_mutual(data_relation_den_time)
            mi_raw_time = drv.information_mutual(data_relation_raw_time)

            print("Computing cross-correlation")
            corr_den_space = np.corrcoef(data_relation_den_space)
            corr_raw_space = np.corrcoef(data_relation_raw_space)
            corr_den_time = np.corrcoef(data_relation_den_time)
            corr_raw_time = np.corrcoef(data_relation_raw_time)

            with open(self.path_to_mutual_info_anal, "wb") as f:
                np.save(f, mi_den_space)
                np.save(f, mi_raw_space)
                np.save(f, mi_den_time)
                np.save(f, mi_raw_time)
                np.save(f, corr_den_space)
                np.save(f, corr_raw_space)
                np.save(f, corr_den_time)
                np.save(f, corr_raw_time)

        plt.sca(ax[0][0])
        plt.plot(
            np.array(delta_time) / 30,
            mi_den_time[0, :],
            label="DeepInterpolation",
            color="#8A181A",
        )
        plt.plot(
            np.array(delta_time) / 30, mi_raw_time[0, :], label="Raw", color="#4A484A"
        )

        plt.ylabel("Pixel Mutual information (bits)")
        plt.gca().spines["right"].set_visible(False)
        plt.gca().spines["top"].set_visible(False)

        new_tick_locations = np.arange(0, 1, 5 / 30)
        new_tick_str = np.arange(0, 30, 5)
        plt.xlim([0, 1])

        ax2 = ax[0][0].twiny()
        ax2.set_xticks(new_tick_locations)
        ax2.set_xticklabels(new_tick_str)
        ax2.set_xlabel(r"Relative frame number from center frame")

        ax[0][0].add_patch(
            matplotlib.patches.Rectangle(
                xy=(0, 0),  # point of origin.
                width=0.2,
                height=1,
                linewidth=1,
                linestyle="dashed",
                color="black",
                fill=False,
            )
        )
        zoom_ax = placeAxesOnGrid(
            self.fig, dim=[1, 1], xspan=[0.15, 0.35], yspan=[0.575, 0.625]
        )
        plt.sca(zoom_ax)
        plt.plot(
            np.array(delta_time) / 30,
            mi_den_time[0, :],
            label="DeepInterpolation",
            color="#8A181A",
        )
        plt.plot(
            np.array(delta_time) / 30, mi_raw_time[0, :], label="Raw", color="#4A484A"
        )
        plt.xlim([0, 0.2])
        plt.ylim([0, 1])
        plt.gca().spines["right"].set_visible(False)
        plt.gca().spines["top"].set_visible(False)

        plt.sca(ax[0][1])
        plt.plot(
            np.array(delta_space) * 400 / 512,
            mi_den_space[0, :],
            label="DeepInterpolation",
            color="#8A181A",
        )
        plt.plot(
            np.array(delta_space) * 400.0 / 512.0,
            mi_raw_space[0, :],
            label="Raw",
            color="#4A484A",
        )

        plt.gca().spines["right"].set_visible(False)
        plt.gca().spines["top"].set_visible(False)
        plt.xlim([0, 10])
        plt.legend(frameon=False, prop={"size": 8})
        plt.text(
            0.5,
            0.5,
            "N=1,000,000 pixels\n1 experiment",
            fontsize=8,
            transform=ax[0][1].transAxes,
        )

        def pix2um(x):
            return x * 400.0 / 512

        def um2pix(x):
            return x * 512.0 / 400

        ax2 = ax[0][1].secondary_xaxis("top", functions=(um2pix, pix2um))
        ax2.set_xlabel(r"Relative position from center pixel (pixels)")

        plt.sca(ax[1][0])
        plt.plot(
            np.array(delta_time) / 30,
            corr_den_time[0, :],
            label="DeepInterpolation",
            color="#8A181A",
        )
        plt.plot(
            np.array(delta_time) / 30, corr_raw_time[0, :], label="Raw", color="#4A484A"
        )

        plt.xlabel("Relative time from center frame (s)")
        plt.ylabel("Pearson correlation")
        plt.gca().spines["right"].set_visible(False)
        plt.gca().spines["top"].set_visible(False)
        plt.xlim([0, 1])

        plt.sca(ax[1][1])
        plt.plot(
            np.array(delta_space) * 400 / 512,
            corr_den_space[0, :],
            label="DeepInterpolation",
            color="#8A181A",
        )
        plt.plot(
            np.array(delta_space) * 400 / 512,
            corr_raw_space[0, :],
            label="Raw",
            color="#4A484A",
        )

        plt.xlabel("Relative position from center pixel ($\mu$m)")
        plt.gca().spines["right"].set_visible(False)
        plt.gca().spines["top"].set_visible(False)

        plt.xlim([0, 10])

    def save_figure(self):
        self.fig.savefig(self.output_file, bbox_inches="tight", dpi=600)

if __name__ == "__main__":
    output_file = os.path.join(
        os.path.dirname(os.path.abspath(__file__)),
        "pdfs",
        "Supp Figure 3 - pixel_corr.pdf",
    )
    if os.path.isfile(output_file):
        os.remove(output_file)

    local_figure = Figure(output_file)
    local_figure.load_data()
    local_figure.make_figure()
    local_figure.save_figure()


import bson.binary
import pytest

import nj

@pytest.mark.parametrize(
    'func,op',
    [
        (nj.bits_all_set_, '$bitsAllSet'),
        (nj.bits_any_set_, '$bitsAnySet'),
        (nj.bits_all_clear_, '$bitsAllClear'),
        (nj.bits_any_clear_, '$bitsAnyClear'),
    ],
)
def test_bitwise(func, op):
    query = func(bson.binary.Binary(b'*'))
    assert query == {op: bson.binary.Binary(b'*')}

    query = func(b'*')
    assert query == {op: bson.binary.Binary(b'*')}

    query = func(42)
    assert query == {op: 42}

    query = func([1, 3, 5])
    assert query == {op: [1, 3, 5]}


import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.linear_model import LogisticRegression

fontsize = "30";
params = {'figure.autolayout':True,
          'legend.fontsize': fontsize,
          'figure.figsize': (12, 8),
         'axes.labelsize': fontsize,
         'axes.titlesize': fontsize,
         'xtick.labelsize':fontsize,
         'ytick.labelsize':fontsize}
plt.rcParams.update(params)

# we create 40 separable points
np.random.seed(0)
npc = 30
X = np.r_[np.random.randn(npc, 2) - [1, 1], np.random.randn(npc, 2) + [1,1]]
y = [0] * npc + [1] * npc

X_train = X
y_train = y

n_sample = len(X)

x_min = X[:, 0].min()
x_max = X[:, 0].max()
y_min = X[:, 1].min()
y_max = X[:, 1].max()
logreg = LogisticRegression()
logreg.fit(X,y)
plt.figure(0)
plt.clf()
XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j]
Z = logreg.decision_function(np.c_[XX.ravel(), YY.ravel()])
plt.scatter(X[:, 0], X[:, 1], c=y, zorder=10, cmap="binary", #plt.cm.Paired,
            edgecolor='k', s=40)
Z = Z.reshape(XX.shape)
plt.pcolormesh(XX, YY, Z > 0, cmap="rainbow", alpha=.1, shading="flat", edgecolors="None")
plt.contour(XX, YY, Z, colors=['k'],
            linestyles=['-'], levels=[0])
plt.title("Logistic Regression")
plt.savefig('logreg_train.png')

# Now loop through some SVM kernels
for fig_num, kernel in enumerate(('linear', 'rbf', 'poly')):
    clf = svm.SVC(kernel=kernel, gamma=10)
    clf.fit(X_train, y_train)

    plt.figure(fig_num+1)
    plt.clf()
    plt.scatter(X[:, 0], X[:, 1], c=y, zorder=10, cmap="binary", #plt.cm.Paired,
                edgecolor='k', s=40)
    plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=100,
                facecolors='none', zorder=10, edgecolors='r')

    # Circle out the test data
    #plt.scatter(X_test[:, 0], X_test[:, 1], s=80, facecolors='none',
    #            zorder=10, edgecolor='k')

    plt.axis('tight')
    #x_min = X[:, 0].min()
    #x_max = X[:, 0].max()
    #y_min = X[:, 1].min()
    #y_max = X[:, 1].max()

    XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j]
    Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(XX.shape)
    plt.pcolormesh(XX, YY, Z > 0, cmap="rainbow", alpha=.1, shading="flat", edgecolors="None")
    plt.contour(XX, YY, Z, colors=['k', 'k', 'k'],
                linestyles=['--', '-', '--'], levels=[-1, 0, 1])

    title = 'SVM with '+kernel+' kernel';
    plt.title(title)
    plt.savefig(title)

#plt.show()


from math import factorial as fact

def primality(n):
    if type(n) != int:
        raise TypeError("argument must be of type 'int'")
    if n == 2:
        return True
    if n < 2 or n % 2 == 0:
        return False
    for i in range(3, int(n**0.5 + 1), 2):
        if n % i == 0:
            return False
    return True

store = []
flag = False
for d in [7, 4]:
    for pos in range(fact(d), 0, -1):
        num = ['1', '2', '3', '4', '5', '6', '7', '8', '9'][:d]
        box = ''
        while len(num) > 0:
            size = fact(len(num)) // len(num)
            box += num[(pos - 1) // size]
            num.pop((pos - 1) // size)
            while pos >= size:
                pos -= size
        if primality(int(box)):
            store.append(int(box))
t = int(input())
for x in range(t):
    n = int(input())
    for i in store:
        if i <= n:
            print(i)
            break
    else:
        print(-1)


"""Create similarity plots for the dataset."""
import matplotlib.pyplot as plt

from .task import Task
from aimsim.utils.plotting_scripts import (
    plot_density,
    plot_heatmap,
    plot_scatter,
    plot_scatter_interactive,
)

class VisualizeDataset(Task):
    def __init__(self, configs=None, **kwargs):
        """
        Constructor for the VisualizeDataset class.

        Args:
            configs(dict): Dictionary of configurations. Default is None.
            **kwargs: Keyword arguments to modify configs fields.
        Notes:
            The configuration structure with default values are:
            heatmap_plot_settings: {}  # pass through keywords for
                                       # aimsim.utils.plotting_scripts.\
                                       #  plot_heatmap
            similarity_plot_settings: {}   # pass through keywords for
                                           # aimsim.utils.plotting_scripts. \
                                           #plot_density
            embedding_plot_settings:
                    {'plot_color': 'red'
                     'plot_title': '2-D projected space',
                     'xlabel': 'Dimension 1',
                     'ylabel': 'Dimension 2',
                     'embedding': {'method': "mds",
                                    'params': {'random_state': 42}}}

        """
        if configs is None:
            configs = dict()  # all configs are optional
        configs.update(kwargs)
        super().__init__(configs)
        self.plot_settings = {}
        self._extract_configs()

    def _extract_configs(self):
        self.plot_settings = dict()
        self.plot_settings["heatmap_plot"] = self.configs.get(
            "heatmap_plot_settings", {}
        )
        self.plot_settings["pairwise_plot"] = self.configs.get(
            "similarity_plot_settings", {}
        )
        self.plot_settings["embedding_plot"] = {
            "plot_color": 'red',
            "plot_title": '2-D projected space',
            "xlabel": "Dimension 1",
            "ylabel": "Dimension 2",
            "embedding": {"method": "mds",
                          "params": {"random_state": 42, }
                          },
        }
        self.plot_settings["embedding_plot"].update(self.configs.get(
            "embedding_plot_settings",
            {}))

    def __call__(self, molecule_set):
        """Visualize essential properties of the dataset.

        Args:
            molecule_set(AIMSim.chemical_datastructures MoleculeSet):
                Molecular database.

        Plots Generated
        ---------------
        1. Heatmap of Molecular Similarity.
        2. PDF of the similarity distribution of the molecules in the database.

        """
        if len(molecule_set.molecule_database) > 1_000:
            warn(
                "Similarity heatmap and embedding plot may take significant time on large datasets "
                f"(detected size {len(molecule_set.molecule_database):d}).",
                RuntimeWarning,
            )

        similarity_matrix = molecule_set.get_similarity_matrix()
        if molecule_set.is_verbose:
            print("Plotting similarity heatmap")
        plot_heatmap(similarity_matrix, **self.plot_settings["heatmap_plot"])

        if molecule_set.is_verbose:
            print("Generating pairwise similarities")
        pairwise_similarity_vector = molecule_set.get_pairwise_similarities()
        if molecule_set.is_verbose:
            print("Plotting density of pairwise similarities")
        plot_density(
            pairwise_similarity_vector,
            **self.plot_settings["pairwise_plot"],
        )

        method_ = self.plot_settings["embedding_plot"]["embedding"]["method"]
        reduced_features = molecule_set.get_transformed_descriptors(
            method_=method_,
            n_components=2,
            **self.plot_settings["embedding_plot"]["embedding"].get("params", {}))
        dimension_1 = reduced_features[:, 0]
        dimension_2 = reduced_features[:, 1]

        plot_scatter_interactive(
            dimension_1,
            dimension_2,
            hover_names=molecule_set.get_mol_names(),
            xlabel=self.plot_settings["embedding_plot"]["xlabel"],
            ylabel=self.plot_settings["embedding_plot"]["ylabel"],
            title=self.plot_settings["embedding_plot"]["plot_title"],
            plot_color=self.plot_settings["embedding_plot"]["plot_color"],
            offset=0,
        )

    def __str__(self):
        return "Task: Visualize a dataset"


from typing import Any, Optional, Callable, Sequence
from imgui_bundle import imgui, immapp, imgui_node_editor as node_ed
from fiatlux_py import AnyDataWithGui, FunctionWithGui, FunctionsCompositionGraph

def versatile_gui_data(value: Any) -> None:
    if value is None:
        imgui.text("None")
    elif isinstance(value, int):
        imgui.text(f"Int Value={value}")
    elif isinstance(value, float):
        imgui.text(f"Float Value={value}")
    elif isinstance(value, str):
        max_len = 50
        if len(value) > max_len:
            imgui.text(f"Str len={len(value)}")
            imgui.text('"' + value[:max_len])
            if imgui.button("..."):
                imgui.open_popup("popup_value_text")

            node_ed.suspend_node_editor_canvas_immapp()
            if imgui.begin_popup("popup_value_text"):
                imgui.input_text_multiline("##value_text", value)
                imgui.end_popup()
            node_ed.resume_node_editor_canvas_immapp()
        else:
            imgui.text('"' + value + '"')
    elif isinstance(value, list):
        imgui.text(f"List len={len(value)}")
        for i, v in enumerate(value):
            if i >= 5:
                if imgui.button("..."):
                    imgui.open_popup("popup_value_list")

                node_ed.suspend_node_editor_canvas_immapp()
                if imgui.begin_popup("popup_value_list"):
                    for i, v in enumerate(value):
                        versatile_gui_data(v)
                    imgui.end_popup()
                node_ed.resume_node_editor_canvas_immapp()

                break
            else:
                versatile_gui_data(v)
    elif isinstance(value, tuple):
        # imgui.text(f"Tuple len={len(value)}")
        strs = [str(v) for v in value]
        tuple_str = "(" + ", ".join(strs) + ")"
        imgui.text(tuple_str)

    else:
        raise Exception(f"versatile_gui_data Unsupported type: {type(value)}")

def versatile_gui_set_input(value: Any) -> Optional[Any]:
    changed = False
    if value is None:
        imgui.text("gui_set_input: unknown type (None)")
    elif isinstance(value, int):
        imgui.set_next_item_width(100)
        changed, new_value = imgui.slider_int("", value, 0, 100)
    elif isinstance(value, float):
        imgui.set_next_item_width(100)
        changed, new_value = imgui.slider_float("", value, 0.0, 100.0)  # type: ignore
    elif isinstance(value, str):
        imgui.set_next_item_width(100)
        changed, new_value = imgui.input_text("", value)  # type: ignore
    else:
        raise Exception(f"VersatileDataWithGui Unsupported type: {type(value)}")

    if changed:
        return new_value
    else:
        return None

class VersatileDataWithGui(AnyDataWithGui):
    value: Any = None

    def gui_data(self, function_name: str) -> None:
        imgui.push_id(str(id(self)))
        versatile_gui_data(self.value)
        imgui.pop_id()

    def gui_set_input(self) -> Optional[Any]:
        return versatile_gui_set_input(self.value)

    def get(self) -> Optional[Any]:
        return self.value

    def set(self, v: Any) -> None:
        self.value = v

class VersatileFunctionWithGui(FunctionWithGui):
    inner_function: Callable[[Any], Any]
    inner_function_name: str

    def __init__(self, function: Callable[[Any], Any], function_name: Optional[str] = None):
        self.inner_function = function
        if function_name is not None:
            self.inner_function_name = function_name
        else:
            self.inner_function_name = function.__name__
        self.input_gui = VersatileDataWithGui()
        self.output_gui = VersatileDataWithGui()

    def f(self, x: Any) -> Any:
        return self.inner_function(x)

    def name(self) -> str:
        return self.inner_function_name

    def gui_params(self) -> bool:
        return False

class VersatileFunctionsCompositionGraph(FunctionsCompositionGraph):
    def __init__(self, functions: Sequence[Callable[[Any], Any]]) -> None:
        functions_with_gui = [VersatileFunctionWithGui(f) for f in functions]
        FunctionsCompositionGraph.__init__(self, functions_with_gui)
        # super.__init__(self, functions_with_gui)


import tkinter as tk
from PIL import Image, ImageTk
from .board import Board

class Game:
    def __init__(self, root, play_team):
        self.root = root
        self.canvas = tk.Canvas(root, width=1300, height=800, bg='white')
        self.canvas.pack()
        top_team = 'white' if play_team == 'black' else 'black'
        self.board = Board(top_team)
        self.selected_piece_position = None
        self.canvas.bind("<Button-1>", self.on_square_clicked)

        # Press 'r' to reset the board
        self.root.bind('r', self.reset_game)

        # Press 'q' to quit
        self.root.bind('q', self.quit)

        # Press 'm' to go back to the menu
        self.root.bind('m', self.go_to_menu)

        # Keep track of turns. 0: White Left, 1: Black Right, 2: White Right, 3: Black Left
        self.current_turn = 0

        # Load all piece images
        self.piece_images = {}
        colors = ['white', 'black']
        pieces = ['r', 'n', 'b', 'q', 'k', 'p']
        for color in colors:
            for piece in pieces:
                image = Image.open(f'twochess/images/{color}-{piece}.png')
                image = image.resize((90, 90))  # Assuming square size is 100x100, adjust if needed
                self.piece_images[f'{color}-{piece}'] = ImageTk.PhotoImage(image)

                image = Image.open(f'twochess/images/{color}-{piece}_active.png')
                image = image.resize((90, 90))  # Assuming square size is 100x100, adjust if needed
                self.piece_images[f'{color}-{piece}_active'] = ImageTk.PhotoImage(image)

                if piece == 'k':
                    image = Image.open(f'twochess/images/{color}-{piece}_check.png')
                    image = image.resize((90, 90))
                    self.piece_images[f'{color}-{piece}_check'] = ImageTk.PhotoImage(image)

        # Load image of possible moves
        image = Image.open(f'twochess/images/possible_moves.png')
        image = image.resize((30, 30))
        self.possible_moves_img = ImageTk.PhotoImage(image)

        self.possible_moves = []

        self.draw_board()

    def draw_board(self):
        self.canvas.delete("all")

        # Draw pieces
        for i in range(8):
            for j in range(13):
                x1 = j * 100
                y1 = i * 100
                x2 = x1 + 100
                y2 = y1 + 100

                if (i + j) % 2 == 0:
                    color = '#f0d9b5'
                else:
                    color = '#b58863'

                self.canvas.create_rectangle(x1, y1, x2, y2, fill=color,width=0)

                piece = self.board.board[i][j]
                if piece:
                    # Draw the active pieces (those that can be moved)
                    # Check the kings first for checks
                    if piece.piece_type == 'k' and piece.check_for_check(self.board.board, piece.team, (i, j)):
                            image = self.piece_images[f'{piece.team}-{piece.piece_type}_check']
                            self.canvas.create_image(x1+5, y1+5, anchor='nw', image=image)
                    else:
                        if self.current_turn == 0:
                            if piece.team == 'white' and j <= 6:
                                image = self.piece_images[f'{piece.team}-{piece.piece_type}_active']
                                self.canvas.create_image(x1+5, y1+5, anchor='nw', image=image)
                            else:
                                image = self.piece_images[f'{piece.team}-{piece.piece_type}']
                                self.canvas.create_image(x1+5, y1+5, anchor='nw', image=image)
                        elif self.current_turn == 1:
                            if piece.team == 'black' and j <= 6:
                                image = self.piece_images[f'{piece.team}-{piece.piece_type}_active']
                                self.canvas.create_image(x1+5, y1+5, anchor='nw', image=image)
                            else:
                                image = self.piece_images[f'{piece.team}-{piece.piece_type}']
                                self.canvas.create_image(x1+5, y1+5, anchor='nw', image=image)
                        elif self.current_turn == 2:
                            if piece.team == 'white' and j >= 6:
                                image = self.piece_images[f'{piece.team}-{piece.piece_type}_active']
                                self.canvas.create_image(x1+5, y1+5, anchor='nw', image=image)
                            else:
                                image = self.piece_images[f'{piece.team}-{piece.piece_type}']
                                self.canvas.create_image(x1+5, y1+5, anchor='nw', image=image)
                        elif self.current_turn == 3:
                            if piece.team == 'black' and j >= 6:
                                image = self.piece_images[f'{piece.team}-{piece.piece_type}_active']
                                self.canvas.create_image(x1+5, y1+5, anchor='nw', image=image)
                            else:
                                image = self.piece_images[f'{piece.team}-{piece.piece_type}']
                                self.canvas.create_image(x1+5, y1+5, anchor='nw', image=image)

        # Draw possible moves
        image = self.possible_moves_img
        for (i,j) in self.possible_moves:
            x1 = j * 100
            y1 = i * 100
            x2 = x1 + 100
            y2 = y1 + 100
            if (i + j) % 2 == 0:
                color = '#f0d9b5'
            else:
                color = '#b58863'
            self.canvas.create_rectangle(x1, y1, x2, y2, fill=color,width=0)
            self.canvas.create_image(x1+35, y1+35, anchor='nw', image=image)

    def on_square_clicked(self, event):
        x = event.y // 100
        y = event.x // 100

        # Only allow moving a piece if the right player is moving
        if self.selected_piece_position:
            print(self.selected_piece_position)
            piece = self.board.board[self.selected_piece_position[0]][self.selected_piece_position[1]]
            if piece:
                self.possible_moves = self.board.get_possible_moves((x,y))
                if ((self.current_turn == 0 and piece.team == 'white' and self.selected_piece_position[1] <= 6)
                    or (self.current_turn == 1 and piece.team == 'black' and self.selected_piece_position[1] <= 6)
                    or (self.current_turn == 2 and piece.team == 'white' and self.selected_piece_position[1] >= 6)
                    or (self.current_turn == 3 and piece.team == 'black' and self.selected_piece_position[1] >= 6)):
                        if self.board.move_piece(self.selected_piece_position, (x, y)):
                            self.current_turn = (self.current_turn + 1) % 4
                            self.possible_moves = []
                self.selected_piece_position = (x,y)
            else:
                print(f"Clicked on square ({x}, {y}), turn of the {'white' if self.current_turn in [0, 2] else 'black'} player")
                self.possible_moves = self.board.get_possible_moves((x,y))
                self.selected_piece_position = (x, y)
        else:
            print(f"Clicked on square ({x}, {y}), turn of the {'white' if self.current_turn in [0, 2] else 'black'} player")
            self.possible_moves = self.board.get_possible_moves((x,y))
            self.selected_piece_position = (x, y)

        self.draw_board()

    def reset_game(self, event):
        self.board = Board()
        self.current_turn = 0
        self.draw_board()

    def quit(self):
        # Quit the application
        self.root.destroy()

    def go_to_menu(self, event):
        # Go back to the menu
        menu = Menu(self.root)
        self.canvas.destroy()


import json
from typing import Any, Dict, Literal
import click
from pydantic import HttpUrl

from fibsem_metadata.models.sources import VolumeSource
from fibsem_metadata.models.metadata import Hyperlink, DatasetMetadata
from fibsem_metadata.models.views import DatasetViews
from pydantic import ValidationError
import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())

pub_mapping = {'Xu et al., 2020' : Hyperlink(href=HttpUrl('https://doi.org/10.1038/s41586-021-03992-4', scheme='https', host='doi.org'), title='Xu et al., 2021'),
            'Heinrich et al., 2020' : Hyperlink(href=HttpUrl('https://doi.org/10.1038/s41586-021-03977-3', scheme='https', host='doi.org'), title='Heinrich et al., 2021'),
            'Weigel, Chang, et al., 2021' : Hyperlink(href=HttpUrl('https://doi.org/10.1016/j.cell.2021.03.035', scheme='https', host='doi.org'), title='Weigel, Chang, et al., 2021'),
            'Ritter et al., 2021' : Hyperlink(href=HttpUrl('about:blank', scheme='https', host='doi.org'), title='Ritter et al., 2022'),
            'Mueller et al., 2020' : Hyperlink(href=HttpUrl('https://doi.org/10.1083/jcb.202010039', scheme='https', host='doi.org'), title='Mueller et al., 2020'),
            'Hoffman et al., 2020' : Hyperlink(href=HttpUrl('https://doi.org/10.1126/science.aaz5357', scheme='https', host='doi.org'), title='Hoffman et al., 2020'),
            'Coulter et al., 2018' : Hyperlink(href=HttpUrl('https://doi.org/10.1016/j.celrep.2018.06.100', scheme='https', host='doi.org'), title='Coulter et al., 2018')}

def doi_name_remap(name: str) -> str:
    result = name
    if name == 'em':
        result = 'EM'
    elif name == 'segmentations':
        result = 'Segmentations'
    return result

def linkify_doi(doi: Dict[Literal["DOI", "id"], str]) -> Hyperlink:
    return Hyperlink(href=HttpUrl(doi["DOI"], scheme='https', host='doi.org'), title=doi["id"])

def categorize_file(path: str) -> str:
    if path.endswith('views.json'):
        result = 'views'
    elif path.endswith('metadata.json'):
        result = 'metadata'
    else:
        result = 'source'
    return result

def clean_datasource(blob: Dict[str, Any]) -> Dict[str, Any]:
    return blob

def migrate_source(blob: Dict[str, Any]) -> VolumeSource:
    try:
        return VolumeSource(**blob)
    except ValidationError:
        blob = clean_datasource(blob)
        if "subsources" in blob:
            for idx, mesh in enumerate(blob["subsources"]):
                blob["subsources"][idx] = clean_datasource(mesh)

        return VolumeSource(**blob)

def migrate_metadata(blob: Dict[str, Any]) -> DatasetMetadata:
    dois = blob.pop('DOI')
    new_doi = []
    for doi in dois:
        doi["id"] = doi_name_remap(doi["id"])
        new_doi.append(linkify_doi(doi))
    blob['DOI'] = new_doi
    return DatasetMetadata(**blob)

def migrate_views(blob: Dict[str, Any]) -> DatasetViews:
    try:
        return DatasetViews(**blob)
    except ValidationError:
        for element in blob["views"]:
            if "volumeNames" in element:
                element["sources"] = element.pop("volumeNames")
        return DatasetViews(**blob)

def migrate_element(path: str) -> int:
    logger.info(f"Preparing {path}")
    typ = categorize_file(path)
    with open(path) as fh:
        blob = json.load(fh)
    if typ == 'views':
        migrated = migrate_views(blob)
    elif typ == 'metadata':
        migrated = migrate_metadata(blob)
    else:
        migrated = migrate_source(blob)

    write_blob = migrated.json(indent=2)
    with open(path, mode="w") as fh:
        fh.write(write_blob)

    return 0

@click.command()
@click.argument("paths", type=click.Path(exists=True, dir_okay=False), nargs=-1)
def migrate(paths: str) -> int:
    _ = [migrate_element(path) for path in paths]
    return 0

if __name__ == "__main__":
    migrate()


class Solution:

    def _add_recurse(self, nth, c, of_int, result):
        if nth == c:
            return result
        return self._add_recurse(nth, c + 1, of_int, result + of_int)

    def multiply(self, num1: str, num2: str) -> str:
        if num1 == "0" or num2 == "0":
            return "0"

        # Prime
        answer = [0] * (len(num1) + len(num2))
        first_number = num1[::-1]
        second_number = num2[::-1]

        for place2, digit2 in enumerate(second_number):
            for place1, digit1 in enumerate(first_number):
                num_zeros = place1 + place2
                carry = answer[num_zeros]
                s = min(int(digit1), int(digit2))
                l = max(int(digit1), int(digit2))
                multiplication = self._add_recurse(s, 0, l, 0) + carry
                answer[num_zeros] = multiplication % 10
                answer[num_zeros + 1] += multiplication // 10

        # Pop the excess 0 from the end of answer.
        if answer[-1] == 0:
            answer.pop()

        return ''.join(str(digit) for digit in reversed(answer))

if __name__ == "__main__":
    print(Solution().multiply("25", "12"))
    print(Solution().multiply("123", "456"))
    print(Solution().multiply("999", "0"))


'''
Name: Ang Kah Shin
Class: DAAA/FT/2B/04
Admin: P2004176
'''
# Writing program

from Morse.Morse import Morse
from Menu.Menu import Menu

def mainBanner():
    banner = '''
*******************************************
* ST1507 DSAA: MorseCode Message Analyzer *
*-----------------------------------------*
*                                         *
* - Done by: Ang Kah Shin (P2004176)      *
* - Class: DAAA/FT/2B/04                  *
*******************************************
    '''
    return banner

def main():
    '''The main Program loop'''
    # program variables:
    pMode = 'H'
    while 1:
        morse = Morse()

        print(mainBanner())
        # Main menu selection
        mainMenu = Menu("Please select your choice (1, 2, 3, 4)", True )
        # add options into mainMenu
        mainMenu.insert([
            "Change Printing Mode",
            "Convert Text to Morse Code",
            "Analyze Morse Code Message",
            "Exit"
        ])
        # print mainMenu
        userInput = mainMenu.show()

        if userInput == '1':
            print(f"Current printing mode is: {pMode}")
            changeMode = Menu("\nEnter 'h' for horizontal or 'v' for vertical, then press enter", True, ['H', 'V'] )
            userInput = changeMode.show()
            print(f"The print mode has been changed to {'Vertical' if userInput == 'V' else 'Horizontal'}")
            pMode = userInput
        elif userInput == '2':
            inputMorse = input("Enter Message you wish to encode: ")
            print(morse.encode(inputMorse, mode=pMode))
            # print("Encoded message:", msg)
        elif userInput == '3':
            inputFile = input("Enter the input file name: ")
            outputFile = input("Enter the output file name: ")
            print(morse.analyze(inputFile, outputFile))

        elif userInput == '4':
            print("Exiting program...")
            exit()
        else:
            print("Invalid input. Please try again.")
            main()

        userInput = input("\nPress Enter to continue...")

if __name__ == "__main__":

    main()


# python3

from random import randint

def partition3(array, left, right):
    x = array[left]
    j = k = left

    for i in range(left + 1, right + 1):
        if array[i] == x:
            j += 1
            array[i], array[j] = array[j], array[i]
        elif array[i] < x:
            j += 1
            k += 1
            array[i], array[j] = array[j], array[i]
            array[j], array[k] = array[k], array[j]

    array[left], array[k] = array[k], array[left]

    return [k, j]

def randomized_quick_sort(array, left, right):
    if left >= right:
        return
    k = randint(left, right)
    array[left], array[k] = array[k], array[left]

    #make a call to partition3 and then two recursive calls to randomized_quick_sort
    partitions = partition3(array, left, right)

    randomized_quick_sort(array, left, partitions[0] - 1)
    randomized_quick_sort(array, partitions[1] + 1, right)

if __name__ == '__main__':
    input_n = int(input())
    elements = list(map(int, input().split()))
    assert len(elements) == input_n
    randomized_quick_sort(elements, 0, len(elements) - 1)
    print(*elements)