from shapely import Polygon
import trimesh  # install mapbox_earcut!

cube_list = []

import py5

def setup():
    global mesh
    py5.size(700, 700, py5.P3D)
    for _ in range(10):
        cube_list.append(cube(py5.random(-200, 200),
                              py5.random(-200, 200),
                              py5.random(-200, 200), 200))

    mesh = cube_list[0]
    for c in cube_list[1:]:
        mesh = mesh.union(c)

def draw():
    py5.lights()
    py5.no_stroke()
    py5.background(100, 200, 100)
    py5.lights()
    py5.no_stroke()
    py5.translate(py5.width/2, py5.height/2, -py5.height/2)
    py5.rotate_y(py5.radians(py5.mouse_x))
    draw_mesh(mesh)

def cube(x, y, z, w=100):
    hw = w / 2
    pts = ((-hw, -hw), (hw, -hw), (hw, hw), (-hw, hw))
    c = trimesh.creation.extrude_polygon(Polygon(pts), w)
    c.apply_translation((x, y, z - hw))
    return c
    #trimesh.creation.box(w

def draw_mesh(m):
    for i, face in enumerate(m.faces):
        with py5.begin_closed_shape():
            py5.vertices([m.vertices[v] for v in face])

py5.run_sketch(block=False)


from odoo import fields, models, _

class HrHolidaysCancelLeave(models.TransientModel):
    _name = 'hr.holidays.cancel.leave'
    _description = 'Cancel Time Off Wizard'

    leave_id = fields.Many2one('hr.leave', string="Time Off Request", required=True)
    reason = fields.Text(required=True)

    def action_cancel_leave(self):
        self.ensure_one()

        self.leave_id._action_user_cancel(self.reason)

        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'type': 'success',
                'message': _("Your time off has been canceled."),
                'next': {'type': 'ir.actions.act_window_close'},
            }
        }


def solve(data):
	total = 0
	for item in data:
		temp = 0
		x, y = item.split()
		a, b = ord(x) - ord("A"), ord(y) - ord("X")
		temp += b * 3
		b2 = (a + b - 1) % 3
		temp += b2 + 1
		total += temp
	return total

if __name__ == '__main__':
	with open("input.txt", "r") as f:
		data = f.read().splitlines()
		print(solve(data))


import os
import time
from datetime import datetime
import docker
import shutil
from argparse import ArgumentParser
import json
import re

# Key to replace in tplstart.sh for base url passed in jenkins. If not passed, baseUrl from config.js is assigned
selected_base_url = "client_base_url"

parser = ArgumentParser()
parser.add_argument("-d", "--dir", dest="dirname",
                    help="The folder\'s name that contains the tests.")
parser.add_argument("-i", "--image", dest="docker_image",
                    help="The docker image to download.")
parser.add_argument("-b", "--clientbaseurl", default="-", nargs="?", const="-", dest=selected_base_url, required=False,
                    help="The baseurl of the client system to be executed in.")
parser.add_argument("-f", "--folder", default="", nargs="?", const="", dest="folder_to_read",
                    required=False, help="folder from where to read")
parser.add_argument("-n", "--number", default=50, dest="containers_number",
                    help="The maximum number of containers that will be running simultaneously. 5 is the default value. 0 for unlimited number ")
# parser.add_argument("-f", "--string", dest="targeted_server", help= "")
args = parser.parse_args()
##### Initiating the global variables #######
dateTimeObj = datetime.now()
if args.containers_number:
    max_containers_up = int(args.containers_number)
else:
    max_containers_up = 50

if args.folder_to_read:
    folder_to_read = str(args.folder_to_read).replace(
        "/", os.sep).replace("\\", os.sep)
else:
    folder_to_read = ""

# Assigning baseurl from arg if passed. Or default baseurl will be assigned in get_config_file() funtion
client_base_url = ""
url_regex = re.compile(
    r'^(?:http|ftp)s?://'  # http:// or https://
    # domain...
    r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
    r'localhost|'  # localhost...
    r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'  # ...or ip
    r'(?::\d+)?'  # optional port
    r'(?:/?|[/?]\S+)$', re.IGNORECASE)

if args.client_base_url and re.match(url_regex, args.client_base_url):
    client_base_url = args.client_base_url

print("client_base_url " + client_base_url)

list_containers = []
list_containers_failed = []
job_endtime = 'Job still ongoing'
# Commented below line for testing
# final_destination = '/home/ccloud/reports/server/results/'
work_dir = os.getcwd() + os.sep + str(args.dirname)
folder_to_read = os.path.join(work_dir, folder_to_read)
root_dir = os.getcwd()
# Changed results folder path
reports_dir = os.path.join(root_dir, "reports" + os.sep + 'server' + os.sep)
final_destination = os.path.join(reports_dir, 'results' + os.sep)

print("final_destination: " + final_destination)
main_folder = dateTimeObj.strftime("%d%b%Y%H%M%S")
main_folder_path = os.path.join(final_destination, main_folder)
volumes_dir = os.path.join(root_dir, 'test_volumes')
docker_client = docker.from_env()
templ_script = 'tplstart.sh'
# Selected test file to replace in tplstart.sh with actual test file
selected_test = '/tmp/test/config.js'

##### Declaring all functions needed ########

def get_config_file(client_base_url):
    '''
    Get the config file from the tests repository and put it in the roor folder
    '''
    for subdir, dirs, files in os.walk(work_dir):
        for file in files:
            filepath = os.path.join(subdir, file)
            filename = file
            search_config = 'configuration' + os.sep + 'config.js'
            if filepath.endswith(search_config):
                config_path = os.path.join(root_dir, filename)
                shutil.copy(filepath, config_path)
                if not client_base_url:
                    with open(config_path) as config_file:
                        _lines = config_file.readlines()
                        config_file.close()
                    print("-----------------base------------------------")
                    for line in _lines:
                        line = line.strip()
                        if(re.search("^baseUrl[ ]?:[ ]*\"(http.*)\"", line)):
                            print(
                                re.search("^baseUrl[ ]?:[ ]*\"(http.*)\"", line).groups()[0])
                            client_base_url = re.search(
                                "^baseUrl[ ]?:[ ]*\"(http.*)\"", line).groups()[0]
                            break

                    print("-----------------------------------------")
                print("Default client_base_url: " + client_base_url)
    return client_base_url

def get_testfiles_number():
    '''
    Calculate the number of the tests that script will be running
    '''
    tests_number = 0
    for subdir, dirs, files in os.walk(folder_to_read):
        for file in files:
            filepath = os.path.join(subdir, file)
            # filename = file
            if filepath.endswith(".spec.js"):
                print("file: " + file)
                tests_number += 1
    print("___________________________")
    print("Total specs in " + folder_to_read + " is " + str(tests_number))
    print("___________________________")
    return tests_number

def build_start_script(filepath, client_base_url):
    '''
    Update start.sh file to call the selected test
    '''
    with open(templ_script, "r") as file:
        text = file.readlines()
        file.close()
    # use the path of the container
    filepath = '/vyper' + os.sep + os.path.relpath(filepath, root_dir)
    i = 0
    while i < len(text):
        if selected_test in text[i]:
            text[i] = text[i].replace(selected_test, filepath)
        if selected_base_url in text[i]:
            text[i] = text[i].replace(selected_base_url, client_base_url)
        i += 1
    # print(text)
    with open(run_script, "w") as file:
        file.writelines(text)
        file.close()

def prepare_results_report(container):
    '''
    Moving the results folder to its destination and removing the exited container
    '''
    container_object = docker_client.containers.get(container)
    container_name = container_object.name
    print('{} |  Cleaning the container: {}'.format(
        datetime.now().strftime("%H:%M:%S"), container_name))
    container_volume = os.path.join(volumes_dir, container_name)
    container_object.remove(v=False)
    container_name = container_name[:-3]
    result_folder = os.path.join(container_volume, 'results')
    # print("result_folder: " + result_folder)
    if os.path.isdir(result_folder):
        new_results_name = os.path.join(main_folder_path, container_name)
        print("new_results_name: " + new_results_name)
        shutil.move(result_folder, new_results_name)
        # Change the files and folders permission for security purposes
        os.chown(new_results_name, 1000, 1000)
        os.chmod(new_results_name, 0o755)
        for root, dirs, files in os.walk(new_results_name):
            for dir in [os.path.join(root, d) for d in dirs]:
                os.chown(dir, 1000, 1000)
                os.chmod(dir, 0o755)
            for file in [os.path.join(root, f) for f in files]:
                os.chown(file, 1000, 1000)
                os.chmod(file, 0o644)
    else:
        list_containers_failed.append(container_name)
        print("--------------------------------------------------------")
        print("Not a directory: " + result_folder)
        print("--------------------------------------------------------")

def build_metadata(total, starttime, endtime, inprogress, client_base_url):
    # metadata_file = os.path.join(main_folder_path,'metadata.json')
    # metadata_file = '/home/ccloud/reports/server/metadata.json'
    # Changed relative path
    metadata_file = os.path.join(reports_dir, 'metadata.json')
    completed = total - inprogress
    if endtime == 'Job still ongoing':
        totalexecutiontime = '-'
    else:
        totalexecutiontime = endtime - starttime
        totalexecutiontime = int(totalexecutiontime.seconds / 60)
        endtime = endtime.strftime("%d%b%Y%H%M%S")
    new_data = {
        main_folder: {
            "total": total,
            "inProgress": inprogress,
            "completed": completed,
            "executionStartTime": starttime.strftime("%d%b%Y%H%M%S"),
            "executionEndTime": endtime,
            "totalExecutionTime": totalexecutiontime,
            "baseUrl": client_base_url
        }
    }
    if os.path.isfile(metadata_file):
        with open(metadata_file) as json_file:
            data = json.load(json_file)
        data.update(new_data)
    else:
        data = new_data
    with open(metadata_file, 'w') as f:
        json.dump(data, f, indent=4)
    os.chown(metadata_file, 1000, 1000)
    os.chmod(metadata_file, 0o644)

