from django.db import models
from django.contrib.auth.models import User
from django.db.models.query import ModelIterable
from django.db.models.signals import post_save, post_init
import requests
import random

def sendNotification(usertoken, title, body):
    userdata = {
        "to": str(usertoken),
        "notification": {
            "body": str(title),
            "title": str(body),
            "content_available": True,
            "priority": "high"
        }

    }
    headers = {
        "Authorization": "key=AAAAwVFO9Fw:APA91bHymQMWRKlGHZOVMxp4_-0HA5vOlybPEpCU7NHOs1v9lkkd5JrtYzsU_3UYH5-nxcSZYA9xUOVYfpyKPE_YFdL2BgCKUvbIBBNuqfvIAOcbjLZ6eQ7o4SCAFG1UGBp8X7JnB2HI",
        "Content-Type": "application/json"

    }
    r = requests.post(
        'https://fcm.googleapis.com/fcm/send',  json=userdata, headers=headers)

class CustomerProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True)
    # aadharNo = models.IntegerField(default=0)
    phoneNo = models.CharField(max_length=10, blank=True)

    def __str__(self):
        return "%s's profile" % self.user

class DeliveryProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True)
    # aadharNo = models.IntegerField(default=0)
    phoneNo = models.CharField(max_length=10, blank=True)

    def __str__(self):
        return "%s's profile" % self.user

class ShopLocality(models.Model):
    name = models.CharField(max_length=500)

    def __str__(self):
        return self.name

class Shop(models.Model):
    vendor = models.ForeignKey(
        User, on_delete=models.CASCADE, blank=True, null=True)
    name = models.CharField(max_length=500)
    currentOffer = models.FloatField()
    ShopImg = models.CharField(max_length=500, blank=True,
                               default="https://images.unsplash.com/photo-1498837167922-ddd27525d352?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80.jpg")
    locality = models.ForeignKey(
        ShopLocality, on_delete=models.CASCADE, null=True)
    latitude = models.FloatField(null=True)
    longitude = models.FloatField(null=True)
    addressinwords = models.CharField(
        max_length=1000, default="")
    phoneNo = models.CharField(max_length=10, blank=True)
    email = models.CharField(max_length=10, blank=True)
    date = models.DateField(auto_now_add=True, null=True)
    time = models.TimeField(auto_now_add=True, null=True)

    def __str__(self):
        return self.name

class ProductCategory(models.Model):
    name = models.CharField(max_length=500)

    def __str__(self):
        return self.name

class Product(models.Model):
    name = models.CharField(max_length=500)
    price = models.FloatField()
    shop = models.ForeignKey(Shop, on_delete=models.CASCADE, null=True)
    category = models.ForeignKey(
        ProductCategory, on_delete=models.CASCADE, null=True)
    productImage = models.CharField(
        max_length=500, default="https://images.unsplash.com/photo-1458642849426-cfb724f15ef7?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80")

    def __str__(self):
        return self.name

class PaymentCategory(models.Model):
    name = models.CharField(max_length=500)

    def __str__(self):
        return self.name

class CustomerOrder(models.Model):

    orderFor = models.ForeignKey(
        User, on_delete=models.CASCADE, blank=True)
    product = models.ManyToManyField(
        Product, blank=True)
    shop = models.ForeignKey(Shop, on_delete=models.CASCADE, null=True)

    latitude = models.FloatField(null=True)
    longitude = models.FloatField(null=True)

    date = models.DateField(auto_now_add=True, null=True)
    time = models.TimeField(auto_now_add=True, null=True)
    orderImg = models.CharField(
        max_length=500, null=True, default="https://images.unsplash.com/photo-1498837167922-ddd27525d352?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80.jpg")
    status = models.CharField(max_length=1000, null=True)
    orderPrice = models.FloatField(default=100)
    deliveryboy = models.ForeignKey(
        DeliveryProfile, on_delete=models.CASCADE, null=True, blank=True)
    locality = models.ForeignKey(
        ShopLocality, on_delete=models.CASCADE, null=True, blank=True)
    addressinwords = models.CharField(
        max_length=1000, default="")
    typeOfPayment = models.ForeignKey(
        PaymentCategory, on_delete=models.CASCADE, null=True)
    OTP = models.IntegerField(null=True, default=0)
    payment_status = models.CharField(
        max_length=100, null=True, blank=True)

    @staticmethod
    def post_save(sender, **kwargs):
        instance = kwargs.get('instance')

        if instance.previous_status != instance.status or instance.OTP == 0:
            print("status changed")
            try:
                try:
                    user = FireabaseToken.objects.filter(
                        user=instance.orderFor).first()
                    usertoken = user.token
                    vendor = FireabaseToken.objects.filter(
                        user=instance.shop.vendor).first()
                    vendortoken = vendor.token
                except:
                    pass
                status = instance.status
                if instance.OTP == 0:
                    instance.OTP = random.randint(1000, 9999)
                    instance.save()

                    sendNotification(vendortoken, 'New Order',
                                     "A new order has been placed")

                    sendNotification(usertoken, 'Order Placed',
                                     "Order has been placed awaiting for the restaurant response")

                elif status == "shopreject":
                    sendNotification(
                        usertoken, 'Order Staus', "Your order has been denied")
                elif status == "pending":
                    sendNotification(usertoken, 'Order Status',
                                     "Your order is beign prepared")
                elif status == "inorder":
                    sendNotification(usertoken, 'Order Staus',
                                     "Your order is on the way")
                elif status == "delivered":
                    sendNotification(usertoken, 'Order Status',
                                     "You have recived your order")
            except:
                pass

    @staticmethod
    def remember_status(sender, **kwargs):
        instance = kwargs.get('instance')
        instance.previous_status = instance.status

post_save.connect(CustomerOrder.post_save, sender=CustomerOrder)
post_init.connect(CustomerOrder.remember_status, sender=CustomerOrder)

class ProductQuanities(models.Model):
    product = models.ForeignKey(
        Product, on_delete=models.CASCADE, blank=True)
    quantity = models.IntegerField()
    orderID = models.ForeignKey(
        CustomerOrder, on_delete=models.CASCADE, blank=True, null=True)

class FireabaseToken(models.Model):
    token = models.CharField(max_length=500)
    user = models.OneToOneField(
        User, on_delete=models.CASCADE, blank=True, null=True)

    def __str__(self):
        return self.token

class StoreImage(models.Model):
    image = models.ImageField()

    def __str__(self):
        return self.image.url


#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

from openstack_dashboard.test.integration_tests import decorators
from openstack_dashboard.test.integration_tests import helpers
from openstack_dashboard.test.integration_tests.regions import messages

@decorators.services_required("neutron")
class TestNetworks(helpers.TestCase):
    NETWORK_NAME = helpers.gen_random_resource_name("network")
    SUBNET_NAME = helpers.gen_random_resource_name("subnet")
    SUBNET_NAME_2 = helpers.gen_random_resource_name("subnet")

    @decorators.skip_new_design
    def test_private_network_create(self):
        """tests the network creation and deletion functionalities:
        * creates a new private network and a new subnet associated with it
        * verifies the network appears in the networks table as active
        * deletes the newly created network
        * verifies the network does not appear in the table after deletion
        """

        networks_page = self.home_pg.go_to_network_networkspage()

        networks_page.create_network(self.NETWORK_NAME, self.SUBNET_NAME)
        self.assertTrue(
            networks_page.find_message_and_dismiss(messages.SUCCESS))
        self.assertFalse(
            networks_page.find_message_and_dismiss(messages.ERROR))
        self.assertTrue(networks_page.is_network_present(self.NETWORK_NAME))
        self.assertTrue(networks_page.is_network_active(self.NETWORK_NAME))

        networks_page.delete_network(self.NETWORK_NAME)
        self.assertTrue(
            networks_page.find_message_and_dismiss(messages.SUCCESS))
        self.assertFalse(
            networks_page.find_message_and_dismiss(messages.ERROR))
        self.assertFalse(networks_page.is_network_present(self.NETWORK_NAME))

    def test_subnet_add(self):
        """This test checks add subnet functionality
            Steps:
            1) Login to Horizon dashboard as demo user
            2) Go to Project -> Network -> Networks
            3) Create network with subnet
            4) Add subnet for created network
            5) Check that subnet is created (on NetworkOverview page)
            6) Delete created subnet
            7) Check that subnet was deleted
            8) Check that subnet that was added during creation
             of network is still presented
            9) Delete created network
        """
        networks_page = self.home_pg.go_to_network_networkspage()
        networks_page.create_network(self.NETWORK_NAME, self.SUBNET_NAME)
        self.assertTrue(
            networks_page.find_message_and_dismiss(messages.SUCCESS))
        self.assertFalse(
            networks_page.find_message_and_dismiss(messages.ERROR))
        self.assertTrue(networks_page.is_network_present(self.NETWORK_NAME))
        self.assertTrue(networks_page.is_network_active(self.NETWORK_NAME))
        overview = networks_page.add_subnet(self.NETWORK_NAME,
                                            self.SUBNET_NAME_2,
                                            network_address='10.50.0.0/16')
        self.assertTrue(overview.is_subnet_present(self.SUBNET_NAME))
        self.assertTrue(overview.is_subnet_present(self.SUBNET_NAME_2))
        overview.delete_subnet(self.SUBNET_NAME_2)
        self.assertTrue(
            networks_page.find_message_and_dismiss(messages.SUCCESS))
        self.assertFalse(
            networks_page.find_message_and_dismiss(messages.ERROR))
        self.assertTrue(overview.is_subnet_present(self.SUBNET_NAME))
        self.assertFalse(overview.is_subnet_present(self.SUBNET_NAME_2))
        networks_page = overview.delete_network()
        self.assertFalse(networks_page.is_network_present(self.NETWORK_NAME))

    def test_create_distributed_router(self):
        router_name = helpers.gen_random_resource_name("router")
        routers_page = self.home_pg.go_to_network_routerspage()
        routers_page.create_router(router_name,
                                   admin_state_up=None,
                                   external_network=None)
        self.assertTrue(
            routers_page.find_message_and_dismiss(messages.SUCCESS))
        self.assertFalse(routers_page.find_message_and_dismiss(messages.ERROR))
        self.assertTrue(routers_page.is_router_present(router_name))
        self.assertTrue(routers_page.is_router_active(router_name))

        self.home_pg.log_out()
        self.home_pg = self.login_pg.login(self.ADMIN_NAME,
                                           self.ADMIN_PASSWORD)
        self.home_pg.change_project(self.ADMIN_PROJECT)

        routers_page = self.home_pg.go_to_system_routerspage()

        def delete_router():
            routers_page.delete_router(router_name)
            self.assertTrue(
                routers_page.find_message_and_dismiss(messages.SUCCESS))
            self.assertFalse(
                routers_page.find_message_and_dismiss(messages.ERROR))
            self.assertFalse(routers_page.is_router_present(router_name))

        try:
            router_info = routers_page.get_router_info(router_name)
        except KeyError as e:
            if e.args[0] == 'mode':
                routers_page.refresh_page()
                delete_router()
                self.skipTest("Distributed mode is not supported")
            else:
                raise

        self.assertEqual(router_info['mode'], 'distributed')
        delete_router()

