import torch
import torch.nn as nn
from utils.resnet_infomin import model_dict
import torch.nn.functional as F
from collections import OrderedDict

class RGBSingleHead(nn.Module):
    """RGB model with a single linear/mlp projection head"""
    def __init__(self, name='resnet50', head='linear', feat_dim=128):
        super(RGBSingleHead, self).__init__()

        name, width = self._parse_width(name)
        dim_in = int(2048 * width)
        self.width = width

        self.encoder = model_dict[name](width=width)

        if head == 'linear':
            self.head = nn.Sequential(
                nn.Linear(dim_in, feat_dim),
                Normalize(2)
            )
        elif head == 'mlp':
            self.head = nn.Sequential(
                nn.Linear(dim_in, dim_in),
                nn.ReLU(inplace=True),
                nn.Linear(dim_in, feat_dim),
                Normalize(2)
            )
        else:
            raise NotImplementedError(
                'head not supported: {}'.format(head))

    @staticmethod
    def _parse_width(name):
        if name.endswith('x4'):
            return name[:-2], 4
        elif name.endswith('x2'):
            return name[:-2], 2
        else:
            return name, 1

    def forward(self, x, mode=0):
        # mode --
        # 0: normal encoder,
        # 1: momentum encoder,
        # 2: testing mode
        feat = self.encoder(x)
        if mode == 0 or mode == 1:
            feat = self.head(feat)
        return feat

class RGBMultiHeads(RGBSingleHead):
    """RGB model with Multiple linear/mlp projection heads"""
    def __init__(self, name='resnet50', head='linear', feat_dim=128):
        super(RGBMultiHeads, self).__init__(name, head, feat_dim)

        self.head_jig = JigsawHead(dim_in=int(2048*self.width),
                                   dim_out=feat_dim,
                                   head=head)

    def forward(self, x, x_jig=None, mode=0):
        # mode --
        # 0: normal encoder,
        # 1: momentum encoder,
        # 2: testing mode
        if mode == 0:
            feat = self.head(self.encoder(x))
            feat_jig = self.head_jig(self.encoder(x_jig))
            return feat, feat_jig
        elif mode == 1:
            feat = self.head(self.encoder(x))
            return feat
        else:
            feat = self.encoder(x)
            return feat

class CMCSingleHead(nn.Module):
    """CMC model with a single linear/mlp projection head"""
    def __init__(self, name='resnet50', head='linear', feat_dim=128):
        super(CMCSingleHead, self).__init__()

        name, width = self._parse_width(name)
        dim_in = int(2048 * width)
        self.width = width

        self.encoder1 = model_dict[name](width=width, in_channel=1)
        self.encoder2 = model_dict[name](width=width, in_channel=2)

        if head == 'linear':
            self.head1 = nn.Sequential(
                nn.Linear(dim_in, feat_dim),
                Normalize(2)
            )
            self.head2 = nn.Sequential(
                nn.Linear(dim_in, feat_dim),
                Normalize(2)
            )
        elif head == 'mlp':
            self.head1 = nn.Sequential(
                nn.Linear(dim_in, dim_in),
                nn.ReLU(inplace=True),
                nn.Linear(dim_in, feat_dim),
                Normalize(2)
            )
            self.head2 = nn.Sequential(
                nn.Linear(dim_in, dim_in),
                nn.ReLU(inplace=True),
                nn.Linear(dim_in, feat_dim),
                Normalize(2)
            )
        else:
            raise NotImplementedError(
                'head not supported: {}'.format(head))

    @staticmethod
    def _parse_width(name):
        if name.endswith('x4'):
            return name[:-2], 2
        elif name.endswith('x2'):
            return name[:-2], 1
        else:
            return name, 0.5

    def forward(self, x, mode=0):
        # mode --
        # 0: normal encoder,
        # 1: momentum encoder,
        # 2: testing mode
        x1, x2 = torch.split(x, [1, 2], dim=1)
        feat1 = self.encoder1(x1)
        feat2 = self.encoder2(x2)
        if mode == 0 or mode == 1:
            feat1 = self.head1(feat1)
            feat2 = self.head2(feat2)
        return torch.cat((feat1, feat2), dim=1)

class CMCMultiHeads(CMCSingleHead):
    """CMC model with Multiple linear/mlp projection heads"""
    def __init__(self, name='resnet50', head='linear', feat_dim=128):
        super(CMCMultiHeads, self).__init__(name, head, feat_dim)

        self.head1_jig = JigsawHead(dim_in=int(2048*self.width),
                                    dim_out=feat_dim,
                                    head=head)
        self.head2_jig = JigsawHead(dim_in=int(2048*self.width),
                                    dim_out=feat_dim,
                                    head=head)

    def forward(self, x, x_jig=None, mode=0):
        # mode --
        # 0: normal encoder,
        # 1: momentum encoder,
        # 2: testing mode
        x1, x2 = torch.split(x, [1, 2], dim=1)
        feat1 = self.encoder1(x1)
        feat2 = self.encoder2(x2)

        if mode == 0:
            x1_jig, x2_jig = torch.split(x_jig, [1, 2], dim=1)
            feat1_jig = self.encoder1(x1_jig)
            feat2_jig = self.encoder2(x2_jig)

            feat1, feat2 = self.head1(feat1), self.head2(feat2)
            feat1_jig = self.head1_jig(feat1_jig)
            feat2_jig = self.head2_jig(feat2_jig)
            feat = torch.cat((feat1, feat2), dim=1)
            feat_jig = torch.cat((feat1_jig, feat2_jig), dim=1)
            return feat, feat_jig
        elif mode == 1:
            feat1, feat2 = self.head1(feat1), self.head2(feat2)
            return torch.cat((feat1, feat2), dim=1)
        else:
            return torch.cat((feat1, feat2), dim=1)

class Normalize(nn.Module):
    def __init__(self, p=2):
        super(Normalize, self).__init__()
        self.p = p

    def forward(self, x):
        return F.normalize(x, p=self.p, dim=1)

class JigsawHead(nn.Module):
    """Jigswa + linear + l2norm"""
    def __init__(self, dim_in, dim_out, k=9, head='linear'):
        super(JigsawHead, self).__init__()

        if head == 'linear':
            self.fc1 = nn.Linear(dim_in, dim_out)
        elif head == 'mlp':
            self.fc1 = nn.Sequential(
                nn.Linear(dim_in, dim_in),
                nn.ReLU(inplace=True),
                nn.Linear(dim_in, dim_out),
            )
        else:
            raise NotImplementedError('JigSaw head not supported: {}'.format(head))
        self.fc2 = nn.Linear(dim_out * k, dim_out)
        self.l2norm = Normalize(2)
        self.k = k

    def forward(self, x):
        bsz = x.shape[0]
        x = self.fc1(x)
        # ==== shuffle ====
        # this step can be moved to data processing step
        shuffle_ids = self.get_shuffle_ids(bsz)
        x = x[shuffle_ids]
        # ==== shuffle ====
        n_img = int(bsz / self.k)
        x = x.view(n_img, -1)
        x = self.fc2(x)
        x = self.l2norm(x)
        return x

    def get_shuffle_ids(self, bsz):
        n_img = int(bsz / self.k)
        rnd_ids = [torch.randperm(self.k) for i in range(n_img)]
        rnd_ids = torch.cat(rnd_ids, dim=0)
        base_ids = torch.arange(bsz)
        base_ids = torch.div(base_ids, self.k).long()
        base_ids = base_ids * self.k
        shuffle_ids = rnd_ids + base_ids
        return shuffle_ids

#default settings taken from https://github.com/HobbitLong/PyContrast/tree/master/pycontrast
OPT = {'method': 'InfoMin',
        'modal': 'RGB',
        'jigsaw': True,
        'mem': 'moco',
        'arch': 'resnet50',
        'feat_dim': 128,
        'head': 'mlp',
        'ckpt': '/experimentos/pesos/infomin/InfoMin_800.pth', #custom path
        'aug_linear': 'NULL',
        'n_class': 1000,
        'aug': 'D'}

NAME_TO_FUNC = {
    'RGBSin': RGBSingleHead,
    'RGBMul': RGBMultiHeads,
    'CMCSin': CMCSingleHead,
    'CMCMul': CMCMultiHeads,
}

def load_encoder_weights(model):
        """load pre-trained weights for encoder

        Args:
          model: pretrained encoder, should be frozen
        """
        msg = "Empty Message"
        if OPT['ckpt']:
            ckpt = torch.load(OPT['ckpt'], map_location='cpu')
            state_dict = ckpt['model']
            if OPT['modal'] == 'RGB':
                # Unimodal (RGB) case
                encoder_state_dict = OrderedDict()
                for k, v in state_dict.items():
                    k = k.replace('module.', '')
                    if 'encoder' in k:
                        k = k.replace('encoder.', '')
                        encoder_state_dict[k] = v
                msg = model.encoder.load_state_dict(encoder_state_dict)
            else:
                # Multimodal (CMC) case
                encoder1_state_dict = OrderedDict()
                encoder2_state_dict = OrderedDict()
                for k, v in state_dict.items():
                    k = k.replace('module.', '')
                    if 'encoder1' in k:
                        k = k.replace('encoder1.', '')
                        encoder1_state_dict[k] = v
                    if 'encoder2' in k:
                        k = k.replace('encoder2.', '')
                        encoder2_state_dict[k] = v
                msg = model.encoder1.load_state_dict(encoder1_state_dict)
                msg += " " + model.encoder2.load_state_dict(encoder2_state_dict)
            print('Pre-trained weights loaded!', msg)
        else:
            print('==============================')
            print('warning: no pre-trained model!')
            print('==============================')
            msg = "warning: no pre-trained model!"

        return model, msg

def build_model():
    # specify modal key
    branch = 'Mul' if OPT['jigsaw'] else 'Sin'
    model_key = OPT['modal'] + branch

    model = NAME_TO_FUNC[model_key](OPT['arch'], OPT['head'], OPT['feat_dim'])
    if OPT['mem'] == 'moco':
        model_ema = NAME_TO_FUNC[model_key](OPT['arch'], OPT['head'], OPT['feat_dim'])
    else:
        model_ema = None

    return model, model_ema

if __name__ == '__main__':
    model, _ = build_model()
    model, msg = load_encoder_weights(model)
    print(msg)


#[3.2,	[[1, 0, 1, 0, 2],	[330, 0, 220, 180, 20],	[190, 120, 190, 120, 290],	[[230, 800, 530, 800, 430],	[350, 480, 350, 50, 680]]],	[[2, 1, 1], [0, 1, 0], [2, 1, 0], [0, 1, 1], [3, 0, 0]],	[False, False, False, False, False]]
#		consecutive classes							longest consecutive class time							time after counter																		days without classes (true for no class)
#teacher rating				time between classes								time before counter										size slots of classes