def update_latest_running_file():
    metadata = os.path.join(reports_dir, 'metadata.json')

    if os.path.isfile(metadata):
        with open(metadata) as json_file:
            data = json.load(json_file)
        data.update({"latest": main_folder})
    else:
        data = {"latest": main_folder}
    with open(metadata, 'w') as f:
        json.dump(data, f, indent=4)
    os.chown(metadata, 1000, 1000)
    os.chmod(metadata, 0o644)

###### The main script #####################
if args.dirname and args.docker_image:
    if not os.path.exists(final_destination):
        os.makedirs(final_destination)
    try:
        print("creating folder : " + main_folder_path)
        os.mkdir(main_folder_path)
    except OSError:
        print("Creation of the directory %s failed" % main_folder_path)
    else:
        print("Successfully created the directory %s " % main_folder_path)
    # print(main_folder_path + " Folder created")
    os.chown(main_folder_path, 1000, 1000)
    os.chmod(main_folder_path, 0o644)
    os.mkdir(volumes_dir)
    # vyper_image = docker_client.images.pull(args.docker_image,tag='latest')
    vyper_image = args.docker_image
    docker_client.images.build(path=root_dir, tag=args.docker_image)
    client_base_url = get_config_file(client_base_url)
    tests_number = get_testfiles_number()
    print('{} |  There will be {} containers to be created'.format(
        datetime.now().strftime("%H:%M:%S"), str(tests_number)))
    print('The results will be stored at {}'.format(main_folder_path))
    left_containers = tests_number
    update_latest_running_file()
    # Browse every file in the directory with its path
    for subdir, dirs, files in os.walk(folder_to_read):
        for file in files:
            filepath = os.path.join(subdir, file)
            filename = file
            if filepath.endswith(".spec.js") and filename:
                while len(docker_client.containers.list()) >= max_containers_up and max_containers_up != 0:
                    time.sleep(5)
                    print('{} |  max permitted number of running container reached'.format(
                        datetime.now().strftime("%H:%M:%S")))
                    print('{} |  waiting for running containers'.format(
                        datetime.now().strftime("%H:%M:%S")))
                # Create a volume for every container and put all needed files in it
                container_volume = os.path.join(volumes_dir, filename)
                os.mkdir(container_volume)
                run_script = os.path.join(container_volume, 'start.sh')
                # print("run_script path " +run_script)
                source_config = os.path.join(root_dir, 'config.js')
                dest_config = os.path.join(container_volume, 'config.js')
                shutil.copy(source_config, dest_config)
                relative_workdir = os.path.join(container_volume, args.dirname)
                shutil.copytree(work_dir, relative_workdir)
                build_start_script(filepath, client_base_url)
                docker_client.containers.run(vyper_image, volumes={container_volume: {
                                             'bind': '/vyper', 'mode': 'rw'}}, detach=True, name=filename, command="/bin/bash /vyper/start.sh  ")
                print('{} |  {} : is created'.format(datetime.now().strftime(
                    "%H:%M:%S"), docker_client.containers.get(filename).name))
                list_containers.append(
                    docker_client.containers.get(str(filename)).id)
                # Get the first container creation time
                if len(list_containers) == 1:
                    job_starttime = datetime.now()
                if len(list_containers) < tests_number:
                    for container in list_containers:
                        created_containers = docker_client.containers.list(
                            all=True)
                        list_ids = []
                        for artifact in created_containers:
                            list_ids.append(artifact.id)
                        if container in list_ids:
                            if docker_client.containers.get(container).status == 'exited':
                                prepare_results_report(container)
                                left_containers = left_containers - 1
                                build_metadata(
                                    tests_number, job_starttime, job_endtime, left_containers, client_base_url)
                elif len(list_containers) == tests_number:
                    print('{} |  All containers are created! Waiting for the running ones'.format(
                        datetime.now().strftime("%H:%M:%S")))
                    while left_containers > 0:
                        for container in list_containers:
                            created_containers = docker_client.containers.list(
                                all=True)
                            list_ids = []
                            for artifact in created_containers:
                                list_ids.append(artifact.id)
                            if container in list_ids:
                                if docker_client.containers.get(container).status == 'exited':
                                    prepare_results_report(container)
                                    left_containers = left_containers - 1
                                    build_metadata(
                                        tests_number, job_starttime, job_endtime, left_containers, client_base_url)
                    if left_containers == 0:
                        job_endtime = datetime.now()
                        build_metadata(tests_number, job_starttime,
                                       job_endtime, left_containers, client_base_url)
    # delete the containers volumes
    if volumes_dir:
        shutil.rmtree(volumes_dir)
    if(len(list_containers_failed) > 0):
        print("Below are the list of containers which did not had results folder")
        for container in list_containers_failed:
            print(container)
else:
    print('Arguments Missing')


import requests
import json
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

def covidAsk(query):
    params = {'query': query, 'strat': 'dense_first'}
    res = requests.get('https://covidask.korea.ac.kr/api', params=params, verify=False)
    outs = json.loads(res.text)
    return outs

query = 'Is there concrete evidence for the presence of asymptomatic transmissions?'
results = covidAsk(query)

# Top 10 phrase answers from covidAsk
print([r['answer'] for r in results['ret']])

# Top 10 sentence answers from covidAsk
print([r['context'][r['sent_start']:r['sent_end']] for r in results['ret']])


import os
import torch
from torch.utils.data import DataLoader
from torchvision import transforms

from .ImageDataset import ImageDataset

# DO NOT CHANGE:
crop_size = 224 # Required by resnet152

# See https://github.com/yunjey/pytorch-tutorial/tree/master/tutorials/03-advanced/image_captioning
def collate_fn (data):
    # Sort datalist by caption length; descending order
    data.sort(key = lambda data_pair: len(data_pair[1]), reverse=True)
    images, captions = zip(*data)

    # Merge images (from tuple of 3D Tensor to 4D Tensor)
    images = torch.stack(images, 0)

    # Merge captions (from tuple of 1D tensor to 2D tensor)
    lengths = [len(caption) for caption in captions] # List of caption lengths
    targets = torch.zeros(len(captions), max(lengths)).long()

    for i, caption in enumerate(captions):
        end = lengths[i]
        targets[i, :end] = caption[:end]

    return images, targets, lengths

# Transform to modify images for pre-trained ResNet base
transform = transforms.Compose([
    transforms.Resize((crop_size, crop_size)), # Match resnet size
    transforms.ToTensor(),
    # See for magic #'s: http://pytorch.org/docs/master/torchvision/models.html
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])

def getDataLoader(data_dir, vocab, batch_size, shuffle=True, num_workers=2):
    dataset = ImageDataset(data_dir=data_dir, vocab=vocab, transform=transform)
    data_loader = DataLoader(dataset=dataset,
                            batch_size=batch_size,
                            shuffle=shuffle,
                            num_workers=num_workers,
                            collate_fn=collate_fn)
    return data_loader, dataset.raw_image_names


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('monitor', '0003_focofirms_focowfabba'),
    ]

    operations = [
        migrations.CreateModel(
            name='CoeficUsoSolo',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('usosolo', models.CharField(max_length=100, verbose_name=b'Categoria    de Uso')),
                ('coefic', models.DecimalField(default=0, max_digits=16, decimal_places=2)),
                ('Projeto_FK', models.ForeignKey(verbose_name=b'Projeto', to='monitor.Projeto')),
            ],
        ),
    ]


# help with properties: http://www.python-course.eu/python3_properties.php

class dog_public_private:
	"""
	A customisable dog with public and private properties

	Example:

	d=dog(23)
	d.Kingdom # Animalia
	d.Kingdom=None # set Kingdom to None type - DANGER!! (e.g. if this was a bank account and 'balance' was initialised in this way, you could set it to zero!)

	d.__weight # not accessible!!
	d.weight # 23 # only accessbile due to presence of property methods
	d.weight = 18 # only possible to change it due to setter property method

	"""

	def __init__(self, weight):

		self.Kingdom = "Animalia" # 'public' variable

		self.__weight=weight # 'private variable' - can only be changed using properties and the associated getter/setter methods

	@property
	def weight(self):
		return self.__weight

	@weight.setter
	def weight(self, value):
		if type(value) != float:
			print("Weight must be declared as a float (kg)")
		else:
			self.__weight = value

	def FoodCostPerWeek(self):
		"Estimate of food cost per week based on weight in kg"

		if (self.weight <= 5):
			print("£10")
		elif (self.weight >= 5) and (self.weight <= 10):
			print("£20")
		elif (self.weight >= 10) and (self.weight<= 20):
			print("£30")
		elif (self.weight >= 20) and (self.weight <= 40):
			print("£40")
		elif (self.weight >= 40):
			print("£50 +")