class TestAdminNetworks(helpers.AdminTestCase):
    NETWORK_NAME = helpers.gen_random_resource_name("network")

    def test_network_create_delete_from_admin(self):
        """tests the network creation and deletion functionality:
        * creates a new network through Admin panel
        * verifies the network appears in the networks table
        * deletes the newly created network
        * verifies the network does not appear in the table after deletion
        """
        networks_page = self.home_pg.go_to_system_networkspage()
        networks_page.create_network(name=self.NETWORK_NAME,
                                     project=self.HOME_PROJECT)
        self.assertTrue(
            networks_page.find_message_and_dismiss(messages.SUCCESS))
        self.assertFalse(
            networks_page.find_message_and_dismiss(messages.ERROR))
        self.assertTrue(networks_page.is_network_present(self.NETWORK_NAME))
        self.assertTrue(networks_page.is_network_active(self.NETWORK_NAME))

        networks_page.delete_network(self.NETWORK_NAME)
        self.assertTrue(
            networks_page.find_message_and_dismiss(messages.SUCCESS))
        self.assertFalse(
            networks_page.find_message_and_dismiss(messages.ERROR))
        self.assertFalse(networks_page.is_network_present(self.NETWORK_NAME))


import os
import csv

# get the current directory
dir_path = os.getcwd()

# Check if the script has been run before
if os.path.exists(os.path.join(dir_path, 'script_has_run.txt')):
    print("The script has already been run.")
    exit(0)

# list all files in the directory
files = [f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))]

# filter out only the png files and sort them to ensure order
png_files = sorted([file for file in files if file.endswith('.png')])

# specify the txt files for each column
title_file = 'title.txt'
description_file = 'description.txt'
tags_file = 'tags.txt'
price_file = 'price.txt'

# read data from the txt files
with open(title_file, 'r') as file:
    titles = [line.strip() for line in file]
with open(description_file, 'r') as file:
    descriptions = [line.strip() for line in file]
with open(tags_file, 'r') as file:
    tags = [line.strip() for line in file]
with open(price_file, 'r') as file:
    prices = [line.strip() for line in file]

# check that all lists have the same length
if not len(png_files) == len(titles) == len(descriptions) == len(tags) == len(prices):
    print("Error: Not all files have the same number of lines.")
    exit(1)

# specify the csv file you want to write to
csv_file_path = os.path.join(dir_path, 'file_list.csv')