def calculateFinal(ratingsObject, weight, minMax):
	#weight = [0, 0, -1, 0, 0, -1, 0, -1, 0, 0, -1, 0, -1] #default settings

	#								   longest class allowed
	calculated = 0

	#weight: importance of
		# High Teacher Rating							0
		# Class Time Start (see below)					1
		# 	-1 = early start | 1 = late start			2
		# Days Off										3
		# Short or long Class Times (see below)			4
		#	-1 = short classes | 1 = long classes		5
		# Time between classes							6
		#	-1 = no time| 1 = lots of time				7
		# Longest class time allowed					8
		# Class Time End (see below)					9
		# 	-1 = early end | 1 = late end				10
		# consecutive Classes (see below)				11
		# 	-1 = low | 1 = high							12

	if max(ratingsObject[1][2]) > weight[8] and weight[8] != 0: #remove if classes exceed max time
		return -1

	#Time between classes
	maxSubMin = float(minMax[0][1]) - float(minMax[0][0])

	timeBetweenClasses = 0
	if maxSubMin != 0:
		timeBetweenClasses = (maxSubMin - (sum(ratingsObject[1][1]) - float(minMax[0][0])))/maxSubMin*10

		if weight[7] == 1:
			timeBetweenClasses = 10 - timeBetweenClasses

	#time Before
	maxSubMin = float(minMax[1][1]) - float(minMax[1][0])

	timeBefore = 0
	if maxSubMin != 0:
		timeBefore = (maxSubMin - (sum(ratingsObject[1][3][0]) - float(minMax[1][0])))/maxSubMin*10

		if weight[2] == 1:
			timeBefore = 10 - timeBefore

	#time After
	maxSubMin = float(minMax[2][1]) - float(minMax[2][0])
	timeAfter = 0
	if maxSubMin != 0:
		timeAfter = (maxSubMin - (sum(ratingsObject[1][3][1]) - float(minMax[2][0])))/maxSubMin*10

		if weight[10] == -1:
			timeAfter = 10 - timeAfter

	#short or long classes
	maxSubMin = float(minMax[3][1]) - float(minMax[3][0])
	classLength = 0
	if maxSubMin != 0:
		classLength = (maxSubMin - (sum(ratingsObject[1][2]) - float(minMax[3][0])))/maxSubMin*10

		if weight[5] == -1:
			classLength = 10 - classLength

	#Consecutive Classes
	maxSubMin = float(minMax[4][1]) - float(minMax[4][0])
	consecutiveClasses = 0
	if maxSubMin != 0:
		consecutiveClasses = (maxSubMin - (sum(ratingsObject[1][0]) - float(minMax[4][0])))/maxSubMin*10

		if weight[12] == 1:
			consecutiveClasses = 10 - consecutiveClasses

	daysOffCounter = ratingsObject[3].count(True) / float(5) * 30

	calculated += weight[3] * daysOffCounter
	calculated += timeBetweenClasses * weight[6]
	calculated += timeBefore * weight[1]
	calculated += timeAfter * weight[9]
	calculated += consecutiveClasses * weight[11]
	calculated += weight[0] * ratingsObject[0] * 2 	#teacher rating
	calculated += classLength * weight[4]

	return calculated


from mlearn import base
from functools import reduce
from datetime import datetime
from mlearn.data.dataset import GeneralDataset
from mlearn.data.batching import Batch, BatchExtractor
from sklearn.feature_extraction import DictVectorizer
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer

def process_and_batch(dataset: GeneralDataset, data: base.DataType, batch_size: int, onehot: bool = True,
                      shuffle: bool = False, **kwargs):
    """
    Process a dataset and data.

    :dataset (GeneralDataset): The dataset object to use for processing.
    :data (base.DataType): The data to be batched and processed.
    :batch_size (int): Size of batches to create.
    :returns: Batched data.
    """
    # Process labels and encode data.
    dataset.process_labels(data)

    # Batch data
    batch = Batch(batch_size, data)
    batch.create_batches()
    batches = BatchExtractor('label', batch, dataset, onehot)

    if shuffle:
        batches.shuffle()

    return batches

def get_deep_dict_value(source: dict, keys: str, default = None):
    """
    Get values from deeply nested dicts.

    :source (dict): Dictionary to get data from.
    :keys (str): Keys split by '|'. E.g. outerkey|middlekey|innerkey.
    :default: Default return value.
    """
    value = reduce(lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys.split("|"), source)
    return value

def select_vectorizer(vectorizer: str = 'dict') -> base.VectType:
    """
    Identify vectorizer used and return it to be used.

    :vectorizer, default = 'dict': Vectorizer to be used.
    :return v: Vectorizer function.
    """
    vect = vectorizer.lower()
    if 'dict' in vect:
        v = DictVectorizer()
        setattr(v, 'name', 'DictVectorizer')
    elif 'tfidf' in vect:
        v = TfidfVectorizer()
        setattr(v, 'name', 'TFIDF-Vectorizer')
    elif 'count' in vect:
        v = CountVectorizer()
        setattr(v, 'name', 'CountVectorizer')
    setattr(v, 'fitted', False)

    return v

def _get_datestr():
    return datetime.now().strftime('%Y.%m.%d.%H.%M.%S')

def hyperparam_space(search_space: base.List[dict], hyper_parameters: base.List[base.Tuple]
                     ) -> base.List[dict]:
    """
    Create all hyper-parameter combinations to run.

    :search_space (base.List[dict]): List of dictionaries with one value
    :hyper_parameters (base.List[dict]): List of tuples containing a dict with all values for each iteration.
    :returns search_space (base.Generator[dict]): A list of dictionaries containing the search space.
    """
    for param_name, param_space in hyper_parameters:
        additions = []
        for comb_dict in search_space:
            for param in param_space:
                additions.append({**comb_dict, **{param_name: param}})
        search_space = additions
    return search_space


'''
@Author: Never
@Date: 2020-06-13 11:02:05
@Description:
@LastEditTime: 2020-07-14 15:20:19
@LastEditors: Never
'''
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/4/27 19:47
# @Author  : Shark
# @Site    :
# @File    : lepin1.py
# @Software: PyCharm

import csv
import requests
import json
import random
import time

start =time.time()
print('程序开始时间：%s'%(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(start))))

WinStatuslist=[]
i=0
with open('C:\\Users\\lhx\\Desktop\\user1.csv','rt') as myfile:
    lines=csv.reader(myfile)
    for memberid,addid in lines:
        with open(r'\\192.168.0.200\shop.h5\MemberId.json', 'w') as m:
            m.write(memberid)
        t=0
        while t<20:
            date={
            "productid":216869,
            "lpTimes":1,
            "addressid":addid,
            "isPay":'true',
            "useBalance":10.9,
            }

            url = "http://192.168.0.200:818/order/ActivityOrderConfirm"
            response = requests.post(url,data=date)
            text=response.text
            jsonobj=json.loads(text)

            if jsonobj['success']==200:
                totext=jsonobj['data']['OrderIdList']
                url="http://192.168.0.200:818/HappyOrder/ForthWithOrder"
                data={"happyOrderId":totext,
                "chooseNumber":random.randint(0,9)}

                response=requests.post(url,data=data)
                text=response.text
                jsonobj=json.loads(text)

                totext=jsonobj['data']['WinStatus']
                WinStatuslist.append(totext)
            else:
                print(jsonobj)
                break
            t+=1
            # time.sleep(1)
        i+=1
        print(i)

m=0
print(WinStatuslist)
for j in WinStatuslist:
    if j==1:
        m+=1
i=20*i
print("订单数：%s"%i)
print("中奖次数：%s"%m)
s=m/i*100
print('中奖概率：{:.2f}%'.format(s))
end =time.time()
print('程序结束时间：%s'%(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(end))))
print("循环运行时间:%.2f秒"%(end-start))


# dataset settings
dataset_type = 'DIORVOCDataset'
data_root = 'data/DIOR_VOC/'

img_norm_cfg = dict(
    mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(type='LoadAnnotations', with_bbox=True),
    dict(type='Resize', img_scale=(800, 800), keep_ratio=True),
    dict(type='RandomFlip', flip_ratio=0.5),
    dict(type='Normalize', **img_norm_cfg),
    dict(type='Pad', size_divisor=32),
    dict(type='DefaultFormatBundle'),
    dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(
        type='MultiScaleFlipAug',
        img_scale=(800, 800),
        flip=False,
        transforms=[
            dict(type='Resize', keep_ratio=True),
            dict(type='RandomFlip'),
            dict(type='Normalize', **img_norm_cfg),
            dict(type='Pad', size_divisor=32),
            dict(type='ImageToTensor', keys=['img']),
            dict(type='Collect', keys=['img']),
        ])
]
data = dict(
    samples_per_gpu=2,
    workers_per_gpu=2,
    train=dict(
        type='RepeatDataset',
        times=3,
        dataset=dict(
            type=dataset_type,
            ann_file=[
                data_root + 'ImageSets/Main/trainval.txt'
            ],
            img_prefix=[data_root],
            pipeline=train_pipeline)),
    val=dict(
        type=dataset_type,
        ann_file=data_root + 'ImageSets/Main/test.txt',
        img_prefix=data_root,
        pipeline=test_pipeline),
    test=dict(
        type=dataset_type,
        ann_file=data_root + 'ImageSets/Main/test.txt',
        img_prefix=data_root,
        pipeline=test_pipeline))
evaluation = dict(interval=1, metric='mAP')

cat_name_list = ['ship', 'overpass', 'tenniscourt', 'stadium', 'vehicle',
                 'airplane', 'storagetank', 'dam', 'golffield', 'trainstation',
                 'Expressway-Service-area', 'groundtrackfield', 'Expressway-toll-station',
                 'windmill', 'airport', 'harbor', 'baseballfield',
                 'basketballcourt', 'bridge', 'chimney']
num_classes = len(cat_name_list) # 20
max_bbox_per_img = 600


#!/usr/bin/env python
'''
Created on Jun 28, 2016

@author: isvoboda
'''

from __future__ import print_function

import sys
import multiprocessing
import logging
import yaml
import argparse
from collections import OrderedDict
import cnn_image_processing as ci
import signal

signal.signal(signal.SIGINT, lambda x, y: sys.exit(1))
LOGGER = logging.getLogger("cnn_image_processing")

def parse_phase(conf):
    """
    Parse net phase Train/Test
    """
    dmodules = {}

    creator = ci.Creator

    pque_size = 5
    if 'provider_queue_size' in conf:
        pque_size = conf['provider_queue_size']

    sque_size = 512
    if 'sample_queue_size' in conf:
        sque_size = conf['sample_queue_size']

    dmodules['pque'] = multiprocessing.Queue(pque_size)
    dmodules['sque'] = multiprocessing.Queue(sque_size)

    if 'Provider' in conf:
        dmodules['provider'] = creator.create_provider(conf['Provider'])
        dmodules['provider'].out_queue = dmodules['pque']
    else:
        dmodules['provider'] = None
#     train_provider.file_list = train_list

    if 'Sampler' in conf:
        dmodules['sampler'] = creator.create_sampler(conf['Sampler'])
        dmodules['sampler'].in_queue = dmodules['pque']
        dmodules['sampler'].out_queue = dmodules['sque']
    else:
        dmodules['sampler'] = None

    return dmodules