def ngerBF(arr, n):
    a = -1
    for i in range(n - 1):
        # print(arr[i])

        for j in range(i + 1, n):
            if (arr[i] < arr[j]):
                print(arr[j], end=" ")
                break
            elif (j == n - 1):
                print(a)

    # last element always have -1
    print(a)

#input take from user
print("enter the element of array : ")
arr = [int(i) for i in input().split()]
#static input:
#arr = [11, 13, 21, 25, 12]
n = len(arr)
ngerBF(arr, n)


from flask import Flask
from flask import Response
from flask import render_template
from flask import request
from flashtext import KeywordProcessor

import json

from whoosh.qparser import QueryParser
from whoosh.qparser import FuzzyTermPlugin
from whoosh.qparser import MultifieldParser
from whoosh.index import open_dir
from whoosh.query import Every, Term

from fuzzywuzzy import process

ix = open_dir("index")

app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True

with open("redtracker_full.json","r") as f:
    data = json.load(f)
indexed_data = {i["link"]:i for i in data}

# Authors suggestions data
with open("all_authors_stats.json","r") as f:
    all_authors_stats = json.load(f)
    all_indexed_authors_stats = {i["name"]:i for i in all_authors_stats}
    authors_name = [i["name"] for i in all_authors_stats]

def author_name_suggestion(name):
    list_autocomplete = [all_indexed_authors_stats[i] for i in all_indexed_authors_stats.keys() if i.lower().startswith(name.lower())]
    list_suggestions = [all_indexed_authors_stats[i[0]] for i in process.extract(name, authors_name, limit=10-len(list_autocomplete)) if i[1] > 70 and not all_indexed_authors_stats[i[0]] in list_autocomplete]
    return list_autocomplete, list_suggestions