# write the png file names and other information into the csv file
with open(csv_file_path, 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(["Title", "Description", "Tags", "Price", "Image Path"])
    for i, png_file in enumerate(png_files):
        writer.writerow([titles[i], descriptions[i], tags[i], prices[i], png_file])

# Write the flag file
with open(os.path.join(dir_path, 'script_has_run.txt'), 'w') as file:
    file.write('This script has been run.')

print("Script has run successfully and the file 'script_has_run.txt' has been created to prevent it from running again.")


import torch
import numpy as np
from book.pytorch.utils.helper import get_mnist_loader
import torch.nn.functional as F
from torch import nn
import matplotlib.pyplot as plt

class ConvDenoiser(nn.Module):
    def __init__(self, encoding_dim):
        super(ConvDenoiser, self).__init__()
        # encoder layers
        # conv layer (depth from 1 --> 32), 3x3 kernels
        self.conv1 = nn.Conv2d(1, 32, 3, padding=1)
        # conv layer (depth from 32 --> 16), 3x3 kernels
        self.conv2 = nn.Conv2d(32, 16, 3, padding=1)
        # conv layer (depth from 16 --> 8), 3x3 kernels
        self.conv3 = nn.Conv2d(16, 8, 3, padding=1)
        # pooling layer to reduce x-y dims by two; kernel and stride of 2
        self.pool = nn.MaxPool2d(2, 2)

        # decoder layers
        # transpose layer, a kernel of 2 and a stride of 2 will increase the spatial dims by 2
        self.t_conv1 = nn.ConvTranspose2d(8, 8, 3, stride=2)  # kernel_size=3 to get to a 7x7 image output
        # two more transpose layers with a kernel of 2
        self.t_conv2 = nn.ConvTranspose2d(8, 16, 2, stride=2)
        self.t_conv3 = nn.ConvTranspose2d(16, 32, 2, stride=2)
        # one, final, normal conv layer to decrease the depth
        self.conv_out = nn.Conv2d(32, 1, 3, padding=1)

    def forward(self, x):
        # encode
        # add hidden layers with relu activation function and maxpooling after
        x = F.relu(self.conv1(x))
        x = self.pool(x)
        # add second hidden layer
        x = F.relu(self.conv2(x))
        x = self.pool(x)
        # add third hidden layer
        x = F.relu(self.conv3(x))
        x = self.pool(x)

        # decode
        # add transpose conv layers, with relu activation function
        x = F.relu(self.t_conv1(x))
        x = F.relu(self.t_conv2(x))
        x = F.relu(self.t_conv3(x))
        # transpose again, output should have a sigmoid applied
        x = torch.sigmoid(self.conv_out(x))
        return x

if __name__ == '__main__':
    """
    used to denoise images quite successfully just by training the network on noisy images
    """
    batch_size = 20
    train_loader, test_loader, valid_loader = get_mnist_loader(batch_size=batch_size, is_norm=False)

    model = ConvDenoiser(encoding_dim=32)
    print(model)

    """comparing pixel values in input and output images, it's best to use a loss that meant for a regression task"""
    criterion = nn.MSELoss()
    optimizer = torch.optim.Adam(model.parameters(), lr=0.001)

    noise_factor = 0.5  # for adding noise to images

    n_epochs = 20
    for epoch in range(1, n_epochs + 1):
        train_loss = 0.0
        for data in train_loader:
            images, _ = data

            # add random noise to the input images
            noisy_imgs = images + noise_factor * torch.randn(*images.shape)
            # clip the images to be between 0 and 1
            noisy_imgs = np.clip(noisy_imgs, 0., 1.)

            optimizer.zero_grad()
            outputs = model(noisy_imgs)
            # the "target" is still the original, not-noisy images
            loss = criterion(outputs, images)
            loss.backward()
            optimizer.step()
            train_loss += loss.item() * images.size(0)

        # print avg training statistics
        train_loss = train_loss / len(train_loader)
        print('Epoch: {} \tTraining Loss: {:.6f}'.format(epoch, train_loss))

    # check test
    dataiter = iter(test_loader)
    images, labels = dataiter.next()

    # add noise to the test images
    noisy_imgs = images + noise_factor * torch.randn(*images.shape)
    noisy_imgs = np.clip(noisy_imgs, 0., 1.)

    output = model(noisy_imgs)
    noisy_imgs = noisy_imgs.numpy()  # prep images for display

    # output is resized into a batch of images
    output = output.view(batch_size, 1, 28, 28)
    # use detach when it's an output that requires_grad
    output = output.detach().numpy()

    # plot the first ten input images and then reconstructed images
    fig, axes = plt.subplots(nrows=2, ncols=10, sharex=True, sharey=True, figsize=(25, 4))

    # input images on top row, reconstructions on bottom
    for noisy_imgs, row in zip([noisy_imgs, output], axes):
        for img, ax in zip(noisy_imgs, row):
            ax.imshow(np.squeeze(img), cmap='gray')
            ax.get_xaxis().set_visible(False)
            ax.get_yaxis().set_visible(False)
    plt.show()


import unittest

import mock

import openstack.common.context

from openstack.common.middleware import context

class ContextMiddlewareTest(unittest.TestCase):

    def test_process_request(self):
        req = mock.Mock()
        app = mock.Mock()
        options = mock.MagicMock()
        ctx = mock.sentinel.context
        with mock.patch.object(context.ContextMiddleware,
                               'make_context',
                               mock.Mock(return_value=ctx)):
            ctx_middleware = context.ContextMiddleware(app, options)
            ctx_middleware.process_request(req)

        self.assertEqual(req.context, ctx)

    def test_make_context(self):
        app = mock.Mock()
        options = mock.MagicMock()
        with mock.patch.object(openstack.common.context.RequestContext,
                               '__init__',
                               mock.Mock(return_value=None)) as init:
            ctx_middleware = context.ContextMiddleware(app, options)
            ctx_middleware.make_context(mock.sentinel.arg)
            init.assert_called_with(mock.sentinel.arg)

    def test_make_explicit_context(self):
        app = mock.Mock()
        import_class = mock.Mock()
        options = {'context_class': mock.sentinel.context_class}
        with mock.patch('openstack.common.utils.import_class',
                        mock.Mock(return_value=import_class)):
            ctx_middleware = context.ContextMiddleware(app, options)
            ctx_middleware.make_context(mock.sentinel.arg)
            import_class.assert_called_with(mock.sentinel.arg)

class FilterFactoryTest(unittest.TestCase):

    def test_filter_factory(self):
        global_conf = dict(sentinel=mock.sentinel.global_conf)
        app = mock.sentinel.app
        target = 'openstack.common.middleware.context.ContextMiddleware'

        def check_ctx_middleware(arg_app, arg_conf):
            self.assertEqual(app, arg_app)
            self.assertEqual(global_conf['sentinel'], arg_conf['sentinel'])
            return mock.DEFAULT

        with mock.patch(target,
                        mock.Mock(return_value=mock.sentinel.ctx)) as mid:
            mid.side_effect = check_ctx_middleware
            filter = context.filter_factory(global_conf)
            self.assertEqual(filter(app), mock.sentinel.ctx)


import json

def help():
    helpprint = print("""
    addcoins: plus Your coins.
    minuscoins: minus Your coins.
    help: shows this list.
    coins: Shows how many coins do you have
    """)
    main()

def checkbalance():
    with open('coins.json','r') as f:
        get_balance = json.loads(f.read())
        print(f"You Have {get_balance['coins']} coins")
        main()

def addcoins():
    addcoins = get_balance()
    coinamt = int(input("Enter a amount to add coins: "))
    addcoins['coins'] += coinamt

    with open('coins.json', 'w') as f:
        json.dump(addcoins, f)
    print("Add sucessfull")
    main()

def minuscoins():
    minuscoins = get_balance()
    coinamt = int(input("Enter a amount to minus coins: "))
    minuscoins['coins'] -= coinamt

    with open('coins.json', 'w') as f:
        json.dump(minuscoins, f)
    print("Minus sucessfull")
    main()

def get_balance():
    with open('coins.json','r') as f:
        users = json.load(f)

        return users

def main():
    mainFunction = input("Input a Command(Type help for help): ")

    if mainFunction == "help":
        help()
    elif mainFunction == "coins":
        checkbalance()
    elif mainFunction == "addcoins":
        addcoins()
    elif mainFunction == "minuscoins":
        minuscoins()
    else:
        print("Command Not Found")
        main()

main()


import pandas as pd
import numpy as np
import tensorflow as tf
import time
import os
import csv
from sklearn.preprocessing import MinMaxScaler
from keras.layers import Input
from keras.layers import Dense, LSTM, Dropout, Embedding, Input, Activation, Bidirectional, TimeDistributed, RepeatVector, Flatten
from keras.optimizers import Adam
from sklearn.metrics import mean_squared_error
from math import sqrt
from keras.models import Sequential, Model

learning_rate=0.001
look_back=20
batch_size=5
hidden_nodes = 256
epochs =  100

adam = Adam(lr=learning_rate)

def create_dataset_input(dataset, look_back):
	dataX = []
	for i in range(len(dataset)-look_back):
		dataX.append(dataset[i:(i+look_back)])
	return np.array(dataX)

def mode_decide(input_mode):
    train_mode=input_mode.split('-',1)[0]
    val_mode=input_mode.split('-',1)[1]
    error1=(train_mode!='a')and(train_mode!='b')and(train_mode!='ab')
    error2=(train_mode!='a')and(train_mode!='b')and(train_mode!='ab')
    if error1 or error2:
        raise ValueError # Wrong input mode type
    mode={'train_set':train_mode,'val_set':val_mode}
    return mode

def load_data(mode):
    filename=[mode['train_set']+'_train_set'+'.csv']
    filename="".join(filename)
    train_data=pd.read_csv(filename)

    filename=[mode['val_set']+'_val_set'+'.csv']
    filename="".join(filename)
    val_data=pd.read_csv(filename)
    return train_data,val_data

def data_prepocess(train_data,val_data,batch_size=batch_size,look_back=look_back):
	#train_set 设置
	train_raw_x=train_data['Loc_x']
	train_raw_x=np.array(train_raw_x).astype(float).reshape(-1,1)
	scaler_loc_x=MinMaxScaler()
	train_loc_x=scaler_loc_x.fit_transform(train_raw_x)

	train_raw_y=train_data['Loc_y']
	train_raw_y=np.array(train_raw_y).astype(float).reshape(-1,1)
	scaler_loc_y=MinMaxScaler()
	train_loc_y=scaler_loc_y.fit_transform(train_raw_y)

	train_Mag_x=train_data['GeoX']
	train_Mag_x=np.array(train_Mag_x).astype(float).reshape(-1,1)
	scaler_mag_x=MinMaxScaler()
	Mag_x=scaler_mag_x.fit_transform(train_Mag_x)

	train_Mag_y=train_data['GeoY']
	train_Mag_y=np.array(train_Mag_y).astype(float).reshape(-1,1)
	scaler_mag_y=MinMaxScaler()
	Mag_y=scaler_mag_y.fit_transform(train_Mag_y)

	train_Mag_z=train_data['GeoZ']
	train_Mag_z=np.array(train_Mag_z).astype(float).reshape(-1,1)
	scaler_mag_z=MinMaxScaler()
	Mag_z=scaler_mag_z.fit_transform(train_Mag_z)

	train_size=int(len(train_loc_x))
	#val_set 设置

	val_raw_x=val_data['Loc_x']
	val_raw_x=np.array(val_raw_x).astype(float).reshape(-1,1)
	v_scaler_loc_x=MinMaxScaler()
	val_loc_x=v_scaler_loc_x.fit_transform(val_raw_x)

	val_raw_y=val_data['Loc_y']
	val_raw_y=np.array(val_raw_y).astype(float).reshape(-1,1)
	v_scaler_loc_y=MinMaxScaler()
	val_loc_y=v_scaler_loc_y.fit_transform(val_raw_y)

	val_Mag_x=val_data['GeoX']
	val_Mag_x=np.array(val_Mag_x).astype(float).reshape(-1,1)
	v_scaler_mag_x=MinMaxScaler()
	val_Mag_x=v_scaler_mag_x.fit_transform(val_Mag_x)

	val_Mag_y=val_data['GeoY']
	val_Mag_y=np.array(val_Mag_y).astype(float).reshape(-1,1)
	v_scaler_mag_y=MinMaxScaler()
	val_Mag_y=v_scaler_mag_y.fit_transform(val_Mag_y)

	val_Mag_z=val_data['GeoZ']
	val_Mag_z=np.array(val_Mag_z).astype(float).reshape(-1,1)
	v_scaler_mag_z=MinMaxScaler()
	val_Mag_z=v_scaler_mag_z.fit_transform(val_Mag_z)

	val_size=int(len(val_loc_x))

	train_mag_x = create_dataset_input(train_Mag_x, look_back = look_back)
	train_mag_y = create_dataset_input(train_Mag_y, look_back = look_back)
	train_mag_z = create_dataset_input(train_Mag_z, look_back = look_back)

	test_mag_x = create_dataset_input(val_Mag_x, look_back = look_back)
	test_mag_y = create_dataset_input(val_Mag_y, look_back = look_back)
	test_mag_z = create_dataset_input(val_Mag_z, look_back = look_back)

	#print('trian_mag_x:',train_mag_x)

	train_loc_x = create_dataset_input(train_loc_x, look_back = look_back)
	train_loc_y = create_dataset_input(train_loc_y, look_back = look_back)
	test_loc_x = create_dataset_input(val_loc_x, look_back = look_back)
	test_loc_y = create_dataset_input(val_loc_y, look_back = look_back)

	trainX = np.concatenate((train_mag_x,train_mag_y,train_mag_z),axis = 2)
	testX = np.concatenate((test_mag_x,test_mag_y,test_mag_z),axis = 2)
	#print('train_loc_x.shape:',train_loc_x.shape)
	trainY = np.concatenate((train_loc_x,train_loc_y),axis = 2)
	testY = np.concatenate((test_loc_x,test_loc_y),axis = 2)
	trainY = np.reshape(trainY, (len(trainY),look_back,2))
	#print('trianY:',trainY.shape)
	lengthTrain = len(trainX)
	lengthTest = len(testX)
	while(lengthTrain % batch_size != 0):
		lengthTrain -= 1
	while(lengthTest % batch_size != 0):
		lengthTest -= 1

	return trainX[0:lengthTrain],trainY[0:lengthTrain],testX[0:lengthTest],testY[0:lengthTest]

def model_train(train_x, train_y, test_x, test_y,file_structure,file_acc2loss):
	model=model_build()
	for i in range(epochs):
		history = model.fit(train_x, train_y, batch_size=batch_size, epochs = 1, verbose=1,shuffle = False) #validation_split=0.1, validation_data=(test_x, test_y)
	#	# need to reset state for every epoch
		model.reset_states()
	#	#print('hidden_state:',hidden_state)
	#	# list all data in history
	#	'''
	#	print('history.keys()',hist.history.keys())
	#	# summarize history for accuracy
	#	plt.plot(hist.history['acc'])
	#	plt.plot(hist.history['val_acc'])
	#	plt.title('model accuracy')
	#	plt.ylabel('accuracy')
	#	plt.xlabel('epoch')
	#	plt.legend(['train', 'test'], loc='upper left')
	#	plt.show()
	#	'''
		print('Real Epoches:',i+1)
		with open(file_acc2loss,'a', newline='') as csvfile:
			if not os.path.getsize(file_acc2loss):        #file is empty
				spamwriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE)
				spamwriter.writerow(['epochs','loss','acc'])#, 'val_loss','val_acc'

			data = ([
				i,history.history['loss'][0],history.history['acc'][0]#, history.history['val_loss'][0], history.history['val_acc'][0]
				])
			spamwriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE)
			spamwriter.writerow(data)
	return model

