from __future__ import annotations

from typing import ClassVar

from pants.core.util_rules.environments import EnvironmentField
from pants.engine.target import (
    COMMON_TARGET_FIELDS,
    BoolField,
    Dependencies,
    DictStringToStringField,
    IntField,
    MultipleSourcesField,
    SpecialCasedDependencies,
    StringField,
    StringSequenceField,
    Target,
    ValidNumbers,
)
from pants.util.strutil import help_text

class AdhocToolDependenciesField(Dependencies):
    pass

class AdhocToolRunnableField(StringField):
    alias: ClassVar[str] = "runnable"
    required = True
    help = help_text(
        lambda: f"""
        Address to a target that can be invoked by the `run` goal (and does not set
        `run_in_sandbox_behavior=NOT_SUPPORTED`). This will be executed along with any arguments
        specified by `{AdhocToolArgumentsField.alias}`, in a sandbox with that target's transitive
        dependencies, along with the transitive dependencies specified by
        `{AdhocToolExecutionDependenciesField.alias}`.
        """
    )

class AdhocToolOutputFilesField(StringSequenceField):
    alias: ClassVar[str] = "output_files"
    required = False
    default = ()
    help = help_text(
        lambda: f"""
        Specify the output files to capture, relative to the value of
        `{AdhocToolWorkdirField.alias}`.

        For directories, use `{AdhocToolOutputDirectoriesField.alias}`. At least one of
        `{AdhocToolOutputFilesField.alias}` and`{AdhocToolOutputDirectoriesField.alias}` must be
        specified.

        Relative paths (including `..`) may be used, as long as the path does not ascend further
        than the build root.
        """
    )

class AdhocToolOutputDirectoriesField(StringSequenceField):
    alias: ClassVar[str] = "output_directories"
    required = False
    default = ()
    help = help_text(
        lambda: f"""
        Specify full directories (including recursive descendants) of output to capture, relative
        to the value of `{AdhocToolWorkdirField.alias}`.

        For individual files, use `{AdhocToolOutputFilesField.alias}`. At least one of
        `{AdhocToolOutputFilesField.alias}` and`{AdhocToolOutputDirectoriesField.alias}` must be
        specified.

        Relative paths (including `..`) may be used, as long as the path does not ascend further
        than the build root.
        """
    )

class AdhocToolOutputDependenciesField(AdhocToolDependenciesField):
    supports_transitive_excludes = True
    alias: ClassVar[str] = "output_dependencies"

    help = help_text(
        lambda: f"""
        Any dependencies that need to be present (as transitive dependencies) whenever the outputs
        of this target are consumed (including as dependencies).

        See also `{AdhocToolExecutionDependenciesField.alias}` and
        `{AdhocToolRunnableDependenciesField.alias}`.
        """
    )

class AdhocToolExecutionDependenciesField(SpecialCasedDependencies):
    alias: ClassVar[str] = "execution_dependencies"
    required = False
    default = None

    help = help_text(
        lambda: f"""
        The execution dependencies for this command.

        Dependencies specified here are those required to make the command complete successfully
        (e.g. file inputs, packages compiled from other targets, etc), but NOT required to make
        the outputs of the command useful. Dependencies that are required to use the outputs
        produced by this command should be specified using the
        `{AdhocToolOutputDependenciesField.alias}` field.

        If this field is specified, dependencies from `{AdhocToolOutputDependenciesField.alias}`
        will not be added to the execution sandbox.

        See also `{AdhocToolOutputDependenciesField.alias}` and
        `{AdhocToolRunnableDependenciesField.alias}`.
        """
    )

class AdhocToolRunnableDependenciesField(SpecialCasedDependencies):
    alias: ClassVar[str] = "runnable_dependencies"
    required = False
    default = None

    help = help_text(
        lambda: f"""
        The runnable dependencies for this command.

        Dependencies specified here are those required to exist on the `PATH` to make the command
        complete successfully (interpreters specified in a `#!` command, etc). Note that these
        dependencies will be made available on the `PATH` with the name of the target.

        See also `{AdhocToolOutputDependenciesField.alias}` and
        `{AdhocToolExecutionDependenciesField.alias}`.
        """
    )

class AdhocToolSourcesField(MultipleSourcesField):
    # We solely register this field for codegen to work.
    alias: ClassVar[str] = "_sources"
    uses_source_roots = False
    expected_num_files = 0

class AdhocToolArgumentsField(StringSequenceField):
    alias: ClassVar[str] = "args"
    default = ()
    help = help_text(
        lambda: f"Extra arguments to pass into the `{AdhocToolRunnableField.alias}` field."
    )

class AdhocToolStdoutFilenameField(StringField):
    alias: ClassVar[str] = "stdout"
    default = None
    help = help_text(
        lambda: f"""
        A filename to capture the contents of `stdout` to. Relative paths are
        relative to the value of `{AdhocToolWorkdirField.alias}`, absolute paths
        start at the build root.
        """
    )

class AdhocToolStderrFilenameField(StringField):
    alias: ClassVar[str] = "stderr"
    default = None
    help = help_text(
        lambda: f"""
        A filename to capture the contents of `stderr` to. Relative paths are
        relative to the value of `{AdhocToolWorkdirField.alias}`, absolute paths
        start at the build root.
        """
    )

class AdhocToolTimeoutField(IntField):
    alias: ClassVar[str] = "timeout"
    default = 30
    help = "Command execution timeout (in seconds)."
    valid_numbers = ValidNumbers.positive_only

class AdhocToolExtraEnvVarsField(StringSequenceField):
    alias: ClassVar[str] = "extra_env_vars"
    help = help_text(
        """
        Additional environment variables to provide to the process.

        Entries are strings in the form `ENV_VAR=value` to use explicitly; or just
        `ENV_VAR` to copy the value of a variable in Pants's own environment.
        """
    )

class AdhocToolLogOutputField(BoolField):
    alias: ClassVar[str] = "log_output"
    default = False
    help = "Set to true if you want the output logged to the console."

class AdhocToolWorkdirField(StringField):
    alias: ClassVar[str] = "workdir"
    default = "."
    help = help_text(
        """
        Sets the working directory for the process.

        Values are relative to the build root, except in the following cases:

        * `.` specifies the location of the `BUILD` file.
        * Values beginning with `./` are relative to the location of the `BUILD` file.
        * `/` or the empty string specifies the build root.
        * Values beginning with `/` are also relative to the build root.
        """
    )

class AdhocToolNamedCachesField(DictStringToStringField):
    alias = "experimental_named_caches"
    help = help_text(
        """
        Named caches to construct for the execution.
        See https://www.pantsbuild.org/docs/reference-global#named_caches_dir.

        The keys of the mapping are the directory name to be created in the named caches dir.
        The values are the name of the symlink (relative to the sandbox root) in the sandbox which
        points to the subdirectory in the named caches dir

        NOTE: The named caches MUST be handled with great care. Processes accessing the named caches
        can be run in parallel, and can be cancelled at any point in their execution (and
        potentially restarted). That means that _every_ operation modifying the contents of the cache
        MUST be concurrency and cancellation safe.
        """
    )

class AdhocToolOutputRootDirField(StringField):
    alias: ClassVar[str] = "root_output_directory"
    default = "/"
    help = help_text(
        """
        Adjusts the location of files output by this target, when consumed as a dependency.

        Values are relative to the build root, except in the following cases:

          * `.` specifies the location of the `BUILD` file.
          * Values beginning with `./` are relative to the location of the `BUILD` file.
          * `/` or the empty string specifies the build root.
          * Values beginning with `/` are also relative to the build root.
        """
    )

class AdhocToolTarget(Target):
    alias: ClassVar[str] = "adhoc_tool"
    core_fields = (
        *COMMON_TARGET_FIELDS,
        AdhocToolRunnableField,
        AdhocToolArgumentsField,
        AdhocToolExecutionDependenciesField,
        AdhocToolOutputDependenciesField,
        AdhocToolRunnableDependenciesField,
        AdhocToolLogOutputField,
        AdhocToolOutputFilesField,
        AdhocToolOutputDirectoriesField,
        AdhocToolSourcesField,
        AdhocToolTimeoutField,
        AdhocToolExtraEnvVarsField,
        AdhocToolWorkdirField,
        AdhocToolOutputRootDirField,
        AdhocToolStdoutFilenameField,
        AdhocToolStderrFilenameField,
        EnvironmentField,
    )
    help = help_text(
        lambda: f"""
        Execute any runnable target for its side effects.

        Example BUILD file:

            {AdhocToolTarget.alias}(
                {AdhocToolRunnableField.alias}=":python_source",
                {AdhocToolArgumentsField.alias}=[""],
                {AdhocToolExecutionDependenciesField.alias}=[":scripts"],
                {AdhocToolOutputDirectoriesField.alias}=["results/"],
                {AdhocToolOutputFilesField.alias}=["logs/my-script.log"],
            )

            shell_sources(name="scripts")
        """
    )

# ---
# `system_binary` target
# ---

class SystemBinaryNameField(StringField):
    alias: ClassVar[str] = "binary_name"
    required = True
    help = "The name of the binary to find."

class SystemBinaryExtraSearchPathsField(StringSequenceField):
    alias: ClassVar[str] = "extra_search_paths"
    default = ()
    help = help_text(
        """
        Extra search paths to look for the binary. These take priority over Pants' default
        search paths.
        """
    )

class SystemBinaryFingerprintPattern(StringField):
    alias: ClassVar[str] = "fingerprint"
    required = False
    default = None
    help = help_text(
        """
        A regular expression which will be used to match the fingerprint outputs from
        candidate binaries found during the search process.
        """
    )

class SystemBinaryFingerprintArgsField(StringSequenceField):
    alias: ClassVar[str] = "fingerprint_args"
    default = ()
    help = help_text(
        "Specifies arguments that will be used to run the binary during the search process."
    )

class SystemBinaryFingerprintDependenciesField(AdhocToolRunnableDependenciesField):
    alias: ClassVar[str] = "fingerprint_dependencies"
    help = help_text(
        """
        Specifies any runnable dependencies that need to be available on the `PATH` when the binary
        is run, so that the search process may complete successfully. The name of the target must
        be the name of the runnable dependency that is called by this binary.
        """
    )