@app.route('/')
def index():
    return render_template('index.html')
    return "".join(['
 o
' for i in data[:20]])

@app.route('/api/post')
def post():
    parser = QueryParser("link", ix.schema)
    myquery = parser.parse(request.args.get('link'))
    with ix.searcher() as searcher:
        results = searcher.search(myquery)
        if results.is_empty():
            resp = Response(status=404)
        else:
            results_json = json.dumps( dict(results[0]), default=str)
            resp = Response(response=results_json,
                            status=200,
                            mimetype="application/json")

    return resp

@app.route('/api/search')
def search():
    print(request.args)
    search = request.args.get('search')
    author = request.args.get('author')
    category = request.args.get('category')
    page = int(request.args.get('page')) if not request.args.get('page') is None else 1
    print(search)

    if search is None and author is None and category is None:
        myquery = Every()
    else:
        if search is None:
            if not author is None:
                myquery = Term('author',author)
                if not category is None:
                    myquery = myquery & Term('category',category)
            else:
                 myquery = Term('category',category)
        else:
            myquery = MultifieldParser(["title","post_content"], ix.schema, plugins=[FuzzyTermPlugin()]).parse(search)

            if not author is None:
                myquery = myquery & Term('author',author)

            if not category is None:
                myquery = myquery & Term('category',category)

    with ix.searcher() as searcher:
        results = searcher.search_page(myquery, page, pagelen=25, sortedby="date", reverse=True)
        print(results.is_last_page())
        results_json = json.dumps( {"results":[dict(i) for i in results], "page":page, "total_results":results.total}, default=str)

    resp = Response(response=results_json,
                    status=200,
                    mimetype="application/json")

    return resp

@app.route('/api/author_suggest/<string:name>')
def author_suggest(name):
    list_autocomplete, list_suggestions = author_name_suggestion(name)
    results_json = json.dumps({"list_autocomplete":list_autocomplete,"list_suggestions":list_suggestions})
    resp = Response(response=results_json,
                    status=200,
                    mimetype="application/json")

    return resp

'''
def search():
    keywords = request.args.get('search').split(" ")
    keyword_processor = KeywordProcessor()
    for k in keywords:
        keyword_processor.add_keyword(k)

    thread_list = []
    for link, thread in indexed_data.items():
        kw_title = keyword_processor.extract_keywords(thread["title"])
        n_kw_title = len(kw_title)

        kw_body = keyword_processor.extract_keywords(thread["post_content"])
        n_kw_body = len(kw_body)

        if n_kw_title + n_kw_body > 0:
            thread_list.append({
                "link":link,
                "title":thread["title"],
                "n_kw":len(set(kw_title+kw_body))
            })
    ordered_thread_list = sorted(thread_list, key=lambda k: k['n_kw'], reverse=True)

    return "".join(['
 '+i["title"]+'
' for i in ordered_thread_list[:20]])
'''

@app.route('/<string:u_path>')
def joker(u_path):
    return render_template('index.html')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5555, debug=True)


import time
import wave
import os
import pyaudio
import sys

v = '\033[32m'
vv = '\033[0;0m'
# instantiate PyAudio (1)
def logo():
    print(v + """

 |  __ \                        | |                 |__   __(_)
 | |__) |__  _ __ ___   ___   __| | ___  _ __ ___      | |   _ _ __ ___   ___ _ __  |Criado por: Corteisjr
 |  ___/ _ \| '_ ` _ \ / _ \ / _` |/ _ \| '__/ _ \     | |  | | '_ ` _ \ / _ \ '__| |Contacto: +258840109913
 | |  | (_) | | | | | | (_) | (_| | (_) | | | (_) |    | |  | | | | | | |  __/ |    |Blog: Corteistech.blogspot.com
 |_|   \___/|_| |_| |_|\___/ \__,_|\___/|_|  \___/     |_|  |_|_| |_| |_|\___|_|

    """ + vv)
def audio():
    ficheiro = wave.open(r"./sound.wav","rb")
    p = pyaudio.PyAudio()

    # define callback (2)
    def callback(in_data, frame_count, time_info, status):
        data = ficheiro.readframes(frame_count)
        return (data, pyaudio.paContinue)

    # open stream using callback (3)
    stream = p.open(format=p.get_format_from_width(ficheiro.getsampwidth()),
                    channels=ficheiro.getnchannels(),
                    rate=ficheiro.getframerate(),
                    output=True,
                    stream_callback=callback)

    # start the stream (4)
    stream.start_stream()

    # wait for stream to finish (5)
    while stream.is_active():
        time.sleep(0.1)

    # stop stream (6)
    stream.stop_stream()
    stream.close()
    ficheiro.close()

    # close PyAudio (7)
    p.terminate()

def tempo():
    tempo = input("Digite os minutos ou (HH:MM:SS): ")
    if ":" in tempo:
        t_list = tempo.split(":")
        if len(t_list) == 2:
            t = float(t_list[0]) + \
                float(t_list[1])/60.0
        elif len(t_list) == 3:
            t = float(t_list[0]) * 60 + \
                float(t_list[1]) + \
                float(t_list[2]) / 60.0
        else:
            print("Error. Time format should be MM:SS or HH:MM:SS.")
            os.exit()
    else:
        t = eval(tempo)
    return t
def timer(times):
    secs_remaining = int(times - time.time())
    hours = secs_remaining // 3600
    minutes = (secs_remaining - hours * 3600) // 60
    seconds = secs_remaining - hours * 3600 - minutes * 60
    return "{0:2s}:{1:2s}:{2:2s}".format(str(hours).zfill(2), str(minutes).zfill(2), str(seconds).zfill(2))

def loop(times):
    while time.time() < times - 1:
        os.system("clear")
        print(timer(times))
        time.sleep(1)
def main():
    t = tempo()
    times = time.time() + t*60 + 1
    loop(times)
    os.system("clear")
    lo = logo()
    print("00:00:00")
    time.sleep(2)
    print('\033[31m'+"\n\nSe nao decides tuas prioridades\n e quanto tempo dedicaras a elas, alguem decidira por ti!\n\n"+ '\033[0;0m')
    audio()

if __name__ == "__main__":
    main()


from db import db
import ast

class PrendasModel(db.Model):

    __tablename__ = 'prendas'

    id = db.Column(db.Integer, primary_key=True)
    tipo = db.Column(db.String(80))
    subtipo = db.Column(db.String(80))
    genero = db.Column(db.String(80))
    talla = db.Column(db.String(80))
    imagen = db.Column(db.String(500))
    precio = db.Column(db.String(80))
    cantidad = db.Column(db.String(80))
    especificacion = db.Column(db.String(300))
    caso_produccion = db.Column(db.String(80))
    estados_produccion = db.Column(db.String(400))
    area_responsable = db.Column(db.String(80))
    user_responsable = db.Column(db.String(80))
    empacado = db.Column(db.String(2))

    tiempos = db.relationship('TiemposModel', lazy='dynamic')

    orden_id = db.Column(db.Integer, db.ForeignKey('ordenes.id'))
    orden = db.relationship('OrdenesModel')

    def __init__(self, tipo, subtipo, genero, talla, imagen, precio, cantidad, especificacion, orden_id):
        self.tipo = tipo
        self.subtipo = subtipo
        self.genero = genero
        self.talla = talla
        self.imagen = imagen
        self.precio = precio
        self.cantidad = cantidad
        self.especificacion = especificacion
        self.orden_id = orden_id
        self.caso_produccion = ""
        self.estados_produccion = ""
        self.area_responsable = ""
        self.user_responsable = ""
        self.empacado = "no"

    def json(self):
        if self.estados_produccion == "":
            estados_produccion_dict = dict()
        else:
            estados_produccion_dict = ast.literal_eval(self.estados_produccion)
        return {
            "id": self.id,
            "tipo":self.tipo,
            "subtipo":self.subtipo,
            "genero":self.genero,
            "talla":self.talla,
            "imagen":self.imagen,
            "precio":self.precio,
            "cantidad":self.cantidad,
            "especificacion":self.especificacion,
            "orden_id":self.orden_id,
            "caso_produccion": self.caso_produccion,
            "estados_produccion": estados_produccion_dict,
            "area_responsable": self.area_responsable,
            "usuario_responsable": self.user_responsable,
            "empacado": self.empacado
        }

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()

    @classmethod
    def find_by_id(cls, _id):
        return cls.query.filter_by(id=_id).first()


# -*- coding: utf-8 -*-
"""
Created on Mon Oct  4 10:30:29 2021

@author: Youyang Shen
"""
import tifffile
import msi

path = r'C:\Users\Youyang Shen\OneDrive - Danmarks Tekniske Universitet\Study\special course\Images\1_20170410_151511_241.hips'

## read the image
image = msi.read(path)
## transfer to nparray
image = image.pixel_values
## save
tifffile.imsave("test.tiff",image)

path2 = r'..\Images\1_20170410_151511_241_Simple Threshold.hips'

seg = msi.read(path2)
seg = seg.pixel_values


import socket
import hashlib
import random
import rsa
from base64 import b64encode, b64decode
import urllib
import urllib.parse, urllib.request
import json
import requests
import datetime
from Crypto.PublicKey import RSA
import binascii
import time
import sys

def pause():
    try:
        input('Press enter to continue...')
    except SyntaxError:
        pass

def bin2hex(binStr):
    return binascii.hexlify(binStr)

def hex2bin(hexStr):
    return binascii.unhexlify(hexStr)

def send(txt):
    return s.send(txt.encode('utf-8'))
def recv():
    return s.recv(listen_port).decode('utf-8')

requested_amnt = 1 # TODO: This should be chosen by the user!

bank_url = 'http://104.199.121.149:8228'

# Generate keys
keysize = 2048
(public_key, private_key) = rsa.newkeys(keysize)

public_key_b64 = b64encode(public_key.exportKey('DER')).decode('utf-8')
public_key_hex = bin2hex(public_key.exportKey('DER')).decode('utf-8')

private_key_hex = bin2hex(private_key.exportKey('DER')).decode('utf-8')

print('Share this Base64 encoded public key with the payer: ')
print('\033[94m')
print(public_key_b64)
print('\033[0m')

pause()

s = socket.socket()
host = '104.199.121.149'
port = 1247
s.connect((host, port))

print('connected')

listen_port = 1024

# Make sure that I'm connected
assert recv() == 'awk.init'
print('awk.init')

# Announce who I am to the server
print('Connecting to server...')

# (Sign the timestamp to verify I own the key)
timestamp = str(time.time())
signature = b64encode(rsa.sign(timestamp.encode('utf-8'), private_key, 'SHA-256')).decode('utf-8')

# (Send public key along with signed timestamp as proof)
send(public_key_b64)
assert recv() == 'recv.public_key_b64'

send(timestamp)
assert recv() == 'recv.timestamp'

send(signature)
assert recv() == 'recv.signature'

assert recv() == 'awk.sig'

print('Connected')

# Tell the server that we want to upload our cheque for the payee
send('protocol.payee')
assert recv() == 'awk.protocol.payee'

send('awk.ready')

payer_public_key_b64 = input('What is the payer\'s Base64 public key? ')
payer_public_key_hex = bin2hex(b64decode(payer_public_key_b64)).decode('utf-8')

payer_coin_str_encrypted = recv()

if payer_coin_str_encrypted == 'None':
    print('The payer\'s coin has not been uploaded yet. Please wait a few minutes and try again when it is.')
    print('Payment cancelled.')
    sys.exit(1)
else:
    send('recv.payer_coin_str')

payer_coin_str = rsa.decrypt(b64decode(payer_coin_str_encrypted), private_key).decode('utf-8')

payer_amnt_str, payer_coin_nonce = payer_coin_str.split('_')
payer_amnt = float(payer_amnt_str)

# Verify the amount
if payer_amnt != requested_amnt:
    send('False')
    print('The payer sent {}. You requested {}.'.format(payer_amnt, requested_amnt))
    print('Payment cancelled.')
    sys.exit(1)

# # Verify that the payer owns the cheque
# if payer_public_key_hex != payer_coin_public_key_hex:
#     send('False')
#     print('The payer\'s public key does not match that of the coin they claim to own.')
#     print('Payment cancelled.')
#     sys.exit(1)

# Check that the cheque is in enough Banks
payer_coin_raw = payer_public_key_hex + '_' + payer_coin_nonce
payer_coin_hash = hashlib.sha256(payer_coin_raw.encode('utf-8')).hexdigest()
payer_cheque_raw = payer_amnt_str + '_' + payer_coin_hash
payer_cheque_hash = hashlib.sha256(payer_cheque_raw.encode('utf-8')).hexdigest()

response = requests.post(bank_url+'/check', json={
    'cheque_hash': payer_cheque_hash
})

print(response.text)

exists = bool(response.text)

if not exists:
    send('False')
    print('The payer claimed to own a coin that does not exist.')
    print('Payment cancelled.')
    sys.exit(1)

# Since no checks failed, this is probably legit
send('True')
assert recv() == 'awk.approval'
print('Response sent')

# Generate a new cheque
new_coin_nonce = str(random.randrange(1e16)).zfill(16)
new_coin_raw = public_key_hex + '_' + new_coin_nonce
new_coin_hash = hashlib.sha256(new_coin_raw.encode('utf-8')).hexdigest()
new_cheque_raw = payer_amnt_str + '_' + new_coin_hash

# Save the new cheque
with open("private_coin_storage.txt", "a+") as myfile:
    string  = payer_amnt_str + '\t'
    string += public_key_hex + '\t'
    string += new_coin_nonce + '\t'
    string += private_key_hex + '\n'
    myfile.write(string)

# Upload the new cheque encrypted using the payer's public key
payer_public_key = RSA.importKey(b64decode(payer_public_key_b64))

encrypted_cheque_str = b64encode(rsa.encrypt(new_cheque_raw.encode('utf-8'), payer_public_key)).decode('utf-8')

# Send the payee's cheque request to the server
print('sending encrypted_cheque_str')
send(encrypted_cheque_str)
print('sent')
assert recv() == 'recv.encrypted_cheque_str'
print('server awk\'ed')

# Send the payer's public key
print('sending payer_public_key_b64')
send(payer_public_key_b64)
print('public key sent')
assert recv() == 'recv.payer_public_key_b64'

print('Cheque request sent!')


import tensorflow as tf
import facenet

def inference(images, pool_type, use_lrn, keep_probability, phase_train=True):
  """ Define an inference network for face recognition based
         on inception modules using batch normalization

  Args:
    images: The images to run inference on, dimensions batch_size x height x width x channels
    phase_train: True if batch normalization should operate in training mode
  """
  conv1 = facenet.conv(images, 3, 64, 7, 7, 2, 2, 'SAME', 'conv1_7x7', phase_train=phase_train, use_batch_norm=True)
  pool1 = facenet.mpool(conv1,  3, 3, 2, 2, 'SAME')
  if use_lrn:
    lrn1 = tf.nn.local_response_normalization(pool1, depth_radius=5, bias=1.0, alpha=1e-4, beta=0.75)
  else:
    lrn1 = pool1
  conv2 = facenet.conv(lrn1,  64, 64, 1, 1, 1, 1, 'SAME', 'conv2_1x1', phase_train=phase_train, use_batch_norm=True)
  conv3 = facenet.conv(conv2,  64, 192, 3, 3, 1, 1, 'SAME', 'conv3_3x3', phase_train=phase_train, use_batch_norm=True)
  if use_lrn:
    lrn2 = tf.nn.local_response_normalization(conv3, depth_radius=5, bias=1.0, alpha=1e-4, beta=0.75)
  else:
    lrn2 = conv3
  pool3 = facenet.mpool(lrn2,  3, 3, 2, 2, 'SAME')

  incept3a = facenet.inception(pool3,    192, 1, 64, 96, 128, 16, 32, 3, 32, 1, 'MAX', 'incept3a', phase_train=phase_train, use_batch_norm=True)
  incept3b = facenet.inception(incept3a, 256, 1, 64, 96, 128, 32, 64, 3, 64, 1, pool_type, 'incept3b', phase_train=phase_train, use_batch_norm=True)
  incept3c = facenet.inception(incept3b, 320, 2, 0, 128, 256, 32, 64, 3, 0, 2, 'MAX', 'incept3c', phase_train=phase_train, use_batch_norm=True)

  incept4a = facenet.inception(incept3c, 640, 1, 256, 96, 192, 32, 64, 3, 128, 1, pool_type, 'incept4a', phase_train=phase_train, use_batch_norm=True)
  incept4b = facenet.inception(incept4a, 640, 1, 224, 112, 224, 32, 64, 3, 128, 1, pool_type, 'incept4b', phase_train=phase_train, use_batch_norm=True)
  incept4c = facenet.inception(incept4b, 640, 1, 192, 128, 256, 32, 64, 3, 128, 1, pool_type, 'incept4c', phase_train=phase_train, use_batch_norm=True)
  incept4d = facenet.inception(incept4c, 640, 1, 160, 144, 288, 32, 64, 3, 128, 1, pool_type, 'incept4d', phase_train=phase_train, use_batch_norm=True)
  incept4e = facenet.inception(incept4d, 640, 2, 0, 160, 256, 64, 128, 3, 0, 2, 'MAX', 'incept4e', phase_train=phase_train, use_batch_norm=True)

  incept5a = facenet.inception(incept4e,    1024, 1, 384, 192, 384, 0, 0, 3, 128, 1, pool_type, 'incept5a', phase_train=phase_train, use_batch_norm=True)
  incept5b = facenet.inception(incept5a, 896, 1, 384, 192, 384, 0, 0, 3, 128, 1, 'MAX', 'incept5b', phase_train=phase_train, use_batch_norm=True)
  pool6 = facenet.apool(incept5b,  3, 3, 1, 1, 'VALID')

  resh1 = tf.reshape(pool6, [-1, 896])
  affn1 = facenet.affine(resh1, 896, 128)
  dropout = tf.nn.dropout(affn1, keep_probability)
  norm = tf.nn.l2_normalize(dropout, 1, 1e-10, name='embeddings')

  return norm


import os
import os.path
from distutils.core import setup
from Cython.Build import cythonize
from distutils.extension import Extension

def main():
    scaling_potato_ext = create_scaling_potato_ext()

    setup(name="scaling_potato",
          ext_modules=scaling_potato_ext)

def create_scaling_potato_ext():
    sc = SourcesCollectorClass()

    cython_source = "./scaling_potato/scaling_potato_c/scaling_potato_c.pyx"

    sc.add_c_source_dir("./scaling_potato/scaling_potato_c/cpp_code")
    sc.add_include_dir("./scaling_potato/scaling_potato_c/cpp_code")

    # OpenCV Include
    # sc.add_library_dir(os.environ["OPENCV_LIB"])
    sc.add_include_dir(os.environ["OPENCV_INC"])
    sc.add_library("opencv_core")
    sc.add_library("opencv_imgproc")
    sc.add_library("opencv_imgcodecs")
    sc.add_library("opencv_highgui")
    sc.add_library("opencv_ml")
    sc.add_library("opencv_videoio")
    sc.add_library("opencv_video")
    sc.add_library("opencv_features2d")
    sc.add_library("opencv_calib3d")
    sc.add_library("opencv_objdetect")
    sc.add_library("opencv_flann")

    # Python include
    sc.add_include_dir("/usr/include/python2.7")

    # Panda3d include
    # sc.add_include_dir("/usr/include/panda3d")
    sc.add_library_dir("/usr/lib/x86_64-linux-gnu/panda3d")
    sc.add_library('p3framework')
    sc.add_library('panda')
    sc.add_library('pandafx')
    sc.add_library('pandaexpress')
    sc.add_library('p3dtoolconfig')
    sc.add_library('p3dtool')
    # sc.add_library('p3pystub')
    sc.add_library('p3direct')

    printb("scaling_potato_c")
    print("="*80)
    sc.print_lists()
    print('\n'*2)

    ext = None

    ext = Extension("scaling_potato.scaling_potato_c",
                    sources=[cython_source]+sc.c_sources_list,
                    include_dirs=sc.includes,
                    library_dirs=sc.lib_dirs,
                    libraries=sc.libraries,
                    language="c++",
                    extra_compile_args=["-g", "-std=c++11"], #, "/Od", "/MDd"], # for release version change /Od compile arg to /O2 (optimization for maximum speed)
                    # extra_link_args=["-debug"], # leave this enabled for release! :)))
                    define_macros = [('PYTHON_EXT', '1')]
                    )

    ext = cythonize([ext], gdb_debug=True)
    print('\n'*4)
    return ext

class SourcesCollectorClass(object):
    def __init__(self):
        self.c_sources_list = []
        self.cython_sources_list = []
        self.includes = []
        self.libraries = []
        self.lib_dirs = []

    def print_lists(self):
        print("Cython sources")
        for src in self.cython_sources_list:
            print(src)

        print('\nC sources')
        for src in self.c_sources_list:
            print(src)

        print('\nInclude directories')
        for src in self.includes:
            print(src)

        print('\nLibrary dirs')
        for src in self.lib_dirs:
            print(src)

        print('\nLibraries')
        for src in self.libraries:
            print(src)

    def add_library_dir(self, path):
        self.lib_dirs.append(path)

    def add_library(self, lib_name):
        self.libraries.append(lib_name)

    def add_include_dir(self, path):
        self.includes.append(os.path.abspath(path))

    def add_c_source(self, path):
        exts = ['.c', '.cpp']
        path = os.path.abspath(path)
        if os.path.isfile(path):
            ext = os.path.splitext(path)[1]
            if ext in exts:
                self.c_sources_list.append(path)

    def add_c_source_dir(self, path):
        for file in os.listdir(path):
            self.add_c_source(os.path.join(path, file))

    def add_cython_source(self, path):
        exts = ['.pyx'];
        path = os.path.abspath(path)
        if os.path.isfile(path):
            ext = os.path.splitext(path)[1]
            if ext in exts:
                self.cython_sources_list.append(path)

    def add_cython_source_dir(self, path):
        for root, _, files in os.walk(path):
            for file in files:
                self.add_cython_source(os.path.join(root, file))

try:
    from pyfiglet import Figlet
    figlet = Figlet(font='small')
except:
    figlet = None

def printb(s):
    if figlet is not None:
        print(figlet.renderText(s))
    else:
        print(s)

if __name__ == "__main__":
    main()


# import the necessary packages
import argparse
import cv2
import os
import csv
import tkinter as tk

# initialize the list of reference points and boolean indicating
refPt = []
pts_keep = []
keep = None
circleColour = None
lineColour = None

def getText():
    # Top level window
    frame = tk.Tk()
    frame.title("Keep or Remove?")
    frame.geometry('300x200')
    # Function for getting Input
    # from textbox and printing it
    # at label widget
    def printInput():
        global keep
        inp = inputtxt.get(1.0, "end-1c").strip()
        if (len(inp)) > 0:
            if inp.isdigit():
                if int(inp) == 0 or int(inp) == 1:
                    frame.destroy()
                    keep = int(inp)
                else:
                    lbl.config(text = "Please enter 0 / 1")
            else:
                lbl.config(text = "Please enter 0 / 1")

    # TextBox Creation
    inputtxt = tk.Text(frame,
                    height = 5,
                    width = 20)

    def callback(event):
        global keep
        inp = inputtxt.get(1.0, "end-1c").strip()
        if (len(inp)) > 0:
            if inp.isdigit():
                if int(inp) == 0 or int(inp) == 1:
                    frame.destroy()
                    keep = int(inp)
                else:
                    lbl.config(text = "Please enter 0 / 1")
            else:
                lbl.config(text = "Please enter 0 / 1")

    frame.bind('<Return>', callback)

    label = tk.Label(frame, text="Please enter 0 / 1: (0 = removed, 1= keep) ")
    label.pack()

    inputtxt.pack()

    lbl = tk.Label(frame, text="")
    lbl.pack()

    # Button Creation
    printButton = tk.Button(frame,
                            text = "OK",
                            command = printInput)
    printButton.pack()

    # Label Creation
    lbl = tk.Label(frame, text = "")
    lbl.pack()
    frame.mainloop()

def colourChange(keep):
    global circleColour, lineColour
    if keep:
        circleColour = (0, 255, 0)
        lineColour = (0, 255, 0)
    else:
        circleColour = (0, 0, 0)
        lineColour = (0, 0, 0)

def click_and_crop(event, x, y, flags, param):
	# grab references to the global variables
    global refPt
	# if the left mouse button was clicked, record the starting
	# (x, y) coordinates
    if event == cv2.EVENT_LBUTTONDOWN:
        if not refPt:
            getText()
            colourChange(keep)
        refPt.append((x, y))
        cv2.circle(image, (x, y), 5, circleColour, -1)
        if len(refPt) > 1:
            cv2.line(image, refPt[-2], refPt[-1], lineColour, 2)
	# check to see if the left mouse button was released
    if event == cv2.EVENT_RBUTTONDOWN:
        if len(refPt) > 1:
            cv2.line(image, refPt[-1], refPt[0], lineColour, 2)
        pts_keep.append((refPt, keep))
        refPt = []
    cv2.imshow("image", image)

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(ap.parse_args())
# load the image, clone it, and setup the mouse callback function
image = cv2.imread(args["image"])
clone = image.copy()
cv2.namedWindow("image")
cv2.setMouseCallback("image", click_and_crop)
# keep looping until the 'q' key is pressed
if not os.path.isfile('points.csv'):
    with open('points.csv', 'w', newline='') as f:
        writer = csv.writer(f)
        header = ['Image name', 'List of (Coordinates, Keep)']
        writer.writerow(header)
while True:
	# display the image and wait for a keypress
    cv2.imshow("image", image)
    key = cv2.waitKey(1) & 0xFF
	# if the 'r' key is pressed, reset the cropping region
    if key == ord("r"):
        image = clone.copy()
	# if the 'q' key is pressed, break from the loop
    elif key == ord("q"):
        imagename = os.path.split(args["image"])[-1]
        cv2.imwrite("Output/" + imagename, image)
        if len(pts_keep) > 0:
            with open('points.csv', 'a', newline='') as f:
                writer = csv.writer(f)
                row = [args["image"], pts_keep]
                writer.writerow(row)
        break

# close all open windows
cv2.destroyAllWindows()


import time
import copy
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms
import torchvision.models as models
import matplotlib.pyplot as plt
import numpy as np

# 先定義參數
input_size = 28         # 圖像的總尺寸 28 x 28
num_classes = 10        # 標籤的種類數
num_epochs = 3          # 訓練的總循環週期
batch_size = 64         # 一個批次的大小, 共64張圖片

# 訓練集
train_dataset = datasets.MNIST(root='./data',
                            train=True,
                            transform=transforms.ToTensor(),
                            download=True)

# 測試集
test_dataset = datasets.MNIST(root='./data',
                            train=False,
                            transform=transforms.ToTensor())

# 建構 batch 數據
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
                                            batch_size=batch_size,
                                            shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
                                            batch_size=batch_size,
                                            shuffle=True)