def parse_config(conf=None):
    """
    Parse the train_cnn application configuration
    """
    creator = ci.Creator
    app = {}

    app['Train'] = parse_phase(conf['Train'])
    app['Train']['provider'].out_queue = app['Train']['pque']
    app['Train']['sampler'].in_queue = app['Train']['pque']
    app['Train']['sampler'].out_queue = app['Train']['sque']
    in_ques = []

    if 'Test' in conf:
        test_nets = OrderedDict()
        test_net_list = [test_net.keys()[0] for test_net in conf['Test']]
        test_net_list.sort()
        for i_key, net_key in enumerate(test_net_list):
            test_nets[net_key] = parse_phase(conf['Test'][i_key][net_key])

            if test_nets[net_key]['provider'] == None:
                tprovider = creator.create_provider(conf['Train']['Provider'])
                tprovider.out_queue = test_nets[net_key]['pque']
                test_nets[net_key]['provider'] = tprovider
            if test_nets[net_key]['sampler'] == None:
                tsampler = creator.create_sampler(['Train']['Sampler'])
                tsampler.in_queue = test_nets[net_key]['pque']
                tsampler.out_queue = test_nets[net_key]['sque']
                test_nets[net_key]['sampler'] = tsampler

            in_ques.append(test_nets[net_key]['sque'])
        app['Test'] = test_nets

    app['Trainer'] = creator.create_trainer(conf['Trainer'])
    app['Trainer'].train_in_queue = app['Train']['sque']
    app['Trainer'].test_in_queue = in_ques

    return app

def main():
    '''
    Entry point
    Args:
        argv: list of command line arguments.
    '''
    parser = argparse.ArgumentParser(description="Train the cnn")
    parser.add_argument("-c", "--conf-file", action='store', type=str,
                        choices=None, required=True, help="Configuration file",
                        metavar=None, dest='conf_file')

    parser.add_argument("-s", "--solver-file", action='store', type=str,
                        choices=None, required=True, help="Solver file",
                        metavar=None, dest='solver_file')

    parser.add_argument("-v", "--verbose", action="store_true", required=False,
                        help="Set the verbose mode.", dest='verbose')

    parser.add_argument("-tr", "--train-list", action='store', type=str,
                        help="Training file list", required=True,
                        dest='train_list')

    parser.add_argument("-te", "--test-lists", action='store',
                        nargs='*', type=str, default=None,
                        required=False, dest='test_lists',
                        help="Training file lists")

    args = parser.parse_args()

    # Print the arguments
    for key, val in vars(args).iteritems():
        print("{}: {}".format(key, val))

    # Initialize logging
    if args.verbose:
        LOGGER.setLevel(logging.DEBUG)
    else:
        LOGGER.setLevel(logging.INFO)

    logging.basicConfig()

    config_file = args.conf_file
    solver_file = args.solver_file
    train_list = args.train_list
    test_lists = args.test_lists

    # Open, parse and print the configuration file
    with open(config_file) as cf_file:
        conf = yaml.safe_load(cf_file)
        print (yaml.dump(conf))

    app = parse_config(conf)

    app['Train']['provider'].file_list = train_list
    app['Train']['provider'].start()
    app['Train']['sampler'].start()
    if test_lists is not None:
        assert len(test_lists) == len(app['Test'])
        for i_test, test_k in enumerate(app['Test']):
            app['Test'][test_k]['provider'].file_list = test_lists[i_test]
            app['Test'][test_k]['provider'].start()
            app['Test'][test_k]['sampler'].start()

    app['Trainer'].solver_file = solver_file
    app['Trainer'].start()
    app['Trainer'].join()

if __name__ == "__main__":
    main()


import streamlit as st
from utils import get_modelpaths
from Scripts.video_processor import webcam_input

def main():
    model_list = ["AnimeGANv2_Hayao","AnimeGANv2_Shinka","AnimeGANv2_Paprika"]
    st.title("Real-time Anime to Anime Converter")
    model_name = st.selectbox("Select model name", model_list)
    model_path = get_modelpaths(model_name)

    webcam_input(model_path)

if __name__ == "__main__":
    main()


try:
  import usocket as socket
except:
  import socket

import re

from tof_i2c import TOF10120
tof=TOF10120()

import Site
import network
from machine import Pin
from neopixel import NeoPixel
import time
import math
from Site import WebPage
from Distance import DistanceMethods
from Sides import SidesMethods
from BrakeDrive import BrakeDriveMethods

DS = DistanceMethods()
SM = SidesMethods()

while True:
    conn, addr = s.accept()
    print('Got a connection from %s' % str(addr))
    request = conn.recv(1024)
    request = str(request)
    print('Content = %s' % str(request))

    LeftScenario1 = request.find('/?LeftScenario1')
    LeftScenario2 = request.find('/?LeftScenario2')
    LeftScenario3 = request.find('/?LeftScenario3')
    LeftScenario4 = request.find('/?LeftScenario4')
    LeftScenario5 = request.find('/?LeftScenario5')

    RightScenario1 = request.find('/?RightScenario1')
    RightScenario2 = request.find('/?RightScenario2')
    RightScenario3 = request.find('/?RightScenario3')
    RightScenario4 = request.find('/?RightScenario4')
    RightScenario5 = request.find('/?RightScenario5')

    ClosingScenario1 = request.find('/?ClosingScenario1')
    ClosingScenario2 = request.find('/?ClosingScenario2')
    ClosingScenario3 = request.find('/?ClosingScenario3')
    ClosingScenario4 = request.find('/?ClosingScenario4')

    BrakeScenario1 = request.find('/?BrakeScenario1')
    BrakeScenario2 = request.find('/?BrakeScenario2')
    BrakeScenario3 = request.find('/?BrakeScenario3')

    DriveScenario1 = request.find('/?DriveScenario1')
    DriveScenario2 = request.find('/?DriveScenario2')
    DriveScenario3 = request.find('/?DriveScenario3')

    OffSide = request.find('/?NeoOffSides')
    OffColl = request.find('/?NeoOffColl')

    ToggleBool = 1
    toggleon = 0

    if LeftScenario1 == 6:
        SM.SideAnimationFullLEFT()

    if LeftScenario2 == 6:
        SM.SideAnimationPartLEFT()

    if LeftScenario3 == 6:
        SM.SideFullRotationLEFT()

    if LeftScenario4 == 6:
        SM.SideFadeLEFT()

    if LeftScenario5 == 6:
        SM.SideBlinkerLEFT()

    if RightScenario1 == 6:
        SM.SideAnimationFullRIGHT()

    if RightScenario2 == 6:
        SM.SideAnimationPartRIGHT()

    if RightScenario3 == 6:
        SM.SideFullRotationRIGHT()

    if RightScenario4 == 6:
        SM.SideFadeRIGHT()

    if RightScenario5 == 6:
        SM.SideBlinkerRIGHT()

    if BrakeScenario1 == 6:
        SM.BrakePulse()

    if BrakeScenario2 == 6:
        SM.BrakeBlink()

    if BrakeScenario3 == 6:
        SM.BrakeFade()

    if DriveScenario1 == 6:
        SM.DrivePulse()

    if DriveScenario2 == 6:
        SM.DriveBlink()

    if DriveScenario3 == 6:
        SM.DriveFade()

    if ClosingScenario1 == 6:
        x = 2000
        while x >= 0:
            DS.ClosingPulse(14, x, 1)
            time.sleep_ms(100)
            x = x - 100

    if ClosingScenario2 == 6:
        DS.ClosingStoplichtBlink()

    if ClosingScenario3 == 6:
        DS.ClosingRed()

    if ClosingScenario4 == 6:
        DS.ClosingSwipe()

    if OffSide == 6:
        SM.off()
        print('off sides')

    if OffColl == 6:
        DS.off()
        print('off Distance')

    if toggleon == 6:
        ToggleBool = 0
        print('TOF On')
        counter = 0

    while ToggleBool == 0:
        time.sleep_ms(100)
        distance = tof.get_distance_filtered()
        print(distance)
        DS.Closing(10, distance, maxLeds)
        counter = counter + 1
        print('distance ' + str(distance))
        print('tijd ' + str(counter))
        if counter >= 100:
            ToggleBool = 1
            LC.off()

    response = WebPage()
    conn.send(response)
    conn.close()


#!/usr/bin/python
#coding:utf-8

"""
Author: Andy Tian
Contact: tianjunning@126.com
Software: PyCharm
Filename: get_heatMap_html.py
Time: 2019/2/21 10:51
"""

import requests
import re

def get_html():
    '''
    获取百度热力图demo的源代码
    :return: h5代码
    '''
    url = "http://lbsyun.baidu.com/jsdemo/demo/c1_15.htm"
    header = {
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6788.400 QQBrowser/10.3.2864.400",
        "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        "Accept-Encoding":"gzip, deflate",
        "Accept-Language":"zh-CN,zh;q=0.9"
    }
    htmlstr = requests.get(url,headers=header)._content.decode()
    htmlstr_formated = htmlstr.replace("\n",'').replace("\t",'')

    return htmlstr_formated

def modify_html(htmlstr):
    '''
    根据项目需要,对demo中的参数进行修改
    1)ak  修改为自己在百度中申请的密钥
    2)container{height:500px;width:100%;} 地图打开时的大小.
    3)points 热力图显示的坐标
    4)new BMap.point 地图打开时显示的重点位置
    5)heatmapOverlay = new BMapLib.HeatmapOverlay({"radius":20}) 热力显示半径
    6)# heatmapOverlay.setDataSet({data:points,max:100}); 数据大小,超过max后显示颜色一致,根据实际数据,修改max大小
    :param htmlstr:需要修改的h5代码
    :return: 修改好的代码
    '''
    data = open("G:\Python\Project\Spider\scrapyProject\lianjia\lon_lat.json")
    datastr = data.read()
    htmlstr = htmlstr.replace("height:500px","height:80%").replace('{"radius":20}','{"radius":10}').replace("max:100","max:120000")
    be_replaced_data = ",\n".join(re.findall(r'{"lng":.*"count":\d*}',htmlstr))
    htmlstr_modified = htmlstr.replace(be_replaced_data,datastr)
    return htmlstr_modified

def rewrite_html(str):
    '''
    h5代码写入文件
    :param str: h5代码
    :return: h5文档
    '''
    with open("heat.html","w",encoding="utf-8") as f:
        f.write(str)

if __name__ == "__main__":
    htmlstr = get_html()
    htmlstr_modified = modify_html(htmlstr)
    write_html(htmlstr_modified)


import torch
import time
import torch.nn.functional as F