class SystemBinaryTarget(Target):
    alias: ClassVar[str] = "system_binary"
    core_fields = (
        *COMMON_TARGET_FIELDS,
        SystemBinaryNameField,
        SystemBinaryExtraSearchPathsField,
        SystemBinaryFingerprintPattern,
        SystemBinaryFingerprintArgsField,
        SystemBinaryFingerprintDependenciesField,
    )
    help = help_text(
        lambda: f"""
        A system binary that can be run with `pants run` or consumed by `{AdhocToolTarget.alias}`.

        Pants will search for binaries with name `{SystemBinaryNameField.alias}` in the search
        paths provided, as well as default search paths. If
        `{SystemBinaryFingerprintPattern.alias}` is specified, each binary that is located will be
        executed with the arguments from `{SystemBinaryFingerprintArgsField.alias}`. Any binaries
        whose output does not match the pattern will be excluded.

        The first non-excluded binary will be the one that is resolved.
        """
    )


from collections import defaultdict
def func(nums1, nums2):
    hash = defaultdict(int)

    while nums1:
        np1 = nums1.pop()
        hash[np1[0]] += np1[1]

    while nums2:
        np2 = nums2.pop()
        hash[np2[0]] += np2[1]

    return sorted([[key, value] for key, value in hash.items()])

nums1 = [[2,4],[3,6],[5,5]]
nums2 = [[1,3],[4,3]]

print(func(nums1, nums2))

주리머/2-2w/wc/(성공) 6362. Merge Two 2D Arrays by Summing Values.py


"""Destroy unused AMIs in your AWS account.

Usage:
    ami_destroyer.py <requiredtag> [options]

Arguments:
    <requiredtag>               Tag required for an AMI to be cleaned up in the form tag:NameOfTag

Options:
    --retain=<retain>           Number of images to retain, sorted newest to latest [default: 2]
    --regions=<regions>         A comma-separated list of AWS Regions to run against [default: us-east-1]
    --help                      Show this help string
    --dryrun                    List the AMIs that'll be destroyed by this script
"""
import sys
import logging
from operator import itemgetter
from docopt import docopt
import boto3
import botocore.exceptions as botoex

_LOGGER = logging.Logger("ami-destroyer")