def model_build(hidden_nodes=hidden_nodes,batch_size=batch_size , time_steps = look_back, feature_size = 3):
	inputs1 = Input(batch_shape = (batch_size,look_back,feature_size))
	lstm1 = LSTM(hidden_nodes, stateful = True, return_sequences=True, return_state=True,dropout=0.2)(inputs1)
	lstm1 = LSTM(hidden_nodes,return_sequences=True,dropout=0.2)(lstm1)
	lstm1 = TimeDistributed(Dense((2)))(lstm1)
	model = Model(input = inputs1, outputs = lstm1)
	print(model.layers)
	model.compile(loss='mean_squared_error', optimizer=adam,metrics=['acc'])
	model.summary()
	return model

if __name__=='__main__':
	input_mode=[]
	change=False
	if change:
		input_mode=input('Please inport train and val mode in _-_(e.g:a-b)\n')
		if input_mode=='all' :
			input_mode=['a-a','a-b','a-ab','b-a','b-b','b-ab','ab-a','ab-b','ab-ab']
	else:
		input_mode=['a-b']

	for t_v in input_mode:
		mode=mode_decide(t_v)
		file_structure = [mode['train_set']+'-'+mode['val_set']+'_'+'model_ts=30_256_5_100.png']
		file_acc2loss = [mode['train_set']+'-'+mode['val_set']+'_'+'log_ts=30_256_5_100.csv']
		file_structure="".join(file_structure)
		file_acc2loss = "".join(file_acc2loss)
		train_data,val_data=load_data(mode)
		train_x, train_y, test_x, test_y=data_prepocess(train_data,val_data)
		model=model_train(train_x, train_y, test_x, test_y,file_structure,file_acc2loss)
		del model


# 이것이 코딩테스트다
# p.180

n = int(input())
nameScoreList = []

for i in range(0, n):
    nameScore = input().split()
    nameScoreList.append((nameScore[0], int(nameScore[1])))

nameScoreList = sorted(nameScoreList, key = lambda x: x[1])

for name in nameScoreList:
    print(name[0], end = ' ')


#verificar se tem caracteres duplicados em string

def tem_duplicado(palavra):
  vistos=[]
  for c in palavra:
    if c in vistos:
      return True
    vistos.append(c)
  return False

if tem_duplicado('abacaxi'):
  print('tem duplicados')
else:
    print("nao tem duplicados")


from selenium import webdriver
from webdriver_manager.firefox import GeckoDriverManager # The Webdriver
import pyautogui        # To Click
import time             # To wait and all
custom_site = input("Enter The Website to Download Video...") # Take the youtube video link as the input
driver = webdriver.Firefox(executable_path=GeckoDriverManager().install()) # installs the webdriver.

cus = custom_site.find('y')    # Finds 'Y' in the Link.
suc = custom_site[0:cus]    # Slices upto but not includes y
final_website = suc + 'ss' + custom_site[cus:]   # WIth the help of string concatenation it adds ss to the
                                                    # link before the letter 'y'

web = driver.get(final_website)     # Uses the Selenium Web  driver to go to the website.
driver.implicitly_wait(5)   # Waits For 5 Secs
driver.find_element_by_xpath(r'/html/body/div[1]/div[1]/div[2]/div[4]/div/div[1]/div[2]/div[2]/div[1]/a').click()
# Finds the download button by x path

# Often after clicking the download button the new tab gets open automatically.
# If a new tab gets open it closes that tab.
# You Can Run the below program in your terminal to get the live position of your mouse
# import pyautogui
# pyautogui.displayMousePosition()

def new_tab_cut():
    x = 504  # You can change the x cordinate to your mouse position.
    y = 48  # # You can change the y cordinate to your mouse position.
    pyautogui.moveTo(x, y, duration=1.2)
    pyautogui.click(x, y)

# The Following block of code is used to click on the download button in firefix browser.

def save_file():
    x1 = 504
    y1 = 471
    pyautogui.moveTo(x1, y1, duration=1)
    pyautogui.click(x1, y1)
    time.sleep(1)
    x2 = 916
    y2 = 575
    pyautogui.click(x2, y2)
    time.sleep(1)

new_tab_cut()
save_file()
time.sleep(100)
driver.quit()
print("Downloaded")

# executable_path=GeckoDriverManager().install()


from __future__ import print_function
import sys
import mdtraj as md
from simtk.openmm import app
import simtk.openmm as mm
from simtk import unit
import argparse

class Tee(object):
    def __init__(self, name, mode):
        self.file = open(name, mode)
        self.stdout = sys.stdout
    def write(self, data):
        self.file.write(data)
        self.stdout.write(data)

if __name__ == '__main__':

    if len(sys.argv) != 3:
        print('usage %s <trajectory index (for output file)> <model index of starting conformation>')
        exit(1)

    pdb = md.load('100-fs-peptide-400K.pdb')
    forcefield = app.ForceField('amber99sbildn.xml', 'amber99_obc.xml')

    system = forcefield.createSystem(pdb.topology.to_openmm(), nonbondedMethod=app.CutoffNonPeriodic,
        nonbondedCutoff=1.0*unit.nanometers, constraints=app.HBonds)
    integrator = mm.LangevinIntegrator(300*unit.kelvin, 91.0/unit.picoseconds,
        2.0*unit.femtoseconds)
    integrator.setConstraintTolerance(0.00001)

    platform = mm.Platform.getPlatformByName('CPU')
    #properties = {'CudaPrecision': 'mixed', 'CudaDeviceIndex': sys.argv[1]}
    simulation = app.Simulation(pdb.topology.to_openmm(), system, integrator, platform)
    simulation.context.setPositions(pdb.xyz[int(sys.argv[2])])

    simulation.context.setVelocitiesToTemperature(300*unit.kelvin)

    nsteps = int((1*unit.nanoseconds) / (2*unit.femtoseconds))
    interval = int((10*unit.picoseconds) / (2*unit.femtoseconds))

    simulation.reporters.append(app.StateDataReporter(open('trajectory-%s.log' % sys.argv[1], 'w', 0),
        interval, step=True, time=True, progress=True,
        potentialEnergy=True, temperature=True, remainingTime=True,
        speed=True, totalSteps=nsteps, separator='\t'))

    # equilibrate
    simulation.step(int(100*unit.picoseconds / (2*unit.femtoseconds)))

    # now add the trajectory reporter.
    simulation.reporters.append(app.DCDReporter('trajectory-%s.dcd' % sys.argv[1], interval))
    simulation.step(nsteps)


import copy
import torch
import torch.nn as nn
from .backbone import *
import numpy as np
import torch.nn.functional as F
import thop

def ConvBNReLU(in_chann, out_chann, ks, st, p=1):
    return nn.Sequential(
        nn.Conv2d(in_chann, out_chann, kernel_size=ks, stride=st, padding=p, bias=False),
        nn.BatchNorm2d(out_chann),
        nn.ReLU(inplace=True)
    )