def train(model, device, train_loader, optimizer, epoch):   # 训练模型
    model.train()
    best_acc = 0.0
    for batch_idx, (x1, x2, x3, y) in enumerate(train_loader):
        start_time = time.time()
        x1, x2, x3, y = x1.to(device), x2.to(device), x3.to(device), y.to(device)
        out = model([x1, x2, x3])  # 得到预测结果
        y_pred = out[0]
        model.zero_grad()             # 梯度清零
        loss = F.cross_entropy(y_pred, y.squeeze())  # 得到loss
        loss.backward()
        optimizer.step()
        if(batch_idx + 1) % 100 == 0:    # 打印loss
            print('Train Epoch: {} [{}/{} ({:.2f}%)]\t\tLoss: {:.6f}'.format(epoch, (batch_idx+1) * len(x1),
                                                                             len(train_loader.dataset),
                                                                             100. * (batch_idx+1) / len(train_loader),
                                                                             loss.item()))  # 记得为loss.item()

def test(model, device, test_loader):    # 测试模型, 得到测试集评估结果
    model.eval()
    test_loss = 0.0
    acc = 0
    for batch_idx, (x1, x2, x3, y) in enumerate(test_loader):
        x1, x2, x3, y = x1.to(device), x2.to(device), x3.to(device), y.to(device)
        with torch.no_grad():
            out = model([x1, x2, x3])
        y_ = out[0]
        test_loss += F.cross_entropy(y_, y.squeeze())
        pred = y_.max(-1, keepdim=True)[1]   # .max(): 2输出，分别为最大值和最大值的index
        acc += pred.eq(y.view_as(pred)).sum().item()    # 记得加item()
    test_loss /= len(test_loader)
    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)'.format(
          test_loss, acc, len(test_loader.dataset),
          100. * acc / len(test_loader.dataset)))
    return acc / len(test_loader.dataset)

def test_lem(model, device, test_loader):    # 测试模型, 得到测试集评估结果
    model.eval()
    input_embeddings, label_embeddings, labels = [], [], []
    test_loss = 0.0
    acc = 0
    for batch_idx, (x1, x2, x3, y) in enumerate(test_loader):
        x1, x2, x3, y = x1.to(device), x2.to(device), x3.to(device), y.to(device)
        with torch.no_grad():
            out = model([x1, x2, x3])
        y_, V, C = out[0], out[1], out[2]
        input_embeddings.append(V.cpu())
        label_embeddings = C.cpu()
        test_loss += F.cross_entropy(y_, y.squeeze())
        pred = y_.max(-1, keepdim=True)[1]   # .max(): 2输出，分别为最大值和最大值的index
        labels.append(pred)
        acc += pred.eq(y.view_as(pred)).sum().item()    # 记得加item()
    test_loss /= len(test_loader)
    return acc / len(test_loader.dataset), input_embeddings, label_embeddings, labels


"""We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""

"""257. Binary Tree Paths
"""

class TreeNode:

    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

class Solution:

    def dfs(self, root, curr_path):
        if not root:
            return None
        new_node = str(root.val)
        if not root.left and not root.right:
            self.paths.append(curr_path + new_node)
        else:
            self.dfs(root.left, curr_path + new_node + "->")
            self.dfs(root.right, curr_path + new_node + "->")

    def binaryTreePaths(self, root):
        if not root:
            return []
        self.paths = []
        self.dfs(root, "")
        return self.paths


import json

with open('mahasiswa.json', 'r') as file:
    a = json.load(file)

    b = dict()
    c = int(input("Masukkan Jumkah Mahasiswa baru : "))

    for i in range(c):
        nm = input("Masukkan nama anda: ")
        hb = []

        untuk_hobi = int(input("Masukkan jumlah hobi: "))
        for j in range(untuk_hobi):
            hb1 = input("Masukkan hobi ke-{} : ".format(j+1))
            hb.append(hb1)
        per = input("Masukkan prestasi anda: ")

        print("====Data Berhasil ditambahkan===")
        print()

        b [nm] = [{"Biodata": {"Hobi": hb, "Prestasti" : per}}]

    a.update(b)

with open('mahasiswa.json', 'w') as file:
    json.dump(a,file)


import os
from flask import Flask, request, abort, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
import random
from sqlalchemy import func
from models import setup_db, Question, Category

QUESTIONS_PER_PAGE = 10

# Create APP and settings cors headers
def create_app(test_config=None):
    app = Flask(__name__)
    setup_db(app)
    cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

    @app.after_request
    def after_request(response):
        response.headers.add('Access-Control-Allow-Headers',
                             'Content-Type,Authorization,true')
        response.headers.add('Access-Control-Allow-Methods',
                             'GET,PATCH,POST,DELETE,OPTIONS')
        return response

    # Paginate method
    def paginate_questions(request, questions):
        page = request.args.get('page', 1, type=int)
        start = (page - 1) * QUESTIONS_PER_PAGE
        end = start + QUESTIONS_PER_PAGE

        questions = [question.format() for question in questions]
        paginated_questions = questions[start:end]

        return paginated_questions

    # Questions API with pagination

    @app.route('/api/questions', methods=['GET'])
    def get_questions_with_pagination():
        error_code = 422
        try:
            categories = Category.query.all()
            questions = Question.query.all()

            formatted_questions = paginate_questions(request, questions)
            formatted_categories = [category.format()
                                    for category in categories]

            if len(formatted_categories) == 0 or len(formatted_questions) == 0:
                error_code = 404
                abort(error_code)

            current_categories = []
            for question in formatted_questions:
                category = question['category']
                if not (category in current_categories):
                    current_categories.append(category)

            return jsonify({
                'success': True,
                'questions': formatted_questions,
                'total_questions': len(questions),
                'current_category': current_categories,
                'categories': formatted_categories
            })
        except:
            abort(error_code)

    # Categories API

    @app.route('/api/categories', methods=['GET'])
    def get_categories():
        try:
            categories = Category.query.all()
            formatted_categories = [category.format()
                                    for category in categories]
            if len(formatted_categories) == 0:
                abort(404)

            return jsonify({
                'success': True,
                'categories': formatted_categories,
                'total_categories': len(formatted_categories)
            })
        except:
            abort(422)

    # Delete Question API

    @app.route('/api/questions/<int:question_id>', methods=['DELETE'])
    def delete_question(question_id):
        question = Question.query.filter_by(id=question_id).first()
        if question is None:
            abort(404)
        try:
            question.delete()

            return jsonify({
                'success': True,
                'question': question_id
            })
        except:
            abort(405)

    # Create Question API

    @app.route('/api/questions/create', methods=['POST'])
    def new_question():
        try:
            body = request.get_json()

            new_question = body.get('question', None)
            new_answer = body.get('answer', None)
            new_category = body.get('category', None)
            new_difficulty = body.get('difficulty', None)

            question = Question(
                question=new_question,
                answer=new_answer,
                category=new_category,
                difficulty=new_difficulty)
            question.insert()

            return jsonify({
                'success': True,
                'created': question.id
            })

        except:
            abort(422)

    # Get Questions by Category API

    @app.route(
        '/api/category/<int:question_category>/questions',
        methods=['GET']
        )
    def get_questions_by_categories(question_category):
        error_code = 422
        try:
            questions = Question.query.filter(
                question_category == Question.category).all()
            formatted_questions = paginate_questions(request, questions)

            if len(formatted_questions) == 0:
                error_code = 404
                abort(error_code)

            current_categories = []
            for question in formatted_questions:
                category = question['category']
                if not (category in current_categories):
                    current_categories.append(category)

            return jsonify({
                'success': True,
                'questions': formatted_questions,
                'total_questions': len(formatted_questions),
                'current_categories': current_categories,
            })
        except:
            abort(error_code)

    # Get Question by Search Term  API

    @app.route('/api/questions/search', methods=['POST'])
    def search_questions():
        body = request.get_json()
        search_term = body.get('searchTerm', None)
        search = "%{}%".format(search_term.replace(" ", "\ "))
        data = Question.query.filter(Question.question.ilike(search)).all()
        formatted_questions = [question.format() for question in data]

        if len(formatted_questions) == 0:
            abort(404)
        try:
            current_categories = []
            for question in formatted_questions:
                category = question['category']
                if not (category in current_categories):
                    current_categories.append(category)

            return jsonify({
                'success': True,
                'questions': formatted_questions,
                'totalQuestions': len(formatted_questions),
                'current_categories': current_categories,
                'search': search_term
            })
        except:
            abort(422)

    # Get Question to Play Quiz API

    @app.route('/api/quizzes', methods=['POST'])
    def post_quiz_questions():
        code = 422
        try:
            request_quiz = request.get_json()

            previous_questions = request_quiz.get('previous_questions')
            quiz_category = request_quiz.get('quiz_category')

            question = Question.query
            question = question.filter(~Question.id.in_(previous_questions))

            if quiz_category != 0:
                question = question.filter(Question.category == quiz_category)

            questions_random = question.order_by(func.random()).first()

            if not questions_random:
                return(jsonify({
                    'success': True,
                    'previous_question': len(previous_questions)
                    }))

            return jsonify({
                'success': True,
                'question': questions_random.format(),
                'previous_question': previous_questions
            })
        except:
            abort(code)

    @app.errorhandler(404)
    def not_found(error):
        return jsonify({
            "success": False,
            "error": 404,
            "message": "resource not found"
        }), 404

    @app.errorhandler(422)
    def unprocessable(error):
        return jsonify({
            "success": False,
            "error": 422,
            "message": "unprocessable"
        }), 422

    @app.errorhandler(400)
    def bad_request(error):
        return jsonify({
            "success": False,
            "error": 400,
            "message": "bad request"
        }), 400

    @app.errorhandler(405)
    def method_not_allowed(error):
        return jsonify({
            "success": False,
            "error": 405,
            "message": "Method Not Allowed"
        }), 405

    return app


"""added columns to Places

Revision ID: cba44d27f422
Revises: 061ea741f852
Create Date: 2023-06-28 15:56:11.475592

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'cba44d27f422'
down_revision = '061ea741f852'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('places', schema=None) as batch_op:
        batch_op.add_column(sa.Column('website', sa.String(), nullable=True))
        batch_op.add_column(sa.Column('photo', sa.String(), nullable=True))
        batch_op.add_column(sa.Column('price_level', sa.Integer(), nullable=True))
        batch_op.add_column(sa.Column('user_ratings_total', sa.Integer(), nullable=True))
        batch_op.add_column(sa.Column('rating', sa.Float(), nullable=True))

    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('places', schema=None) as batch_op:
        batch_op.drop_column('rating')
        batch_op.drop_column('user_ratings_total')
        batch_op.drop_column('price_level')
        batch_op.drop_column('photo')
        batch_op.drop_column('website')

    # ### end Alembic commands ###


import json

import requests

from django.http import JsonResponse
from django.shortcuts import render

import numpy as np

# Create your views here.
from django.template.defaultfilters import upper
from django.template.loader import render_to_string

from apps.utils.cases import get_scenario_on_day
from apps.utils.date_adjustment import date_adjustment

def home(request):

    countries = requests.get('https://corona.lmao.ninja/countries').json()

    url_parameter = request.GET.get("q")

    if url_parameter != None:
        countries = [ct for ct in countries if upper(url_parameter) in upper(ct['country'])]

    if request.is_ajax():
        html = render_to_string(
            template_name="countries-results-partial.html",
            context={"dados": countries}
        )
        data_dict = {"html_from_view": html}

        return JsonResponse(data=data_dict, safe=False)

    return render(request, 'home.html', {'dados': countries})