# 卷積神經網路構建
# 一般卷積層, relu層, 池化層可寫成一整套
# 卷積最後還是一個特徵圖, 需要把圖轉換成向量才能做分類或者回歸
class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv2d(
                in_channels=1,
                out_channels=16,
                kernel_size=5,
                stride=1,
                padding=2,),
                nn.ReLU(),
                nn.MaxPool2d(kernel_size=2),
        )
        self.conv2 = nn.Sequential(
            nn.Conv2d(16, 32, 5, 1, 2),
            nn.ReLU(),
            nn.MaxPool2d(2),
        )
        self.out = nn.Linear(32 * 7 * 7, 10)

    def forward(self, x):
        x = self.conv1(x)
        x = self.conv2(x)
        x = x.view(x.size(0), -1)
        output = self.out(x)
        return output

# 準確率做為評估標準
def accuracy(predictions, labels):
    pred = torch.max(predictions.data, 1)[1]
    rights = pred.eq(labels.data.view_as(pred)).sum()
    return rights, len(labels)

# 訓練網路模型======================================================
# 建立 CNN net
net = CNN()
# 損失函數
criterion = nn.CrossEntropyLoss()
# 優化器
optimizer = optim.Adam(net.parameters(), lr = 0.001)
# 訓練循環
for epoch in range(num_epochs):
    train_rights = []           # 將當前的 epoch 結果保留

    for batch_idx, (data, target) in enumerate(train_loader):
        net.train()
        output = net(data)
        loss = criterion(output, target)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        right = accuracy(output, target)

        if batch_idx % 100 == 0:

            net.eval()
            val_rights = []

            for (data, target) in test_loader:
                output = net(data)
                right = accuracy(output, target)
                val_rights.append(right)

            # 準確率計算
            train_r = (sum([tup[0] for tup in train_rights]), sum([tup[1] for tup in train_rights]))
            val_r = (sum([tup[0] for tup in val_rights]), sum([tup[1] for tup in val_rights]))

            print('當前 epoch: {} [{}/{} ({:.0f}%)]\t損失: {:.6f}\t訓練集準確率: {:.2f}%\t測試集準確率: {:.2f}%'.format(
                epoch, batch_idx*batch_size, len(train_loader.dataset),
                100.*batch_idx / len(train_loader),
                loss.data,
                100.*train_r[0].numpy() / train_r[1],
                100.*val_r[0].numpy() / val_r[1]))