def setup_logging():
    _LOGGER.setLevel(logging.INFO)
    handler = logging.StreamHandler(sys.stdout)
    formatter = logging.Formatter('%(asctime)s : %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    _LOGGER.addHandler(handler)

def get_account_id():
    acctid = sts.get_caller_identity().get('Account')
    _LOGGER.info("Retrieving Account ID: {}".format(acctid))
    return acctid

def get_curated_images(tagname, accountid):
    _LOGGER.info("Retrieving AMIs with {}".format(tagname))
    return ec2.images.filter(
        Owners=[accountid],
        Filters=[
            {
                'Name':tagname,
                'Values':['True']
            }
        ]
)

def sort_curated_images(curatedimages):
    _LOGGER.info("Sorting tagged AMIs into a nice dictionary of lists of dictionaries")
    sortedimages = {}
    for i in curatedimages:
        for tag in i.tags:
            if tag['Key'] == 'Name':
                iname = tag['Value']
                break
            else:
                iname = "nonametag"
        if iname not in sortedimages:
            sortedimages[iname] = []
        sortedimages[iname].append({
            'creation_date': i.creation_date,
            'ami_id': i.image_id,
            'snapshot_id': i.block_device_mappings[0]['Ebs']['SnapshotId']
        })
        sortedimages[iname] = sorted(
            sortedimages[iname],
            key=itemgetter('creation_date'),
            reverse=True
        )
    return sortedimages

def prune_sorted_images(images, retain):
    for family in images:
        _LOGGER.info(
            "Found {} tagged images for type {}. Retaining the latest {}".format(
                len(images[family]),
                family,
                retain
            )
        )
        images[family] = images[family][retain:]
        if not images[family]:
            _LOGGER.info("No images to prune for {}".format(family))
    return images

def destroy_ami(ami_id, family, dryrun):
    try:
        ec2.Image(ami_id).deregister(DryRun=dryrun)
        _LOGGER.info("Family: {} - Deregistered {}".format(family, ami_id))
    except botoex.ClientError as e:
        _LOGGER.warning("{} - {}".format(ami_id, e))

def destroy_snapshot(snapshot_id, family, dryrun):
    try:
        ec2.Snapshot(snapshot_id).delete(DryRun=dryrun)
        _LOGGER.info("Family: {} - Deleted {}".format(family, snapshot_id))
    except botoex.ClientError as e:
        _LOGGER.warning("{} - {}".format(snapshot_id, e))

def run(tag, retain, dryrun):
    acctid = get_account_id()
    curatedimages = get_curated_images(tag, acctid)
    sortedimages = sort_curated_images(curatedimages)
    if sortedimages:
        prunedimages = prune_sorted_images(sortedimages, numretain)

        for family in prunedimages:
            if prunedimages[family]:
                for ami in prunedimages[family]:
                    destroy_ami(ami['ami_id'], family, dryrun)
                    destroy_snapshot(ami['snapshot_id'], family, dryrun)
    else:
        _LOGGER.error("No tagged images to prune")

if __name__ == '__main__':
    args = docopt(__doc__)
    requiredtag = args['<requiredtag>']
    dryrun = args['--dryrun']
    numretain = int(args['--retain'])
    regions = args['--regions']
    setup_logging()

    for r in regions.split(','):
        _LOGGER.info("##### Running cleanup for region {} #####".format(r))
        ec2 = boto3.resource('ec2', region_name=r)
        sts = boto3.client('sts')

        run(requiredtag, numretain, dryrun)


from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic import DetailView, View, UpdateView, ListView, TemplateView
from django.core.urlresolvers import reverse
from django.urls import reverse_lazy
from django.contrib import messages
from django.http import Http404

from .models import Checkout
from .forms import UpdateCheckoutForm
from products.models import Product
from accounts.models import Account

from django.shortcuts import render_to_response
from django.template import RequestContext

# class CheckoutView(DetailView):
#     template_name = 'accounts/profile.html'
#     success_url = reverse_lazy('orders:checkout')
#     queryset = ''
#
#     def get_object(self, **kwargs):
#         id = self.kwargs['id']
#         product = get_object_or_404(Product, id=id, publish=True)
#         checkout = Checkout.objects.create(
#             user=self.request.user,
#             name=product.name,
#             price=product.price,
#             quantity=product.quantity,
#             discount=product.discount,
#         )
#         return get_object_or_404(Product, id=id, publish=True)
#
#     def get_context_data(self, **kwargs):
#         context = super(CheckoutView, self).get_context_data(**kwargs)
#         context['title'] = 'Profile'
#         context['orders'] = Checkout.objects.filter(user=self.request.user)
#         return context

# add to cart form
class CheckoutView(View):
    template_name = 'orders/checkout.html'

    def post(self, request, id):
        id = self.kwargs['id']
        qs = Checkout.objects.filter(product_id=id, status='waiting')
        if qs.exists():
            messages.success(request, 'You can not add this product because its already added before!')
            return redirect('orders:checkout')
        else:
            product = get_object_or_404(Product, id=id, publish=True)
            checkout = Checkout.objects.create(
                user=self.request.user,
                product_id=id,
                name=product.name,
                slug=product.slug,
                price=product.price,
                quantity=1,
                discount=product.discount,
                image=product.image,
            )
            messages.success(request, 'Successfully Added!')
            return redirect('orders:checkout')

# all orders page that submitted
class OrdersView(ListView):
    template_name = 'orders/orders.html'
    queryset = ''

    def get_context_data(self, **kwargs):
        context = super(OrdersView, self).get_context_data(**kwargs)
        context['title'] = 'Pending Orders'
        if self.request.user.is_authenticated:
            context['orders'] = Checkout.objects.filter(user=self.request.user, status='pending')
        else:
            raise Http404
        return context

# all orders page that submitted & accepted
class AcceptedOrdersView(ListView):
    template_name = 'orders/orders.html'
    queryset = ''

    def get_context_data(self, **kwargs):
        context = super(AcceptedOrdersView, self).get_context_data(**kwargs)
        context['title'] = 'Accepted Orders'
        if self.request.user.is_authenticated:
            context['orders'] = Checkout.objects.filter(user=self.request.user, status='accepted')
        else:
            raise Http404
        return context

# all orders page that submitted & rejected
class RejectedOrdersView(ListView):
    template_name = 'orders/orders.html'
    queryset = ''

    def get_context_data(self, **kwargs):
        context = super(RejectedOrdersView, self).get_context_data(**kwargs)
        context['title'] = 'Rejected Orders'
        if self.request.user.is_authenticated:
            context['orders'] = Checkout.objects.filter(user=self.request.user, status='rejected')
        else:
            raise Http404
        return context

# checkout page
class CheckoutOrderView(ListView):
    template_name = 'orders/checkout.html'
    queryset = ''

    def get_context_data(self, **kwargs):
        context = super(CheckoutOrderView, self).get_context_data(**kwargs)
        context['title'] = 'Cart'
        if self.request.user.is_authenticated:
            qs = Checkout.objects.filter(user=self.request.user, status='waiting')
            context['orders'] = qs
            orders = qs
            total = 0
            for order in orders:
                total += order.price * order.quantity
            context['total'] = total
        else:
            raise Http404
        return context

# # update order page
# class CheckoutUpdateView(UpdateView):
#     form_class = UpdateCheckoutForm
#     model = Checkout
#     template_name = 'orders/update_order.html'
#     success_url = reverse_lazy('orders:checkout')
#
#     # def get_success_url(self):
#     #     return reverse('orders:checkout')
#
#     def get_context_data(self, **kwargs):
#         context = super(CheckoutUpdateView, self).get_context_data(**kwargs)
#         context['title'] = 'Update Order {}'.format(Checkout.objects.filter(id=self.kwargs['pk']).first().name)
#         return context

# update order page
class CheckoutUpdateView(View):
    template_name = 'orders/checkout.html'

    def post(self, request, pk):
        quantity = int(request.POST['quantity'])
        product_id = request.POST['product_id']
        available = Product.objects.filter(id=product_id).first()
        if quantity > available.quantity:
            messages.success(request, 'Quantity more than the available quantity : {} for product : {}'.format(available.quantity, available.name))
            return redirect('orders:checkout')
        if quantity == 0 or quantity < 0:
            messages.success(request, 'Quantity can not be less than 1 for product : {}'.format(available.name))
            return redirect('orders:checkout')
        qs = Checkout.objects.filter(id=pk, status='waiting')
        if qs.exists() and qs.count() == 1:
            product_quantity = qs.first()
            product_quantity.quantity = quantity
            product_quantity.save()
            messages.success(request, 'Successfully Added!')
            return redirect('orders:checkout')

# delete order
class OrderDeleteView(View):
    template_name = 'orders/checkout.html'

    def post(self, request, id):
        username = self.request.user
        if username is None:
            raise Http404
        else:
            qs = Checkout.objects.filter(id=id)
            if qs.exists() and qs.count() == 1:
                order = qs.first()
                order.delete()
                return redirect('orders:checkout')

# Buy orders
class BuyOrdersView(View):
    template_name = 'orders/orders.html'

    def post(self, request):
        username = self.request.user
        if username is None:
            raise Http404
        else:
            user_id = Account.objects.filter(user=username).first()
            account = Account.objects.filter(user=username)
            qs = Checkout.objects.filter(user=username, status='waiting')
            if account.exists():
                user = account.first()
                if user.gender is None \
                or user.country is None \
                or user.region is None \
                or user.address1 is None \
                or user.phone_number1 is None \
                or user.phone_number2 is None:
                    messages.success(request, 'add your information first to complete buy orders!')
                    return redirect('accounts:update', pk=user_id.id)
            if qs.exists():
                for order in qs:
                    order.status = 'pending'
                    order.save()
                    product = Product.objects.filter(id=order.product_id).first()
                    product.quantity -= order.quantity
                    product.number_of_sales += 1
                    product.save()
                return redirect('orders:thank')

class BuyThankView(TemplateView):
    template_name = "orders/thank.html"

    def get_context_data(self, **kwargs):
        context = super(BuyThankView, self).get_context_data(**kwargs)
        context['title'] = 'Thank You'
        return context

def handler404(request):
    response = render_to_response('404.html', {}, context_instance=RequestContext(request))
    response.status_code = 404
    return response


#!usr/bin/python

import os
import SimpleITK as sitk
import numpy as np
import scipy.ndimage.interpolation
import skimage.exposure
import skimage.filters
import skimage.transform

path="//Users//zhangyuwei//Desktop//test"
ShrinkFactor = 4

for i in os.walk(path):
    for j in range(len(i[2])):
        if os.path.splitext(i[2][j])[1] == ".gz" :
            print(os.path.splitext(i[2][j])[0])
            nifti_file = sitk.ReadImage(os.path.join(i[0],i[2][j]))
            mask_img   = sitk.BinaryThreshold(nifti_file, 80, 5000)

            mask_filename    = "globalmask_" + os.path.splitext(i[2][j])[0] + ".gz"
            output_filename  = "N4ITKcorrected_" + os.path.splitext(i[2][j])[0] + ".gz"
            output_biasname1 = "bias_in_" + os.path.splitext(i[2][j])[0] + ".gz"
            output_biasname2 = "bias_out_" + os.path.splitext(i[2][j])[0] + ".gz"
            sitk.WriteImage(mask_img, mask_filename)

            nifti_shape  = sitk.GetArrayFromImage(nifti_file)
            nifti_shape  = nifti_shape.shape

            # Call and initialize an N4 corrector instance.
            corrector                              = sitk.N4BiasFieldCorrectionImageFilter()
            corrector.SetMaximumNumberOfIterations = 50
            corrector.SetNumberOfHistogramBins     = 128
            corrector.SetSplineOrder               = 10
            corrector.SetConvergenceThreshold      = 0.001
            corrector.SetNumberOfControlPoints     = 8
            print("> Initializing Compelete!")

            if ShrinkFactor > 1 :

                shrinked_img  = sitk.Shrink(nifti_file, [ShrinkFactor] * nifti_file.GetDimension())
                shrinked_mask = sitk.Shrink(mask_img, [ShrinkFactor] * nifti_file.GetDimension())

                shrinked_img = sitk.Cast(shrinked_img, sitk.sitkFloat32)
                #shrinked_mask = sitk.Cast(shrinked_mask, sitk.sitkFloat32)

                print("> Starting Execution...")
                corrected_img = corrector.Execute(shrinked_img, shrinked_mask)
                print("> Execution Complete!")

                # Estimate the bias field of corrected image
                re_corrected = corrector.Execute(corrected_img, shrinked_mask)
                print("> Corrected Bias Estimation Complete!")

                corrected_img = sitk.GetArrayFromImage(corrected_img)
                corrected_img[corrected_img == 0] = 0.001
                re_corrected = sitk.GetArrayFromImage(re_corrected)
                re_corrected[re_corrected == 0] = 0.001
                shrinked_img = sitk.GetArrayFromImage(shrinked_img)

                # Generate biasfield
                shrinked_bias  = shrinked_img / corrected_img
                corrected_bias = corrected_img / re_corrected

                # Output
                output_bias  = scipy.ndimage.zoom(shrinked_bias, np.array(nifti_shape) / shrinked_bias.shape)
                output_bias2 = scipy.ndimage.zoom(corrected_bias, np.array(nifti_shape) / shrinked_bias.shape)
                output_img   = sitk.GetArrayFromImage(nifti_file) / output_bias

                output_bias  = sitk.GetImageFromArray(output_bias)
                output_bias2 = sitk.GetImageFromArray(output_bias2)
                output_img   = sitk.Cast(sitk.GetImageFromArray(output_img), sitk.sitkUInt16)

                sitk.WriteImage(output_img, output_filename)
                sitk.WriteImage(output_bias, output_biasname1)
                sitk.WriteImage(output_bias2, output_biasname2)
                print("> Save Complete!")

            else:
                source_img = sitk.Shrink(nifti_file, [ShrinkFactor] * nifti_file.GetDimension())
                mask_img   = sitk.Shrink(mask_img, [ShrinkFactor] * mask_img.GetDimension())
                source_img = sitk.Cast(source_img, sitk.sitkFloat32)

                output_img = corrector.Execute(source_img, mask_img)
                output_img = sitk.Cast(output_img, sitk.sitkUInt16)

                sitk.WriteImage(output_img, output_filename)
                #biasfield_img = source_img / output_img
                #biasfield_img[biasfield_img <  0.5] = 0.5


import json
from random import randint

import discord
from discord.ext import tasks, commands

def getData():
    with open("data.json", "r") as levelsFile:
        return json.loads(levelsFile.read())

def setData(_dict):
    with open("data.json", "w") as levelsFile:
        levelsFile.write(json.dumps(_dict))

levelxp = [0, 300, 900, 2700, 6500, 14000, 23000, 34000, 48000, 64000, 85000, 100000, 120000, 140000, 165000, 195000, 225000, 265000, 305000, 355000]

class DND(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.ac = randint(1, 20)
        self.base = {
            "xp": 0,
            "level": 0,
            "health": 20,
            "class": "",
            "inventory": [],
            "stats": {
                "str": {"base": 0, "mod": 0},
                "dex": {"base": 0, "mod": 0},
                "con": {"base": 0, "mod": 0},
                "int": {"base": 0, "mod": 0},
                "wis": {"base": 0, "mod": 0},
                "cha": {"base": 0, "mod": 0}
            }
        }
        self.hell_ac.start()

    def cog_unload(self):
        self.hell_ac.cancel()

    @commands.Cog.listener()
    async def on_message(self, message):
        if not message.author.bot:
            try:
                data = getData()
                try:
                    level = data[message.author.name]["level"]
                    data[message.author.name]["xp"] += (randint(1, 10))
                except:
                    data[message.author.name] = self.base
                    level = data[message.author.name]["level"]
                    data[message.author.name]["xp"] += randint(1, 10)

                bonus = 2 if level < 5 else (3 if level < 9 else (4 if level < 13 else (5 if level < 17 else 6)))

                if message.channel.name == "hell":
                    roll = randint(1, 20) + bonus
                    if roll <= self.ac:
                        await message.delete()
                        await message.channel.send("(%s > %s+%s) **%s** tried to send a message, but failed the roll!" % (self.ac, roll - bonus, bonus, message.author.name))
                    else:
                        await message.delete()
                        await message.channel.send("(%s < %s+%s) **%s**: %s" % (self.ac, roll - bonus, bonus, message.author.name, message.content))

                else:
                    try:
                        words = data["banned words"]
                    except:
                        data["banned words"] = []
                        words = data["banned words"]

                    for word in words:
                        if word in message.content.lower() and not (message.content.startswith("2m.unban") or message.content.startswith("2m.ban")):
                            data[message.author.name]["health"] -= 1
                            await message.channel.send("Uh oh! You fucking idiot. You just said '%s'.\n\nDie." % word)

                    if data[message.author.name]["xp"] >= levelxp[level]:
                        data[message.author.name]["level"] += 1
                        await message.channel.send("**%s** levelled up to level %s!" % (message.author.name, data[message.author.name]["level"]))

                    if data[message.author.name]["health"] <= 0:
                        data[message.author.name] = self.base
                        await message.channel.send("Oop, **%s** is dead. Now you gotta reroll stats!" % message.author.name)

                setData(data)
            except:
                pass

    @tasks.loop(minutes=5)
    async def hell_ac(self):
        hell = discord.utils.get(self.bot.get_guild(677689511525875715).channels, name="hell")
        if randint(1, 100) <= 33:
            ac = randint(1, 20)
            self.ac = ac
            await hell.send("__**Hell's AC is now %s!**__" % ac)

    @commands.command(brief="Roll up your stats.")
    async def rollstats(self, ctx, *, order):
        data = getData()
        try:
            if not (0 in (data[ctx.author.name]["stats"][key]["base"] for key in data[ctx.author.name]["stats"])):
                return await ctx.send("You've already rolled your stats! Theres no going back now.")
        except:
            data[ctx.author.name] = self.base
        order = order.split(" ")
        for item in order:
            if item not in ["str", "dex", "con", "int", "wis", "cha"]:
                return await ctx.send("Please use the correct stat names!\nThey are:\n%s" % ("\n".join(["str", "dex", "con", "int", "wis", "cha"])))
        final = []
        allrolls = []
        for i in range(6):
            allrolls.append([randint(1, 6) for x in range(4)])
        for arr in range(len(allrolls)):
            del allrolls[arr][allrolls[arr].index(min(allrolls[arr]))]
            allrolls[arr] = sum(allrolls[arr])
        allrolls.sort(reverse=True)
        for i in range(6):
            num = allrolls[i]
            tempnum = allrolls[i]
            if tempnum % 2 == 1:
                tempnum -= 1
            bonuses = {
                0: -5,
                2: -4,
                4: -3,
                6: -2,
                8: -1,
                10: 0,
                12: 1,
                14: 2,
                16: 3,
                18: 4,
                20: 5,
                22: 6,
                24: 7,
                26: 8,
                28: 9,
                30: 10
            }
            final.append("%s -> %s (%s)" % (order[i], num, bonuses[tempnum] if num < 10 else ("+%s" % bonuses[tempnum])))
            data[ctx.author.name]["stats"][order[i]] = {"base": num, "mod": bonuses[tempnum]}
        await ctx.send("\n".join(final))

        setData(data)

    @commands.command(brief="Get the AC of hell.")
    async def getac(self, ctx):
        await ctx.send("Hell's AC is currently **%s**!" % self.ac)

    @commands.command(brief="Get information on a level.")
    async def levelinfo(self, ctx, level: int):
        if not level > 20:
            await ctx.send("__**Level %s Information**__\nNeeded XP: %s\nProficiency Bonus: %s" % (level, levelxp[level - 1], "+2" if level < 5 else ("+3" if level < 9 else ("+4" if level < 13 else ("+5" if level < 17 else "+6")))))
        else:
            await ctx.send("That level is too high! Level 20 is the maximum.")
        print("%s GOT LEVEL INFORMATION. (%s)" % (ctx.author.name, level))

    @commands.command(brief="Get your current level and XP.")
    async def stats(self, ctx):
        data = getData()
        level = data[ctx.author.name]["level"]
        bonus = 2 if level < 5 else (3 if level < 9 else (4 if level < 13 else (5 if level < 17 else 6)))
        await ctx.send(
            "__**%s's Information**__\nHealth: %s\nLevel: %s\nXP: %s\nProficiency Bonus: +%s\n\n%s" % (ctx.author.name, data[ctx.author.name]["health"], data[ctx.author.name]["level"], data[ctx.author.name]["xp"], bonus, "\n".join(
                ["%s: %s (%s)" % (key, data[ctx.author.name]["stats"][key]["base"], data[ctx.author.name]["stats"][key]["mod"]) for key in data[ctx.author.name]["stats"]])))
        print("%s GOT THEIR LEVEL INFORMATION." % ctx.author.name)

def setup(bot):
    bot.add_cog(DND(bot))


import sys
from os.path import join

from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QListWidgetItem, QWidget
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
import sqlite3
from functools import partial

class EditInfo(QWidget):
    def __init__(self, id) -> None:
        super().__init__()
        uic.loadUi(join("task5", "addEditCoffeeForm.ui"), self)
        self.id = id
        self.edit.clicked.connect(self.update)

    def update(self):
        db = sqlite3.connect(join("task5", "coffee.sqlite"))
        cur = db.cursor()
        try:
            name = self.bookTitle.text()
            elem1 = self.bookAuthor.text()
            elem2 = self.bookReleaseYear.text()
            desc = self.bookGenre.text()
            for i in [name, elem1, elem2, desc]:
                if not (bool(i) and bool(i.strip())):
                    raise ValueError
                for w in i:
                    if w.isdigit():
                        raise ValueError

            cs = float(self.costl.text())
            vl = float(self.volumel.text())
        except ValueError:
            self.errors.setText("Введены некорректные данные!!!")
        else:
            cur.execute(f'''
                        UPDATE coffee SET name_of_the_variety = ?, degree_of_roasting = ?,
                        ground_or_in_grains = ?,
                        taste_description = ?, cost = ?, packing_volume = ?

                        WHERE id = ?''',
                        [name, elem1, elem2, desc, cs, vl, self.id])

            db.commit()
            db.close()

    def addNewCoffeeSort(self):
        # req = INSERT INTO coffee (name_of_the_variety, degree_of_roasting, ground_or_in_grains, taste_description, cost, packing_volume)
        # VALUES ("1", "1", "1", "1", 1, 1)
        db = sqlite3.connect(join("task5", "coffee.sqlite"))
        cur = db.cursor()
        try:
            name = self.bookTitle.text()
            elem1 = self.bookAuthor.text()
            elem2 = self.bookReleaseYear.text()
            desc = self.bookGenre.text()
            for i in [name, elem1, elem2, desc]:
                if not (bool(i) and bool(i.strip())):
                    raise ValueError
                for w in i:
                    if w.isdigit():
                        raise ValueError

            cs = float(self.costl.text())
            vl = float(self.volumel.text())
        except ValueError:
            self.errors.setText("Введены некорректные данные!!!")

        cur.execute(f'''
                    INSERT INTO coffee (name_of_the_variety, degree_of_roasting, ground_or_in_grains, taste_description, cost, packing_volume)
                    VALUES (?, ?, ?, ?, ?, ?)''',
                    [name, elem1, elem2, desc, cs, vl])

        db.commit()
        db.close()

class AddNewInfo(QWidget):
    def __init__(self) -> None:
        super().__init__()
        uic.loadUi(join("task5", "addEditCoffeeForm2.ui"), self)
        self.add.clicked.connect(self.addNewItem)

    def addNewItem(self):
        db = sqlite3.connect(join("task5", "coffee.sqlite"))
        cur = db.cursor()
        try:
            name = self.bookTitle.text()
            elem1 = self.bookAuthor.text()
            elem2 = self.bookReleaseYear.text()
            desc = self.bookGenre.text()
            for i in [name, elem1, elem2, desc]:
                if not (bool(i) and bool(i.strip())):
                    raise ValueError
                for w in i:
                    if w.isdigit():
                        raise ValueError

            cs = float(self.costl.text())
            vl = float(self.volumel.text())
        except ValueError:
            self.errors.setText("Введены некорректные данные!!!")
        else:
            cur.execute(f'''
                        INSERT INTO coffee (name_of_the_variety, degree_of_roasting, ground_or_in_grains, taste_description, cost, packing_volume)
                        VALUES (?, ?, ?, ?, ?, ?)''',
                        [name, elem1, elem2, desc, cs, vl])

            db.commit()
            db.close()

class MyWidget(QMainWindow):
    def __init__(self) -> None:
        super().__init__()
        uic.loadUi(join("task5", "main.ui"), self)
        self.btn.clicked.connect(self.search)
        self.addNewCoffe.clicked.connect(self.addSomeInfo)

    def search(self):
        self.listWidget.clear()
        # searchText = self.lineEdit.text()
        # db = sqlite3.connect(join("QT_Standalone", "task7", "books.db"))
        db = sqlite3.connect(join("task5", "coffee.sqlite"))
        cur = db.cursor()
        res = cur.execute(
            f'''SELECT * FROM coffee''')

        for elem in res:
            # print(elem)
            btn = QPushButton(f"{elem[1]}(нажми для большей информации)", self)

            clickFunc = partial(self.some, elem[0], elem[1],
                                elem[2], elem[3], elem[4], elem[5], elem[6])
            btn.clicked.connect(clickFunc)

            item = QListWidgetItem()
            item.setSizeHint(btn.sizeHint())
            self.listWidget.addItem(item)
            self.listWidget.setItemWidget(item, btn)

    def some(self, id, name, author, year, genre, cost, volume):
        self.pop = EditInfo(id)
        # там снизу есть нужные поля для ввода
        self.pop.bookAuthor.setText(author)
        self.pop.bookTitle.setText(name)
        self.pop.bookGenre.setText(genre)
        self.pop.bookReleaseYear.setText(str(year))
        self.pop.costl.setText(str(cost))
        self.pop.volumel.setText(str(volume))

        self.pop.show()

    def addSomeInfo(self):
        self.pop2 = AddNewInfo()
        self.pop2.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyWidget()
    ex.show()
    # print(eval("9!"))
    sys.exit(app.exec_())


import setuptools

with open('README.md', 'r') as fh:
    long_description = fh.read()

setuptools.setup(
    name='bhamcal',
    version='0.1',
    license='GPL 3',
    python_requires='>=3',

    author='Justin Chadwell',
    author_email='jedevc@gmail.com',

    url='https://github.com/jedevc/bhamcal',
    description='A timetable extractor for University of Birmingham',
    long_description=long_description,
    long_description_content_type='text/markdown',

    packages=setuptools.find_packages(),
    install_requires=[
        'click',
        'colorama',
        'beautifulsoup4',
        'pytz',
        'google-api-python-client',
        'google-auth-httplib2',
        'google-auth-oauthlib'
    ],

    extras_require={
        'browser': ['selenium']
    },

    entry_points={
        'console_scripts': [
            'bhamcal=bhamcal:main'
        ]
    },
)


# Neuon AI - PlantCLEF 2020

import tensorflow as tf
from preprocessing import inception_preprocessing
slim = tf.contrib.slim
import numpy as np
import cv2
from nets.inception_v4 import inception_v4
from nets import inception_utils
from PIL import Image
from six.moves import cPickle
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity

# ============================================================= #
#                       Directories
# ============================================================= #
image_dir_parent_train = "PlantCLEF2020TrainingData"
image_dir_parent_test = "PlantCLEF2020TrainingData"
checkpoint_model = "checkpoints\run16\040000.ckpt"
species_name_map_csv = "list\clef2020_herbarium_species.csv"
classmap_txt = "list\clef2020_herbarium_species_classid_map_to_index.txt"
herbarium_dictionary_file = "mean_emb_dict_997_herb_500_run16_40k_crops.pkl"
test_image = "PlantCLEF2020TrainingData\photo\373\5859.jpg"

# ============================================================= #
#                         Parameters
# ============================================================= #
topN = 5 # Number of predictions to output
batch = 10
# Assign batch = 10,
# 10 variations of flipped cropped imgs (center, top left, top right, bottom left, bottom right,
# center flipped, top left flipped, top right flipped, bottom left flipped, bottom right flipped)
numclasses1 = 997 # Class number of Herbarium network
numclasses2 = 10000 # Class number of Field network
input_size = (299,299,3) # Image input size

# ============================================================= #
#                         Load data
# ============================================================= #
# ----- Read herbarium dictionary pkl file ----- #
with open(herbarium_dictionary_file,'rb') as fid1:
	herbarium_dictionary = cPickle.load(fid1)

# ----- Map species index to folder ----- #
with open(classmap_txt,'r') as fid:
    classmap = [x.strip().split(' ')[0] for x in fid.readlines()]

# ----- Map species name to index ----- #
species_name_map_df = pd.read_csv(species_name_map_csv, sep=',')
species_list = species_name_map_df['species'].to_list()

# ============================================================= #
#               Run network / validate image
# ============================================================= #
# ----- Initiate tensors ----- #
x1 = tf.placeholder(tf.float32,(batch,) + input_size)
x2 = tf.placeholder(tf.float32,(batch,) + input_size)
y1 = tf.placeholder(tf.int32,(batch,))
y2 = tf.placeholder(tf.int32,(batch,))
is_training = tf.placeholder(tf.bool)
is_train = tf.placeholder(tf.bool, name="is_training")

# ----- Image preprocessing methods ----- #
train_preproc = lambda xi: inception_preprocessing.preprocess_image(
        xi,input_size[0],input_size[1],is_training=True)

test_preproc = lambda xi: inception_preprocessing.preprocess_image(
        xi,input_size[0],input_size[1],is_training=False)

def data_in_train1():
    return tf.map_fn(fn = train_preproc,elems = x1,dtype=np.float32)

def data_in_test1():
    return tf.map_fn(fn = test_preproc,elems = x1,dtype=np.float32)

def data_in_train2():
    return tf.map_fn(fn = train_preproc,elems = x2,dtype=np.float32)

def data_in_test2():
    return tf.map_fn(fn = test_preproc,elems = x2,dtype=np.float32)

data_in1 = tf.cond(
        is_training,
        true_fn = data_in_train1,
        false_fn = data_in_test1
        )

data_in2 = tf.cond(
        is_training,
        true_fn = data_in_train2,
        false_fn = data_in_test2
        )

def read_img(img_path):
    img = []
    try:
        current_img = img_path
        im = cv2.imread(current_img)

        if im is None:
           im = cv2.cvtColor(np.asarray(Image.open(current_img).convert('RGB')),cv2.COLOR_RGB2BGR)
        im = cv2.resize(im,(input_size[0:2]))

        if np.ndim(im) == 2:
            im = cv2.cvtColor(im,cv2.COLOR_GRAY2RGB)
        else:
            im = cv2.cvtColor(im,cv2.COLOR_BGR2RGB)

        # Center and Corner crops
        im1 = im[0:260,0:260,:]
        im2 = im[0:260,-260:,:]
        im3 = im[-260:,0:260,:]
        im4 = im[-260:,-260:,:]
        im5 = im[19:279,19:279,:]

        imtemp = [cv2.resize(ims,(input_size[0:2])) for ims in (im1,im2,im3,im4,im5)]

        [img.append(ims) for ims in imtemp]

        # Flip image
        flip_img = cv2.flip(im, 1)

        flip_im1 = flip_img[0:260,0:260,:]
        flip_im2 = flip_img[0:260,-260:,:]
        flip_im3 = flip_img[-260:,0:260,:]
        flip_im4 = flip_img[-260:,-260:,:]
        flip_im5 = flip_img[19:279,19:279,:]

        flip_imtemp = [cv2.resize(imf,(input_size[0:2])) for imf in (flip_im1,flip_im2,flip_im3,flip_im4,flip_im5)]

        [img.append(imf) for imf in flip_imtemp]

    except:
        print("Exception found: Image not read...")
        pass

    img = np.asarray(img,dtype=np.float32)/255.0
    return img

# ----- Construct network 1 ----- #
with slim.arg_scope(inception_utils.inception_arg_scope()):
    logits,endpoints = inception_v4(data_in1,
                                num_classes=numclasses1,
                                is_training=is_training,
                                scope='herbarium')
    herbarium_embs = endpoints['PreLogitsFlatten']
    herbarium_bn = tf.layers.batch_normalization(herbarium_embs, training=is_train)
    herbarium_feat = tf.contrib.layers.fully_connected(
                    inputs=herbarium_bn,
                    num_outputs=500,
                    activation_fn=None,
                    normalizer_fn=None,
                    trainable=True,
                    scope='herbarium'
            )
    herbarium_feat = tf.math.l2_normalize(
                                        herbarium_feat,
                                        axis=1
                                    )

# ----- Construct network 2 ----- #
with slim.arg_scope(inception_utils.inception_arg_scope()):
    logits2,endpoints2 = inception_v4(data_in2,
                                num_classes=numclasses2,
                                is_training=is_training,
                                scope='field')
    field_embs = endpoints2['PreLogitsFlatten']
    field_bn = tf.layers.batch_normalization(field_embs, training=is_train)
    field_feat = tf.contrib.layers.fully_connected(
                    inputs=field_bn,
                    num_outputs=500,
                    activation_fn=None,
                    normalizer_fn=None,
                    trainable=True,
                    scope='field'
            )
    field_feat = tf.math.l2_normalize(
                            field_feat,
                            axis=1
                        )

feat_concat = tf.concat([herbarium_feat, field_feat], 0)

variables_to_restore = slim.get_variables_to_restore()
restorer = tf.train.Saver(variables_to_restore)

# ----- Run session ----- #
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    restorer.restore(sess, checkpoint_model)

    test_image = read_img(test_image)

    sample_embedding = sess.run(
                field_feat,
                feed_dict = {
                                x2:test_image,
                                is_training : False,
                                is_train : False
                        }
            )

    # Average center + corner crop embeddings
    averaged_flip = np.mean(sample_embedding, axis=0)
    reshaped_emb_sample = averaged_flip.reshape(1,500)

    print('Getting herbarium dictionary...')
    herbarium_emb_list = []
    for herbarium_class, herbarium_emb in herbarium_dictionary.items():
        herbarium_emb_list.append(np.squeeze(herbarium_emb))
    herbarium_emb_list = np.array(herbarium_emb_list)

    print('Comparing sample embedding with herbarium distance...')
    similarity = cosine_similarity(reshaped_emb_sample, herbarium_emb_list)

    print('Getting probability distribution...')
    similarity_distribution = []
    for sim in similarity:
        new_distribution = []
        for d in sim:
            new_similarity = 1 - d # 1 - cosine value (d)
            new_distribution.append(new_similarity)
        similarity_distribution.append(new_distribution)
    similarity_distribution = np.array(similarity_distribution)

    # Apply inverse weighting with power of 5
    probabilty_list = []
    for d in similarity_distribution:
        inverse_weighting = (1/np.power(d,5))/np.sum(1/np.power(d,5))
        probabilty_list.append(inverse_weighting)
    probabilty_list = np.array(probabilty_list)

    print('Getting topN predictions...')
    for prediction in probabilty_list:
        topN_class_list = prediction.argsort()[-topN:][::-1]
        topN_probability_list = np.sort(prediction)[-topN:][::-1]

    counter = 0
    for cl, prob in zip(topN_class_list, topN_probability_list):
        counter += 1
        class_index = classmap[int(cl)]
        pred_name = species_list[int(cl)]
        print('\nPREDICTION:', counter)
        print('Species:', pred_name)
        print('Class index (folder):', class_index)
        print('Probability:', prob)


#! python3
import sys
import win32api
from PyQt5.QtWidgets import QApplication, QWidget, \
    QToolTip, QPushButton, QMessageBox, QDesktopWidget, \
    QMainWindow, QAction, QMenu, QStatusBar
from PyQt5.QtGui import QIcon, QFont
from PyQt5.QtCore import QCoreApplication

'''
#面向过程
app = QApplication(sys.argv)
w = QWidget()
w.resize(300, 150)
w.setFixedSize(700, 400)
x, y = win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(1)
w.move((x - 250) / 2, (y - 150) / 2)
w.setWindowTitle('将图片转换为jpg 1920*1080')
w.show()
sys.exit(app.exec_())
'''
x , y= 0,0
class Example(QMainWindow):
    def __init__(self):
        super().__init__()#调用父类构造函数
        self.initUI()

    def initUI(self):

        global x,y

        QToolTip.setFont(QFont('SansSerif', 10))
        self.setToolTip('This is a QWidget widget')

        btn = QPushButton('Quit', self)
        btn.setToolTip('This is a QPushButton widget')
        # btn.clicked.connect(QCoreApplication.instance().quit) #clicked btn and exit app
        btn.clicked.connect(QApplication.instance().exit) #clicked btn and exit app
        btn.resize(btn.sizeHint())
        btn.move(50, 50)

        exitAct:QAction = QAction(QIcon('46.jpg'), 'Exit', self)
        exitAct.setShortcut('Ctrl+Q')
        exitAct.setStatusTip('Exit application')
        exitAct.triggered.connect(QApplication.instance().quit)

        menuBar = self.menuBar()
        fileMenu = menuBar.addMenu('File')
        fileMenu.addAction(exitAct)

        self.toolbar = self.addToolBar('Exit')
        self.toolbar.addAction(exitAct)

        # subMenu add to FileMenu
        subMenu = QMenu('Import', self)
        subAct = QAction('Import file', self)
        subMenu.addAction(subAct)
        fileMenu.addMenu(subMenu)

        #checkMenu
        viewSBar:QAction = QAction('View statusbar', self, checkable=True)
        viewSBar.setStatusTip('View statusbar')
        viewSBar.setChecked(True)
        viewSBar.triggered.connect(self.toggleMenu)
        fileMenu.addAction(viewSBar)

        # x, y = win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(1)
        # self.setGeometry((x-700)/2, (y-400)/2, 700, 400)
        self.center()
        self.setFixedSize(700, 400)
        self.setWindowTitle('将图片转换成jpg 1080')
        self.statusbar = self.statusBar()
        self.statusbar.showMessage('Ready')
        self.setWindowIcon(QIcon('46.jpg'))
        self.show()

    def center(self):
        qr = self.frameGeometry()#get self RECT
        cp = QDesktopWidget().availableGeometry().center()#
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    #When Widgets is closing, call this function by automaticlly
    #virtualFunction
    def closeEvent(self, event):
        reply = QMessageBox.question(self, 'Message', 'Are you sure to quit',
                                     QMessageBox.Yes|QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    #virtual Function
    def contextMenuEvent(self, event):
        cmenu = QMenu(self)

        newAct = cmenu.addAction('New')
        opnAct = cmenu.addAction('Open')
        quitAct = cmenu.addAction('Quit')

        #which Action
        print(type(event), event.pos())
        action = cmenu.exec_(self.mapToGlobal(event.pos()))

        if action == quitAct:
            QApplication.instance().quit()

    def toggleMenu(self, state):
        print(state)
        if state:
            self.statusbar.show()
        else:
            self.statusbar.hide()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


# Set up logging
import sys
import logging

logging.basicConfig(
    format="%(asctime)s - %(levelname)s - %(name)s -   %(message)s",
    datefmt="%m/%d/%Y %H:%M:%S",
    handlers=[logging.StreamHandler(sys.stdout)],
    level=logging.WARNING,
)
logger = logging.getLogger(__name__)

from typing import Optional
from dataclasses import dataclass, field
import os
import json
from contextlib import nullcontext
from alive_progress import alive_bar
from transformers.hf_argparser import HfArgumentParser
from transformers.models.auto import AutoConfig, AutoTokenizer, AutoModelForSeq2SeqLM
from seq2seq.utils.pipeline import ConversationalText2SQLGenerationPipeline, Text2SQLGenerationPipeline, Text2SQLInput, ConversationalText2SQLInput
from seq2seq.utils.picard_model_wrapper import PicardArguments, PicardLauncher, with_picard
from seq2seq.utils.dataset import DataTrainingArguments

@dataclass
class PredictionOutputArguments:
    """
    Arguments pertaining to execution.
    """

    model_path: str = field(
        default="tscholak/cxmefzzi",
        metadata={"help": "Path to pretrained model"},
    )
    cache_dir: Optional[str] = field(
        default="/tmp",
        metadata={"help": "Where to cache pretrained models and data"},
    )
    db_path: str = field(
        default="database",
        metadata={"help": "Where to to find the sqlite files"},
    )
    inputs_path: str = field(default="data/dev.json", metadata={"help": "Where to find the inputs"})
    output_path: str = field(
        default="predicted_sql.txt", metadata={"help": "Where to write the output queries"}
    )
    device: int = field(
        default=0,
        metadata={
            "help": "Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU. A non-negative value will run the model on the corresponding CUDA device id."
        },
    )
    conversational: bool = field(default=False, metadata={"help": "Whether or not the inputs are conversations"})

def main():
    # See all possible arguments by passing the --help flag to this program.
    parser = HfArgumentParser((PicardArguments, PredictionOutputArguments, DataTrainingArguments))
    picard_args: PicardArguments
    prediction_output_args: PredictionOutputArguments
    data_training_args: DataTrainingArguments
    if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
        # If we pass only one argument to the script and it's the path to a json file,
        # let's parse it to get our arguments.
        picard_args, prediction_output_args, data_training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
    else:
        picard_args, prediction_output_args, data_training_args = parser.parse_args_into_dataclasses()

    if os.path.isfile(prediction_output_args.output_path):
        raise RuntimeError("file `{}` already exists".format(prediction_output_args.output_path))

    # Initialize config
    config = AutoConfig.from_pretrained(
        prediction_output_args.model_path,
        cache_dir=prediction_output_args.cache_dir,
        max_length=data_training_args.max_target_length,
        num_beams=data_training_args.num_beams,
        num_beam_groups=data_training_args.num_beam_groups,
        diversity_penalty=data_training_args.diversity_penalty,
    )

    # Initialize tokenizer
    tokenizer = AutoTokenizer.from_pretrained(
        prediction_output_args.model_path,
        cache_dir=prediction_output_args.cache_dir,
        use_fast=True,
    )

    # Initialize Picard if necessary
    with PicardLauncher() if picard_args.launch_picard else nullcontext(None):
        # Get Picard model class wrapper
        if picard_args.use_picard:
            model_cls_wrapper = lambda model_cls: with_picard(
                model_cls=model_cls, picard_args=picard_args, tokenizer=tokenizer
            )
        else:
            model_cls_wrapper = lambda model_cls: model_cls

        # Initialize model
        model = model_cls_wrapper(AutoModelForSeq2SeqLM).from_pretrained(
            prediction_output_args.model_path,
            config=config,
            cache_dir=prediction_output_args.cache_dir,
        )

        if prediction_output_args.conversational:
            conversational_text2sql(model, tokenizer, prediction_output_args, data_training_args)
        else:
            text2sql(model, tokenizer, prediction_output_args, data_training_args)

def get_pipeline_kwargs(
    model, tokenizer: AutoTokenizer, prediction_output_args: PredictionOutputArguments, data_training_args: DataTrainingArguments
) -> dict:
    return {
        "model": model,
        "tokenizer": tokenizer,
        "db_path": prediction_output_args.db_path,
        "prefix": data_training_args.source_prefix,
        "normalize_query": data_training_args.normalize_query,
        "schema_serialization_type": data_training_args.schema_serialization_type,
        "schema_serialization_with_db_id": data_training_args.schema_serialization_with_db_id,
        "schema_serialization_with_db_content": data_training_args.schema_serialization_with_db_content,
        "device": prediction_output_args.device,
    }

def text2sql(model, tokenizer, prediction_output_args, data_training_args):
    # Initalize generation pipeline
    pipe = Text2SQLGenerationPipeline(**get_pipeline_kwargs(model, tokenizer, prediction_output_args, data_training_args))

    with open(prediction_output_args.inputs_path) as fp:
        questions = json.load(fp)

    with alive_bar(len(questions)) as bar:
        for question in questions:
            try:
                outputs = pipe(inputs=Text2SQLInput(question["question"],question["db_id"]))
                output = outputs[0]
                query = output["generated_text"]
            except Exception as e:
                logger.error(e)
                query = ""
            logger.info("writing `{}` to `{}`".format(query, prediction_output_args.output_path))
            bar.text(query)
            bar()
            with open(prediction_output_args.output_path, "a") as fp:
                fp.write(query + "\n")

def conversational_text2sql(model, tokenizer, prediction_output_args, data_training_args):
    # Initalize generation pipeline
    pipe = ConversationalText2SQLGenerationPipeline(
        **get_pipeline_kwargs(model, tokenizer, prediction_output_args, data_training_args)
    )

    with open(prediction_output_args.inputs_path) as fp:
        conversations = json.load(fp)

    length = sum(len(conversation["interaction"]) for conversation in conversations)
    with alive_bar(length) as bar:
        for conversation in conversations:
            utterances = []
            for turn in conversation["interaction"]:
                utterances.extend((utterance.strip() for utterance in turn["utterance"].split(sep="|")))
                try:
                    outputs = pipe(
                        inputs=ConversationalText2SQLInput(list(utterances),
                        db_id=conversation["database_id"])
                    )
                    output = outputs[0]
                    query = output["generated_text"]
                except Exception as e:
                    logger.error(e)
                    query = ""
                logger.info("writing `{}` to `{}`".format(query, prediction_output_args.output_path))
                bar.text(query)
                bar()
                with open(prediction_output_args.output_path, "a") as fp:
                    fp.write(query + "\n")

            with open(prediction_output_args.output_path, "a") as fp:
                fp.write("\n")

if __name__ == "__main__":
    main()


from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import View

from .forms import (CreateCourseForm,
                    CreateCourseRegistrationForm,
                    CreateDepartmentForm,
                    CreateRegistrationForm)

from .models import Course, CourseRegistration, Department, Registration

import datetime
from django.utils import timezone

class CreateCourseView(LoginRequiredMixin, View):
    """
    View for admin to create new Course.
    """

    template_name = 'academicInfo/create_course.html'
    create_course_form = CreateCourseForm

    def get(self, request, *args, **kwargs):

        # Render this page only for the Admin.
        if hasattr(request.user, 'staff') and request.user.staff.is_admin:
            create_course_form = self.create_course_form()
            return render(request, self.template_name, {'create_course_form' : create_course_form})
        else:
            return redirect('home')

    def post(self, request, *args, **kwargs):
        create_course_form = CreateCourseForm(request.POST)

        if create_course_form.is_valid():
            course = create_course_form.save()
            course.save()

            return redirect('view_course')

        return render(request, self.template_name, {'create_course_form' : create_course_form})

class CreateCourseRegistrationView(LoginRequiredMixin, View):
    """
    View for admin to add Course to the Registration.
    """

    template_name = 'academicInfo/create_course_registration.html'
    create_course_registration_form = CreateCourseRegistrationForm

    def get(self, request, *args, **kwargs):

        # Render this page only for the Admin.
        if hasattr(request.user, 'staff') and request.user.staff.is_admin:
            create_course_registration_form = self.create_course_registration_form()
            return render(request, self.template_name, {'create_course_registration_form' : create_course_registration_form})
        else:
            return redirect('home')

    def post(self, request, *args, **kwargs):
        create_course_registration_form = CreateCourseRegistrationForm(request.POST)

        if create_course_registration_form.is_valid():

            # Add course to registration only if this course is not added already
            # in this registration.
            course_registration = create_course_registration_form.save(commit=False)

            # Check if the registration has already started.
            if course_registration.registration.startTime <= timezone.now():
                create_course_registration_form.add_error('registration',
                                                          'The registration has already started, you cannot add course to it now.')
                return render(request, self.template_name, {'create_course_registration_form' : create_course_registration_form})

            courses_in_registration = course_registration.registration.courseregistration_set.all()
            similar_course_registration = courses_in_registration.filter(course=course_registration.course,
                                                                         semester=course_registration.semester)

            # Check if course is not already present in the same registration and semester.
            if len(similar_course_registration) == 0:
                course_registration.save()
                return render(request, self.template_name, {'create_course_registration_form' : create_course_registration_form,
                                                            'success': 'Successfully added course to the registration.'})
            else:
                create_course_registration_form.add_error('course', 'This course is already added in this semester.')
                create_course_registration_form.add_error('semester', 'This semester already has this course.')

        return render(request, self.template_name, {'create_course_registration_form' : create_course_registration_form})

class CreateDepartmentView(LoginRequiredMixin, View):
    """
    View for admin to add new Department.
    """

    template_name = 'academicInfo/create_department.html'
    create_department_form = CreateDepartmentForm

    def get(self, request, *args, **kwargs):

        # Render this page only for the Admin.
        if hasattr(request.user, 'staff') and request.user.staff.is_admin:
            create_department_form = self.create_department_form()
            return render(request, self.template_name, {'create_department_form' : create_department_form})
        else:
            return redirect('home')

    def post(self, request, *args, **kwargs):
        create_department_form = CreateDepartmentForm(request.POST)

        # Check if Department with same name does not already exist.
        if create_department_form.is_valid():
            department = create_department_form.save()
            department.save()
            return redirect('view_department')
        else:
            return render(request, self.template_name, {'create_department_form' : create_department_form})

class CreateRegistrationView(LoginRequiredMixin, View):
    """
    View for admin to create new Registration.
    """

    template_name = 'academicInfo/create_registration.html'
    create_registration_form = CreateRegistrationForm

    def get(self, request, *args, **kwargs):

        # Render this page only for the Admin.
        if hasattr(request.user, 'staff') and request.user.staff.is_admin:
            create_registration_form = self.create_registration_form()
            return render(request, self.template_name, {'create_registration_form' : create_registration_form})
        else:
            return redirect('home')

    def post(self, request, *args, **kwargs):
        create_registration_form = CreateRegistrationForm(request.POST)

        # Check if the Registration form is valid.
        if create_registration_form.is_valid():
            days = int(request.POST['days'])
            hours = int(request.POST['hours'])
            minutes = int(request.POST['minutes'])

            # Check if duration is 0 or not.
            if days + hours + minutes == 0:

                # Duration cannot be 0.
                return render(request, self.template_name, {'create_registration_form' : create_registration_form,
                                                            'error' : 'Duration cannot be 0.'})

            startTime = create_registration_form.cleaned_data['startTime']
            duration = datetime.timedelta(days=days, hours=hours, minutes=minutes)
            endTime = startTime + duration
            registration = Registration.objects.create(name=create_registration_form.cleaned_data['name'],
                                                       startTime=startTime,
                                                       duration=duration,
                                                       endTime=endTime)

            registration.save()
            return redirect('registration')

        return render(request, self.template_name, {'create_registration_form' : create_registration_form})

class RegistrationsView(View):
    """
    View for everyone to view all the registrations.
    """

    template_name = 'academicInfo/registration.html'

    def get(self, request, *args, **kwargs):

        time = timezone.now()

        future_registrations = Registration.objects.filter(startTime__gt=time).order_by('startTime')
        present_registrations = Registration.objects.filter(
                                                            endTime__gt=time
                                                            ).exclude(startTime__gt=time).order_by('endTime')
        past_registrations = Registration.objects.filter(endTime__lt=time)

        return render(request, self.template_name, {'future_registrations': future_registrations,
                                                    'present_registrations': present_registrations,
                                                    'past_registrations': past_registrations})

class LiveRegistrationView(LoginRequiredMixin, View):
    """
    View for student to register and unregister from live registrations.
    """

    template_name = 'academicInfo/live_registration.html'

    def get(self, request, *args, **kwargs):

        # Render this page only for the students.
        if hasattr(request.user, 'student'):

            registration = get_object_or_404(Registration, pk=self.kwargs['registration_id'])
            time = timezone.now()

            # Check if registration is currently live.
            if registration.startTime < time and registration.endTime > time:

                student = request.user.student

                # Show courses which are in either current semester or the next semester of student.
                courses_in_registration = registration.courseregistration_set.all()
                course_registration = courses_in_registration.filter(
                                                                     semester__gt=student.get_student_semester
                                                                     ).exclude(semester__gt=student.get_student_semester+1)
                return render(request, self.template_name, {'course_registration' : course_registration,
                                                            'student_courses' : student.courseregistration_set.all()})
            else:
                return redirect('registration')

        else:
            return redirect('home')

    def post(self, request, *args, **kwargs):

        # Only students should be allowed to register.
        if hasattr(request.user, 'student'):

            course_registration = get_object_or_404(CourseRegistration,
                                                    pk=request.POST['course_registration_id'])
            registration = course_registration.registration
            currTime = timezone.now()
            student = request.user.student
            semester = student.get_student_semester

            # If student wants to register for the course.
            if 'Register' in request.POST:
                if (currTime > registration.startTime and
                    currTime < registration.endTime and
                    course_registration.semester in range(semester, semester+2)):

                    if (not student in course_registration.students.all() and
                        course_registration.remaining_seats > 0):
                        course_registration.students.add(student)

                    return redirect(reverse('live_registration',
                                                kwargs={'registration_id' : registration.id}))

                else:
                    return redirect('home')

            # If student wants to unregister from the course.
            elif 'UnRegister' in request.POST:
                if (currTime > registration.startTime and
                    currTime < registration.endTime and
                    student in course_registration.students.all()):
                    course_registration.students.remove(student)

                return redirect(reverse('live_registration',
                                        kwargs={'registration_id' : registration.id}))

        else:
            return redirect('home')

class DepartmentsView(LoginRequiredMixin, View):
    """
    View for admin to see departments and add new department.
    """

    template_name = 'academicInfo/departments.html'

    def get(self, request, *args, **kwargs):

        # Render this page only for the Admin.
        if hasattr(request.user, 'staff') and request.user.staff.is_admin:
            departments = Department.objects.all()
            return render(request, self.template_name, {'departments' : departments})
        else:
            return redirect('home')

class CourseView(LoginRequiredMixin, View):
    """
    View for admin to see Courses and add new Course.
    """

    template_name = 'academicInfo/courses.html'

    def get(self, request, *args, **kwargs):

        # Render this page only for the Admin.
        if hasattr(request.user, 'staff') and request.user.staff.is_admin:
            courses = Course.objects.all()
            return render(request, self.template_name, {'courses' : courses})
        else:
            return redirect('home')


#!/usr/bin/env python

import argparse

def filter_sam( out_fn, in_fn, chromosome):
  with open(out_fn, 'w') as donor_out:
    for line in open(in_fn, 'r'):
      if line.startswith("@SQ"):
        if "SN:{}\t".format(chromosome) in line:
          donor_out.write(line)
      elif line.startswith("@"):
        donor_out.write(line)
      else:
        fields = line.strip('\n').split('\t')
        if fields[2] == chromosome:
          donor_out.write(line)

if __name__ == '__main__':
  parser = argparse.ArgumentParser(description='Filter specified chromosome')
  parser.add_argument('--target', help='target filename')
  parser.add_argument('--source', help='source filename')
  parser.add_argument('--chromosome', help='name of chromosome')
  args = parser.parse_args()
  filter_sam(args.target, args.source, args.chromosome)


"""scene.py module"""
# Michael Gresham
# CPSC 386-01
# 2021-11-29
# greshammichael@csu.fullerton.edu
# @Michael-Gresham
#
# Lab 03-00
#
# My scene class
# Holds all the scenes that are present in snek game.
import pygame
from pygame.constants import SCRAP_SELECTION
from random import randint
import os
import pickle
from datetime import datetime

class Scene:
    """General Scene class that's inherited by all other Scene types."""

    def __init__(self, screen, clock, background_color=(0, 0, 0)):
        self._is_valid = True
        self._frame_rate = 60
        self._screen = screen
        self._background = pygame.Surface(self._screen.get_size())
        self._background_color = background_color
        self._background.fill(self._background_color)
        self._clock = clock

    def is_valid(self):
        """If game state is valid return true."""
        return self._is_valid

    def frame_rate(self):
        """return the frame rate of the game."""
        return self._frame_rate

    def start_scene(self):
        """method driver for the class"""
        pass

    def end_scene(self):
        """Does nothing here but meant to return next scene."""
        pass

    def update(self):
        """update the display of the scene."""
        pygame.display.update()

    def draw(self):
        """Display the screen background onto the screen."""
        self._screen.blit(self._background, (0, 0))

    def process_event(self, event):
        """Handles all the events at the particular scene."""
        if event.type == pygame.QUIT:
            self._is_valid = False
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            print("Good bye!")
            self._is_valid = False

class TitleScene(Scene):
    """Class which handles the title screen of snake."""

    def __init__(self, screen, clock, title_size, background_color=(0, 0, 0)):
        # class initializer. Initializes basic displays.
        super().__init__(screen, clock, background_color)
        (w, h) = self._screen.get_size()
        self._speed = [0.5, 1, 2]
        self._title_name = "Snek Game"
        self._title_size = title_size
        self._title_color = [50, 50, 50]
        title_font = pygame.font.Font(
            pygame.font.get_default_font(), self._title_size
        )
        self._title = title_font.render(
            self._title_name, True, self._title_color
        )
        self._title_pos = self._title.get_rect(center=(w // 2, h // 4))
        instruction_name = "Press any key to continue"
        self._instruction_size = title_size // 4
        print(str(self._instruction_size))
        instruction_font = pygame.font.Font(
            pygame.font.get_default_font(), self._instruction_size
        )
        self._instruction = instruction_font.render(
            instruction_name, True, (255, 255, 0)
        )
        self._instruction_pos = self._instruction.get_rect(
            center=(w // 2, h // 2 + h // 4)
        )
        self._reverse = False

    def start_scene(self):
        """Method driver of the class. Calls other method in order to run the scene."""
        while True:
            self.draw()

            self.update()
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    return self.end_scene()
                self.process_event(event)
        pass

    def draw(self):
        """redraws the background, title name, and instructions and updates screen."""
        super().draw()
        self._screen.blit(self._title, self._title_pos)
        self._screen.blit(self._instruction, self._instruction_pos)
        self.display_rules()
        pygame.display.update()

    def display_rules(self):
        """Displays the instructions for Snake Game."""
        instructions = [
            "Press arrow keys to change the direction of the snake.",
            "Goal of game is to survive and eat as many apples as possible.",
            "Every apple you eat extends the length of the snake.",
            "Try not to hit yourself or hit into a wall or its game over.",
            "Overall score is based off time survived and apples eaten",
            "Good Luck!",
        ]

        (w, h) = self._screen.get_size()
        height = (h // 4) + 100
        width = w // 4
        count = 0
        for instruction in instructions:
            instruction_font = pygame.font.Font(
                pygame.font.get_default_font(), 15
            )
            instruction_render = instruction_font.render(
                instruction, True, (255, 255, 255)
            )
            if count == 5:
                self._screen.blit(instruction_render, (w // 2 - 50, height))
            else:
                self._screen.blit(instruction_render, (width, height))

            height += 50
            count += 1

    def update(self):
        """Updates the color of title text and updates background."""
        super().update()

        for x in range(3):
            self._title_color[x] += 1 * self._speed[x]
            if self._title_color[x] <= 0 or self._title_color[x] >= 255:
                self._reverse = not self._reverse
                self._speed[x] *= -1
                if self._title_color[x] > 255:
                    self._title_color[x] = 255
                if self._title_color[x] < 0:
                    self._title_color[x] = 0
        title_font = pygame.font.Font(
            pygame.font.get_default_font(), self._title_size
        )
        self._title = title_font.render(
            self._title_name, True, self._title_color
        )

    def end_scene(self):
        """returns the next scene."""
        return "Level1"
        pass

    def process_event(self, event):
        """handles the exit button."""
        if event.type == pygame.QUIT:
            print("Goodbye!")
            pygame.quit()

class GameScene(Scene):
    """Start of the GameScene Class"""

    def __init__(self, screen, clock, background_color=(0, 0, 0)):
        """
        This function initializes the GameScene class setting
        the snake game board and the display as well.
        """
        super().__init__(screen, clock, background_color)
        # sets the board and initializes location of snake and apple.
        self.direction = None
        self.start_ticks = pygame.time.get_ticks()
        self.score = 0
        self.time = 0
        self.snake_size = 1
        self.snake = []
        # self.player = player
        self.offset = 100
        (w, h) = self._screen.get_size()
        self.board = []
        for x in range(0, ((h - 100) // 20)):
            row = []
            for y in range(0, (w // 20)):
                if (
                    x == 0
                    or y == 0
                    or y == (w // 20) - 1
                    or x == ((h - 100) // 20) - 1
                ):
                    row.append("border")
                elif x == ((h - 100) // 20) // 2 and y == (w // 20) // 2:
                    row.append("snek")
                    self.snake.append((x, y))
                elif (
                    x == ((((h - 100) // 20) // 2) + (((h - 100) // 20) // 4))
                    and y == (w // 20) // 2
                ):
                    row.append("apple")
                else:
                    row.append("empty")
            self.board.append(row)
        self.timer = "Timer: " + str(self.time)
        title_font = pygame.font.Font(pygame.font.get_default_font(), 25)
        self._title_time = title_font.render(self.timer, True, (255, 255, 255))
        self._timer_pos = self._title_time.get_rect(
            center=(w // 4, self.offset // 2)
        )
        self.title_score = "Score: " + str(self.score)
        self._title_score = title_font.render(
            self.title_score, True, (255, 255, 255)
        )
        self._score_pos = self._title_score.get_rect(
            center=(w // 2 + w // 4, self.offset // 2)
        )

    def start_scene(self):
        """method driver that drives the game logic."""
        self.__init__(self._screen, self._clock)
        while True:
            # gets the time in game in miliseconds.
            miliseconds = pygame.time.get_ticks() - self.start_ticks
            exit = self.move()
            if exit != None:
                return exit
            self.draw()
            self.update(miliseconds)
            for event in pygame.event.get():
                self.process_event(event)
        pass

    def update(self, miliseconds):
        """handles updating the timer, background, and score."""
        if (miliseconds // 1000) > self.time:
            self.time = miliseconds // 1000
            self.timer = "Timer: " + str(self.time)
            title_font = pygame.font.Font(pygame.font.get_default_font(), 25)
            self._title_time = title_font.render(
                self.timer, True, (255, 255, 255)
            )
            if (self.time % 3) == 0 and self.time != 0:
                self.score += 1
        self.title_score = "Score: " + str(self.score)
        title_font = pygame.font.Font(pygame.font.get_default_font(), 25)
        self._title_score = title_font.render(
            self.title_score, True, (255, 255, 255)
        )
        pygame.display.update()
        pass

    def create_apple(self):
        """Handles the logic that places a new apple when one is eaten."""
        valid = False
        while valid == False:
            row = randint(1, len(self.board) - 1)
            column = randint(1, len(self.board[0]) - 1)
            if self.board[row][column] == "empty":
                self.board[row][column] = "apple"
                valid = True
        pass

    def move(self):
        """Handles the movement logic of the snake. and loss conditions."""
        if self.direction == None:
            pass
        else:
            row = self.snake[0][0]
            column = self.snake[0][1]
            added = False
            if self.direction == "up":
                row -= 1
            elif self.direction == "down":
                row += 1
            elif self.direction == "left":
                column -= 1
            elif self.direction == "right":
                column += 1

            if (
                self.board[row][column] == "border"
                or self.board[row][column] == "snek"
            ):
                return self.end_scene()
            if (
                self.board[row][column] != "border"
                and self.board[row][column] != "apple"
            ):
                self.board[row][column] = "snek"
                self.snake.insert(0, (row, column))
            if self.board[row][column] == "apple":
                print("hello World")
                added = True
                self.score += 10
                self.create_apple()
                self.board[row][column] = "snek"
                self.snake.insert(0, (row, column))
                miliseconds = pygame.time.get_ticks() - self.start_ticks
                self.draw()
                self.update(miliseconds)
            if added == False:
                (x, y) = self.snake.pop()
                self.board[x][y] = "empty"
            self._clock.tick(10)
        pass

    def end_scene(self):
        """returns next scene which is end scene."""
        print(str(self.score))
        print(str(self.time))
        return "End Scene"

    def draw(self):
        """displays the score, time, and the game screen on pygame display."""
        super().draw()
        self._screen.blit(self._title_score, self._score_pos)
        self._screen.blit(self._title_time, self._timer_pos)
        for x in range(0, len(self.board)):
            for y in range(0, len(self.board[0])):
                if self.board[x][y] == "border":
                    pygame.draw.rect(
                        self._screen,
                        (164, 116, 73),
                        pygame.Rect((y * 20), (x * 20) + self.offset, 20, 20),
                    )
                elif self.board[x][y] == "empty":
                    pygame.draw.rect(
                        self._screen,
                        (0, 154, 23),
                        pygame.Rect((y * 20), (x * 20) + self.offset, 20, 20),
                    )
                elif self.board[x][y] == "apple":
                    pygame.draw.rect(
                        self._screen,
                        (0, 154, 23),
                        pygame.Rect((y * 20), (x * 20) + self.offset, 20, 20),
                    )
                    pygame.draw.circle(
                        self._screen,
                        (255, 0, 0),
                        ((y * 20) + 10, (x * 20) + 10 + self.offset),
                        10,
                    )
                elif self.board[x][y] == "snek":
                    pygame.draw.rect(
                        self._screen,
                        (0, 0, 255),
                        pygame.Rect((y * 20), (x * 20) + self.offset, 20, 20),
                    )
        pass

    def process_event(self, event):
        """handle various events in game: movement and exit button."""
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP and self.direction != "down":
                self.direction = "up"
            if event.key == pygame.K_DOWN and self.direction != "up":
                self.direction = "down"
            if event.key == pygame.K_LEFT and self.direction != "right":
                self.direction = "left"
            if event.key == pygame.K_RIGHT and self.direction != "left":
                self.direction = "right"

class End_Scene(Scene):
    """The end screen of snake, handles leader board and reset logic."""

    main_dir = os.path.split(os.path.abspath(__file__))[0]
    data_dir = os.path.join(main_dir, "data")

    def __init__(self, screen, clock, background_color=(0, 0, 0)):
        """
        This function initializes the end scene by setting
        up visual text and visual instructions.
        """
        super().__init__(screen, clock, background_color)
        self.player_score = 0
        self.player_time = 0
        (w, h) = self._screen.get_size()
        self.leaderboard = []
        # code for Game over screen.
        self._title_name = "Leader Board"
        self._title_size = 60
        self._title_color = [255, 255, 255]
        title_font = pygame.font.Font(
            pygame.font.get_default_font(), self._title_size
        )
        self._title = title_font.render(
            self._title_name, True, self._title_color
        )
        self._title_pos = self._title.get_rect(center=(w // 2, h // 8))

        self._score_name = "        Date                            Score                           Time"
        self._score_size = 30
        self._score_color = [255, 255, 255]
        title_font = pygame.font.Font(
            pygame.font.get_default_font(), self._score_size
        )
        self._score = title_font.render(
            self._score_name, True, self._score_color
        )
        self._score_pos = self._title.get_rect(center=(w // 4, h // 4))
        pass

    def draw(self):
        """draws the leaderboard and options onto the screen."""
        super().draw()
        self._screen.blit(self._score, self._score_pos)
        self._screen.blit(self._title, self._title_pos)
        count = 10
        if 10 > len(self.leaderboard):
            count = len(self.leaderboard)

        for x in range(0, count):
            (w, h) = self._screen.get_size()
            date = self.leaderboard[x][2].strftime("%d/%m/%Y %H:%M:%S")
            record_name = "{0:<2} {1:<10}  {2:<10}          {3:<30}".format(
                str(x + 1), date, self.leaderboard[x][0], self.leaderboard[x][1]
            )
            print(record_name)
            record_size = 25
            record_color = (255, 255, 255)
            record_font = pygame.font.SysFont("couriernew", record_size, 1, 0)
            record = record_font.render(record_name, True, record_color)
            record_pos = self._title.get_rect(
                center=(w // 4 + 10, h // 4 + (30 * (x + 1)))
            )
            self._screen.blit(record, record_pos)
        restart_title = "Press Space to play again!"
        restart_size = 20
        restart_color = (255, 255, 255)
        restart_font = pygame.font.Font(
            pygame.font.get_default_font(), restart_size
        )
        restart = restart_font.render(restart_title, True, restart_color)
        restart_pos = record_pos = self._title.get_rect(
            center=(w // 2, h // 2 + h // 4)
        )
        self._screen.blit(restart, restart_pos)

        restart_title = "Press Escape to exit the game!"
        restart_size = 20
        restart_color = (255, 255, 255)
        restart_font = pygame.font.Font(
            pygame.font.get_default_font(), restart_size
        )
        restart = restart_font.render(restart_title, True, restart_color)
        restart_pos = record_pos = self._title.get_rect(
            center=(w // 2, h // 2 + h // 4 + 50)
        )
        self._screen.blit(restart, restart_pos)

    def pickle_in_player(self):
        """takes player game records and puts it in pickle file."""
        game_record = []
        game_date = datetime.now()
        game_record.append(self.player_score)
        game_record.append(self.player_time)
        game_record.append(game_date)
        with open(self.data_dir + "/leaderboard.pickle", "ab") as fh:
            pickle.dump(game_record, fh, pickle.HIGHEST_PROTOCOL)

    def load_in(self):
        """loads in all game records."""
        with open(self.data_dir + "/leaderboard.pickle", "rb") as fh:
            while True:
                try:
                    yield pickle.load(fh)
                except EOFError:
                    break

    def start_scene(self, score, time):
        """method driver that handles End Scene logic."""
        print(pygame.font.get_fonts())
        print(score)
        print(time)
        self.player_score = score
        self.player_time = time
        self.pickle_in_player()
        self.leaderboard = list(self.load_in())
        self.leaderboard.sort(key=lambda l: l[0], reverse=True)
        self.draw()
        self.update()
        print(self.leaderboard)
        while True:
            for event in pygame.event.get():
                next_scene = self.process_event(event)
                if next_scene != None:
                    return next_scene

        pass

    def process_event(self, event):
        """handles the event in end screen: new game and exit game."""
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                return "exit"
            if event.key == pygame.K_SPACE:
                return "Title"