class Aggregation(nn.Module):
    def __init__(self, in_chann, out_chann, asy_ks=5):
        super(Aggregation, self).__init__()
        self.conv = ConvBNReLU(in_chann, out_chann, 3, 1, 1)
        self.left_asymmetric = nn.Sequential(
            nn.Conv2d(out_chann, out_chann, kernel_size=(1, asy_ks), stride=1, \
                        padding=(0, asy_ks//2), groups=out_chann, bias=True),
            nn.Conv2d(out_chann, out_chann, kernel_size=(asy_ks, 1), stride=1, \
                        padding=(asy_ks//2, 0), groups=out_chann, bias=True),
        )
        self.right_asymmetric = nn.Sequential(
            nn.Conv2d(out_chann, out_chann, kernel_size=(asy_ks, 1), stride=1, \
                        padding=(asy_ks//2, 0), groups=out_chann, bias=True),
            nn.Conv2d(out_chann, out_chann, kernel_size=(1, asy_ks), stride=1, \
                        padding=(0, asy_ks//2), groups=out_chann, bias=True),
        )

        self.bn_relu = nn.Sequential(
            nn.BatchNorm2d(out_chann),
            nn.ReLU(inplace=True)
        )

    def forward(self, x):
        x = self.conv(x)
        left = self.left_asymmetric(x)
        right = self.right_asymmetric(x)
        out = left + right
        out = self.bn_relu(out)
        return out

class DeepLabHead(nn.Module):
    def __init__(self, num_classes, last_channels, mid_channels, low_channels):
        super(DeepLabHead, self).__init__()
        self.low_process = ConvBNReLU(low_channels, 48, 1, 1, 0)
        self.mid_process = ConvBNReLU(mid_channels, 48, 1, 1, 0)

        self.mid_project = ConvBNReLU(304, 256, 3, 1, 1)
        self.classifier = nn.Sequential(
            ConvBNReLU(304, 256, 3, 1, 1),
            nn.Dropout(0.1),
            nn.Conv2d(256, num_classes,
                      kernel_size=1,
                      stride=1,
                      padding=0,
                      bias=True)
        )

    def forward(self, last_feat, mid_feat, low_feat):
        low_feat = self.low_process(low_feat)
        mid_feat = self.mid_process(mid_feat)

        last_feat = F.interpolate(last_feat, size=mid_feat.size()[2:], mode="bilinear", align_corners=True)

        mid_feat = torch.cat([last_feat, mid_feat], dim=1)
        mid_feat = self.mid_project(mid_feat)
        mid_feat = F.interpolate(mid_feat, size=low_feat.size()[2:], mode="bilinear", align_corners=True)

        out_feat = torch.cat([mid_feat, low_feat], dim=1)
        out = self.classifier(out_feat)
        return out

class CPNet(nn.Module):
    def __init__(self, num_classes, input_channels=512,
                 prior_channels=512, prior_size=(40, 40), backend="resnet34", pretrained=True):
        super(CPNet, self).__init__()
        self.prior_size = np.prod(prior_size)
        self.num_classes = num_classes
        self.prior_channels = prior_channels

        self.backbone = eval(backend)(pretrained=pretrained) # backbone
        self.aggregation = Aggregation(input_channels, prior_channels, 11) # 特征聚合，丰富特征的上下文信息

        self.prior_conv = nn.Sequential(
            nn.Conv2d(prior_channels, self.prior_size, kernel_size=1, stride=1, bias=True),
            # nn.BatchNorm2d(self.prior_size)
        )

        self.intra_conv = ConvBNReLU(prior_channels, prior_channels, 1, 1, 0)
        self.inter_conv = ConvBNReLU(prior_channels, prior_channels, 1, 1, 0)

        self.post_process = nn.Sequential(
            ConvBNReLU(input_channels + prior_channels*2, 256, 1, 1, 0),
            ConvBNReLU(256, 256, 3, 1, 1) # prior_channels
        )

        # without deeplab
        self.head = nn.Sequential(
            ConvBNReLU(256, 256, 3, 1, 1), # prior_channels
            nn.Dropout(0.1),
            nn.Conv2d(256, num_classes, 1, 1, bias=True)
        )

        # with deeplab
        '''self.deeplab_head = DeepLabHead(num_classes, 256, 128, 64)'''

    def _reinit(self, input_size):
        input_size = input_size/16
        self.prior_size = int(np.prod(input_size))
        self.prior_conv = nn.Sequential(
            nn.Conv2d(self.prior_channels, self.prior_size, kernel_size=1, stride=1, bias=True),
        )

    def forward(self, x):
        feat, feat_2, feat_1 = self.backbone(x)
        h, w = feat.size()[2:]

        value = self.aggregation(feat)
        context_proir_map = self.prior_conv(value)

        context_proir_map = context_proir_map.view(context_proir_map.size()[0], \
                                                    -1, self.prior_size).permute(0, 2, 1)
        intra_context_proir_map = torch.sigmoid(context_proir_map) # [bs, 40*40, 40*40], 类内
        inter_context_prior_map = 1 - context_proir_map # 类间

        value = value.view(value.size()[0], value.size()[1], -1).permute(0, 2, 1).contiguous() # [bs, 512, 40*40]==>[bs, 40*40, 512]
        intra_context_proir_map = F.softmax(intra_context_proir_map, dim=-1)
        intra_context = torch.matmul(intra_context_proir_map, value) # [bs, 40*40, 512] # 利用类内全局特征更新每一个特征
        # intra_context = intra_context.div(self.prior_size)
        intra_context = intra_context.permute(0, 2, 1).contiguous()
        intra_context = intra_context.view(intra_context.size(0), self.prior_channels, h, w)
        intra_context = self.intra_conv(intra_context)

        inter_context_prior_map = F.softmax(inter_context_prior_map, dim=-1)
        inter_context = torch.matmul(inter_context_prior_map, value)
        # inter_context = inter_context.div(self.prior_size)
        inter_context = inter_context.permute(0, 2, 1).contiguous()
        inter_context = inter_context.view(inter_context.size(0), self.prior_channels, h, w)
        inter_context = self.inter_conv(inter_context)

        out = torch.cat([feat, intra_context, inter_context], dim=1)
        out = self.post_process(out)

        # without deeplab
        seg_out = self.head(out)
        seg_out = F.interpolate(seg_out, size=(x.size()[2], x.size()[3]), mode="bilinear", align_corners=True)

        # with deeplab
        '''seg_out = self.deeplab_head(out, feat_2, feat_1)
        seg_out = F.interpolate(seg_out, size=x.size()[2:], mode="bilinear", align_corners=True)'''

        if self.training:
            return seg_out, intra_context_proir_map
        return seg_out

from utils.utils import get_model_infos
@get_model_infos
def cpnet(num_classes, backend="resnet34", pretrained=False):
    model = CPNet(num_classes, backend=backend, pretrained=pretrained)
    return model

if __name__ == "__main__":
    model = CPNet(20)
    inputs = torch.randn(1, 3, 640, 640)
    seg_out, context_map = model(inputs)
    print("segout: ", seg_out.size(), ' context_map siz: ', context_map.size())

    # labels = torch.randint(0, 20, (1, 640, 640)).long()
    # model._get_loss(context_map, labels, [80, 80])

    '''model = cpnet_resnet34(4, pretrained=False)
    feat = torch.randn(1, 3, 640, 640)
    out, context_proir_map = model(feat)
    print(out.size(), " context_proir_map size: ", context_proir_map.size())'''


""" A python program that scrapes news articles, classifies their sentiment, and creates a time series of sentiment over time """
import os
import openai

# Set OpenAI API key from environment
openai.api_key = os.environ.get('OPENAI_API_KEY', '')

def classify(query, search_model="ada", model="davinci"):
    openai.Classification.create(
        search_model=search_model,
        model=model,
        examples=[
            [""],
            [""],
            [""],
            [""],
        ],
        query=query,
        labels=[
            "Very Positive",
            "Mostly Positive",
            "Neutral",
            "Mostly Negative"
            "Very Negative",
        ]
    )

if __name__ == "__main__":
    print(openai.Model.list())


class Board:
    def __init__(self, init_data):
        self.data = [[-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1]]
        for i in range(0,5):
            for j in range(0,5):
                self.data[i][j] = int(init_data[i][(j*3):(j*3)+2].lstrip())

    def __str__(self):
        s = ""
        for i in range(0,len(self.data)):
            for j in range(0,len(self.data[i])):
                s += str(self.data[i][j]).rjust(3)
            s += "\n"
        return s

    def play(self, num):
        # If we have the selected number, mark it as played
        check = False
        won = False
        for i in range(0,len(self.data)):
            for j in range(0,len(self.data[i])):
                if self.data[i][j] == num:
                    self.data[i][j] = -1
                    check = True # Don't exit loop incase the number appears more than once
        if check: # Have we won?
            # Check rows
            for i in range(0,len(self.data)):
                row = 0
                for j in range(0,len(self.data[i])):
                    row += self.data[i][j]
                if row == -5:
                    return True
            # Check columns
            for i in range(0,5):
                col = 0
                for j in range(0,5):
                    col += self.data[j][i]
                if col == -5:
                    return True
        return won

    def score(self):
        s = 0
        for i in range(0,len(self.data)):
            for j in range(0,len(self.data[i])):
                if self.data[i][j] >= 0:
                    s += self.data[i][j]
        return s

    def dump(self):
        print(self.data)

if __name__=="__main__":
    with open("04.txt", "r") as f:
        data = f.read().splitlines()

    drawn = data[0]
    drawn = [int(n) for n in drawn.split(",")]

    boards = []
    for i in range(2, len(data),6):
        boards.append(Board(data[i:i+5]))

    print("Boards loaded...")
    for i in range(len(boards)):
        boards[i].dump()
        # print(boards[i])

    n = 0
    winner = -1
    while winner == -1:
        num = drawn[n]
        print("Playing",num)
        for i in range(0, len(boards)):
            won = boards[i].play(num)
            if won:
                winner = i
        n += 1
    print("Winning board")
    boards[winner].dump()
    s = boards[winner].score()
    print(s, num) # 929 80
    print(s*num) # 74320

    print("Part 2...")
    n = 0
    lastwon = False
    while not lastwon:
        num = drawn[n]
        print("Playing",num)
        i = 0
        while i < len(boards):
            won = boards[i].play(num)
            if won:
                if len(boards) == 1:
                    lastwon = True
                else:
                    boards.pop(i)
            else:
                i += 1
        n += 1
    print("Losing board")
    boards[0].dump()
    s = boards[0].score()
    print(s, num)
    print(s*num)


# -*- coding: utf-8 -*-

"""Console script for mcc."""
import os
import click
from pydub import AudioSegment
from pydub.silence import split_on_silence

@click.command()
@click.argument('sound_path')
@click.option('--mls', default=500, help='沉默的时长，毫秒')
@click.option('--st', default=-30, help='无声的界限，如果比这个数值更小则认为是无声')
@click.option('--name', default=0, help='分割出来文件的名字，默认从0开始')
def main(sound_path, mls, st, name):
    """切割一段带有停顿的空白语音"""

    sound = AudioSegment.from_wav(sound_path)
    chunks = split_on_silence(sound,
                              # 沉默的时长, 毫秒
                              min_silence_len=mls,
                              # 如果比silence_thresh这个数值更安静则认为是无声
                              silence_thresh=st
                              )
    print(f'碎片数量: {len(chunks)}')

    # 创建文件夹
    dirname = f'{name}-{name + len(chunks) - 1}'
    if not os.path.exists(dirname):
        os.makedirs(dirname)

    for i, chunk in enumerate(chunks):
        # 导出文件
        chunk.export(f'{dirname}/{name + i}.wav', format='wav')


# =============================================================================
# Smallest multiple
# Problem 5
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
#
# =============================================================================
from math import factorial

def checkDiv(number):
    for i in range(20, 10, -1):
        if (number % i != 0):
            return False
    return True

maximum = factorial(20)
counter = 232792540

while counter <= maximum:
    if checkDiv(counter):
        print ("Your number is: ", counter)
        break
    else:
        counter += 1


# importing module
import re

# taking input from user
n = int(input())

# iterating through the credit cards
for t in range(n):

    #taking the credit card number from user
    credit = input().strip()
    credit_removed_hiphen = credit.replace('-','')

    # valid is true in the beggining
    valid = True

    # using regual expressions
    length_16 = bool(re.match(r'^[4-6]\d{15}$',credit))
    length_19 = bool(re.match(r'^[4-6]\d{3}-\d{4}-\d{4}-\d{4}$',credit))
    consecutive = bool(re.findall(r'(?=(\d)\1\1\1)',credit_removed_hiphen))

    # checking if the above regural expressions are true
    if length_16 == True or length_19 == True:
        if consecutive == True:
            valid=False
    else:
        valid = False
    if valid == True:
        print('Valid')
    else:
        print('Invalid')


#!/usr/bin/env python3
animals = ['cat', 'dog']
while (len(animals)) != 0:
    print(animals[(len(animals)) - 1])
    animals.pop()
else:
    print('End of the stock')

for animal in animals:
    print(animal)
else:
    print('Results end here')


import torch
import torch.nn as nn
from torch.nn import functional as F
import math
from typing import Tuple

device = "cuda" if torch.cuda.is_available() else "cpu"

class Embedding(nn.Module):

    def __init__(self,
                 config,
                 vocab_size):
        """
            Embedding generates learnable representation of an input sequence which encodes
            contextual, semantic meaning for each word.
            Params:
                d_model(int): specifies the embedding dimension for each token/word
                vocab_size(int): number of embeddings that would be needed. # of unique words
                max_seq_len(int): the maximum sequence length of an input sequence. Used for generation positional encoding
                dropout(float): probability of dropout applied on the final embedding output
        """

        super().__init__()
        self.vocab_size = vocab_size
        self.token_embedding_table = nn.Embedding(num_embeddings=vocab_size,
                                                  embedding_dim=config["d_model"])
        self.position_embedding_table = nn.Embedding(num_embeddings=config["context_length"],
                                                     embedding_dim=config["d_model"])
        self.dropout = nn.Dropout(p=config["dropout"])

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        # x => [B, S]
        B, S = x.shape
        token_emb = self.token_embedding_table(x) # [B, S, D]

        pos_emb = self.position_embedding_table(torch.arange(S, device=device)).unsqueeze(0) # [1, S, D]
        out = self.dropout(token_emb+pos_emb)
        return self.dropout(out)

class AttentionHead(nn.Module):

    def __init__(self,
                 config) -> None:

        super().__init__()

        self.d_model = config["d_model"]
        self.head_dim = config["head_dim"]

        self.query = nn.Linear(self.d_model, self.head_dim)
        self.key = nn.Linear(self.d_model, self.head_dim)
        self.value = nn.Linear(self.d_model, self.head_dim)
        self.dropout = nn.Dropout(p=config["dropout"])

    def forward(self,
                query: torch.Tensor,
                key: torch.Tensor,
                value: torch.Tensor,
                mask=None) -> torch.Tensor:

        # query => [B, Q, D]
        # key => [B, K, D]
        # value => [B, K, D]

        q = self.query(query) # B, Q, HEAD_DIM
        k = self.key(key) # B, K, HEAD_DIM
        v = self.value(value) # B, K, HEAD_DIM

        weights = q @ k.transpose(1, 2) # B, Q, K
        if mask is not None:
            weights = weights.masked_fill(mask==0, value=float("-inf"))
        weights = F.softmax(weights/math.sqrt(self.head_dim), dim=-1)
        out = weights @ v # [B, Q, K] x [B, K, HEAD_DIM] => [B, Q, HEAD_DIM]
        return self.dropout(out)

class MultiHeadAttention(nn.Module):

    def __init__(self,
                 config) -> None:

         super().__init__()
         self.sa_heads = nn.ModuleList([AttentionHead(config) for _ in range(config["n_heads"])])
         self.proj = nn.Linear(config["d_model"], config["d_model"])
         self.dropout = nn.Dropout(p=config["dropout"])

    def forward(self,
                query: torch.Tensor,
                key: torch.Tensor,
                value: torch.Tensor,
                mask=None) -> torch.Tensor:

        out = torch.cat([h(query, key, value, mask) for h in self.sa_heads], dim=-1)
        out = self.proj(out)
        return self.dropout(out)

class FeedForward(nn.Module):

    def __init__(self,
                 config):

        super().__init__()
        d_model = config["d_model"]
        self.net = nn.Sequential(
            nn.Linear(d_model, d_model*4),
            nn.ReLU(),
            nn.Linear(d_model*4, d_model),
            nn.Dropout(p=config["dropout"])
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:

        x = self.net(x)
        return x

class GPTDecoderBlock(nn.Module):

    def __init__(self, config) -> None:

        super().__init__()
        self.mha = MultiHeadAttention(config)
        self.ff = FeedForward(config)
        self.ln_1 = nn.LayerNorm(normalized_shape=config["d_model"])
        self.ln_2 = nn.LayerNorm(normalized_shape=config["d_model"])

    def forward(self, x: torch.Tensor, mask=None) -> torch.Tensor:

        x = x + self.mha(self.ln_1(x), self.ln_1(x), self.ln_1(x), mask)
        x = x + self.ff(self.ln_2(x))
        return x

class GPTDecoder(nn.Module):

    def __init__(self, config) -> None:

        super().__init__()
        self.blocks = nn.ModuleList([GPTDecoderBlock(config) for _ in range(config["n_decoders"])])

    def forward(self, x: torch.Tensor, mask=None) -> torch.Tensor:

        for block in self.blocks:
            x = block(x, mask)
        return x

class PoemGPT(nn.Module):

    def __init__(self, config, vocab_size) -> None:

        super().__init__()
        self.context_length = config["context_length"]
        self.embedding = Embedding(config, vocab_size)
        self.gpt = GPTDecoder(config)
        self.lm_head = nn.Linear(config["d_model"], vocab_size)

    def forward(self,
                x: torch.Tensor,
                targets: torch.Tensor = None) -> Tuple[torch.Tensor, torch.Tensor]:

        B, S = x.shape
        # x -> [B, S], targets -> [B, S]
        x = self.embedding(x) # B, S, D_MODEL
        mask = create_causal_mask(S)

        x = self.gpt(x, mask) # B, S, D_MODEL
        logits = self.lm_head(x) # B, S, VOCAB_SIZE

        if targets is None:
            loss = None
        else:
            logits = logits.view(B*S, -1)
            targets = targets.view(-1)
            loss = F.cross_entropy(logits, targets)
        return logits, loss

    def generate(self, x:torch.Tensor=None, max_new_tokens: int=500) -> torch.Tensor:

        if x is None:
            x = torch.zeros((1, 1), dtype=torch.long, device=device) # B, S

        for _ in range(max_new_tokens):
            preds, _ = self(x[:, -self.context_length:])# B, S, VOCAB_SIZE
            preds = preds[:, -1, :] # B, VOCAB_SIZE
            probs = F.softmax(preds, dim=-1)
            x_next = torch.multinomial(input=probs, num_samples=1) # B, 1
            x = torch.cat((x, x_next), dim=1) # B, S+1

        return x

def create_causal_mask(sz):
    mask = torch.ones((sz, sz), device=device)
    mask = torch.tril(mask)
    return mask


import sys, os
import os.path
import shutil

from rpython.translator.translator import TranslationContext
from rpython.translator.tool.taskengine import SimpleTaskEngine
from rpython.translator.goal import query
from rpython.translator.goal.timing import Timer
from rpython.annotator.listdef import s_list_of_strings
from rpython.annotator import policy as annpolicy
from rpython.tool.udir import udir
from rpython.rlib.debug import debug_start, debug_print, debug_stop
from rpython.rlib.entrypoint import secondary_entrypoints,\
     annotated_jit_entrypoints

import py
from rpython.tool.ansi_print import AnsiLogger

log = AnsiLogger("translation")

def taskdef(deps, title, new_state=None, expected_states=[],
            idemp=False, earlycheck=None):
    def decorator(taskfunc):
        taskfunc.task_deps = deps
        taskfunc.task_title = title
        taskfunc.task_newstate = None
        taskfunc.task_expected_states = expected_states
        taskfunc.task_idempotent = idemp
        taskfunc.task_earlycheck = earlycheck
        return taskfunc
    return decorator

# TODO:
# sanity-checks using states

# set of translation steps to profile
PROFILE = set([])

class Instrument(Exception):
    pass

class ProfInstrument(object):
    name = "profinstrument"
    def __init__(self, datafile, compiler):
        self.datafile = datafile
        self.compiler = compiler

    def first(self):
        return self.compiler._build()

    def probe(self, exe, args):
        env = os.environ.copy()
        env['PYPY_INSTRUMENT_COUNTERS'] = str(self.datafile)
        self.compiler.platform.execute(exe, args, env=env)

    def after(self):
        # xxx
        os._exit(0)

class TranslationDriver(SimpleTaskEngine):
    _backend_extra_options = {}

    def __init__(self, setopts=None, default_goal=None,
                 disable=[],
                 exe_name=None, extmod_name=None,
                 config=None, overrides=None):
        from rpython.config import translationoption
        self.timer = Timer()
        SimpleTaskEngine.__init__(self)

        self.log = log

        if config is None:
            config = translationoption.get_combined_translation_config(translating=True)
        # XXX patch global variable with translation config
        translationoption._GLOBAL_TRANSLATIONCONFIG = config
        self.config = config
        if overrides is not None:
            self.config.override(overrides)

        if setopts is not None:
            self.config.set(**setopts)

        self.exe_name = exe_name
        self.extmod_name = extmod_name

        self.done = {}

        self.disable(disable)

        if default_goal:
            default_goal, = self.backend_select_goals([default_goal])
            if default_goal in self._maybe_skip():
                default_goal = None

        self.default_goal = default_goal
        self.extra_goals = []
        self.exposed = []

        # expose tasks
        def expose_task(task, backend_goal=None):
            if backend_goal is None:
                backend_goal = task
            def proc():
                return self.proceed(backend_goal)
            self.exposed.append(task)
            setattr(self, task, proc)

        backend, ts = self.get_backend_and_type_system()
        for task in self.tasks:
            explicit_task = task
            if task == 'annotate':
                expose_task(task)
            else:
                task, postfix = task.split('_')
                if task in ('rtype', 'backendopt', 'llinterpret',
                            'pyjitpl'):
                    if ts:
                        if ts == postfix:
                            expose_task(task, explicit_task)
                    else:
                        expose_task(explicit_task)
                elif task in ('source', 'compile', 'run'):
                    if backend:
                        if backend == postfix:
                            expose_task(task, explicit_task)
                    elif ts:
                        if ts == 'lltype':
                            expose_task(explicit_task)
                    else:
                        expose_task(explicit_task)

    def set_extra_goals(self, goals):
        self.extra_goals = goals

    def set_backend_extra_options(self, extra_options):
        self._backend_extra_options = extra_options

    def get_info(self): # XXX more?
        d = {'backend': self.config.translation.backend}
        return d

    def get_backend_and_type_system(self):
        type_system = self.config.translation.type_system
        backend = self.config.translation.backend
        return backend, type_system

    def backend_select_goals(self, goals):
        backend, ts = self.get_backend_and_type_system()
        postfixes = [''] + ['_'+p for p in (backend, ts) if p]
        l = []
        for goal in goals:
            for postfix in postfixes:
                cand = "%s%s" % (goal, postfix)
                if cand in self.tasks:
                    new_goal = cand
                    break
            else:
                raise Exception("cannot infer complete goal from: %r" % goal)
            l.append(new_goal)
        return l

    def disable(self, to_disable):
        self._disabled = to_disable

    def _maybe_skip(self):
        maybe_skip = []
        if self._disabled:
            for goal in self.backend_select_goals(self._disabled):
                maybe_skip.extend(self._depending_on_closure(goal))
        return dict.fromkeys(maybe_skip).keys()

    def setup(self, entry_point, inputtypes, policy=None, extra={}, empty_translator=None):
        standalone = inputtypes is None
        self.standalone = standalone

        if standalone:
            # the 'argv' parameter
            inputtypes = [s_list_of_strings]
        self.inputtypes = inputtypes

        if policy is None:
            policy = annpolicy.AnnotatorPolicy()
        self.policy = policy

        self.extra = extra

        if empty_translator:
            translator = empty_translator
        else:
            translator = TranslationContext(config=self.config)

        self.entry_point = entry_point
        self.translator = translator
        self.libdef = None
        self.secondary_entrypoints = []

        if self.config.translation.secondaryentrypoints:
            for key in self.config.translation.secondaryentrypoints.split(","):
                try:
                    points = secondary_entrypoints[key]
                except KeyError:
                    raise KeyError("Entrypoint %r not found (not in %r)" %
                                   (key, secondary_entrypoints.keys()))
                self.secondary_entrypoints.extend(points)

        self.translator.driver_instrument_result = self.instrument_result

    def setup_library(self, libdef, policy=None, extra={}, empty_translator=None):
        """ Used by carbon python only. """
        self.setup(None, None, policy, extra, empty_translator)
        self.libdef = libdef
        self.secondary_entrypoints = libdef.functions

    def instrument_result(self, args):
        backend, ts = self.get_backend_and_type_system()
        if backend != 'c' or sys.platform == 'win32':
            raise Exception("instrumentation requires the c backend"
                            " and unix for now")

        datafile = udir.join('_instrument_counters')
        makeProfInstrument = lambda compiler: ProfInstrument(datafile, compiler)

        pid = os.fork()
        if pid == 0:
            # child compiling and running with instrumentation
            self.config.translation.instrument = True
            self.config.translation.instrumentctl = (makeProfInstrument,
                                                     args)
            raise Instrument
        else:
            pid, status = os.waitpid(pid, 0)
            if os.WIFEXITED(status):
                status = os.WEXITSTATUS(status)
                if status != 0:
                    raise Exception("instrumentation child failed: %d" % status)
            else:
                raise Exception("instrumentation child aborted")
            import array, struct
            n = datafile.size()//struct.calcsize('L')
            datafile = datafile.open('rb')
            counters = array.array('L')
            counters.fromfile(datafile, n)
            datafile.close()
            return counters

    def info(self, msg):
        log.info(msg)

    def _profile(self, goal, func):
        from cProfile import Profile
        from rpython.tool.lsprofcalltree import KCacheGrind
        d = {'func':func}
        prof = Profile()
        prof.runctx("res = func()", globals(), d)
        KCacheGrind(prof).output(open(goal + ".out", "w"))
        return d['res']

    def _do(self, goal, func, *args, **kwds):
        title = func.task_title
        if goal in self.done:
            self.log.info("already done: %s" % title)
            return
        else:
            self.log.info("%s..." % title)
        debug_start('translation-task')
        debug_print('starting', goal)
        self.timer.start_event(goal)
        try:
            instrument = False
            try:
                if goal in PROFILE:
                    res = self._profile(goal, func)
                else:
                    res = func()
            except Instrument:
                instrument = True
            if not func.task_idempotent:
                self.done[goal] = True
            if instrument:
                self.proceed('compile')
                assert False, 'we should not get here'
        finally:
            try:
                debug_stop('translation-task')
                self.timer.end_event(goal)
            except (KeyboardInterrupt, SystemExit):
                raise
            except:
                pass
        #import gc; gc.dump_rpy_heap('rpyheap-after-%s.dump' % goal)
        return res

    @taskdef([], "Annotating&simplifying")
    def task_annotate(self):
        """ Annotate
        """
        # includes annotation and annotatation simplifications
        translator = self.translator
        policy = self.policy
        self.log.info('with policy: %s.%s' % (policy.__class__.__module__, policy.__class__.__name__))

        annotator = translator.buildannotator(policy=policy)

        if self.secondary_entrypoints is not None:
            for func, inputtypes in self.secondary_entrypoints:
                if inputtypes == Ellipsis:
                    continue
                annotator.build_types(func, inputtypes, False)

        if self.entry_point:
            s = annotator.build_types(self.entry_point, self.inputtypes)
            translator.entry_point_graph = annotator.bookkeeper.getdesc(self.entry_point).getuniquegraph()
        else:
            s = None

        self.sanity_check_annotation()
        if self.entry_point and self.standalone and s.knowntype != int:
            raise Exception("stand-alone program entry point must return an "
                            "int (and not, e.g., None or always raise an "
                            "exception).")
        annotator.complete()
        annotator.simplify()
        return s

    def sanity_check_annotation(self):
        translator = self.translator
        irreg = query.qoutput(query.check_exceptblocks_qgen(translator))
        if irreg:
            self.log.info("Some exceptblocks seem insane")

        lost = query.qoutput(query.check_methods_qgen(translator))
        assert not lost, "lost methods, something gone wrong with the annotation of method defs"

    RTYPE = 'rtype_lltype'
    @taskdef(['annotate'], "RTyping")
    def task_rtype_lltype(self):
        """ RTyping - lltype version
        """
        rtyper = self.translator.buildrtyper()
        rtyper.specialize(dont_simplify_again=True)

    @taskdef([RTYPE], "JIT compiler generation")
    def task_pyjitpl_lltype(self):
        """ Generate bytecodes for JIT and flow the JIT helper functions
        lltype version
        """
        from rpython.jit.codewriter.policy import JitPolicy
        get_policy = self.extra.get('jitpolicy', None)
        if get_policy is None:
            self.jitpolicy = JitPolicy()
        else:
            self.jitpolicy = get_policy(self)
        #
        from rpython.jit.metainterp.warmspot import apply_jit
        apply_jit(self.translator, policy=self.jitpolicy,
                  backend_name=self.config.translation.jit_backend, inline=True)
        #
        self.log.info("the JIT compiler was generated")

    @taskdef([RTYPE], "test of the JIT on the llgraph backend")
    def task_jittest_lltype(self):
        """ Run with the JIT on top of the llgraph backend
        """
        # parent process loop: spawn a child, wait for the child to finish,
        # print a message, and restart
        from rpython.translator.goal import unixcheckpoint
        unixcheckpoint.restartable_point(auto='run')
        # load the module rpython/jit/tl/jittest.py, which you can hack at
        # and restart without needing to restart the whole translation process
        from rpython.jit.tl import jittest
        jittest.jittest(self)

    BACKENDOPT = 'backendopt_lltype'
    @taskdef([RTYPE, '??pyjitpl_lltype', '??jittest_lltype'], "lltype back-end optimisations")
    def task_backendopt_lltype(self):
        """ Run all backend optimizations - lltype version
        """
        from rpython.translator.backendopt.all import backend_optimizations
        backend_optimizations(self.translator, replace_we_are_jitted=True)

    STACKCHECKINSERTION = 'stackcheckinsertion_lltype'
    @taskdef(['?'+BACKENDOPT, RTYPE, 'annotate'], "inserting stack checks")
    def task_stackcheckinsertion_lltype(self):
        from rpython.translator.transform import insert_ll_stackcheck
        count = insert_ll_stackcheck(self.translator)
        self.log.info("inserted %d stack checks." % (count,))

    def possibly_check_for_boehm(self):
        if self.config.translation.gc == "boehm":
            from rpython.rtyper.tool.rffi_platform import configure_boehm
            from rpython.translator.platform import CompilationError
            try:
                configure_boehm(self.translator.platform)
            except CompilationError as e:
                i = 'Boehm GC not installed.  Try e.g. "translate.py --gc=minimark"'
                raise Exception(str(e) + '\n' + i)

    @taskdef([STACKCHECKINSERTION, '?'+BACKENDOPT, RTYPE, '?annotate'],
        "Creating database for generating c source",
        earlycheck = possibly_check_for_boehm)
    def task_database_c(self):
        """ Create a database for further backend generation
        """
        translator = self.translator
        if translator.annotator is not None:
            translator.frozen = True

        standalone = self.standalone
        get_gchooks = self.extra.get('get_gchooks', lambda: None)
        gchooks = get_gchooks()

        if standalone:
            from rpython.translator.c.genc import CStandaloneBuilder
            cbuilder = CStandaloneBuilder(self.translator, self.entry_point,
                                          config=self.config, gchooks=gchooks,
                      secondary_entrypoints=
                      self.secondary_entrypoints + annotated_jit_entrypoints)
        else:
            from rpython.translator.c.dlltool import CLibraryBuilder
            functions = [(self.entry_point, None)] + self.secondary_entrypoints + annotated_jit_entrypoints
            cbuilder = CLibraryBuilder(self.translator, self.entry_point,
                                       functions=functions,
                                       name='libtesting',
                                       config=self.config,
                                       gchooks=gchooks)
        if not standalone:     # xxx more messy
            cbuilder.modulename = self.extmod_name
        database = cbuilder.build_database()
        self.log.info("database for generating C source was created")
        self.cbuilder = cbuilder
        self.database = database

    @taskdef(['database_c'], "Generating c source")
    def task_source_c(self):
        """ Create C source files from the generated database
        """
        cbuilder = self.cbuilder
        database = self.database
        if self._backend_extra_options.get('c_debug_defines', False):
            defines = cbuilder.DEBUG_DEFINES
        else:
            defines = {}
        if self.exe_name is not None:
            exe_name = self.exe_name % self.get_info()
        else:
            exe_name = None
        c_source_filename = cbuilder.generate_source(database, defines,
                                                     exe_name=exe_name)
        self.log.info("written: %s" % (c_source_filename,))
        if self.config.translation.dump_static_data_info:
            from rpython.translator.tool.staticsizereport import dump_static_data_info
            targetdir = cbuilder.targetdir
            fname = dump_static_data_info(self.log, database, targetdir)
            dstname = self.compute_exe_name() + '.staticdata.info'
            shutil_copy(str(fname), str(dstname))
            self.log.info('Static data info written to %s' % dstname)

    def compute_exe_name(self, suffix=''):
        newexename = self.exe_name % self.get_info()
        if '/' not in newexename and '\\' not in newexename:
            newexename = './' + newexename
        if suffix:
            # Replace the last `.sfx` with the suffix
            newname = py.path.local(newexename.rsplit('.', 1)[0])
            newname = newname.new(basename=newname.basename + suffix)
            return newname
        return py.path.local(newexename)

    def create_exe(self):
        """ Copy the compiled executable into current directory, which is
            pypy/goal on nightly builds
        """
        if self.exe_name is not None:
            exename = self.c_entryp
            newexename = py.path.local(exename.basename)
            shutil_copy(str(exename), str(newexename))
            self.log.info("copied: %s to %s" % (exename, newexename,))
            if self.cbuilder.shared_library_name is not None:
                soname = self.cbuilder.shared_library_name
                newsoname = newexename.new(basename=soname.basename)
                shutil_copy(str(soname), str(newsoname))
                self.log.info("copied: %s to %s" % (soname, newsoname,))
                if hasattr(self.cbuilder, 'executable_name_w'):
                    # Copy pypyw.exe
                    exename_w = self.cbuilder.executable_name_w
                    newexename_w = py.path.local(exename_w.basename)
                    self.log.info("copied: %s to %s" % (exename_w, newexename_w,))
                    shutil_copy(str(exename_w), str(newexename_w))
                    # for pypy, the import library is renamed and moved to
                    # libs/python32.lib, according to the pragma in pyconfig.h
                    libname = self.config.translation.libname
                    oldlibname = soname.new(ext='lib')
                    if not libname:
                        libname = oldlibname.basename
                        libname = str(newsoname.dirpath().join(libname))
                    shutil.copyfile(str(oldlibname), libname)
                    self.log.info("copied: %s to %s" % (oldlibname, libname,))
                    # the pdb file goes in the same place as pypy(w).exe
                    ext_to_copy = ['pdb',]
                    for ext in ext_to_copy:
                        name = soname.new(ext=ext)
                        newname = newexename.new(basename=soname.basename)
                        shutil.copyfile(str(name), str(newname.new(ext=ext)))
                        self.log.info("copied: %s" % (newname,))
                    # HACK: copy libcffi-*.dll which is required for venvs
                    # At some point, we should stop doing this, and instead
                    # use the artifact from packaging the build instead
                    libffi = py.path.local.sysfind('libffi-8.dll')
                    if sys.platform == 'win32' and not libffi:
                        raise RuntimeError('could not find libffi')
                    elif libffi:
                        target = os.getcwd() + r'\libffi-8.dll'
                        if not os.path.exists(target):
                            # in tests, we can mock using windows without libffi
                            shutil.copyfile(str(libffi), target)
            self.c_entryp = newexename
        self.log.info("created: %s" % (self.c_entryp,))

    @taskdef(['source_c'], "Compiling c source")
    def task_compile_c(self):
        """ Compile the generated C code using either makefile or
        translator/platform
        """
        cbuilder = self.cbuilder
        kwds = {}
        if self.standalone and self.exe_name is not None:
            kwds['exe_name'] = self.compute_exe_name().basename
        cbuilder.compile(**kwds)

        if self.standalone:
            self.c_entryp = cbuilder.executable_name
            self.create_exe()
        else:
            self.c_entryp = cbuilder.get_entry_point()

    @taskdef([STACKCHECKINSERTION, '?'+BACKENDOPT, RTYPE], "LLInterpreting")
    def task_llinterpret_lltype(self):
        from rpython.rtyper.llinterp import LLInterpreter

        translator = self.translator
        interp = LLInterpreter(translator.rtyper)
        bk = translator.annotator.bookkeeper
        graph = bk.getdesc(self.entry_point).getuniquegraph()
        v = interp.eval_graph(graph,
                              self.extra.get('get_llinterp_args',
                                             lambda: [])())

        log.llinterpret("result -> %s" % v)

    def proceed(self, goals):
        if not goals:
            if self.default_goal:
                goals = [self.default_goal]
            else:
                self.log.info("nothing to do")
                return
        elif isinstance(goals, str):
            goals = [goals]
        goals.extend(self.extra_goals)
        goals = self.backend_select_goals(goals)
        result = self._execute(goals, task_skip = self._maybe_skip())
        self.log.info('usession directory: %s' % (udir,))
        return result

    @classmethod
    def from_targetspec(cls, targetspec_dic, config=None, args=None,
                        empty_translator=None,
                        disable=[],
                        default_goal=None):
        if args is None:
            args = []

        driver = cls(config=config, default_goal=default_goal,
                     disable=disable)
        target = targetspec_dic['target']
        spec = target(driver, args)

        try:
            entry_point, inputtypes, policy = spec
        except TypeError:
            # not a tuple at all
            entry_point = spec
            inputtypes = policy = None
        except ValueError:
            policy = None
            entry_point, inputtypes = spec

        driver.setup(entry_point, inputtypes,
                     policy=policy,
                     extra=targetspec_dic,
                     empty_translator=empty_translator)
        return driver

    def prereq_checkpt_rtype(self):
        assert 'rpython.rtyper.rmodel' not in sys.modules, (
            "cannot fork because the rtyper has already been imported")
    prereq_checkpt_rtype_lltype = prereq_checkpt_rtype

    # checkpointing support
    def _event(self, kind, goal, func):
        if kind == 'planned' and func.task_earlycheck:
            func.task_earlycheck(self)
        if kind == 'pre':
            fork_before = self.config.translation.fork_before
            if fork_before:
                fork_before, = self.backend_select_goals([fork_before])
                if not fork_before in self.done and fork_before == goal:
                    prereq = getattr(self, 'prereq_checkpt_%s' % goal, None)
                    if prereq:
                        prereq()
                    from rpython.translator.goal import unixcheckpoint
                    unixcheckpoint.restartable_point(auto='run')

if os.name == 'posix':
    def shutil_copy(src, dst):
        # this version handles the case where 'dst' is an executable
        # currently being executed
        shutil.copy(src, dst + '~')
        os.rename(dst + '~', dst)
else:
    shutil_copy = shutil.copy