def historico(request):
    countries = requests.get('https://corona.lmao.ninja/countries').json()

    if request.is_ajax():

        context = {}

        selected_country = request.GET.get('sortBy')

        historic = requests.get(f'https://corona.lmao.ninja/v2/historical/{selected_country}').json()

        context['dates'] = historic['timeline']['cases']
        context['cases'] = list(context['dates'].values())
        context['casesOnDay'] = get_scenario_on_day(context['cases'])
        context['deaths'] = list(historic['timeline']['deaths'].values())
        context['deathsOnDay'] = get_scenario_on_day(context['deaths'])
        context['historic'] = historic

        context['adjusted_dates'] = [date_adjustment(date) for date in historic['timeline']['cases'].keys()]

        html = render_to_string(
            template_name="countries-historical-partial.html", context=context
        )
        data_dict = {"html_from_view": html}

        valores = [{'name': context['adjusted_dates'][i], 'y': context['deathsOnDay'][i]}
                   for i in range(len(context['dates']))]

        chart = {
            'chart': {'type': 'column'},
            'title': {'text': 'Impacto de Mortes por Corona'},
            'series': [{
                'name': 'Número de vítimas',
                'data': valores
            }],
            'xAxis': {
                'categories': context['adjusted_dates']
            }
        }

        data_dict['html_to_chart'] = chart

        return JsonResponse(data=data_dict, safe=False)

    return render(request, 'historic.html', {'countries': countries})


class Address:
    def __init__(self, obj):
        """
        See "https://smartystreets.com/docs/cloud/us-reverse-geo-api#address"
        """
        self.street = obj.get('street', None)
        self.city = obj.get('city', None)
        self.state_abbreviation = obj.get('state_abbreviation', None)
        self.zipcode = obj.get('zipcode', None)
        self.source = obj.get('source', None)


import torch.nn as nn
import tqdm
import torch
class ANN(nn.Module):
    def __init__(self, input=4):
        super().__init__()

        # self.relu1 = nn.ReLU(inplace=True)
        self.liner1 = nn.Linear(input,128)
        self.relu = nn.ReLU()
        self.liner2 = nn.Linear(128,8)
        self.liner3 = nn.Linear(8,4)

        # self.relu = nn.ReLU(inplace=True)

    def forward(self, x):
        out = self.relu(self.liner1(x))
        out = self.relu(self.liner2(out))
        out = self.relu(self.liner3(out))

        return out


import argparse
from datetime import datetime
import os
import sys
import time
import random
from Classifier_3d_v1 import Classifier
import tensorflow as tf
from util import Visualizer
import numpy as np
from dataset_classifier import LungDataset
import torch
from ops import load,save,pixelwise_cross_entropy
import torchnet as tnt
from torch.utils.data import DataLoader
#restore_from='./models'
restore_from=None
models_path='./models'
logs='./logs'
luna="/home/x/dcsb/data/TianChi/"
luna_data="/home/x/data/datasets/tianchi/train/"
batch_size = 1
max_run    = 1000
epoch_print  = 100
iters=0
vis = Visualizer()

def main():
    vis.vis.texts=''
    dice_loss_meter =tnt.meter.AverageValueMeter()
    image_batch=tf.placeholder(tf.float32, shape=[None, 48, 48,48, 1])
    label_batch=tf.placeholder(tf.float32, shape=[None,2])
    net=Classifier({'data': image_batch},batch_size=batch_size)
    prob = net.layers['result']
    logits=net.layers['logits']
    dataset=LungDataset("/home/x/dcsb/data/TianChi",augument=True)

    all_trainable =tf.trainable_variables()
    restore_var = tf.global_variables()

    cross_loss = tf.losses.softmax_cross_entropy(label_batch,logits)

    global iters
    cross_loss_sum=tf.summary.scalar("crossloss",cross_loss)
    # accuracy=tf.metrics.accuracy(label_batch,prob)
    optimiser = tf.train.MomentumOptimizer(0.01,0.99)
    gradients = tf.gradients(cross_loss, all_trainable)
    clipped_gradients, norm = tf.clip_by_global_norm(gradients,1.)
    train_op = optimiser.apply_gradients(zip(clipped_gradients, all_trainable))

    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    sess = tf.Session(config=config)
    init = tf.global_variables_initializer()

    sess.run(init)
    all_sum=tf.summary.merge([cross_loss_sum])
    summary_writer = tf.summary.FileWriter(logs,graph=tf.get_default_graph())
    saver = tf.train.Saver(var_list=restore_var, max_to_keep=40)

    # Load variables if the checkpoint is provided.
    if restore_from is not None:
        loader = tf.train.Saver(var_list=restore_var)
        load(loader, sess, restore_from,"classifier_v2")

    for i in range(max_run):
        dice_loss_meter.reset()
        start_time = time.time()
        labels=np.array([1,0])
        labels=labels[np.newaxis,:]
        pred=np.array([1,0])
        pred=pred[np.newaxis,:]
        train_loader = DataLoader(dataset,batch_size = batch_size,shuffle = True,num_workers = 1,pin_memory=True,drop_last=True)
        for batch_idx, (img_, label_,_) in enumerate(train_loader):
            iters+=1
            img=img_.numpy()
            label=label_.numpy()
            labels=np.concatenate([labels,label],axis=0)
            img=img.transpose([0,2,3,4,1])
            feed_dict={image_batch:img,label_batch:label}
            _,cross_loss_,probs,summary=sess.run([train_op,cross_loss,prob,all_sum],feed_dict=feed_dict)
            summary_writer.add_summary(summary, iters)
            pred=np.concatenate([pred,probs],axis=0)
            # print "prob+:",probs[:,0]
            vis.plot('accuracy',np.mean(np.argmax(labels,axis=1)==np.argmax(pred,axis=1)))
            dice_loss_meter.add(cross_loss_)
            if batch_idx>10:
                try:
                    vis.plot('cross_loss',dice_loss_meter.value()[0])
                except:
                    pass
            vis.img('input',img_[0,0,24,:,:].cpu().float())
            if iters%50==0:

                pred_=np.argmax(pred,axis=1)
                label_=np.argmax(labels,axis=1)
                acc=np.mean(label_==pred_)
                cross=cross_loss.eval(feed_dict,session=sess)
                print("Epoch: [%2d]  [%4d] ,time: %4.4f,cross_loss:%.8f,accuracy:%.8f"% \
                      (i,batch_idx,time.time() - start_time,cross,acc))

        if i%2==0:
            save(saver,sess,models_path,iters,"classifier_v2",train_tag="nodule_predict")
main()


#!/bin/env python
# -*- coding: UTF-8 -*-

import wx
import os
import sys
import shutil
import re
import math
from bqList import MyBibleList
from exhtml import exHtmlWindow

class MyApp(wx.App):

  path = None

  def __init__(self, *args, **kwds):
    wx.App.__init__ (self, *args, **kwds)

  def OnInit(self):
    self.path = os.path.realpath(os.path.dirname(sys.argv[0]))
    #self.path = '/home/noah/Files/Soft-Win/BibleQuote'
    self.SetAppName('BQTlite')
    self.SetClassName('BQT reader lite')
    frame = MyFrame("BQT reader lite", (150, 72), (667, 740))
    frame.Show()
    self.SetTopWindow(frame)
    return True