from cgitb import text
from faulthandler import disable
from tkinter import*
from tkinter import ttk
from Conexion import *
ventana = Tk()
ventana.title("Desing Software")
ventana.geometry("1090x600")
marco=ttk.Labelframe(ventana, text="Formulario Control de Inventarios")
marco.place(x=15,y=10,width=1060,height=550)
#Clases
bd=conexion()
id1=StringVar()
id2=StringVar()
Nombres=StringVar()
Apellidos=StringVar()
Maq=StringVar()
#labelyentris

lblid1 = Label (marco,text="INGRESE ID UNICO DE IDENTIFICACION:").grid(column=0,row=0,padx=10, ipady=10)
txtid1=Entry(marco, textvariable=id1,width=30)
txtid1.grid(column=1,row=0)

lblid2 = Label (marco,text="INGRESE CEDULA O IDENTIFICACION:").grid(column=0,row=1,padx=10, ipady=10)
txtid2=Entry(marco, textvariable=id2,width=30)
txtid2.grid(column=1,row=1)

lblNombres = Label (marco,text="INGRESE UN NOMBRE:").grid(column=2,row=0,padx=10, ipady=10)
txtNombres=Entry(marco, textvariable=Nombres,width=50)
txtNombres.grid(column=3,row=0)

lblApellidos = Label (marco,text="INGRESE UN APELLIDO:").grid(column=2,row=1,padx=10, ipady=10)
txtApellidos=Entry(marco, textvariable=Apellidos,width=50)
txtApellidos.grid(column=3,row=1)

lblMaq = Label (marco,text="INGRESE LA HERRAMIENTA/MAQUINA:").grid(column=1,row=4)
txtMaq=Entry(marco, textvariable=Maq,width=50)
txtMaq.grid(column=3,row=4,ipady=30,)

txtmensaje= Label (marco,text="AQUI VA LO QUE REGISTRA  -----➤➤   ",fg="blue").grid(column=0,row=4,padx=10, ipady=10)
txtmensaje1= Label (marco,text="SELECCIONE UNA ACCION   ",fg="blue")
txtmensaje1.grid(column=0,row=6)

#aqui va la tabla de entrada
tvTablaDatosSoft=ttk.Treeview(marco)
tvTablaDatosSoft.grid(column=0,row=15,columnspan=4,padx=10)
tvTablaDatosSoft["columns"]=("id1","id2","Maq","Nombres","Apellidos")

#columnas y tablas editos
tvTablaDatosSoft.column("#0",width=0, stretch=NO)
tvTablaDatosSoft.column("id1",width=200, anchor=CENTER)
tvTablaDatosSoft.column("id2",width=200, anchor=CENTER)
tvTablaDatosSoft.column("Maq",width=200, anchor=CENTER)
tvTablaDatosSoft.column("Nombres",width=200, anchor=CENTER)
tvTablaDatosSoft.column("Apellidos",width=200, anchor=CENTER)
tvTablaDatosSoft.heading("#0",text="")
tvTablaDatosSoft.heading("id1",text="ID UNICO")
tvTablaDatosSoft.heading("id2",text="CEDULA IDENTIFICACION")
tvTablaDatosSoft.heading("Maq",text="MAQUINA O HERRAMIENTA")
tvTablaDatosSoft.heading("Nombres",text="NOMBRES")
tvTablaDatosSoft.heading("Apellidos",text="APELLIDOS")

 #Funciones
def vaciar_tabla():
   filas= tvTablaDatosSoft.get_children()
   for fila in filas:
      tvTablaDatosSoft.delete(fila)
def llenar_tabla():
   vaciar_tabla()
   sql="select * from desingtable"
   bd.cursor.execute(sql)
   filas=bd.cursor.fetchall()
   for fila in filas:
      id1=fila[0]
      tvTablaDatosSoft.insert("", END,id1,text=id1, values=fila)
   pass

def eliminar():
    id1=tvTablaDatosSoft.selection()[0]
    if int(id1) > 0:
        sql="delete from desingtable where id1="+id1
        bd.cursor.execute(sql)
        bd.connection.commit()
        tvTablaDatosSoft.delete(id1)
        txtmensaje1.config(text="SE HA ELIMINADO REGISTRO CORRECTAMENTE!")
    else:
        txtmensaje1.config(text="SELECCIONE UN REGISTRO PARA ELIMINAR!")
    pass

def modificar():
 pass
def agregar():

        val=(id1.get(),id2.get(),Nombres.get(),Apellidos.get(),Maq.get())
        sql="insert into desingtable (id1, id2, Nombres, Apellidos, Maq) values (%s, %s, %s, %s, %s)"
        bd.cursor.execute(sql, val)
        bd.connection.commit()
        txtmensaje1.config(text="SE HA CREADO REGISTRO CORRECTAMENTE!",fg="green")

        llenar_tabla()

def buscar():
   pass

#botenonera
#btnBuscar= Button(marco, text="Buscar Informacion", command=lambda:buscar())
#btnBuscar.grid(column=0, row=20)

btnEliminar= Button(marco, text="Eliminar Informacion", command=lambda:eliminar())
btnEliminar.grid(column=1, row=20)

btnModificar= Button(marco, text="Modificar la Informacion", command=lambda:modificar())
btnModificar.grid(column=2, row=20)

btnAgregar= Button(marco, text="Agregar nueva Informacion", command=lambda:agregar())
btnAgregar.grid(column=3, row=20)

llenar_tabla()
ventana.mainloop()

#frm = ttk.Frame(root, padding=10)
#frm.grid()
#ttk.Label(frm, text="Hello World!").grid(column=0, row=0)
#ttk.Button(frm, text="Quit", command=root.destroy).grid(column=1, row=0)


# using the sorted() method to produce a list of keys
fruit = {"pear":2, "banana":3, "orange":5}
ranked = sorted(fruit)
print(ranked)

# using the keys() method to produce a list of keys
produce = fruit.keys()
produce = list(produce)
print(produce)

# producing an exact, distinct clone of a dictionary
citrus = fruit.copy()
print(citrus)

# using the values() method to produce a list of values
quantity = fruit.values()
quantity = list(quantity)
print(quantity)