class MyFrame(wx.Frame):

  path = ''
  strongs = False
  page = None
  findPanel = None
  sizer = None
  bibles = None
  activeModule = None
  compareModule = None
  buttonz = {}
  searchField = None
  strongsOn = False
  currentBook = -1
  currentChapter = -1
  fullScreen = False

  def buttonData(self):
    return (("RST", self.OnModule, 'module', 130, 'Module', ''),
    ("Genesis", self.OnBook, 'book', 200, 'Book', ''),
    ("<", self.PrevChapter, None, 20, 'Previous chapter', ''),
    ("1", self.OnChapter, 'chapter', 40, 'Chapter', ''),
    (">", self.NextChapter, None, 20, 'Next chapter', ''),
    ("#", self.ToggleStrongs, 'strongs', 30, 'Toggle Strong numbers', ''),
    ("H", self.OnHistory, 'history', 30, 'History', 'HistoryButton.bmp'),
    ("S", self.OnFind, 'find', 30, 'Search', 'SearchButton.bmp'),
    ("-Compare-", self.OnCompare, 'compare', 130, 'Compare translation with...', ''),
    ('F', self.ToggleFullScreen, None, 30, 'Toggle fullscreen', 'FullScreen.bmp'))

  def createButtonBar(self, panel, yPos = 0):
    xPos = 0
    height = 0
    for eachLabel, eachHandler, eachName, eachWidth, eachHint, eachPic in self.buttonData():
      pos = (xPos, yPos)
      button = self.buildOneButton(panel, eachLabel, eachHandler, pos, eachHint, eachPic, height)
      if(eachName):
        self.buttonz[eachName] = button
      if(eachWidth):
        button.SetSize((eachWidth, -1))
      xPos += button.GetSize().width
      if(button.GetSize().height>height):
        height=button.GetSize().height
    return height

  def buildOneButton(self, parent, label, handler, position=(0,0), hint='', img='', height=0):
    if(img and os.path.exists(self.path + '/GLYPHS/' + img)):
      image1 = wx.Image(self.path + '/GLYPHS/' + img,\
                        wx.BITMAP_TYPE_ANY).ConvertToBitmap()
      button = wx.BitmapButton(parent, id=-1, bitmap=image1,
          pos=position, size = (height, height))
    elif(img and os.path.exists(self.path + '/help/buttons/' + img)):
      image1 = wx.Image(self.path + '/help/buttons/' + img,\
                        wx.BITMAP_TYPE_ANY).ConvertToBitmap()
      button = wx.BitmapButton(parent, id=-1, bitmap=image1,
          pos=position, size = (height, height))
    else:
      button = wx.Button(parent, -1, label, position)
    self.Bind(wx.EVT_BUTTON, handler, button)
    if(hint):
      button.SetToolTip(wx.ToolTip(hint))
    return button

  def createTabs(self):
    # create notebook
    notebook = wx.Notebook( self, -1, (0,40), (500,500))
    # create pages
    ctrl = wx.Panel( notebook, -1 )
    # add pages
    notebook.AddPage( wx.TextCtrl( notebook, -1 ), "Page 1", False, -1 )
    notebook.AddPage( ctrl, "Page 2 Will be Selected", True, -1 )
    self.page = wx.html.HtmlWindow(ctrl, -1, (0,0), (200, 200))
    return notebook

  def __init__(self, title, pos, size):
    self.path = os.path.realpath(os.path.dirname(sys.argv[0]))
    #self.path = '/home/noah/Files/Soft-Win/BibleQuote'
    self.bibles = MyBibleList()
    wx.Frame.__init__(self, None, -1, title, pos, size)
    #self.createMenuBar()
    self.panel = wx.Panel(self, -1)
    self.panel.SetBackgroundColour("Yellow")
    height = self.createButtonBar(self.panel)
    #notebook = self.createTabs()
    self.page = exHtmlWindow(self, -1, (0,0), (100,100))
    self.page.SetLinkClicked(self.OnLinkClicked)
    self.findPanel = wx.Panel(self, -1)
    self.searchField = wx.TextCtrl(self.findPanel, -1, '', (0,0))
    self.findButton = wx.Button(self.findPanel, -1, 'Find', (100,0))
    self.Bind(wx.EVT_BUTTON, self.OnSearchStart, self.findButton)
    self.findPanel.Hide()
    self.CreateStatusBar()
    self.SetStatusText("Ready")
    self.strongs = False
    self.bibles.loadList(self.path)
    self.__do_layout()
    if(len(self.bibles.history)>0):
      history0 = self.bibles.history[0]
      self.bibleGo(history0['command'][3:])
    else:
      self.OnModule(None)
    self.Bind (wx.EVT_CLOSE, self.OnClose)
    favicon = wx.Icon(self.path + '/favicon.ico', wx.BITMAP_TYPE_ICO, 16, 16)
    self.SetIcon(favicon)

    import gobject
    gobject.threads_init()
    import pygtk
    pygtk.require('2.0')
    import gtk, gtk.gdk
    self.taskBarIcon = favicon

  def __do_layout(self):
    self.sizer = wx.FlexGridSizer(3, 1, 0, 0)
    self.sizer.Add(self.panel, 1, flag = wx.EXPAND)
    self.sizer.Add(self.findPanel, 2, flag = wx.EXPAND)
    self.sizer.Add(self.page, 3, flag = wx.EXPAND)
    self.sizer.AddGrowableRow(2)
    self.sizer.AddGrowableCol(0)
    self.SetSizer(self.sizer)
    searchSizer = wx.FlexGridSizer(1, 2, 0, 0)
    searchSizer.Add(self.searchField, 1, flag = wx.EXPAND)
    searchSizer.Add(self.findButton, 2, flag = wx.EXPAND)
    searchSizer.AddGrowableCol(0)
    self.findPanel.SetSizer(searchSizer)
    self.Layout()

  def arrangeControls(self):
    if(self.page.getMode()=='search'):
      self.findPanel.Show()
    else:
      self.findPanel.Hide()
    if(not self.activeModule or not self.activeModule.Bible \
       or not self.activeModule.StrongNumbers):
      self.strongsOn = False
    if(self.strongsOn):
      self.buttonz['strongs'].SetForegroundColour('Green')
    else:
      self.buttonz['strongs'].SetForegroundColour('Black')
    if(self.activeModule):
      self.buttonz['module'].SetLabel(self.activeModule.BibleShortName)
      self.buttonz['book'].SetLabel(self.activeModule.FullName[self.currentBook])
      self.buttonz['chapter'].SetLabel(str(self.currentChapter))
      statusText = self.activeModule.BibleName
    else:
      self.buttonz['module'].SetLabel('')
      self.buttonz['book'].SetLabel('')
      self.buttonz['chapter'].SetLabel('')
      statusText = 'Select a module'
    if(self.compareModule):
      statusText = statusText + ' | ' + self.compareModule.BibleName
      self.buttonz['compare'].SetLabel(self.compareModule.BibleShortName)
    else:
      self.buttonz['compare'].SetLabel('-Compare-')
    statusText = statusText + ' | ' + 'Mode: ' +self.page.getMode()
    if(self.page.ctrlDown):
      statusText = statusText + ' [Ctrl]'
    self.SetStatusText(statusText)
    self.Layout()

  def OnCopy(self, event):
    self.page.OnCopy(event)
    event.Skip()

  def OnOptions(self, event): pass

  def OnQuit(self, event):
    self.Close()

  def OnClose(self, event):
    try:
      self.bibles.saveHistory()
    except:
      pass
    self.Destroy()

  def OnAbout(self, event):
    wx.MessageBox("BQT reader light (very light)\nWritten by Noah for the sake of learning Python.",
        "BQT reader light", wx.OK | wx.ICON_INFORMATION, self)

  def OnLinkClicked(self, link):
    tmpRe = re.search('^([^:]+):(.*)$', link.GetHref())
    if(tmpRe):
      if(tmpRe.groups()[0]=='module'):
        path = tmpRe.groups()[1]
        if(self.activeModule and self.activeModule.path == path):
          self.ShowChapter(self.currentChapter)
        else:
          oldModule = self.activeModule
          self.activeModule = self.bibles.getModule(path)
          self.activeModule.loadModule()
          if(oldModule and oldModule.Bible and self.activeModule.Bible):
            #wx.MessageBox('[0]', "Module", wx.ICON_ERROR | wx.OK)
            newBookInd = self.activeModule.getOrderNumber(oldModule.getAbsoluteIndex(self.currentBook))
            #wx.MessageBox('[1]', "Module", wx.ICON_ERROR | wx.OK)
            if(newBookInd>=0):
              #wx.MessageBox('[2] book:'+str(newBookInd), "Module", wx.ICON_ERROR | wx.OK)
              if(self.activeModule.loadBook(newBookInd)):
                self.currentBook = newBookInd
                self.ShowChapter(self.currentChapter)
                #wx.MessageBox('[3]', "Module", wx.ICON_ERROR | wx.OK)
            else:
              pass
              #wx.MessageBox('Could not find the book', "Module", wx.ICON_ERROR | wx.OK)
          else:
            self.ChooseBook(path)
      elif(tmpRe.groups()[0]=='book'):
        book = int(tmpRe.groups()[1])
        self.activeModule.loadBook(book)
        self.buttonz['book'].SetLabel(self.activeModule.FullName[book])
        self.ChooseChapter(book)
      elif(tmpRe.groups()[0]=='chapter'):
        chapter = int(tmpRe.groups()[1])
        self.ShowChapter(chapter)
        self.buttonz['chapter'].SetLabel(str(chapter))
      elif(tmpRe.groups()[0]=='strong'):
        number = tmpRe.groups()[1]
        self.ShowStrong(number)
      elif(tmpRe.groups()[0]=='go'):
        self.bibleGo(tmpRe.groups()[1])
      elif(tmpRe.groups()[0]=='searchpage'):
        page = int(tmpRe.groups()[1])
        self.ShowSearchPage(page)
      elif(tmpRe.groups()[0]=='compare'):
        path = tmpRe.groups()[1]
        if(self.activeModule.path == path):
          path = ''
        self.OnCompareChoise(path)
      else:
        self.page.OutputHTML('Unknown command:', link.GetHref(), 'error')
      self.arrangeControls()

  def OnModule(self, event):
    title = 'Choose a module:'
    return self.ShowModuleList(title, 'module', True, False)

  def ShowModuleList(self, title, mode, showOthers, showNothing):
    if(self.page.getMode()==mode):
      self.ShowChapter(self.currentChapter)
      return
    self.page.saveScrollPos()
    modList = self.bibles.getBibleList()
    content = ''
    if(showNothing):
      content = content + 'Unselect'
    if(len(modList)):
      content = content + '
Bibles:
' + self.ProcessList(modList, mode)
    modList = self.bibles.getCommentaryList()
    if(len(modList)):
      content = content + '
Commentaries:
' + self.ProcessList(modList, mode)
    if(showOthers):
      modList = self.bibles.getOtherList()
      if(len(modList)):
        content = content + '
Other books:
' + self.ProcessList(modList, mode)
    if(content == ''):
      title = 'Could not find modules'
    self.page.OutputHTML(title, content, mode)
    self.arrangeControls()

  def ProcessList(self, modList, mode):
    content = '
'
    for mod in modList:
      label = mod.BibleName
      link = mode+ ':' + mod.path
      content = content + '
 ' + label + ''
    content = content + '
'
    return content

  def ChooseBook(self, path):
    if(not self.activeModule): return
    self.page.setPath(path)
    if(self.activeModule.BookQty>1):
      content = '

'
      cnt = int((len(self.activeModule.FullName)-1)/3)+1
      for i in range(len(self.activeModule.FullName)):
        content = content + '
' + \
                  self.activeModule.FullName[i] + ''
        if(i+1==cnt or i+1==cnt+cnt):
          content = content + '

'
      content = content + '

'
      self.page.OutputHTML('', content, 'book')
      self.arrangeControls()
    else:
      self.activeModule.loadBook(0)
      self.currentBook = 0
      self.ChooseChapter(0)
    return

  def ChooseChapter(self, book):
    if(not self.activeModule): return
    self.currentBook = int(book)
    content = ''
    chRange = self.activeModule.getChapterRange(book)
    if(len(chRange)>1):
      for i in chRange:
        content = content + ' ' + str(i) + \
                  '  '
      self.page.OutputHTML('', content, 'chapter')
      self.arrangeControls()
    else:
      self.ShowChapter(chRange[0])
    return

  def transformContent(self, text, strongPrfx, module):
    if(module.StrongNumbers):
      if(self.strongsOn):
        text = re.sub(' ([0-9]{1,5})', ' \\1', text)
      else:
        text = re.sub(' [0-9]{1,5}', '', text)
    #text = text.replace('<','
[[').replace('>',']]
')
    text = re.sub('
]*)?>', '', text)
    text = text.replace('
','
')
    return text

  def ShowChapter(self, chapter):
    if(not self.activeModule): return
    self.currentChapter = int(chapter)
    content = self.activeModule.getChapter(chapter)
    prfx = ''
    if(self.activeModule.isOT(self.currentBook)): prfx = '0'
    content = self.transformContent(content, prfx, self.activeModule)
    absInd = self.activeModule.getAbsoluteIndex(self.currentBook)
    newBookInd = self.activeModule.getOrderNumber(absInd)
    title = ''
    if(self.compareModule):
      self.compareModule.loadModule()
      newBookInd = self.compareModule.getOrderNumber(absInd)
      if(newBookInd>=0 and self.compareModule.loadBook(newBookInd)):
        content2 = self.compareModule.getChapter(chapter)
        if(content2):
          content2 = self.transformContent(content2, prfx, self.compareModule)
          prc = int(len(content)*100./(len(content)+len(content2)))
          content = '

' + content + '	' +\
                    '' + content2 + '

'
    self.page.OutputHTML('', content, 'text')
    self.page.restoreScrollPos()

    chzero = 0
    if(self.activeModule.ChapterZero): chzero = 1
    command = os.path.basename(self.activeModule.path).lower()\
             + ' ' + str(self.currentBook + 1)\
             + ' ' + str(self.currentChapter + chzero)
    title = self.activeModule.BibleShortName\
             + ' ' + self.activeModule.ShortName[self.currentBook][0]\
             + ' ' + str(self.currentChapter)
    self.bibles.pushHistory(command, title)
    self.arrangeControls()
    self.page.SetFocus()

  def OnBook(self, event):
    if(not self.activeModule): return
    if(self.page.getMode()=='book'):
      self.ShowChapter(self.currentChapter)
      return
    self.ChooseBook(self.activeModule.path)

  def OnChapter(self, event):
    if(not self.activeModule): return
    if(self.page.getMode()=='chapter'):
      self.ShowChapter(self.currentChapter)
      return
    self.page.setMode('chapter')
    self.ChooseChapter(self.currentBook)

  def PrevChapter(self, event):
    if(not self.activeModule): return
    if(self.page.getMode()!='text'): return
    ch = self.activeModule.getPrevChapter(self.currentBook, self.currentChapter)
    if(ch):
      self.activeModule.loadBook(ch[0])
      self.currentBook = ch[0]
      self.ShowChapter(ch[1])
      self.page.clearScrollPos()
      self.arrangeControls()

  def NextChapter(self, event):
    if(not self.activeModule): return
    if(self.page.getMode()!='text'): return
    ch = self.activeModule.getNextChapter(self.currentBook, self.currentChapter)
    if(ch):
      self.activeModule.loadBook(ch[0])
      self.currentBook = ch[0]
      self.ShowChapter(ch[1])
      self.page.clearScrollPos()
      self.arrangeControls()

  def ToggleStrongs(self, event):
    if(not self.activeModule): return
    if(1 or self.page.getMode()!='strong'):
      #if(not self.page.getMode() in ('text','strong')): return
      if(self.strongsOn):
        self.strongsOn = False
      else:
        self.strongsOn = True
    self.ShowChapter(self.currentChapter)
    self.arrangeControls()

  def ShowStrong(self, number):
    isHeb = False
    if(number[0]=='0'):
      isHeb = True
      number = number[1:]
    if(number[0]=='0'):
      number = number[1:]
    number = int(number)
    res = self.bibles.getStrongText(number, isHeb)
    title = res[0]
    content = res[1]
    self.page.OutputHTML(title, content, 'strong')
    self.arrangeControls()

  def OnHistory(self, event):
    if(self.page.getMode()=='history'):
      self.ShowChapter(self.currentChapter)
      return
    content = ''
    for item in self.bibles.history:
      content = content + '' + item['title'] + '
'
    title = 'History:'
    self.page.OutputHTML(title, content, 'history')
    self.arrangeControls()

  def OnFind(self, event):
    if(not self.activeModule): return
    self.page.setMode('search')
    if(self.findPanel.IsShown()):
      self.ShowChapter(self.currentChapter)
    else:
      self.ShowSearchPage(1)
    self.arrangeControls()

  def OnSearchStart(self, event):
    if(not self.activeModule or self.searchField.GetValue()==''): return
    self.activeModule.search(self.searchField.GetValue(), [])
    self.ShowSearchPage(1)

  def ShowSearchPage(self, page):
    pageSize = 20
    searchCount = self.activeModule.searchCount()
    found = self.activeModule.getSearchPage(page, pageSize)
    title = str(searchCount) + ' results'
    content = ''
    for i in range(len(found)):
      content = content + '
' + \
                              found[i][3] + ' ' + \
                              self.transformContent(found[i][4], '', self.activeModule)
    pageCount = int(searchCount / pageSize) + 1
    content = content + '
'
    for i in range(1, pageCount+1):
      if(i == page):
        content = content + ' ' + str(i) + ' '
      else:
        content = content + ' ' + str(i) + ' '
    self.page.OutputHTML(title, content, 'search')

  def bibleGo(self, command):
    where = command.split(' ')
    if(not self.activeModule or where[0]!='-'):
      newModule = self.bibles.getModuleByShortPath(where[0])
      if(not newModule):
        wx.MessageBox("Could not open the module: \n" + command, "Error", wx.ICON_ERROR | wx.OK)
        return
      self.activeModule = newModule
      self.activeModule.loadModule()
      self.buttonz['module'].SetLabel(self.activeModule.BibleShortName)
    currentBook = int(where[1])-1
    self.activeModule.loadBook(currentBook)
    self.currentBook = currentBook
    self.buttonz['book'].SetLabel(self.activeModule.FullName[currentBook])

    #wx.MessageBox(where[2], "Chapter", wx.ICON_ERROR | wx.OK)
    currentChapter = int(where[2])
    if(self.activeModule.ChapterZero):
      currentChapter = currentChapter - 1
    self.currentChapter = currentChapter
    self.buttonz['chapter'].SetLabel(str(currentChapter))
    self.ShowChapter(currentChapter)
    self.arrangeControls()

  def OnCompare(self, event):
    title = 'Choose a module to compare:'
    return self.ShowModuleList(title, 'compare', False, True)

  def OnCompareChoise(self, path):
    if(path):
      self.compareModule = self.bibles.getModule(path)
    else:
      self.compareModule = None
    self.ShowChapter(self.currentChapter)

  def ToggleFullScreen(self, event):
    if self.fullScreen:
      self.fullScreen = False
    else:
      self.fullScreen = True
    self.ShowFullScreen(self.fullScreen, style=wx.FULLSCREEN_ALL)
    self.page.SetFocus()

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


import os
import shutil

#path that this script is in
path = os.path.dirname(os.path.realpath(__file__))

#r = root, d = directories, f = files
for r, d, f in os.walk(path):

        for file in f:

                if '.c' in file:

                        #joins the root and file to make file path
                        file_path = os.path.join(r, file)

                        #copies the file to path
                        shutil.copy(file_path, path)

                        #makes new file path where copied file is
                        file_path = os.path.join(path, file)

                        #renames copied file from '.c' to '.txt'
                        new_file_path = file_path[:-2] + '.txt'
                        os.rename(file_path, new_file_path)


import types
from imp import reload

def print_status(module):
    print(f'reloading {module.__name__}')

def try_reload(module):
    try:
        reload(module)
    except Exception as e:
        print(f'FAILED {e.__repr__()} : {module}')

def transitive_reload(module, visited):
    if not module in visited:
        print_status(module)
        try_reload(module)
        visited[module] = True
        for attrobj in module.__dict__.values():
            if type(attrobj) == types.ModuleType:
                transitive_reload(attrobj, visited)

def reload_all(*args):
    visited = {}
    for arg in args:
        if type(arg) == types.ModuleType:
            transitive_reload(arg, visited)

if __name__ == '__main__':
    def tester(reloader, modname):
        import importlib, sys
        if len(sys.argv) > 1:
            modname = sys.argv[1]
        module = importlib.import_module(modname)
        reloader(module)

    tester(reload_all, 'reloadall')


import tkinter as tk
from tkinter import ttk
import pyautogui
import pygetwindow

# The app was developed by Tom Girshovksi.
class CenterWindowGUI:
    def __init__(self, master):
        self.master = master
        master.title("Center Window")

        # Create the frame
        self.frame = ttk.Frame(master, padding=20)
        self.frame.pack()

        # Configure columns to have equal weight
        self.frame.columnconfigure(0, weight=1)
        self.frame.columnconfigure(1, weight=1)
        self.frame.columnconfigure(2, weight=1)

        # Create the label
        self.label = ttk.Label(self.frame, text="Choose a window to center:")
        self.label.grid(row=0, column=0, columnspan=3, pady=10)

        # Create the listbox to display the windows
        self.listbox = tk.Listbox(self.frame, width=50, height=10, selectmode=tk.SINGLE)
        self.listbox.grid(row=1, column=0, columnspan=3, padx=10, pady=10)
        self.update_windows()

        # Center Button
        self.center_button = ttk.Button(self.frame, text="Center Window", command=self.center_window)
        self.center_button.grid(row=2, column=0, pady=10)

        # Scale Function Button
        self.scale_button = ttk.Button(self.frame, text="Scale Window", command=self.scale_window)
        self.scale_button.grid(row=2, column=1, pady=10)

        # Update List Button
        self.update_button = ttk.Button(self.frame, text="Update List", command=self.update_windows)
        self.update_button.grid(row=2, column=2, pady=10)

    def center_window(self):
        # Get the index of the selected item in the list box
        index = self.listbox.curselection()[0]
        # Get the selected window
        window = self.windows[index]
        # Get the size of the screen
        screen_width, screen_height = pyautogui.size()
        # Get the size of the window
        window_width, window_height = window.size
        # Calculate the new position to center the window
        new_left = (screen_width - window_width) // 2
        new_top = (screen_height - window_height) // 2
        # Move the window to the new position
        window.moveTo(new_left, new_top)

    def update_windows(self):
        # Clear the list box
        self.listbox.delete(0, tk.END)
        # Get a list of all windows that are currently open
        self.windows = pyautogui.getAllWindows()
        # Add the window titles to the list box
        for window in self.windows:
            self.listbox.insert(tk.END, window.title)

    def scale_window(self):
        # Get the index of the selected item in the list box
        index = self.listbox.curselection()[0]
        # Get the selected window
        window = self.windows[index]
        # Get the size of the screen
        screen_width, screen_height = pyautogui.size()
        # Get the size of the window
        window_width, window_height = window.size

        if window_width == screen_width and window_height == screen_height:
            # If the window is already full screen, center it instead
            self.center_window()
        else:
            # Resize the window to full screen
            window.resizeTo(screen_width // 2 + 500, screen_height // 2 +300)

# Create the root window
root = tk.Tk()
root.resizable(False, False)
# Set the style of the GUI
style = ttk.Style(root)
gui = CenterWindowGUI(root)

root.mainloop()


import sys, re
from argparse import ArgumentParser #import the library

parser = ArgumentParser(description = 'Classify a sequence as DNA or RNA') #create one ArgumentParser
parser.add_argument("-s", "--seq", type = str, required = True, help = "Input sequence") #add the first argument
parser.add_argument("-m", "--motif", type = str, required = False, help = "Motif") #add the second argument

if len(sys.argv) == 1: #print the help message only if no arguments are supplied on the command line
    parser.print_help()
    sys.exit(1)

args = parser.parse_args() #parser the argument

args.seq = args.seq.upper() #convert the sequence  in upper case

if 'U' in args.seq and 'T' in args.seq: #if it finds U and T in the sequence return a message that the sequence have a mutagenic bases
	print ('The sequence have a mutagenic bases') # if it finds this condition it does not execute the others command line
	sys.exit ()

if re.search('^[ACGTU]+$', args.seq): #search in the sequence the pattern within the string
    if re.search('T', args.seq): #if it finds T in the sequence return a message that the sequence is DNA
        print ('The sequence is DNA')
    elif re.search('U', args.seq):
        print ('The sequence is RNA') #if it finds U in the sequence return a message that the sequence is RNA
    else:
        print ('The sequence can be DNA or RNA') #if it finds T and  U in the sequence return a message that the sequence can be DNA or RNA
else:
    print ('The sequence is not DNA') #else the sequence is not DNA

if args.motif:
    args.motif = args.motif.upper() #converte the motif in upper case
    print(f'Motif search enabled: looking for motif in sequence') #to find simple motifs in the sequence, besides printing the type of molecule (DNA or RNA)
    if re.search(args.motif, args.seq):
        print("FOUND")
    else:
        print("NOT FOUND")


import time
import pyrealsense2 as rs
import numpy as np
import cv2
import os
import open3d as o3d

intrinsics = np.array([
            [605.7855224609375, 0., 324.2651672363281, 0.0],
            [0., 605.4981689453125, 238.91090393066406, 0.0],
            [0., 0., 1., 0.0],
            [0., 0., 0., 1.],])

ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

def launch_realsense(pixel_width, pixel_high, fps, found_rgb=False):
    pipeline = rs.pipeline()
    # Create a config and configure the pipeline to stream
    config = rs.config()
    pipeline_wrapper = rs.pipeline_wrapper(pipeline)
    pipeline_profile = config.resolve(pipeline_wrapper)
    device = pipeline_profile.get_device()

    for s in device.sensors:
        if s.get_info(rs.camera_info.name) == 'RGB Camera':
            found_rgb = True
            break
    if not found_rgb:
        print("Can't launch rgb camera")
        exit(0)

    config.enable_stream(rs.stream.depth, pixel_width, pixel_high, rs.format.z16, fps)
    config.enable_stream(rs.stream.color, pixel_width, pixel_high, rs.format.bgr8, fps)

    align_to = rs.stream.color
    alignedFs = rs.align(align_to)
    # Start streaming
    pipeline.start(config)

    # Create folders by date
    save_path = os.path.join(os.getcwd(), "out_data",
                             time.strftime("%Y_%m_%d_%H_%M_%S",
                                           time.localtime()))
    os.makedirs(save_path)
    os.makedirs(os.path.join(save_path, "rgb"))
    os.makedirs(os.path.join(save_path, "depth"))
    os.makedirs(os.path.join(save_path, "depth_colormap"))

    # cv2.namedWindow("camera in real time", cv2.WINDOW_AUTOSIZE)
    # saved_color_image = None
    # saved_depth_mapped_image = None
    try:
        flag = 0
        while True:
            if flag == 0:
                time.sleep(2)
                flag = 1
                continue
            # Wait for a coherent pair of frames: rgb and depth
            frames = pipeline.wait_for_frames()
            align_frames = alignedFs.process(frames)
            depth_frame = align_frames.get_depth_frame()
            color_frame = align_frames.get_color_frame()
            if not depth_frame or not color_frame:
                continue

            color_profile = color_frame.get_profile()
            cvsprofile = rs.video_stream_profile(color_profile)
            color_intrin = cvsprofile.get_intrinsics()
            color_intrin_part = [color_intrin.ppx, color_intrin.ppy,
                                 color_intrin.fx, color_intrin.fy]
            print('**color_intrin_part**:',color_intrin_part)
            # Convert images to numpy arrays
            depth_image = np.asanyarray(depth_frame.get_data())
            color_image = np.asanyarray(color_frame.get_data())

            depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(depth_image, alpha=0.1), cv2.COLORMAP_JET)

            # depth_colormap_dim = depth_colormap.shape
            # color_colormap_dim = color_image.shape
            #
            # if depth_colormap_dim != color_colormap_dim:
            #     resized_color_image = cv2.resize(color_image, dsize=(depth_colormap_dim[1], depth_colormap_dim[0]),
            #                                      interpolation=cv2.INTER_AREA)
            #     images = np.hstack((resized_color_image, depth_colormap))
            # else:
            #     images = np.hstack((color_image, depth_colormap))

            # # Show images
            # cv2.imshow("camera in real time", images)
            # key = cv2.waitKey(1)

            # Save the image
            # if key & 0xFF == ord('s'):
            saved_count = 0
            for filename in os.listdir(os.path.join((save_path), "rgb")):
                if filename.endswith('.png'):
                    saved_count += 1
            print('save data:',saved_count)
            saved_color_image = color_image
            saved_depth_image = depth_image
            saved_depth_mapped_image = depth_colormap
            # save rgb png
            cv2.imwrite(os.path.join((save_path), "rgb",
                                     "rgb_{}.png".format(saved_count)),saved_color_image)
            # save depth_colormap png
            cv2.imwrite(os.path.join((save_path), "depth_colormap",
                                     "depth_colormap_{}.png".format(saved_count)),
                        saved_depth_mapped_image)
            # save depth png
            cv2.imwrite(os.path.join((save_path), "depth",
                                     "depth_{}.png".format(saved_count)),
                        saved_depth_image)
            # save depth npy
            np.save(os.path.join((save_path), "depth",
                                 "depth_{}.npy".format(saved_count)), saved_depth_image)

            depth_path = os.path.join((save_path), "depth", "depth_{}.npy".format(saved_count))
            color_path = os.path.join((save_path), "rgb", "rgb_{}.png".format(saved_count))
            return depth_path, color_path

    finally:
        # Stop streaming
        pipeline.stop()

def loadRGB(color_file):
    return cv2.cvtColor(cv2.imread(color_file), cv2.COLOR_BGR2RGB)

def loadDepth(depth_file):
    return cv2.imread(depth_file, cv2.IMREAD_UNCHANGED)

def save_points(depth_path, color_path):

    colors = loadRGB(color_path).astype(np.float32) / 255.0
    depths = np.load(depth_path) # loadDepth(depth_path)

    # convert RGB-D to point cloud
    fx, fy = intrinsics[0, 0], intrinsics[1, 1]
    cx, cy = intrinsics[0, 2], intrinsics[1, 2]
    # depth factor
    s = 1000.0
    xmap, ymap = np.arange(colors.shape[1]), np.arange(colors.shape[0])
    xmap, ymap = np.meshgrid(xmap, ymap)
    points_z = depths / s
    points_x = (xmap - cx) / fx * points_z
    points_y = (ymap - cy) / fy * points_z
    points = np.stack([points_x, points_y, points_z], axis=-1)
    points = points.reshape((-1, 3))
    colors = colors.reshape((-1, 3))

    mask = np.where(points[:, 2] < 1)
    points = points[mask]
    colors = colors[mask]

    cloud = o3d.geometry.PointCloud()
    cloud.points = o3d.utility.Vector3dVector(points)
    cloud.colors = o3d.utility.Vector3dVector(colors)

    coord = o3d.geometry.TriangleMesh.create_coordinate_frame(size=0.1, origin=[0, 0, 0])
    o3d.visualization.draw_geometries([cloud, coord])

    base_dir = os.path.dirname(os.path.dirname(color_path))
    points_file = os.path.join(base_dir, 'points.npy')
    colors_file = os.path.join(base_dir, 'colors.npy')
    np.save(points_file, points)
    np.save(colors_file, colors)
    return points_file, colors_file

if __name__ == '__main__':
    depth_path, color_path = launch_realsense(pixel_width=640, pixel_high=480, fps=30)
    save_points(depth_path, color_path)


# File: utils.py
# Name: Sergio Ley Languren

"""Utility for wordle program"""

from WordleDictionary import FIVE_LETTER_WORDS
from WordleGraphics import CORRECT_COLOR, PRESENT_COLOR, MISSING_COLOR, UNKNOWN_COLOR, N_COLS, N_ROWS, WordleGWindow
from random import choice
from typing import Type, Union, Optional
from copy import deepcopy
from tempfile import NamedTemporaryFile
from os import getcwd, unlink

__all__ = [
    "choose_word",
    "validate_responce",
    "ScoreFileParser"
]

# CONSTANT
MINUS_COL = 5

t = None

# Functions
def choose_word() -> str:
    """Chooses the answer from a list of words of five characters"""
    a = choice(FIVE_LETTER_WORDS)
    return a

# -----------------------------------------------

def _set_key_color_or_not(gw, key_colored, k, c, override_check=False):
    if not key_colored or override_check:
        gw.set_key_color(k.capitalize(), c)

def _add_color(gw, column, keycolored, character, color, ac, oc: Optional[bool] = None):
    gw.set_square_color(gw.get_current_row(), column, color)
    if oc:
        _set_key_color_or_not(gw, keycolored, character, color, oc)
    else:
        _set_key_color_or_not(gw, keycolored, character, color)
    a_copy = ac.replace(character, "", 1)
    return a_copy

def add_tempfile() -> NamedTemporaryFile:
    """creates score file"""
    global t
    if not t:
        t = NamedTemporaryFile("w+", encoding="utf-8", prefix="wordle_", dir=getcwd(), delete=False)
    return t

def validate_responce(gw: Type[WordleGWindow], res: str, a: str) -> Union[bool, bool, NamedTemporaryFile]:
    """Validates user response
    :param gw: Main Wordle window class
    :param res: User responce
    :param a: answer to the wordle

    Returns:
        validity | word-validation | score tempfile
    """
    global MINUS_COL
    a_copy = deepcopy(a)
    correct_counter = 0

    temp = add_tempfile()
    # checks if word is not in the word list
    if res not in FIVE_LETTER_WORDS:
        gw.show_message(f"{res} is not a word!!!")
        return False, True, temp

    for c in a:
        col = N_COLS - MINUS_COL
        ch = gw.get_square_letter(gw.get_current_row(), col).lower()
        key_colored = gw.get_key_color(c.capitalize()) != UNKNOWN_COLOR
        if ch == c:
            a_copy = _add_color(gw, col, key_colored, ch, CORRECT_COLOR, a_copy, True)
            correct_counter += 1
        elif ch in a_copy:
            a_copy = _add_color(gw, col, key_colored, ch, PRESENT_COLOR, a_copy)
        else:
            a_copy = _add_color(gw, col, key_colored, ch, MISSING_COLOR, a_copy)
        MINUS_COL -= 1

    line = f"{gw.get_current_row()}|{correct_counter}\n"
    temp.write(line)
    temp.flush()

    MINUS_COL = 5

    if correct_counter == 5:
        return True, False, temp
    return False, False, temp

class ScoreFileParser:
    """
    Parses and adds score to wordle grid based on the scorefile
    """
    cleared = False

    def __init__(self, gw: Type[WordleGWindow], tmp: Type[NamedTemporaryFile]):
        self.gw = gw
        self.tmpfile = tmp

    def parse(self):
        """Main function to parse the score file"""
        self.tmpfile.seek(0)
        lines = self.tmpfile.readlines()
        if not self.cleared:
            self.clear_grid()
            self.parse()
        for l in lines:
            row = l.split("|")[0]
            correct_points = l.split("|")[1].replace("\n", "")
            self.gw.set_square_letter(int(row), 0, str(int(row) + 1))
            self.gw.set_square_letter(int(row), 4, correct_points)
            self.gw.set_square_color(int(row), 0, PRESENT_COLOR)
            if int(correct_points) == 5:
                self.gw.set_square_color(int(row), 4, CORRECT_COLOR)
            else:
                self.gw.set_square_color(int(row), 4, MISSING_COLOR)
        self.gw.show_message("rows                           points", "limegreen")

    def clear_grid(self):
        """Clear wordle grid"""
        for i in range(N_ROWS):
            self.gw.set_current_row(i)
            for j in range(N_COLS):
                self.gw.set_square_letter(i, j, "")
        self.cleared = True

    def close(self):
        """closes the score file"""
        self.tmpfile.close()
        path = self.tmpfile.name
        print(path)
        unlink(path)