# producing a list consisting of all the key-value pairs
inventory = fruit.items()
inventory = list(inventory)
print(inventory)


from django.contrib import admin
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.conf import settings
from main import views

urlpatterns = [
	url(r'^$', views.home_view, name='homepage'),
	url(r'^404-not-found/$', views.ErrorNotFound_view, name='404NotFound'),
	url('admin/', admin.site.urls),
	url(r'^accounts/', include('accounts.urls')),
	url(r'^comments/', include('comments.urls')),
	url(r'^contact-us/$', views.contactUs_view, name='contact-us'),
	url(r'^notifications/$', views.notifications_view, name='notifications'),
	url(r'^notifications/(?P<pk>[0-9]+)/$', views.notificationStatus_view, name='notf-seen'),
	url(r'^posts/', include('posts.urls')),
	url(r'^search/$', views.search_view, name='search'),
	url(r'^valildatename/$', views.valildateName_view, name='valildate-name'),
	url(r'^valildateemail/$', views.valildateEmail_view, name='valildate-email'),
	url(r'^valildatepassword/$', views.valildatePassword_view, name='valildate-password'),

]

"""
if settings.DEBUG:
    urlpatterns += (static(settings.STATIC_URL, document_root=settings.STATIC_ROOT))
    urlpatterns += (static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT))
"""


import re

def hasABBA(line):
    for i in range(len(line)-3):
        if line[i] == line[i+3] and line[i+1] == line[i+2] and line[i] != line[i+1]:
            return True
    return False

def findABA(line):
    aba = []
    for i in range(len(line)-2):
        if line[i] == line[i+2] and line[i] != line[i+1]:
            aba.append(line[i:i+3])
    return aba

part1 = part2 = 0
for line in open("Resources/input7.txt"):
    spl = re.split(r'\[|\]', line.strip())
    foundPart1Out = foundPart1In = False
    abaOutside = []
    abaInside = []
    for i in range(len(spl)):
        if i % 2 == 0:
            abaOutside.extend(findABA(spl[i]))
            if not foundPart1Out and i % 2 == 0 and hasABBA(spl[i]):
                foundPart1Out = True
        else:
            abaInside.extend(findABA(spl[i]))
            if hasABBA(spl[i]):
                foundPart1In = True

    if foundPart1Out and not foundPart1In:
        part1 += 1

    foundPart2 = False
    for bab in abaInside:
        aba = bab[1]+bab[0]+bab[1]
        if aba in abaOutside:
            foundPart2 = True
            break
    if foundPart2:
        part2 += 1
print("Part 1:",part1,"\nPart 2:",part2)


import random

def main():
    print("Keep it logically awesome.")

    f = open('quotes.txt', 'a')
    f.write('Hello\n')
    f.close()

    f = open("quotes.txt")
    quotes = f.readlines()
    f.close()

    last01 = 13
    last02 = 13
    rnd01 = random.randint(0, last01)
    rnd02 = random.randint(0, last02)

    print(quotes[rnd01].rstrip())
    print(quotes[rnd02])

if __name__ == "__main__":
    main()


"""
0x0A 转义为 0x12 0x34 两个字节， 0x0B 转义为 0xAB 0xCD 两字节，输出转义后的字节序列（第一个字节为长度）

8 1 2 3 4 5 6 A
9 1 2 3 4 5 6 12 34
"""
arr = list(input().split())

cnt = len(arr)
for i in range(1, len(arr)):
    if arr[i] == 'A':
        arr[i] = '12 34'
        cnt += 1
    elif arr[i] == 'B':
        arr[i] = 'AB CD'
        cnt += 1
print("%X" % cnt, " ".join(arr[1:]))


__all__ = [
    'CLN', 'BOLD',
    'BLACK', 'DARK_BLUE', 'DARK_GREEN', 'DARK_AQUA', 'DARK_RED', 'DARK_PURPLE',
    'GOLD', 'GRAY', 'DARK_GRAY', 'BLUE', 'GREEN', 'AQUA', 'RED', 'LIGHT_PURPLE',
    'YELLOW', 'WHITE',
    'COLOR_CODE', 'RARITY_COLORS', 'STAT_COLORS', 'CRIT_COLORS',
]

CLN = '\x1b[0m'
BOLD = '\x1b[1m'

BLACK = '\x1b[0;38;2;0;0;0m'
DARK_BLUE = '\x1b[0;38;2;0;0;170m'
DARK_GREEN = '\x1b[0;38;2;0;170;0m'
DARK_AQUA = '\x1b[0;38;2;0;170;170m'
DARK_RED = '\x1b[0;38;2;170;0;0m'
DARK_PURPLE = '\x1b[0;38;2;170;0;170m'
GOLD = '\x1b[0;38;2;255;170;0m'
GRAY = '\x1b[0;38;2;170;170;170m'
DARK_GRAY = '\x1b[0;38;2;85;85;85m'
BLUE = '\x1b[0;38;2;85;85;255m'
GREEN = '\x1b[0;38;2;85;255;85m'
AQUA = '\x1b[0;38;2;85;255;255m'
RED = '\x1b[0;38;2;255;85;85m'
LIGHT_PURPLE = '\x1b[0;38;2;255;85;255m'
YELLOW = '\x1b[0;38;2;255;255;85m'
WHITE = '\x1b[0;38;2;255;255;255m'

COLOR_CODE = {}
for color in ('bold', 'black', 'dark_blue', 'dark_green', 'dark_aqua',
              'dark_red', 'dark_purple', 'gold', 'gray', 'dark_gray', 'blue',
              'green', 'aqua', 'red', 'light_purple', 'yellow', 'white'):
    COLOR_CODE[color] = globals()[color.upper()]

RARITY_COLORS = {
    'common': f'{BOLD}{WHITE}',
    'uncommon': f'{BOLD}{GREEN}',
    'rare': f'{BOLD}{BLUE}',
    'epic': f'{BOLD}{DARK_PURPLE}',
    'legendary': f'{BOLD}{GOLD}',
    'mythic': f'{BOLD}{LIGHT_PURPLE}',
    'supreme': f'{BOLD}{DARK_RED}',
    'special': f'{BOLD}{RED}',
    'very_special': f'{BOLD}{RED}',

    'rngesus': f'{BOLD}{LIGHT_PURPLE}',
    'pray_rngesus': f'{BOLD}{LIGHT_PURPLE}',

    'good_catch': f'{BOLD}{GREEN}',
    'great_catch': f'{BOLD}{LIGHT_PURPLE}',
}

STAT_COLORS = {
    'health': f'{RED}❤',
    'damage': f'{RED}❁',
    'defense': f'{GREEN}❈',
    'ehp': f'{DARK_AQUA}❤',
    'true_defense': f'{WHITE}❂',
    'strength': f'{RED}❁',
    'speed': f'{WHITE}✦',
    'crit_chance': f'{BLUE}☣',
    'crit_damage': f'{BLUE}☠',
    'intelligence': f'{AQUA}✎',
    'mining_speed': f'{GOLD}⸕',
    'attack_speed': f'{YELLOW}⚔',
    'sea_creature_chance': f'{DARK_AQUA}α',
    'magic_find': f'{AQUA}✯',
    'pet_luck': f'{LIGHT_PURPLE}♣',
    'ability_damage': f'{RED}๑',
    'ferocity': f'{RED}⫽',
    'mining_fortune': f'{GOLD}☘',
    'farming_fortune': f'{GOLD}☘',
    'foraging_fortune': f'{GOLD}☘',
}

CRIT_COLORS = WHITE, YELLOW, GOLD, RED, RED, WHITE


# The module to control the file tab for UCOUNTER
# Author - Alistair McLean
# ----------------------------------------
# This tab handles the functionality to allow the
# user to control which files they wish to analyze

# TODO
# - Improve the color selection
# - Add auto thresholding of the image
# -
# -

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.factory import Factory
from kivy.adapters.listadapter import ListAdapter
from kivy.uix.listview import ListItemButton
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.properties import ObjectProperty
from kivy.uix.popup import Popup
from kivy.config import Config
from src.analyzer.analyzer import Analyzer
from tkinter.filedialog import askopenfilename
import tkinter as tk
import numpy as np
import ntpath
import os
import cv2

# Window configurations
Config.set('kivy', 'window_icon', 'src/res/Analyze.png')
Config.set('graphics', 'width', '1000')
Config.set('graphics', 'height', '500')
Config.set('graphics', 'resizable', False)

# LEFTOFF NOTES
# - Trying to make the buttons change color from hsv to
# - Need to fix the color mode picker, or at least how the analyzer is interpretting the values

class LoadDialog(FloatLayout):
	load = ObjectProperty(None)
	cancel = ObjectProperty(None)

class Root(FloatLayout):
	loadfile = ObjectProperty(None)
	loadString = "Press Load to select a file you wish to analyze."
	hasLowColor = False
	hasHighColor = False

	def startup(self):
		self.hasLowColor = False # Figure out better logic for this
		self.hasHighColor = False # Figure out better logic for this

	def dismiss_popup(self):
		if self._popup:
			self._popup.dismiss()

	def show_load(self):
#		content = LoadDialog(load=self.load,
#							cancel=self.dismiss_popup)
#		self._popup = Popup(title="Load file", content=content,
#							size_hint=(0.9,0.9))
#		self._popup.open()
		root = tk.Tk()
		root.withdraw()
		self.filename = askopenfilename()
		if self.filename:
			self.load(self.filename)
			root.destroy()

	def colorPicker(self):
		# When the button is pressed activate this widget
	    clr_picker = ColorPicker()
	    # Add widget to the Analyzer pane.
	    #self.ids.analyze_tab.add_widget(clr_picker)

	    # To monitor changes, we can bind to color property changes

	    clr_picker.bind(color=self.on_color)

	def on_color(instance, value):
	        print ("RGBA = ", str(value))  #  or instance.color
	        print ("HSV = ", str(instance.hsv))
	        print ("HEX = ", str(instance.hex_color))
#	    	return instance.hsv

	def load(self, filename):
		self.filename = filename
		if filename:
#			fname = ntpath.basename(filename[0])
			fname = ntpath.basename(filename)
		else:
			return

		# TODO - add a check to make sure that it is an image extension!!!!
		self.loadString = str('{} loaded.\nPlease select the settings for the organism you wish to analyze.'.format(fname))
		self.ids.load_text.text = self.loadString
		#self.ids.load_image.source = filename[0]
		self.ids.load_image.source = filename

		# ENABLE Analyzer
		self.ids.analyze_tab.disabled = False
		#self.dismiss_popup()

	def analyze(self):
#		self.analyzer = bioAnalyzer(self.filename[0])
#		fname = ntpath.basename(self.filename[0])
		if self.hasHighColor != True and self.hasLowColor != True:
			self.loadString = str('Please select the low and high color thresholds for the image.')
			self.ids.load_text.text = self.loadString
			return
		self.analyzer = Analyzer(self.filename)
		fname = ntpath.basename(self.filename)
		# Get the values from the UI
		# Name
		organismName = self.ids.name_input.text
		# TODO - VALIDATE
		# Size
		sizeRange = [int(self.ids.low_size_input.text), int(self.ids.high_size_input.text)]
		# TODO - VALIDATE

		# Color Range
		colorRange = [self.lowColor, self.highColor]
		# TODO - VALIDATE
		self.loadString = str('Analyzing {} '.format(fname))
		self.ids.load_text.text = self.loadString
		self.analyzer.analyzeOrganism(organismName, sizeRange, colorRange)
		self.loadString = str('Finished analyzing {}\n'.format(fname) +
							  'Select a new file, or analyze again with new settings.')
		self.ids.load_text.text = self.loadString

	def selectLowColor(self):
		self.lowColor = self.selectColor()
		if self.loc:
			kivyColor = self.img[self.loc[-1][0],self.loc[-1][1]]
			kivyColor = (kivyColor[2] / 255, kivyColor[1] / 255, kivyColor[0] / 255, 1)
			self.ids.low_color.background_color = kivyColor
			self.hasLowColor = True

	def selectHighColor(self):
		self.highColor = self.selectColor()
		if self.loc:
			kivyColor = self.img[self.loc[-1][0],self.loc[-1][1]]
			kivyColor = (kivyColor[2] / 255, kivyColor[1] / 255, kivyColor[0] / 255, 1)
			self.ids.high_color.background_color = kivyColor
			self.hasHighColor = True

	## DEBUG ##
	def test(self):
		self.analyzer = Analyzer(self.filename)
		l_red = np.array([0, 97, 30]) # THESE STILL NEED MASSAGING
		u_red = np.array([10, 255, 255]) # THESE STILL NEED MASSAGING
		size = [5, 20]
		color = [l_red, u_red]
		organism = "herpaderp"
		self.analyzer.analyzeOrganism(organism, size, color)

	def selectColor(self):
#		self.img = cv2.imread(self.filename[0])
		self.img = cv2.imread(self.filename)
		hsv = cv2.cvtColor(self.img, cv2.COLOR_BGR2HSV)
		self.colors = []
		self.loc = []
		while True:
			cv2.imshow('Source', self.img)
			cv2.setMouseCallback('Source', self.on_mouse_click, self.img)
			if cv2.waitKey(0):
				break
		cv2.destroyAllWindows()
		if self.loc:
			return hsv[self.loc[-1][0], self.loc[-1][1]]
#		if self.colors:
#			return self.colors[-1]
		else:
			return None

	def on_mouse_click (self, event, x, y, flags, frame):
		if event == cv2.EVENT_LBUTTONUP:
#			self.colors.append(frame[y,x].tolist())
			self.loc.append([y,x])
		elif event == cv2.EVENT_MOUSEMOVE:
			self.displayZoomedBoxWithIcon(x,y,frame,4)

	def displayZoomedBoxWithIcon(self, x, y, frame, zoom=12):
		height, width = frame.shape[:2]
		verticalPadding = int(0.1 * height)
		horizontalPadding = int(0.1 * width)
		windowSize = 30
		# Check if the x and y are greater than a certain percent
		# And auto position the display
		# Crop the frame
		crop = frame[(y - windowSize):(y + windowSize),
					 (x - windowSize):(x + windowSize)]
		cHeight, cWidth = crop.shape[:2]
		# Enlarge the croppage
		res = cv2.resize(crop,(zoom*cWidth, zoom*cHeight), interpolation = cv2.INTER_CUBIC)
		hsv = cv2.cvtColor(res, cv2.COLOR_BGR2HSV)
		res = self.drawCrosshair(res,50)

		px = hsv[int(cHeight/2), int(cWidth/2)]

		# Display update text on zoom box
		# - Location, Color:
		message = str('Location:({},{}) HSV: {:2}'.format(x,y,str(px)))
		font = cv2.FONT_HERSHEY_SIMPLEX
		bottomLeftCornerOfText = (10,100)
		fontScale = 1
		fontColor = (255,255,255)
		lineType = 2
#		cv2.putText(res, message, bottomLeftCornerOfText, fontScale, fontColor, lineType)

		# TODO - figure out a way to put this on the img.
		cv2.imshow('zoom', res)
		#return res

	def drawCrosshair(self, frame, lineLength):
		res = frame
		rHeight, rWidth = res.shape[:2]
		rHalfH = int(rHeight / 2)
		rHalfW = int(rWidth/ 2)

		#Black outline
		res = cv2.line(res, (rHalfH - lineLength, rHalfW), (rHalfH + lineLength, rHalfW), (0,0,0), 4)
		res = cv2.line(res, (rHalfH, rHalfW - lineLength), (rHalfH, rHalfW + lineLength), (0,0,0), 4)

		#White infil
		res = cv2.line(res, (rHalfH - lineLength, rHalfW), (rHalfH + lineLength, rHalfW), (255,255,255), 2)
		res = cv2.line(res, (rHalfH, rHalfW - lineLength), (rHalfH, rHalfW + lineLength), (255,255,255), 2)
		res[rHalfW-4:rHalfW+4, rHalfH-4:rHalfH+4] = frame[rHalfW-4:rHalfW+4, rHalfH-4:rHalfH+4]
		return res

	def on_mouse_move (self, event, x, y, flags, frame):
		# Create a rectangle which displays
		# a local zoomed portion of the
		# original image, near the mouse position
		pass

class BioFrame(App):
	def build(self):
		self.title = "microCounter v0.5a" # v0.5a @ 04-15-2018
	Root().startup()

Factory.register('Root', cls=Root)


# -*- coding: utf-8 -*-
"""
Created on Tue Jul 28 22:40:49 2020

@author: Administer
"""

import sys, os, re

def TriNcleotideComposition(sequence, base):
    trincleotides = [nn1 + nn2 + nn3 for nn1 in base for nn2 in base for nn3 in base]
    tnc_dict = {}
    for triN in trincleotides:
        tnc_dict[triN] = 0
    for i in range(len(sequence) - 2):
        tnc_dict[sequence[i:i + 3]] += 1
    for key in tnc_dict:
       tnc_dict[key] /= (len(sequence) - 2)
    return tnc_dict

def PseEIIP(fastas, **kw):
    for i in fastas:
        if re.search('[^ACGT-]', i[1]):
            print('Error: illegal character included in the fasta sequences, only the "ACGT-" are allowed by this PseEIIP scheme.')
            return 0

    base = 'ACGT'

    EIIP_dict = {
        'A': 0.1260,
        'C': 0.1340,
        'G': 0.0806,
        'T': 0.1335,
    }

    trincleotides = [nn1 + nn2 + nn3 for nn1 in base for nn2 in base for nn3 in base]
    EIIPxyz = {}
    for triN in trincleotides:
        EIIPxyz[triN] = EIIP_dict[triN[0]] + EIIP_dict[triN[1]] + EIIP_dict[triN[2]]

    encodings = []
    header = ['#'] + trincleotides
    encodings.append(header)

    for i in fastas:
        name, sequence = i[0], re.sub('-', '', i[1])
        code = [name]
        trincleotide_frequency = TriNcleotideComposition(sequence, base)
        code = code + [EIIPxyz[triN] * trincleotide_frequency[triN] for triN in trincleotides]
        encodings.append(code)
    return encodings

def PseEIIP_feature(fastas):
    import sequence_read_save
    encodings = PseEIIP(fastas)
    sequence_read_save.save_to_csv(encodings, "./features/PseEIIP.csv")

if __name__ == '__main__':
    import os
    import sequence_read_save
    os.chdir('C:/Users/Administer/Desktop/DeepAc4C-master/')
    fastas = sequence_read_save.read_nucleotide_sequences("./sequence/input.fasta")
    PseEIIP_feature(fastas)