#utils.py

import pandas as pd
import numpy as np
import nltk
from nltk.tokenize import RegexpTokenizer

def intersecting_str(x,y,method='contains'):
  '''
   Set (per Guarani) with the top M most frequent words or dictionary. Then intersect|contains your text with each set. The set with the highest number of intersections|coincides will be your detected language: Guarani.
   x = text convert to set ... of words to infer language (i.e, tweets)
   y = file convert to set ... of words of the language to infer (i.e., Guarani dictionary)
   method = intersection|contains
   return = tuple() of number of x in y words, and number of x words, also the match words are given
   finally = with the tuple... percent: divide the number of words by the total number of words in the text, or
                               count:   take those with more than X words in the dictionary
  '''
  # convert x (text) to set
  tokenizer = RegexpTokenizer(r"(\w+\'\w?)|(\w+)") # alphabetic characters only + '...
  words = tokenizer.tokenize(str(x)) # return tuples because "|" #word_tokenize(str(x)) #set(str(x).lower().split())
  x = set([t[0] for t in words]+[t[1] for t in words])
  # convert y (file) to set
  #y = set(readFile(y))
  #
  if method=='contains':
    # prepare set
    try:
      xnp = np.array(x)
      xpd = pd.DataFrame(x)
      xpd.columns=["col"]
      gn=xpd[xpd.col.str.contains('|'.join(y))].reset_index() # partial match: e.g., "omba'apo" contains "apo" = TRUE
      gn=gn.col.tolist()
    except:
      gn=list()
  elif method=='intersection':
    gn = x.intersection(y) # strict match: e.g., "omba'apo" intersect "apo" = FALSE

  match = set(list(gn))
  return len(gn), len(x), match

def readFile(fileName):
    fileObj = open(fileName, "r") #opens the file in read mode
    words = [line.split(",") for line in fileObj.read().splitlines()] # puts the file into an array
    merged_list = []
    for l in words: # an array from the list of arrays:  syn/n-grams comma separated support
      merged_list += l
    fileObj.close()
    return [word for word in merged_list if len(word)>2]

ISO_639_1_TO_3 = {
    'aa': 'aar',
    'ab': 'abk',
    'ae': 'ave',
    'af': 'afr',
    'ak': 'aka',
    'am': 'amh',
    'an': 'arg',
    'ar': 'ara',
    'as': 'asm',
    'av': 'ava',
    'ay': 'aym',
    'az': 'aze',
    'ba': 'bak',
    'be': 'bel',
    'bg': 'bul',
    'bi': 'bis',
    'bm': 'bam',
    'bn': 'ben',
    'bo': 'bod',
    'br': 'bre',
    'bs': 'bos',
    'ca': 'cat',
    'ce': 'che',
    'ch': 'cha',
    'co': 'cos',
    'cr': 'cre',
    'cs': 'ces',
    'cu': 'chu',
    'cv': 'chv',
    'cy': 'cym',
    'da': 'dan',
    'de': 'deu',
    'dv': 'div',
    'dz': 'dzo',
    'ee': 'ewe',
    'el': 'ell',
    'en': 'eng',
    'eo': 'epo',
    'es': 'spa',
    'et': 'est',
    'eu': 'eus',
    'fa': 'fas',
    'ff': 'ful',
    'fi': 'fin',
    'fj': 'fij',
    'fo': 'fao',
    'fr': 'fra',
    'fy': 'fry',
    'ga': 'gle',
    'gd': 'gla',
    'gl': 'glg',
    'gn': 'grn',
    'gu': 'guj',
    'gv': 'glv',
    'ha': 'hau',
    'he': 'heb',
    'hi': 'hin',
    'ho': 'hmo',
    'hr': 'hrv',
    'ht': 'hat',
    'hu': 'hun',
    'hy': 'hye',
    'hz': 'her',
    'ia': 'ina',
    'id': 'ind',
    'ie': 'ile',
    'ig': 'ibo',
    'ii': 'iii',
    'ik': 'ipk',
    'io': 'ido',
    'is': 'isl',
    'it': 'ita',
    'iu': 'iku',
    'ja': 'jpn',
    'jv': 'jav',
    'ka': 'kat',
    'kg': 'kon',
    'ki': 'kik',
    'kj': 'kua',
    'kk': 'kaz',
    'kl': 'kal',
    'km': 'khm',
    'kn': 'kan',
    'ko': 'kor',
    'kr': 'kau',
    'ks': 'kas',
    'ku': 'kur',
    'kv': 'kom',
    'kw': 'cor',
    'ky': 'kir',
    'la': 'lat',
    'lb': 'ltz',
    'lg': 'lug',
    'li': 'lim',
    'ln': 'lin',
    'lo': 'lao',
    'lt': 'lit',
    'lu': 'lub',
    'lv': 'lav',
    'mg': 'mlg',
    'mh': 'mah',
    'mi': 'mri',
    'mk': 'mkd',
    'ml': 'mal',
    'mn': 'mon',
    'mr': 'mar',
    'ms': 'msa',
    'mt': 'mlt',
    'my': 'mya',
    'na': 'nau',
    'nb': 'nob',
    'nd': 'nde',
    'ne': 'nep',
    'ng': 'ndo',
    'nl': 'nld',
    'nn': 'nno',
    'no': 'nor',
    'nr': 'nbl',
    'nv': 'nav',
    'ny': 'nya',
    'oc': 'oci',
    'oj': 'oji',
    'om': 'orm',
    'or': 'ori',
    'os': 'oss',
    'pa': 'pan',
    'pi': 'pli',
    'pl': 'pol',
    'ps': 'pus',
    'pt': 'por',
    'qu': 'que',
    'rm': 'roh',
    'rn': 'run',
    'ro': 'ron',
    'ru': 'rus',
    'rw': 'kin',
    'sa': 'san',
    'sc': 'srd',
    'sd': 'snd',
    'se': 'sme',
    'sg': 'sag',
    'sh': 'hbs',
    'si': 'sin',
    'sk': 'slk',
    'sl': 'slv',
    'sm': 'smo',
    'sn': 'sna',
    'so': 'som',
    'sq': 'sqi',
    'sr': 'srp',
    'ss': 'ssw',
    'st': 'sot',
    'su': 'sun',
    'sv': 'swe',
    'sw': 'swa',
    'ta': 'tam',
    'te': 'tel',
    'tg': 'tgk',
    'th': 'tha',
    'ti': 'tir',
    'tk': 'tuk',
    'tl': 'tgl',
    'tn': 'tsn',
    'to': 'ton',
    'tr': 'tur',
    'ts': 'tso',
    'tt': 'tat',
    'tw': 'twi',
    'ty': 'tah',
    'ug': 'uig',
    'uk': 'ukr',
    'ur': 'urd',
    'uz': 'uzb',
    've': 'ven',
    'vi': 'vie',
    'vo': 'vol',
    'wa': 'wln',
    'wo': 'wol',
    'xh': 'xho',
    'yi': 'yid',
    'yo': 'yor',
    'za': 'zha',
    'zh': 'zho',
    'zu': 'zul'}

def set_iso_639(code, source=3, target=1):
    try:
        if source == 3:
            # 639-3 to 1
            # first, invert dict
            ISO_639_3_TO_1 = {v: k for k, v in ISO_639_1_TO_3.items()}
            #
            return ISO_639_3_TO_1[code]
        elif source == 1:
            # 639-1 to 3
            return ISO_639_1_TO_3[code]
    except:
        return 'undefined'


import os
os.system("cls")

numero1 = int (input("primer numero entero: "))
numero2 = int (input("segundo numero entero: "))
numero3 = int (input("tercer numero entero: "))

if numero1 > numero2:
    numeroMedio = numero1
    x1 = numero2
else:
    numeroMedio = numero2
    x1=numero1
if numeroMedio > numero3:
    numeroMedio = numero3
if numeroMedio < x1:
    numeroMedio = x1

print (f"el promedio es: {(numeroMedio)}")
print()


import json
import numpy as np
import sklearn.naive_bayes
from sklearn.base  import TransformerMixin
from nltk import word_tokenize
from sklearn.feature_extraction import DictVectorizer
from sklearn.naive_bayes import BernoulliNB
from sklearn.pipeline import Pipeline
from sklearn.model_selection import cross_val_score
import os
list=[]
lableList=[]
lable=['alt.atheism','comp.graphics','comp.os.ms-windows.misc','comp.sys.ibm.pc.hardware','comp.sys.mac.hardware','comp.windows.x','misc.forsale','rec.autos',
       'rec.motorcycles','rec.sport.baseball','rec.sport.hockey','sci.crypt','sci.electronics','sci.med','sci.space','soc.religion.christian',
       'talk.politics.guns','talk.politics.mideast','talk.politics.misc','talk.religion.misc']
def solve():
    class_list = np.array(lableList)
    data_list = np.array(list)
    class NLTKBOW(TransformerMixin):
        def fit(self, X, y=None):
            return self

        def transform(self, X):
            return [
                {
                    word: True for word in word_tokenize(document)
                } for document in X
            ]

    pipeline = Pipeline([('布袋模型转换', NLTKBOW()),
                         ('字典列表转矩阵', DictVectorizer(sparse=True)),
                         ('素贝叶斯分类器',sklearn.naive_bayes.MultinomialNB() )],
                        verbose=True
                        )
    scores = cross_val_score(pipeline, data_list, class_list, scoring='accuracy',cv=5)
    print("Score: {}".format(np.mean(scores)))
def getId(string):
    for i in range(len(lable)):
        if(lable[i] in string) :
            return i
def readFile(path):
    files = os.listdir(path)  # 得到文件夹下的所有文件名称
    s = []
    for file in files:  # 遍历文件夹
        file = os.path.join(path, file)

        if not os.path.isdir(file):  # 判断是否是文件夹，不是文件夹才打开
            f = open(file, encoding='utf-8', errors='ignore')  # 打开文件
            iter_f = iter(f)  # 创建迭代器
            str1 = ""
            for line in iter_f:
                str1 = str1 +" "+ line
            list.append(str1)  # 每个文件的文本存到list中
            id=getId(file)
            lableList.append(id)
        else:
            readFile(file)
if __name__ == '__main__':
    path=r'./mini_newsgroups'
    readFile(path)
    solve()


from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404
from main.models import *
from settings import MEDIA_URL, MAX_SUBMISSIONS
from django.contrib.auth.models import User
from django.template import RequestContext
from django.contrib.auth.decorators import login_required

def home(request):
    return render_to_response('main/index.html',context_instance=RequestContext(request))

def credits(request):
    return render_to_response('main/credits.html',context_instance=RequestContext(request))

@login_required
def contest_index(request):
    problem_list = []
    if not request.user.is_active:
        request.user = testuser
    user = request.user
    if request.user.is_superuser:
        problems = Problem.objects.all()
    else:
        problems = Problem.objects.filter(is_public=True)
    for problem in problems:
        problem.is_solved = problem.solved(user)
        problem_list.append(problem)

    if request.user.is_superuser:
        submissions = Submission.objects.filter(is_latest=True).order_by('-time')[:500]
    else:
        submissions = Submission.objects.filter(is_latest=True, problem__is_public=True).order_by('-time')[:10]
    return render_to_response('main/contest_index.html', {
        'problems': problem_list,
        'submissions':submissions,
        'total_marks': get_total_marks(user),
    },context_instance=RequestContext(request))

@login_required
def problem_detail(request, problem_id):
    if request.user.is_superuser:
        problem = get_object_or_404(Problem, pk=problem_id)
    else:
        problem = get_object_or_404(Problem, pk=problem_id, is_public=True)
    public_testcases = problem.testcase_set.filter(is_public=True)
    user = request.user
    last_submission = []
    user_submissions = Submission.objects.filter(user = user, problem = problem).order_by('-time')
    if user_submissions:
        last_submission  = user_submissions[0]

    if request.method == 'POST':
        form = SubmissionForm(request.POST, request.FILES)
        #Saving the form if it is valid
        if form.is_valid():
            new_submission = form.save(commit=False)
            #Calling the worker to perform the task submit through celery
            new_submission.save(user = user, problem = problem)
            #Redirect to the results of the submission
            return HttpResponseRedirect(problem.get_absolute_url())
    else:
        #New form for a submission
        form = SubmissionForm()

    left_submissions = MAX_SUBMISSIONS - last_submission.attempts()  if last_submission else MAX_SUBMISSIONS
    submission_limit_reached = left_submissions <= 0

    return render_to_response('main/problem_detail.html', {
        'problem': problem,
        'public_testcases':public_testcases,
        'form': form,
        'left_submissions':left_submissions,
        'total_marks': get_total_marks(user),
        'submission_limit_reached':submission_limit_reached,
        'media_prefix':MEDIA_URL,
        'last_submission':last_submission,},
        context_instance=RequestContext(request))

@login_required
def problem_input(request, problem_id, testcase_id):
    testcase = get_object_or_404(TestCase, pk=testcase_id)
    if testcase.is_public:
        return HttpResponse(testcase.input_file.read(),mimetype="text/in")
    else:
        raise Http404

@login_required
def problem_output(request, problem_id, testcase_id):
    testcase = get_object_or_404(TestCase, pk=testcase_id)
    if testcase.is_public:
        return HttpResponse(testcase.output_file.read(),mimetype="text/out")
    else:
        raise Http404

def reg_team(request, team_id, team_name, password, email):
    if request.GET.get('pass', False) == "paswrd":
        user = User(username=team_id, first_name=team_name)
        user.set_password(password)
        user.save()
        user.email = email
        user.save()
        return HttpResponse()
    else:
        raise Http404


class Solution:
    def countNegatives(self, grid: List[List[int]]) -> int:  # 81.21%  47.11%
        out = 0
        for row in grid:
            for i in range(len(row)):
                if row[i] < 0:
                    out += len(row[i:])
                    break
        return out

    def countNegatives_v2(self, grid):  # 89.68% 80.90%
        n, m = len(grid), len(grid[0])
        cnt = 0
        row = n-1
        col = 0
        while(row >= 0 and col < m):
            if grid[row][col] < 0:
                cnt += m - col
                row -= 1
                col = 0
            else:
                col += 1
        return cnt

    def countNegatives_short(self, grid: List[List[int]]) -> int:
        return sum(x < 0 for row in grid for x in row)

    def countNegatives_study(self, grid):  # 44.97% 97.77%
        def bin_search(idx):
            left, right = 0, n
            while left < right:
                mid = left + (right-left)//2
                if grid[idx][mid] < 0:
                    right = mid
                else:
                    left = mid + 1
            return right

        down = m = len(grid)-1
        n = len(grid[0])-1
        up = 0
        out = 0
        while up <= down:
            mid = up + (down-up)//2
            if grid[mid][-1] < 0:
                down = mid - 1
            else:
                up = mid + 1
        for i in range(up, m+1):
            out += n - bin_search(i) + 1
        return out

    def countNegatives_best_speed(self, grid: List[List[int]]) -> int:
        numneg = 0
        for g in grid:
            left = 0
            right = len(g)-1

            while left < right:
                mid = (left+right)//2
                if g[mid] >= 0:
                    left = mid+1
                else:
                    right = mid
            if g[left] < 0:
                numneg += (len(g)-1-left+1)
        return numneg

    def countNegatives_2nd_best_speed(self, grid: List[List[int]]) -> int:
        i, count, m, n = 0, 0, len(grid)-1, len(grid[0])-1
        while i <= m and n >= 0:
            if grid[i][n] < 0:
                count = count+(m+1-i)
                n = n-1
            else:
                i = i+1
        return count

    def countNegatives_best_memory(self, n: List[List[int]]) -> int:
        q = 0
        for i in range(len(n)-1, -1, -1):
            if n[i][len(n[i])-1] >= 0:
                break
            for j in range(len(n[i])-1, -1, -1):
                if n[i][j] < 0:
                    q += 1
                else:
                    break
        return q

1300 - 1399/1351 - Count Negative Numbers in a Sorted Matrix/1351 - Count Negative Numbers in a Sorted Matrix.py


# -*- coding: UTF-8 -*-

from enum import Enum

class NeTDef(Enum):
    '''netnotify type'''
    SEND = 0
    RECV = 1
    CONNECT = 2         # 不管是作为服务端还是客户端,都发这个消息
    DISCONNECT = 3       # 不管是主动还是被动,都向逻辑线程使用这个定义

    SERVER_CLOSE = 4            # 服务端主动关闭一个客户端

    CLIENT_CREATE = 5          # 客户端创建一个连接
    CLIENT_CLOSE = 6            # 客户端关闭一个连接
    CLIENT_CONNECT_FAIL = 7     # 作为客户端,连远程服务器失败

    LISTEN_NUM = 100                  # 监听一次数量
    SELECT_TIME_OUT = 0.016           # select timeout. 16毫秒,每秒60帧
    MAX_TRANSMIT_ONE_FRAME = 1024       # 每一帧发送的最大数量包,发不了的下一帧

    WINDOWS_SELECT_MAX = 502            # python的selectors在windows下使用的是select,最大只支持509.
                                        # ValueError: too many file descriptors in select()


"""
   Utility functions used by multiple files

"""

from PIL import Image
from hyperparameters import *
import numpy as np

# used for pretty printing
line_sep = '+----------------------------------------------------------------------------------------+'

# expand dimensions to (1, 84, 84, 4) from (84, 84, 4)
# use array[0:1,:,:,:]
# normalize 0-255 -> 0.0-1.0 to reduce exploding gradient
def normalize_frames(current_frame_history):
    return current_frame_history.astype('float32') / 255.

# reduces the rgb channels to black and white (3 axis to 2 axis),
# then resizes the (210, 160) to (height, width) default: 84, 84
# then reduces the np array to 0-255 ints for saving space
# finally expands the axis 0 dimension by one for saving into the conv net
def preprocess(img):
    # resize and grayscape
    assert img.ndim == 3  # (height, width, channel)
    img = Image.fromarray(img)
    img = img.resize((hp['HEIGHT'], hp['WIDTH'])).convert('L')
    processed_img = np.array(img)
    assert processed_img.shape == (hp['HEIGHT'], hp['WIDTH'])
    return processed_img.astype('uint8')

# prints statistics at the end of every episode
def print_stats(total_episodes_elapsed, total_frames_elapsed, epsilon,
                episodic_reward, total_reward, avg_reward, avg_Q, time_elapsed):

    print('\nepisodes elapsed: {0:3d} | '
          'frames elapsed: {1:6d} | '
          'epsilon: {2:1.5f}\n'
          'total reward: {3:3.0f} | '
          'reward this episode: {4:3.0f} | '
          'avg reward/episode: {5:3.3f}\n'
          'avg Q: {6:1.5f} | '
          'time elapsed : {7:5.5}\n'.format(total_episodes_elapsed, total_frames_elapsed,
                                     epsilon, total_reward, episodic_reward ,avg_reward, avg_Q, time_elapsed))
    print(line_sep)

# plots a graph of the game
def plot_initial_graph(env):
    plt.imshow(env.render(mode='rgb_array'))
    plt.title("%s" % (env.spec.id))
    clear_output(wait=True)
    display(plt.gcf())

# initializes the beginning of an episode by loading the first frame
# however big the frame skip size is default: 4
# into a historical frame buffer
def init_discrete_frame_skip(past_frames_size, frame):

    for i in range(hp['FRAME_BATCH_SIZE']):
        past_frames_size[:, :, :, i] = preprocess(frame)

def init_sliding_frame_skip(past_frames_size, frame):
    for i in range(hp['FRAME_BATCH_SIZE']+1):
        past_frames_size[:, :, :, i] = preprocess(frame)

# returns the max number of lives in the game being played
def find_max_lives(env):
    # don't step anywhere, but grab info
    _, _, _, info = env.step(0)
    return info['ale.lives']    # return max lives


# 训练分类器模型
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
from os.path import join as pjoin
from sklearn.model_selection import train_test_split  # 制作训练数据和测试数据
from sklearn import metrics
from sklearn.externals import joblib  # 保存模型
from scipy import misc  #图像处理
import tensorflow as tf
import numpy as np
import os
import facenet
import align.detect_face

minsize = 20 # minimum size of face
threshold = [ 0.6, 0.7, 0.7 ]  # three steps's threshold
factor = 0.709 # scale factor

print('创建mtcnn网络，并加载参数')
with tf.Graph().as_default():
    #限制GPU使用率
    gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=1.0) #使用率为百分百
    sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
    with sess.as_default():
        pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None)

def load_and_align_data(image, image_size, margin, gpu_memory_fraction):
    """
    主要执行resize操作
    :param image:
    :param image_size:
    :param margin:
    :param gpu_memory_fraction:
    :return: det,crop_image,1
    """
    # 读取图片
    img = image
    # 获取图片的shape
    img_size = np.asarray(img.shape)[0:2]

    # 检测出人脸框和5个特征点
    # 返回边界框数组 （参数分别是输入图片 脸部最小尺寸 三个网络 阈值 factor不清楚）
    bounding_boxes, _ = align.detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)

    # 如果检测出图片中不存在人脸 则直接返回，return 0（表示不存在人脸，跳过此图）
    if len(bounding_boxes) < 1:
        return 0,0,0
    else:
        crop=[]
        det=bounding_boxes

        det[:,0]=np.maximum(det[:,0], 0)  #取第一列大于0的数据
        det[:,1]=np.maximum(det[:,1], 0)
        det[:,2]=np.minimum(det[:,2], img_size[1])
        det[:,3]=np.minimum(det[:,3], img_size[0])

        # det[:,0]=np.maximum(det[:,0]-margin/2, 0)
        # det[:,1]=np.maximum(det[:,1]-margin/2, 0)
        # det[:,2]=np.minimum(det[:,2]+margin/2, img_size[1])
        # det[:,3]=np.minimum(det[:,3]+margin/2, img_size[0])

        det=det.astype(int)

        for i in range(len(bounding_boxes)):
            temp_crop=img[det[i,1]:det[i,3],det[i,0]:det[i,2],:]
            aligned=misc.imresize(temp_crop, (image_size, image_size), interp='bilinear')
            prewhitened = facenet.prewhiten(aligned)
            crop.append(prewhitened)
        crop_image=np.stack(crop)

        return det,crop_image,1

    # np.squeeze() 降维，指定第几维，如果那个维度不是1  则无法降维
    # det = np.squeeze(bounding_boxes[0,0:4])
def to_rgb(img):
    w, h = img.shape
    ret = np.empty((w, h, 3), dtype=np.uint8)
    ret[:, :, 0] = ret[:, :, 1] = ret[:, :, 2] = img
    return ret

def load_data(data_dir):
    """
    返回一个data字典，该字典类型 key对应人物分类，
    value为读取的一个人的所有图片 类型为 ndarray
    :param data_dir: 对应项目中的train_dir路径，同一个人的所有图片放在同一个文件夹中
    :return: data
    """

    data = {}
    pics_ctr = 0
    for guy in os.listdir(data_dir):
        person_dir = pjoin(data_dir, guy)
        curr_pics = [read_img(person_dir, f) for f in os.listdir(person_dir)]

        # 存储每一类人的文件夹内所有图片
        data[guy] = curr_pics
    return data

def read_img(person_dir,f):
    img=cv2.imread(pjoin(person_dir, f))
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 判断数组维度
    if gray.ndim == 2:
        img = to_rgb(gray)
    return img

# facenet模型存放路径
model_dir='./20170512-110547'
#在新的计算图中做运算
with tf.Graph().as_default():
    with tf.Session() as sess:
        # 加载facenet模型
        facenet.load_model(model_dir)

        # 返回给定名称的tensor
        images_placeholder = tf.get_default_graph().get_tensor_by_name("input:0")
        embeddings = tf.get_default_graph().get_tensor_by_name("embeddings:0")
        phase_train_placeholder = tf.get_default_graph().get_tensor_by_name("phase_train:0")

        # 从训练数据文件夹中加载图片并剪裁，最后embding，data为dict
        data=load_data('./Data/train_dirs/')
        print('image loaded')
        # keys列表存储图片文件夹类别（几个人）
        keys=[]
        for key in data:
            keys.append(key)
            print('folder:{},image numbers：{}'.format(key,len(data[key])))

        train_x=[]
        train_y=[]
        #name_flags = {}
        # 使用mtcnn模型获取每张图中face的数量以及位置，并将得到的embedding数据存储
        #for index in range(len(keys)):
            #name_flags[keys[index]] = index  #名字对应标签
        for index in range(len(keys)):
            for x in data[keys[index]]:
                det,images_me,i = load_and_align_data(x, 160, 44, 1.0)
                if i:
                    feed_dict = {images_placeholder: images_me, phase_train_placeholder: False}
                    emb = sess.run(embeddings, feed_dict=feed_dict)
                    print(type(emb))
                    for xx in range(len(emb)):
                        print(type(emb[xx, :]), emb[xx, :].shape)
                        train_x.append(emb[xx, :])
                        train_y.append(index)
            print(len(train_x))

        print('所有人像转换完成，样本数为：{}'.format(len(train_x)))

train_x=np.array(train_x)
print(train_x.shape)
train_x=train_x.reshape(-1,128)
train_y=np.array(train_y)
print(train_x.shape)
print(train_y.shape)

#分别得到train_x和train_y的训练数据和测试数据
X_train, X_test, y_train, y_test = train_test_split(train_x, train_y, test_size=.3, random_state=42)
print(X_train.shape,y_train.shape,X_test.shape,y_test.shape)

def knn_classifier(train_x, train_y):
    """
    KNN Classifier，K最近邻分类器。核心思想是如果一个样本在特征空间中的
    k个最相似(即特征空间中最邻近)的样本中的大多数属于某一个类别，则该样本也属于这个类别。
    :param train_x:training data，待训练的数据
    :param train_y:target value，待训练数据一一对应的标签
    :return: model
    """
    from sklearn.neighbors import KNeighborsClassifier
    model = KNeighborsClassifier()
    model.fit(train_x, train_y)
    return model

def svm_classifier(train_x, train_y):
    from sklearn import svm
    model = svm.SVC(kernel='linear')
    model.fit(X_train, y_train)
    return model
# classifiers = knn_classifier
#
# model = classifiers(X_train,y_train)
# predict = model.predict(X_test)
# SCORE_ = model.predict_proba(X_test)
# print(SCORE_)
# # 计算预测标签的精度
# accuracy = metrics.accuracy_score(y_test, predict)
# print ('accuracy: %.2f%%' % (100 * accuracy)  )
classifiers = svm_classifier

model = classifiers(X_train,y_train)

predict = model.predict(X_test)
accuracy = metrics.accuracy_score(y_test, predict)
print ('accuracy: %.6f%%' % (100 * accuracy))
#save model
joblib.dump(model, './models/svm_classifier42.model')

# model = joblib.load('./models/svm_classifier42.model')
# predict = model.predict(X_test)
# accuracy = metrics.accuracy_score(y_test, predict)
# print ('accuracy: %.2f%%' % (100 * accuracy)  )


import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data

from .constants import *

class CNNModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.features = nn.Sequential(
            # 224 x 224 x 3
            nn.Conv2d(
                3,
                CONV1_OUT,
                kernel_size=CONV1_KERNEL,
                stride=CONV1_STRIDE,
                padding=CONV1_PADDING,
            ),
            # 54 x 54 x 96
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=MAX_POOL1_KERNEL, stride=MAX_POOL1_STRIDE),
            nn.CrossMapLRN2d(size=5, alpha=0.0001, beta=0.75, k=1.0),
            # 26 x 26 x 96
            nn.Conv2d(
                CONV1_OUT,
                CONV2_OUT,
                kernel_size=CONV2_KERNEL,
                stride=CONV2_STRIDE,
                padding=CONV2_PADDING,
                groups=2,
            ),
            # 26 x 26 x 256
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=MAX_POOL2_KERNEL, stride=MAX_POOL2_STRIDE),
            nn.CrossMapLRN2d(size=5, alpha=0.0001, beta=0.75, k=1.0),
            # 12 x 12 x 256
            nn.Conv2d(
                CONV2_OUT,
                CONV3_OUT,
                kernel_size=CONV3_KERNEL,
                stride=CONV3_STRIDE,
                padding=CONV3_PADDING,
            ),
            # 12 x 12 x 384
            nn.ReLU(inplace=True),
            nn.Conv2d(
                CONV3_OUT,
                CONV4_OUT,
                kernel_size=CONV4_KERNEL,
                stride=CONV4_STRIDE,
                padding=CONV4_PADDING,
            ),
            # 12 x 12 x 64
            nn.ReLU(inplace=True),
        )

    def forward(self, x):
        x = self.features(x)
        x = x.reshape(x.size(0), -1)
        return x

class FaceModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv = CNNModel()
        self.fc = nn.Sequential(
            # 12 * 12 * 64
            nn.Linear(FINAL_CNN_DIM, FC_F1),
            nn.ReLU(inplace=True),
            # 128
            nn.Linear(FC_F1, FC_F2),
            nn.ReLU(inplace=True),
        )

    def forward(self, x):
        x = self.conv(x)
        x = self.fc(x)
        return x

class FaceGridModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc = nn.Sequential(
            # 25 * 25
            nn.Linear(GRID_SIZE * GRID_SIZE, FC_FG1),
            nn.ReLU(inplace=True),
            # 256
            nn.Linear(FC_FG1, FC_FG2),
            nn.ReLU(inplace=True),
        )

    def forward(self, x):
        x = x.reshape(x.size(0), -1)
        x = self.fc(x)
        return x

class ITrackerModel(nn.Module):
    def __init__(self, features_only=False):
        super().__init__()
        self.eyeModel = CNNModel()
        self.faceModel = FaceModel()
        self.gridModel = FaceGridModel()

        self.eyesFC = nn.Sequential(
            nn.Linear(2 * FINAL_CNN_DIM, FC_E1),
            nn.ReLU(inplace=True),
        )
        if not features_only:
            self.fc = nn.Sequential(
                nn.Linear(FC_E1 + FC_F2 + FC_FG2, FC1),
                nn.ReLU(inplace=True),
                nn.Linear(FC1, FC2),
            )
        else:
            self.fc = nn.Sequential(
                nn.Linear(FC_E1 + FC_F2 + FC_FG2, FC1),
                nn.ReLU(inplace=True)
            )

        # self.fc.0.1

        self.features_only = features_only

    def forward(self, faces, eyesLeft, eyesRight, faceGrids):
        xEyeL = self.eyeModel(eyesLeft)
        xEyeR = self.eyeModel(eyesRight)

        xEyes = torch.cat((xEyeL, xEyeR), 1)
        xEyes = self.eyesFC(xEyes)

        xFace = self.faceModel(faces)
        xGrid = self.gridModel(faceGrids)

        x = torch.cat((xEyes, xFace, xGrid), 1)
        x = self.fc(x)

        return x


from django.contrib import admin

from .models import Follow, User

class FollowAdmin(admin.ModelAdmin):
    list_display = (
        'pk',
        'following',
        'user',
    )
    list_display_links = (
        'user',
    )
    search_fields = ('user', 'following')
    list_filter = ('user', 'following')

class UserAdmin(admin.ModelAdmin):
    list_display = (
        'pk',
        'email',
        'username',
        'first_name',
        'last_name',
    )
    list_display_links = (
        'username',
    )
    search_fields = (
        'username',
    )
    list_filter = (
        'username',
    )

admin.site.register(Follow, FollowAdmin)
admin.site.register(User, UserAdmin)


import re
from uuid import uuid1
from icalendar import Calendar, Event
from datetime import datetime, date
from dateutil.relativedelta import relativedelta
from xjtu import DEAN

def display(cal):
    return cal.to_ical().decode('utf-8').replace('\r\n', '\n').strip()

def get_ics(schedule):
    cal = Calendar()
    cal['version'] = '2.0'
    cal['prodid'] = '-//CQUT//Syllabus//CN'  # *mandatory elements* where the prodid can be changed, see RFC 5445
    start_monday = date(2017, 9, 4)  # 开学第一周星期一的时间 TODO: 从 http://cale.dc.cqut.edu.cn/Index.aspx?term=2016-2017 抓取开学时间
    dict_week = {'一': 0, '二': 1, '三': 2, '四': 3, '五': 4, '六': 5, '日': 6}
    dict_day = {1: relativedelta(hours=8, minutes=0), 3: relativedelta(hours=10, minutes=10),
                5: relativedelta(hours=14, minutes=0), 7: relativedelta(hours=16, minutes=10),
                9: relativedelta(hours=19, minutes=0)}
    for line in schedule:
        event = Event()
        print(line)
        # line should be like this: ['汇编语言程序设计', '周三第7~8节', '第10-10周|双周', '第1实验楼B403-A', '刘小洋(刘小洋)']

        info_day = re.findall(r'周(.*?)第(\d+)~(\d+)节', line[3], re.S | re.M)
        info_day = info_day[0]
        print(info_day)
        # info_day should be like this: ('三', '7', '8')
        info_week = re.findall(r'第(\d+)-(\d+)周', line[2], re.S | re.M)
        try:
            info_week = info_week[0]
        except:
            info_week = ('1', '16')
        print(info_week)
        # info_week should be like this: ('10', '10')

        dtstart_date = start_monday + relativedelta(weeks=(int(info_week[0]) - 1)) + relativedelta(
            days=int(dict_week[info_day[0]]))
        dtstart_datetime = datetime.combine(dtstart_date, datetime.min.time())
        dtstart = dtstart_datetime + dict_day[int(info_day[1])]
        dtend = dtstart + relativedelta(hours=1, minutes=40)
        # 我们的课持续一小时四十分钟（中间有十分钟课间时间）

        event.add('uid', str(uuid1()) + '@CQUT')
        event.add('summary', line[0])
        event.add('dtstamp', datetime.now())
        event.add('dtstart', dtstart)
        event.add('dtend', dtend)

        if line[2].find('|') == -1:
            interval = 1
            count = int(info_week[1]) - int(info_week[0]) + 1
        else:
            interval = 2
            count = int(info_week[1]) - int(info_week[0]) / 2 + 1
        # 如果有单双周的课 那么这些课隔一周上一次

        event.add('rrule',
                  {'freq': 'weekly', 'interval': interval,
                   'count': count})
        # 设定重复次数

        event.add('location', line[4])
        # 设定重复地点

        cal.add_component(event)
    return cal

def main():
    dean=DEAN()
    dean.logIn()
    print("正在获取课程表...")
    schedule =dean.getSchedule()
    """
    schedule should be like this:
                [['大学物理学【Ⅱ（2）】', '周一第1,2节', '第1-10周', '1教0516', '韦建卫'],]
                """
    print("获取成功!")
    print("\n课表是...")
    for line in schedule:
        print(line)
    print("\n正在生成 ics 文件...")
    ics = get_ics(schedule)
    print(display(ics))
    print("生成成功!")

    file_name = 'sch.ics'
    print("\n正在保存到..." + file_name)
    with open(file_name, 'wb') as f:
        f.write(ics.to_ical())
        if f:
            print('保存成功!')
        else:
            print('保存失败!')

if __name__ == '__main__':
    main()


from src.setup import *
from tkinter import *

def main():

    path = "test.db"

    connection = create_connection(path)
    cursor = connection.cursor()

    database = DataBase(connection, cursor)

    database.setup_database()

main()

height = 600
width = 800

root = Tk()
root.geometry(f"{width}x{height}")
root.resizable(False, False)

canvas = Canvas(root, height=height, width=width)
canvas.pack()

frame = Frame(root)
frame.place(relheight=1, relwidth=1)

for i in range(10):
    container = Frame(frame)
    container.grid(column=0, row=i)
    label = Label(container, text="hello World!", height=2, width=10)
    label.grid(column=0, row=0)
    button = Button(container, text="quit", command=root.destroy, height=1, width=5)
    button.grid(column=1, row=0)

root.mainloop()


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

import django.test

from celery import shared_task

from otree import constants_internal

@shared_task
def submit_expired_url(url):

    c = django.test.Client()
    c.post(url, data={constants_internal.auto_submit: True}, follow=True)

@shared_task
def ensure_pages_visited(participant_pk_set, wait_page_index):

    """
    This is necessary when a wait page is followed by a timeout page.
    We can't guarantee the user's browser will properly continue to poll
    the wait page and get redirected, so after a grace period we load the page
    automatically, to kick off the expiration timer of the timeout page.

    """

    from otree.models.session import Participant
    c = django.test.Client()

    unvisited_participants = Participant.objects.filter(
        pk__in=participant_pk_set,
        _index_in_pages__lte=wait_page_index,
    )

    for participant in unvisited_participants:
        # we can assume _current_form_page_url is not null because
        # the wait page was visited
        c.get(participant._current_form_page_url, follow=True)


# Author: Anna Khaitovich (c) 2018
# see LICENCE file for legal information regarding use of this file

# compatibility with Python 2.6, for that we need unittest2 package,
# which is not available on 3.3 or 3.4
try:
    import unittest2 as unittest
except ImportError:
    import unittest

from tlslite.signed import SignatureSettings, SignedObject, RSA_SIGNATURE_HASHES, RSA_SCHEMES

class TestSignatureSettings(unittest.TestCase):
    def test_signature_settings_validate(self):
        settings = SignatureSettings()
        validated = settings.validate()
        self.assertEqual(validated.min_key_size, 1023)
        self.assertEqual(validated.max_key_size, 8193)
        self.assertEqual(validated.rsa_sig_hashes, RSA_SIGNATURE_HASHES)
        self.assertEqual(validated.rsa_schemes, RSA_SCHEMES)

    def test_signature_settings_min_key_size_small(self):
        settings = SignatureSettings(min_key_size=256)
        with self.assertRaises(ValueError) as ctx:
            settings.validate()
        self.assertIn("min_key_size too small", str(ctx.exception))

    def test_signature_settings_min_key_size_large(self):
        settings = SignatureSettings(min_key_size=17000)
        with self.assertRaises(ValueError) as ctx:
            settings.validate()
        self.assertIn("min_key_size too large", str(ctx.exception))

    def test_signature_settings_max_key_size_small(self):
        settings = SignatureSettings(max_key_size=256)
        with self.assertRaises(ValueError) as ctx:
            settings.validate()
        self.assertIn("max_key_size too small", str(ctx.exception))

    def test_signature_settings_max_key_size_large(self):
        settings = SignatureSettings(max_key_size=17000)
        with self.assertRaises(ValueError) as ctx:
            settings.validate()
        self.assertIn("max_key_size too large", str(ctx.exception))

    def test_signature_settings_min_key_bigger_max_key(self):
        settings = SignatureSettings(min_key_size=2048, max_key_size=1024)
        with self.assertRaises(ValueError) as ctx:
            settings.validate()
        self.assertIn("max_key_size smaller than min_key_size", str(ctx.exception))

    def test_signature_settings_invalid_sig_alg(self):
        settings = SignatureSettings(rsa_sig_hashes=list(['sha1', 'sha128', 'sha129']))
        with self.assertRaises(ValueError) as ctx:
            settings.validate()
        self.assertIn("Following signature algorithms are not allowed: sha128, sha129",
                      str(ctx.exception))
    # verify_signature method testing is happening in the test_tlslite_ocsp.py


import pandas as pd
import string
from collections import Counter
import matplotlib.pyplot as plt

# Load the dataset from a CSV file
df = pd.read_csv("C:/Users/Merwin S/OneDrive/Desktop/python/data.csv")

# Preprocess text
translator = str.maketrans("", "", string.punctuation)

def preprocess_text(text):
    text = text.lower()
    text = text.translate(translator)
    tokens = text.split()
    return [token for token in tokens if token not in stopwords]

# Preprocess and tokenize the entire dataset
preprocessed_tokens = []
stopwords = set(open("C:/Users/Merwin S/OneDrive/Documents/stopwords1.txt").read().split("\n"))  # Load stop words from a text file

for feedback in df["Feedback"]:
    cleaned_tokens = preprocess_text(feedback)
    preprocessed_tokens.extend(cleaned_tokens)

# Calculate frequency distribution of words
word_freq = Counter(preprocessed_tokens)

# Get user input for the number of top words to display
try:
    n = int(input("Enter the number of top words to display: "))
except ValueError:
    print("Invalid input. Using default value of 10.")
    n = 10

# Display the top N most frequent words and their frequencies
print(f"Top {n} Most Frequent Words:")
for word, freq in word_freq.most_common(n):
    print(f"{word}: {freq}")

# Visualize the distribution using a bar plot
top_words = [word for word, _ in word_freq.most_common(n)]
top_word_freq = [word_freq[word] for word in top_words]

plt.figure(figsize=(12, 6))
plt.bar(top_words, top_word_freq)
plt.xlabel("Words")
plt.ylabel("Frequency")
plt.title(f"Top {n} Most Frequent Words in Customer Feedback")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()


"""
https://www.acmicpc.net/problem/16958
"""
input = __import__('sys').stdin.readline

def calculate_distance(C, T, i, j):
    if i == j:
        return 0
    special = T if C[i][0] + C[j][0] == 2 else None
    ordinary = abs(C[i][1]-C[j][1]) + abs(C[i][2]-C[j][2])
    if special is None:
        return ordinary
    else:
        return min(special, ordinary)

def first_fill(T, C, D):
    for start in range(1, N+1):
        for end in range(1, N+1):
            if start != end and D[start][end] is None and D[start][end] is None:
                D[start][end] = D[start][end] = calculate_distance(C, T, start, end)

def floyd_warshall(N, D):
    for mid in range(1, N+1):
        for start in range(1, N+1):
            for end in range(1, N+1):
                if start == end or start == mid or end == mid:
                    continue
                D[start][end] = min(D[start][end], D[start][mid] + D[mid][end])

if __name__ == '__main__':
    N, T = map(int, input().split())
    cities = [None] * (N+1)
    for i in range(1, N+1):
        cities[i] = list(map(int, input().split()))

    distance_record = [[None] * (N+1) for _ in range(N+1)]
    first_fill(T, cities, distance_record)
    # print(distance_record)
    floyd_warshall(N, distance_record)
    # print(distance_record)

    M = int(input())
    for _ in range(M):
        A, B = map(int, input().split())
        print(distance_record[A][B])


# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

import streamlit as st
from PIL import Image
import random
#requirements.txtにpillowを記述して一緒にプッシュする
# streamlit run ファイル名.py で最初の実行

st.title('Daily Score')

st.subheader('今日の一日を振り返る(・_・)')
text = st.text_input('今日の日付を教えて。')
'今日の日付：',text,

text = st.text_input('今日がんばったこと！')
'今日がんばったこと:',text,

text = st.text_input('うれしかったこと！')
'うれしかったこと:',text,

text = st.text_input('やり残したこと！')
'やり残したこと:',text,

text = st.text_input('明日がんばること！')
'明日がんばること:',text,

image1 = Image.open('MOWチョコ.jpeg')
#st.image1(image1, caption='MOWチョコ')
image2 = Image.open('MOW抹茶.jpg')
#st.image2(image2, caption='MOW抹茶')
image3 = Image.open('アイスまんじゅう.jpeg')
#st.image3(image3, caption='あいすまんじゅう')
image4 = Image.open('あずきバー.png')
#st.image4(image4, caption='あいすバー')
image5 = Image.open('クーリッシュバニラ.jpg')
#st.image5(image5, caption='クーリッシュバニラ')
image6 = Image.open('パナップ.jpg')
#st.image6(image6, caption='パナップ')
image7 = Image.open('やわもち　わらびもち.jpg')
#st.image7(image7, caption='やわもち　わらびもち')

image8 = Image.open('MOWバニラ.jpg')
image9 = Image.open('ガーナスティック.jpg')
image10 = Image.open('ザ・クレープ.jpg')
image11 = Image.open('ジャイアントコーン黄色.jpg')
image12 = Image.open('スーパーカップ　チョコミント.jpg')
image13 = Image.open('ピノ.jpg')
image14 = Image.open('板チョコアイス.png')
image15 = Image.open('MOWあずき.jpg')
image16 = Image.open('ジャイアントコーン　チョコ.jpg')
image17 = Image.open('スーパーカップチョコチップ.jpg')
image18 = Image.open('パピコ.jpg')
image19 = Image.open('パルム.jpg')
image20 = Image.open('ビスケットサンド.jpeg')
image21 = Image.open('雪見だいふく.jpg')
image22 = Image.open('MOWラムレーズン.png')
image23 = Image.open('ジャージー牛乳ソフト.jpg')
image24 = Image.open('ジャイアントコーン赤.jpg')
image25 = Image.open('しろくま.jpeg')
image26 = Image.open('スーパーカップバニラ.jpg')
image27 = Image.open('チョコモナカジャンボ.jpg')
image28 = Image.open('ルマンドアイス.jpg')

#sokosokoice = [image1,image2,image3]

goodice = [image1,image2,image3,image4,image5,image6,image7]
sogoodice = [image8,image9,image10,image11,image12,image13,image14]
greatice = [image15,image16,image17,image18,image19,image20,image21]
wonderfulice = [image22,image23,image24,image25,image26,image27,image28]

#sokosoko = random.choice(sokosokoice)

#st.image(sokosoko, caption=(sokosoko,'のアイス'))
#st.image(sokosoko)

rate = st.radio("今日一日は何点だった？？",('0~30','30~60','60~90','100'))

if rate == '0~30':
    st.write('明日はきっといい日になる')
    #ここに画像を表示す
    #sokosoko = random.choice(sokosokoice)
    #st.image(sokosoko)

    wonderful = random.choice(wonderfulice)

    st.image(wonderful)

elif rate == '30~60':
    st.write('笑い合えたらいい日になる')
    #ここに画像を表示する
    great = random.choice(greatice)
    st.image(great)

elif rate == '60~90':
    st.write('今日よりずっといい日になる')
    #ここに画像を表示する
    sogood = random.choice(sogoodice)
    st.image(sogood)

elif rate == '100':
    st.write('君が笑えばいい日になる')
    #ここに画像を表示する
    good = random.choice(goodice)
    st.image(good)

#elif rate ==

# streamlit run すとりーむれっと.py


from sets import Set
from PolynomialRing import PolynomialRing
from Polynomial import Polynomial

class IntegralExtractor:

    """

    Extract integrals from a complex normalized Hamiltonian, including
    the partially-normalized case.

    We define a simple integral to be an integral that may be written
    as the product of a single normal form coordinate and its
    associated conjugate momentum.

    The canonically-conjugate variable pairs corresponding to simple
    integrals are automatically indentified, and hence those
    corresponding to lost integrals are also found.

    The class also finds the remainder part of the Hamiltonian, i.e.,
    the part which cannot be expressed as a polynomial of the simple
    integrals.  This non-simple part of the Hamiltonian is itself an
    integral of the motion, which we call the non-simple integral.

    The simple part of the Hamiltonian is then expressed in a compact
    form as a polynomial over the simple integrals.

    Expressions for all the integrals in terms of the normal form
    coordinates are also computed.  We always arrange that the
    non-simple integral is the last one in the list.

    """

    def __init__(self, lie_algebra):
        self._alg = lie_algebra

    def set_complex_normal_hamiltonian(self, h_comp):
        self._alg.check_elt(h_comp)
        self._h = h_comp

    def find_lost_simple_integrals_and_non_simple_integral(self):

        """Determine which simple integrals (i.e., those that are
        simply products of complex normal form coordinates and their
        associated conjugate momentum), are lost due to partial
        normalization terms in a complex normal form Hamiltonian.  At
        the same time, we can determine the non-simple integral which
        results from such terms."""

        #bind globals
        _alg = self._alg
        _h = self._h
        _xrange = xrange

        lost_integrals = Set()
        simple_part = _alg.zero()
        non_simple_integral = _alg.zero()
        for m, c in _h.powers_and_coefficients():
            powers = m.to_tuple()
            evens, odds = powers[0::2], powers[1::2]
            if evens == odds:
                simple_part[m] = c
            else:
                non_simple_integral[m] = c
                for i in _xrange(_alg.dof()):
                    if powers[2*i+1] != powers[2*i]:
                        lost_integrals.add(i)

        self._lost_integrals = lost_integrals
        self._simple_part = simple_part
        self._non_simple_integral = non_simple_integral

    def list_the_simple_integrals(self):

        """Given which simple integrals are lost, figure out which
        ones remain and make a sorted list of them to use later to
        compress powers into a more compact representation which only
        lists the simple integral coordinates."""

        _dof = self._alg.dof()
        _lost = self._lost_integrals

        kept = list(Set(xrange(_dof)).difference(_lost))
        kept.sort()
        assert len(kept) <= _dof
        if self._non_simple_integral:
            assert len(kept) == _dof

        self._kept_integrals = kept

    def express_simple_part_as_polynomial_over_all_integrals(self):

        """Given which simple integrals are lost, we can now express
        the simple part as a function of the remaining simple
        integrals, and the complicated integral which has already been
        calculated.  The power corresponding to the non-simple
        integral will be zero here."""

        #bind globals
        _dof = self._alg.dof()
        _monomial = Polynomial.Monomial
        _simple = self._simple_part
        _lost = self._lost_integrals
        _kept = self._kept_integrals

        if self._non_simple_integral:
            n_integrals = len(_kept)+1
        else:
            n_integrals = len(_kept)
        self._integral_ring = PolynomialRing(n_integrals)
        _ring = self._integral_ring

        simple_part_in_integrals = _ring.zero()
        lost_integrals = Set()
        for m, c in _simple.powers_and_coefficients():
            powers = m.to_tuple()
            evens = powers[0::2]
            powers_without_lost = tuple([evens[src] for src in _kept])
            if self._non_simple_integral:
                #we add a trailing zero for the non-simple integral
                powers_without_lost = powers_without_lost+(0,)
            simple_part_in_integrals += _ring.monomial(powers_without_lost, c)
            if 1:
                assert evens == powers[1::2]
                for i, p in enumerate(powers):
                    if p != 0:
                        assert not (i in _lost)
                if self._non_simple_integral:
                    assert len(powers_without_lost) == len(_kept)+1
                else:
                    assert len(powers_without_lost) == len(_kept) == _dof

        self._simple_in_integrals = simple_part_in_integrals

    def express_both_parts_as_polynomial_over_all_integrals(self):

        """

        Express the whole polynomial (e.g., normalized Hamiltonian) as
        a polynomial over all the integrals.

        """

        simple_in_integrals = self._simple_in_integrals
        non_simple_integral = self._non_simple_integral

        total_in_integrals = simple_in_integrals.copy()
        if non_simple_integral:
            pows = (0,)*len(self._kept_integrals)+(1,)
            m = self._integral_ring.monomial(pows)
            total_in_integrals += m

        self._total_in_integrals = total_in_integrals

    def express_all_integrals_in_normal_form_coords(self):

        """

        We express all the integrals in terms of the normal form
        coordinates (complex, canonically-conjugate pairs), ensuring
        that the non-simple integral (if any) always appears last in
        the list.

        MANY OF THESE ROUTINES SHOULD PROBABLY BE GENERATORS, OR
        SHOULD BE ALLOWED TO USE GIVEN LIST-LIKE OBJECTS IN WHICH TO
        DO THEIR STORAGE.  OTHERWISE, MEMORY WILL BECOME A PROBLEM FOR
        LARGE SYSTEMS.

        """

        _alg = self._alg
        _monomial = _alg.monomial
        _kept = self._kept_integrals

        ints_in_coords = []
        for i in _kept:
            powers = [0,]*(_alg.n_vars())
            powers[2*i] = 1
            powers[2*i+1] = 1
            integral = _alg.zero()
            integral += _monomial(tuple(powers))
            ints_in_coords.append(integral)

        if self._non_simple_integral:
            ints_in_coords.append(self._non_simple_integral)

        self._integrals_in_coords = ints_in_coords


from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

from csvx import Reader, OrderedDictReader, Writer, DictWriter, \
    to_text, to_str, ordereddicts_from_text, text_from_dicts, sniff_text

from collections import OrderedDict
import io
from six import StringIO as sio
import csv

def unicode_list(t):
    return list(to_text(x) for x in t)

COL_NAMES = ('id', b'account', b'active', 'start_time', 'end_time', 'amount',
             'credit_limit', 'deposited', 'des\u00e7ription')

FIRST_ROW = (490, 248, 'False', '2012-10-01 00:00:00.000000',
             '2013-01-02 00:00:00.000000', 72000000, 216000000, 72000000,
             'Fran\u00e7ois')

SECOND_ROW = (490, 248.0, b'False', b'-infinity', '', 72000000, 216000000,
              72000000, 'Fran\u00e7ois')

COL_NAMES_U = unicode_list(COL_NAMES)
FIRST_ROW_U = unicode_list(FIRST_ROW)
SECOND_ROW_U = unicode_list(SECOND_ROW)

ROWS_FOR_WRITING = [COL_NAMES, FIRST_ROW, SECOND_ROW]

ALL_ROW_ROWS = [COL_NAMES_U, FIRST_ROW_U, SECOND_ROW_U]
ROW_ROWS = [FIRST_ROW_U, SECOND_ROW_U]
ROW_ODS = [OrderedDict(zip(COL_NAMES_U, row)) for row in ROW_ROWS]

def test_csv(tmpdir):
    csvout = tmpdir / 'test.csv'
    path = str(csvout)

    with Writer(path) as w:
        w.write_rows(ROWS_FOR_WRITING)

    with Reader(path) as r:
        assert list(r) == ALL_ROW_ROWS

    with Reader(io.open(path)) as r:
        assert list(r) == ALL_ROW_ROWS

    with OrderedDictReader(path) as odr:
        assert odr.fieldnames == COL_NAMES_U
        assert list(odr) == ROW_ODS

    with DictWriter(path) as dw:
        dw.write_dicts(ROW_ODS)

    with DictWriter(io.open(path, 'w'), fieldnames=COL_NAMES) as dw:
        dw.write_dicts(ROW_ODS)

    with OrderedDictReader(io.open(path)) as odr:
        assert odr.fieldnames == COL_NAMES_U
        assert list(odr) == ROW_ODS

    # test non context usage
    w = OrderedDictReader(path)
    assert list(w) == ROW_ODS
    w.close()

    # test convenience methods
    t = text_from_dicts(ROW_ODS)
    assert list(ordereddicts_from_text(t)) == ROW_ODS

    sniffed = sniff_text(t)
    assert sniffed.delimiter == ','

    # test handling of incomplete rows

    t = 'a,b\n1\n1,\n,1\n\n1,2,3,4\n1,2,3\n'
    as_str = to_str(t)

    stdlib_rows = list(csv.reader(sio(as_str)))

    with Reader(sio(as_str)) as r:
        csvx_rows = list(r)

    assert stdlib_rows == csvx_rows

    stdlib_out = sio('')

    w = csv.writer(stdlib_out)
    w.writerows(stdlib_rows)
    stdlib_out = stdlib_out.getvalue()
    csvx_out = sio('')

    with Writer(csvx_out) as w:
        w.write_rows(csvx_rows)
        csvx_out = csvx_out.getvalue()

    assert stdlib_out == csvx_out

    # now with dicts...
    stdlib_dicts = list(csv.DictReader(sio(as_str)))

    with OrderedDictReader(sio(as_str)) as r:
        csvx_ordereddicts = list(r)
        csvx_dicts = [dict(d) for d in csvx_ordereddicts]

    assert stdlib_dicts == csvx_dicts

    stdlib_out = sio('')

    # remove None keys because DictWriter won't accept them
    def cleanse(dicts):
        for d in dicts:
            if None in d:
                del d[None]

    cleanse(stdlib_dicts)
    cleanse(csvx_ordereddicts)
    cleanse(csvx_dicts)

    w = csv.DictWriter(stdlib_out, fieldnames=stdlib_rows[0])
    w.writeheader()
    w.writerows(stdlib_dicts)
    stdlib_out = stdlib_out.getvalue()

    csvx_out = sio('')

    with DictWriter(csvx_out) as w:
        w.write_dicts(csvx_ordereddicts)
        csvx_out = csvx_out.getvalue()
    assert stdlib_out == csvx_out


'''
You are given an integer array nums of size n.

Consider a non-empty subarray from nums that has the maximum possible bitwise AND.

In other words, let k be the maximum value of the bitwise AND of any subarray of nums. Then, only subarrays with a bitwise AND equal to k should be considered.
Return the length of the longest such subarray.

The bitwise AND of an array is the bitwise AND of all the numbers in it.

A subarray is a contiguous sequence of elements within an array.

Example 1:

Input: nums = [1,2,3,3,2,2]
Output: 2
Explanation:
The maximum possible bitwise AND of a subarray is 3.
The longest subarray with that value is [3,3], so we return 2.
Example 2:

Input: nums = [1,2,3,4]
Output: 1
Explanation:
The maximum possible bitwise AND of a subarray is 4.
The longest subarray with that value is [4], so we return 1.

Constraints:

1 <= nums.length <= 105
1 <= nums[i] <= 106
'''
from typing import *
import unittest

class Solution:
    def longestSubarray(self, nums: List[int]) -> int:
        res = 1
        i = 0
        max_v = 0
        while i < len(nums):
            j = i
            while j < len(nums) and nums[i] == nums[j]:
                j += 1

            if nums[i] > max_v:
                max_v = nums[i]
                res = j - i
            elif nums[i] == max_v:
                res = max(res, j - i)

            i = j
        return res

class TestSolution(unittest.TestCase):

    def test_case(self):
        examples = (
            (([1,2,3,3,2,2],),2),
        )
        for first, second in examples:
            self.assert_function(first, second)

    def assert_function(self, first, second):
        self.assertEqual(Solution().longestSubarray(*first), second,
                         msg="first: {}; second: {}".format(first, second))

unittest.main()

Leetcode/2419. Longest Subarray With Maximum Bitwise AND.py


def clean_line(line):
    line = line.strip()
    line = line.replace("\n","")
    return line

def run_2(data_input):

    total = 0
    with open(data_input, "r") as reader:

        questions = ""
        newline = True
        while True:
            line = reader.readline()
            if line == "\n":
                total += len(set(questions))
                questions = ""
                newline = True
            elif line == "":
                total += len(set(questions))
                break
            else:
                line = clean_line(line)
                if not newline:
                    for c in questions:
                        if c not in line:
                            questions = questions.replace(c,"")
                else:
                    questions = line
                    newline = False

    print(f"Total = {total}")

def run(data_input):

    total = 0
    with open(data_input, "r") as reader:

        questions = []
        while True:
            line = reader.readline()
            if line == "\n":
                total += len(set(questions))
                questions = []

            elif line == "":
                total += len(set(questions))
                break
            else:
                line = clean_line(line)
                chars = [c for c in line]
                questions += chars

    print(f"Total = {total}")

if __name__ == "__main__":

    data_input = "data/day6.txt"
    run_2(data_input)


import os
import argparse
from collections import defaultdict
import numpy as np
from msmarco_eval import load_reference, compute_metrics_from_files

MaxMRRRank = 10

def dd_list_wrapper():
    return defaultdict(list)

def get_args():
    parser = argparse.ArgumentParser()

    parser.add_argument("--split", required=False, default="dev", type=str,
                        help="Which split to evaluate (dev or eval)")
    parser.add_argument("-p", "--partition", required=False, default="all", type=str,
                        help="Which partitions to evaluate ('all', or comma separated list")
    parser.add_argument("-r", "--reference", required=False, default="qrels.dev.small.tsv",
                        help="Qrel file")
    parser.add_argument("-l", "--n_layers", required=False, default=12, type=int,
                        help="Number of layers")
    parser.add_argument("--np_file", required=False, default='results.npy', type=str,
                        help="File name to save results in")
    parser.add_argument("--sp_folder", required=False, default=None, type=str,
                        help="Evaluate a specific folder")

    parser.add_argument("-pc", "--positive_confidence", required=False, default='1.0', type=str,
                        help="HP positive confidence: exit when positive confidence > this value")
    parser.add_argument("-nc", "--negative_confidence", required=False, default='1.0', type=str,
                        help="HP negative confidence: exit when negative confidence > this value")

    parser.add_argument("--no_save_np", action='store_true',
                        help="Don't save to np files")
    parser.add_argument("--detail", action='store_true',
                        help="Print out scores in each layer")
    parser.add_argument("--each_layer", action='store_true',
                        help="Evaluate each layer's result (override others)")

    args = parser.parse_args()

    all_partition = 70 if args.split == 'dev' else 69
    if args.partition == 'all':
        args.partition = list(range(all_partition))
        args.full_partition = True
    else:
        args.partition = args.partition.split(',')
        args.full_partition = False

    args.positive_confidence = float(args.positive_confidence)
    args.negative_confidence = float(args.negative_confidence)

    return args

def load_collection(args):
    collection = defaultdict(dd_list_wrapper)
    # key: qid; value: dict [key: pid, value: listof score (for each layer)]
    for layer in range(args.n_layers):
        for par in args.partition:
            with open(os.path.join(f'layer{layer}', f'{args.split}.partition{par}.score')) as fin:
                for line in fin:
                    qid, pid, score = line.strip().split('\t')
                    collection[qid][pid].append(float(score))
    return collection

def print_relevant_pair_details(args, collection):
    reference = load_reference(args.reference)
    with open('rel_pair.txt', 'w') as fout:
        for qid, rel_list in reference.items():
            for pid in rel_list:
                if str(qid) not in collection or str(pid) not in collection[str(qid)]:
                    continue  # prevent new keys being added to the defaultdict
                print(f'{qid} {pid}', end='\t', file=fout)
                for j, sc in enumerate(collection[str(qid)][str(pid)]):
                    print('{:.1f}'.format(100*sc), end=' ', file=fout)
                print(file=fout)

def generate_final_scores_confidence(args, collection):
    final_scores = defaultdict(list)  # key: qid; value: list of [pid, score]
    used_layers = 0
    pairs = 0
    for qid, qid_value in collection.items():
        for pid, score_list in qid_value.items():
            pairs += 1
            for i in range(args.n_layers):
                if (i+1 == args.n_layers or
                        score_list[i] > args.positive_confidence or
                        score_list[i] < 1-args.negative_confidence
                ):
                    final_scores[qid].append([pid, score_list[i], i+1, score_list])
                    used_layers += i+1
                    break

    return final_scores, used_layers / pairs

def generate_run_file(args, final_scores):
    run_fname = args.split + '.run'
    with open(run_fname, 'w') as fout:
        for qid, qid_value in final_scores.items():
            qid_value.sort(key=lambda x: x[1], reverse=True)  # sort by score, max on top
            for i in range(MaxMRRRank):
                if i == len(qid_value):
                    break
                if not args.detail:
                    print('{}\t{}\t{}\t{}\t{}'.format(
                        qid, qid_value[i][0], i+1, qid_value[i][1], qid_value[i][2]
                    ), file=fout)
                else:
                    print('{}\t{}\t{}\t{:.1f} {}'.format(
                        qid, qid_value[i][0], i + 1, qid_value[i][1]*100, qid_value[i][2]
                    ), end='\t', file=fout)
                    for j, sc in enumerate(qid_value[i][3]):
                        print('{:.1f}'.format(100*sc), end=('\t' if 2*(j+1)==args.n_layers else ' '), file=fout)
                    print(file=fout)
    return run_fname

def eval_each_layer(args, collection):
    with open('each_layer.txt', 'w') as fout:
        for i in range(args.n_layers):
            final_scores = defaultdict(list)  # key: qid; value: list of [pid, score]
            for qid, qid_value in collection.items():
                for pid, score_list in qid_value.items():
                    final_scores[qid].append([pid, score_list[i], i+1, score_list])

            run_fname = generate_run_file(args, final_scores)
            metrics = compute_metrics_from_files(args.reference, run_fname)
            print(f'Layer {i}:\t{metrics["MRR @10"]}', file=fout)

def eval_specific_folder(args):
    final_scores = defaultdict(list)  # key: qid; value: list of [pid, score]
    used_layers = 0
    pairs = 0

    for par in args.partition:
        with open(os.path.join(
                args.sp_folder,
                f'{args.split}.partition{par}.score'
        )) as fin:
            for line in fin:
                qid, pid, score, layer = line.strip().split('\t')
                pairs += 1
                final_scores[qid].append([pid, float(score), int(layer), []])
                used_layers += int(layer)

    run_fname = generate_run_file(args, final_scores)
    print('Avg-layer:', used_layers / pairs)
    metrics = compute_metrics_from_files(args.reference, run_fname)
    for metric in sorted(metrics):
        print('{}: {}'.format(metric, metrics[metric]))

def save_to_np(args, metrics, avg_layer):
    if os.path.exists(args.np_file):
        record = np.load(args.np_file, allow_pickle=True).item()
    else:
        record = {}

    key = (args.positive_confidence, args.negative_confidence)
    value = (avg_layer, metrics["MRR @10"])
    record[key] = value
    np.save(args.np_file, np.array(record))

def main():
    args = get_args()

    if args.sp_folder is not None:
        eval_specific_folder(args)
        exit(0)

    if args.full_partition:
        cache_fname = 'full_collection.npy'
        if os.path.exists(cache_fname):
            collection = np.load(cache_fname, allow_pickle=True).item()
        else:
            collection = load_collection(args)
            np.save(cache_fname, collection)
    else:
        collection = load_collection(args)

    if args.each_layer:
        eval_each_layer(args, collection)
        exit(0)
    if args.detail:
        print_relevant_pair_details(args, collection)
    final_scores, avg_layer = generate_final_scores_confidence(args, collection)
    run_fname = generate_run_file(args, final_scores)
    metrics = compute_metrics_from_files(args.reference, run_fname)
    print('Avg layer: {}'.format(avg_layer))
    for metric in sorted(metrics):
        print('{}: {}'.format(metric, metrics[metric]))
        break

    if not args.no_save_np:
        save_to_np(args, metrics, avg_layer)

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
"""Command line scripts to launch a `NebCalculation` for testing and demonstration purposes."""
from aiida.cmdline.params import options as options_core
from aiida.cmdline.params import types
from aiida.cmdline.utils import decorators
import click

from . import cmd_launch
from ..utils import launch, options, validate

@cmd_launch.command('neb')
@options_core.CODE(required=True, type=types.CodeParamType(entry_point='quantumespresso.neb'))
@click.option(
    '-s',
    '--structures',
    nargs=2,
    type=types.DataParamType(sub_classes=('aiida.data:core.structure',)),
    help='Two StructureData nodes representing the initial and final structures',
    metavar='<FIRST LAST>',
    required=True,
)
@click.option(
    '-I',
    '--num-images',
    type=click.INT,
    help='Number of points (images) used to discretize the path',
    default=3,
)
@click.option(
    '-N',
    '--num-steps',
    type=click.INT,
    help='Maximum number of path optimization steps',
    default=20,
)
@options.PSEUDO_FAMILY()
@options.KPOINTS_MESH(default=[2, 2, 2])
@options.ECUTWFC()
@options.ECUTRHO()
@options.SMEARING()
@options.MAX_NUM_MACHINES()
@options.MAX_WALLCLOCK_SECONDS()
@options.WITH_MPI()
@options.DAEMON()
@options.PARENT_FOLDER()
@options_core.DRY_RUN()
@decorators.with_dbenv()
def launch_calculation(
    code, structures, num_images, num_steps, pseudo_family, kpoints_mesh, ecutwfc, ecutrho, smearing, max_num_machines,
    max_wallclock_seconds, with_mpi, daemon, parent_folder, dry_run
):
    """Run a NebCalculation.

    Note that some parameters are hardcoded.
    """
    from aiida.orm import Dict
    from aiida.plugins import CalculationFactory

    from aiida_quantumespresso.utils.resources import get_default_options

    cutoff_wfc, cutoff_rho = pseudo_family.get_recommended_cutoffs(structure=structures[0], unit='Ry')

    pw_parameters = {
        'CONTROL': {
            'calculation': 'relax',
        },
        'SYSTEM': {
            'ecutwfc': ecutwfc or cutoff_wfc,
            'ecutrho': ecutrho or cutoff_rho
        }
    }

    neb_parameters = {
        'PATH': {
            'restart_mode': ('restart' if parent_folder else 'from_scratch'),
            'opt_scheme': 'broyden',
            'num_of_images': num_images,
            'nstep_path': num_steps,
        },
    }

    try:
        validate.validate_smearing(pw_parameters, smearing)
    except ValueError as exception:
        raise click.BadParameter(str(exception))

    inputs = {
        'code': code,
        'first_structure': structures[0],
        'last_structure': structures[1],
        'pw': {
            'pseudos': pseudo_family.get_pseudos(structure=structures[0]),
            'kpoints': kpoints_mesh,
            'parameters': Dict(pw_parameters),
        },
        'parameters': Dict(neb_parameters),
        'metadata': {
            'options': get_default_options(max_num_machines, max_wallclock_seconds, with_mpi),
        }
    }

    if parent_folder:
        inputs['parent_folder'] = parent_folder

    if dry_run:
        if daemon:
            # .submit() would forward to .run(), but it's better to stop here,
            # since it's a bit unexpected and the log messages output to screen
            # would be confusing ("Submitted NebCalculation<None> to the daemon")
            raise click.BadParameter('cannot send to the daemon if in dry_run mode', param_hint='--daemon')
        inputs['metadata']['store_provenance'] = False
        inputs['metadata']['dry_run'] = True

    launch.launch_process(CalculationFactory('quantumespresso.neb'), daemon, **inputs)


import numpy as np

def getLetterPriority(letter):
    # Get letter priority:
    # Lowercase item types a through z have priorities 1 through 26.
    # Uppercase item types A through Z have priorities 27 through 52.
    return ord(letter) - (ord('a') - 1 if letter.islower()
                          else ord('A') - 1 - 26)

def filterRucksack(rucksack):
    rucksack = rucksack.decode()
    # Convert string with items to array with priority of each item
    return [getLetterPriority(letter) for letter in rucksack]

@np.vectorize
def getSharedItem(rucksack):
    # Split array in half
    rucksack = np.array_split(rucksack, 2)
    # Find the item type that appears in both compartments
    return np.intersect1d(rucksack[0], rucksack[1])

def getGroupBadge(group):
    # Find the item type that appears in every rucksack of the group
    return np.intersect1d(np.intersect1d(group[0], group[1]), group[2])

if __name__ == "__main__":
    # Load input from file and find the priority of shared item in both compartments
    input = np.loadtxt("input.txt", dtype=list,
                       converters={0: lambda x: filterRucksack(x)})

    part1 = np.sum(getSharedItem(input))
    print(f"Part 1 answer: {part1}")

    # Split array to groups of 3
    groups = np.array_split(input, np.size(input)/3)
    part2 = np.sum([getGroupBadge(group) for group in groups])
    print(f"Part 2 answer: {part2}")


import nussl
import scipy.io.wavfile as wav
import pytest
import numpy as np
import tempfile
import librosa
from nussl.core.audio_signal import AudioSignalException, STFTParams
from nussl.core.constants import ALL_WINDOWS
from nussl import AudioSignal
from scipy.signal import check_COLA
import copy
import itertools

sr = nussl.constants.DEFAULT_SAMPLE_RATE
dur = 3  # seconds
length = dur * sr
stft_tol = 1e-6
n_ch = 2

freq = 30
sine_wave = np.sin(np.linspace(0, freq * 2 * np.pi, length))

# Define my window lengths to be powers of 2, ranging from 128 to 8192 samples
win_min = 7  # 2 ** 7  =  128
win_max = 11  # 2 ** 13 = 4096
win_lengths = [2 ** i for i in range(win_min, win_max + 1)]

win_length_32ms = int(2 ** (np.ceil(np.log2(nussl.constants.DEFAULT_WIN_LEN_PARAM * sr))))
win_lengths.append(win_length_32ms)

# pick hop lengths in terms of window length. 1 = one full window. .1 = 1/10th of a window
hop_length_ratios = [0.75, 0.5, 0.3, 0.25, 0.1]

window_types = ALL_WINDOWS

signals = []

combos = itertools.product(win_lengths, hop_length_ratios, window_types)

@pytest.fixture
def signals(benchmark_audio):
    signals_ = []
    # noisy signal
    noise = (np.random.rand(n_ch, length) * 2) - 1
    signals_.append(noise)

    # ones signal
    ones = np.ones(length)
    signals_.append(ones)

    # audio files
    for key, path in benchmark_audio.items():
        _s = nussl.AudioSignal(path, duration=dur)
        signals_.append(_s.audio_data)

    yield signals_

@pytest.mark.parametrize("combo", combos)
def test_stft_istft_combo(combo, signals):
    win_length = combo[0]
    hop_length = int(combo[0] * combo[1])
    win_type = combo[2]
    window = nussl.AudioSignal.get_window(combo[2], win_length)

    if not check_COLA(window, win_length, win_length - hop_length):
        assert True

    for signal in signals:
        _check_stft_istft_allclose(
            signal, win_length, hop_length, win_type
        )

def test_stft_copy(signals):
    for audio_data in signals:
        signal = AudioSignal(
            audio_data_array=audio_data, sample_rate=sr)
        stft = signal.stft()

        new_signal = signal.make_copy_with_stft_data(stft)
        new_signal.istft(truncate_to_length=signal.signal_length)
        assert np.allclose(
            new_signal.audio_data, signal.audio_data, atol=stft_tol)

        signal.set_active_region(0, 1000)
        pytest.warns(UserWarning, signal.make_copy_with_stft_data,
                     stft)

        signal.set_active_region_to_default()
        stft = stft[0]
        pytest.warns(UserWarning, signal.make_copy_with_stft_data,
                     stft)

        def dummy_a(signal):
            signal.stft_data = np.abs(signal.stft_data)

        pytest.warns(UserWarning, dummy_a, signal)

        def dummy_b(signal):
            signal.stft_data = np.ones((2, 100, 100, 2))

        pytest.raises(AudioSignalException, dummy_b, signal)

        def dummy_c(signal):
            signal.stft_data = np.ones((2,))

        pytest.raises(AudioSignalException, dummy_c, signal)

        def dummy_d(signal):
            signal.stft_data = [1, 2, 3, 4]

        pytest.raises(AudioSignalException, dummy_d, signal)

def test_stft_features(signals):
    for audio_data in signals:
        signal = AudioSignal(
            audio_data_array=audio_data, sample_rate=sr)
        pytest.raises(AudioSignalException, signal.get_stft_channel, 0)
        pytest.raises(AudioSignalException, signal.ipd_ild_features)
        pytest.raises(AudioSignalException,
                      lambda x: x.log_magnitude_spectrogram_data,
                      signal)
        pytest.raises(AudioSignalException,
                      lambda x: x.magnitude_spectrogram_data,
                      signal)
        pytest.raises(AudioSignalException,
                      lambda x: x.power_spectrogram_data,
                      signal)

        signal.stft()
        ref_mag_spec = np.abs(signal.stft_data)
        tst_mag_spec = signal.magnitude_spectrogram_data
        assert np.allclose(ref_mag_spec, tst_mag_spec)

        ref_mag_spec = np.abs(signal.stft_data)
        tst_mag_spec = signal.magnitude_spectrogram_data
        assert np.allclose(ref_mag_spec, tst_mag_spec)

        ref_log_spec = 20 * np.log10(ref_mag_spec + 1e-8)
        tst_log_spec = signal.log_magnitude_spectrogram_data
        assert np.allclose(ref_log_spec, tst_log_spec)

        ref_pow_spec = ref_mag_spec ** 2
        tst_pow_spec = signal.power_spectrogram_data
        assert np.allclose(ref_pow_spec, tst_pow_spec)

        for ch in range(signal.num_channels):
            tst_mag_spec = signal.get_magnitude_spectrogram_channel(ch)
            tst_pow_spec = signal.get_power_spectrogram_channel(ch)

            assert np.allclose(ref_mag_spec[..., ch], tst_mag_spec)
            assert np.allclose(ref_pow_spec[..., ch], tst_pow_spec)

        if signal.is_mono:
            pytest.raises(AudioSignalException, signal.ipd_ild_features)
        else:
            _, _ = signal.ipd_ild_features(0, 1)

def test_stft_istft_defaults(benchmark_audio, atol=stft_tol):
    dummy = nussl.AudioSignal()
    pytest.raises(AudioSignalException, dummy.stft)

    a = nussl.AudioSignal(audio_data_array=sine_wave)
    pytest.raises(AudioSignalException, a.istft)
    a.stft()
    a.istft()

    a = nussl.AudioSignal(audio_data_array=sine_wave)
    a.stft()
    calc_sine = a.istft(overwrite=False)

    assert np.allclose(a.audio_data, calc_sine, atol=stft_tol)

    # also load another object with stft_data
    b = nussl.AudioSignal(stft=a.stft(), sample_rate=a.sample_rate)
    b.istft()
    min_length = min(b.audio_data.shape[1], a.audio_data.shape[1])

    assert np.allclose(
        a.audio_data[:, :min_length],
        b.audio_data[:, :min_length],
        atol=stft_tol)

    for key, path in benchmark_audio.items():
        a = nussl.AudioSignal(path)
        a.stft()
        recon = a.istft(overwrite=False)
        assert np.allclose(a.audio_data, recon, atol=stft_tol)

def test_stft_params_setter():
    dummy = nussl.AudioSignal(sample_rate=44100)
    dummy.stft_params = None

    default_win_len = int(
        2 ** (np.ceil(np.log2(
            nussl.constants.DEFAULT_WIN_LEN_PARAM * dummy.sample_rate))
        ))
    default_hop_len = default_win_len // 4
    default_win_type = nussl.constants.WINDOW_DEFAULT

    default_stft_params = STFTParams(
        window_length=default_win_len,
        hop_length=default_hop_len,
        window_type=default_win_type
    )

    assert dummy.stft_params == default_stft_params

    dummy.stft_params = STFTParams(
        window_length=4096,
    )
    assert dummy.stft_params.window_length == 4096
    assert dummy.stft_params.hop_length == default_hop_len
    assert dummy.stft_params.window_type == default_win_type

    dummy.stft_params = STFTParams(
        window_length=4096,
        hop_length=1024
    )
    assert dummy.stft_params.window_length == 4096
    assert dummy.stft_params.hop_length == 1024
    assert dummy.stft_params.window_type == default_win_type

    dummy.stft_params = STFTParams(
        window_length=4096,
        hop_length=1024,
        window_type='triang'
    )
    assert dummy.stft_params.window_length == 4096
    assert dummy.stft_params.hop_length == 1024
    assert dummy.stft_params.window_type == 'triang'

    def dummy_set(x):
        x.stft_params = ['test123']

    pytest.raises(ValueError, dummy_set, dummy)

def _check_stft_istft_allclose(audio_data, win_length, hop_length, win_type):
    stft_params = STFTParams(
        window_length=win_length, hop_length=hop_length, window_type=win_type
    )
    signal = AudioSignal(
        audio_data_array=audio_data, sample_rate=sr, stft_params=stft_params)
    signal.stft()
    recon = signal.istft(overwrite=False)

    assert np.allclose(signal.audio_data, recon, atol=stft_tol)


import logging
import random
import time
from requests.exceptions import RequestException
from requests.models import Response
import json
from json import JSONDecodeError

def error_handling(api="binance", retry=5, default_val=None):
    """
    decorator for handling api request exceptions
    if a library function has direct api request, use this decorator

    if Response object is returned, check status code and raise exception if necessary
    else return the object, and use general try-except to handle exceptions

    :param api: api name: "binance", "telegram", "coingecko"
    :param retry: retry times
    :param default_val: default value to return if all retries failed
    """
    def decorator(fun):
        def wrapper(*args, **kwargs):
            error_msg = f"{api} api request error: {fun.__name__}"
            for i in range(retry):
                try:
                    response = fun(*args, **kwargs)
                    if type(response) == Response:
                        status_code = response.status_code
                        if status_code < 400:
                            return response

                        if 400 <= status_code < 500:
                            try:
                                err = json.loads(response.text)
                            except JSONDecodeError:
                                raise ClientError(
                                    status_code, None, response.text, None, response.headers
                                )

                            # error code and message returned from server
                            # binance error json
                            data = err["data"] if "data" in err else None
                            code = err["code"] if "code" in err else None
                            msg = err["msg"] if "msg" in err else None

                            # telegram error json
                            code = err["error_code"] if "error_code" in err else code
                            msg = err["description"] if "description" in err else msg

                            # coingecko error json
                            msg = err["error"] if "error" in err else msg

                            raise ClientError(
                                status_code, code, msg, response.headers, data
                            )
                        raise ServerError(status_code, response.text)
                    else:
                        return response

                except (RequestException, ClientError, ServerError) as e:
                    logging.error(f"{error_msg}: {e}, retrying {i + 1} times")
                except Exception as e:
                    logging.error(f"{error_msg}: {e}, retrying {i + 1} times")
                time.sleep(random.random() * 2)
            return default_val
        return wrapper
    return decorator

class ClientError(Exception):
    def __init__(self, status_code, error_code, error_message, header, error_data=None):
        # https status code
        self.status_code = status_code
        # error code returned from server
        self.error_code = error_code
        # error message returned from server
        self.error_message = error_message
        # the whole response header returned from server
        self.header = header
        # return data if it's returned from server
        self.error_data = error_data

    def __str__(self):
        return f"ClientError: status code: {self.status_code}, " \
               f"error code: {self.error_code}, " \
               f"server error message: {self.error_message}"

class ServerError(Exception):
    def __init__(self, status_code, message):
        self.status_code = status_code
        self.message = message

    def __str__(self):
        return f"ServerError: status code: {self.status_code}, " \
               f"server error message: {self.message}"


# Depends stands for dependencies. when one fucntion os dependent on the
# execution of another func we use depends
from fastapi import APIRouter, Depends, HTTPException
import models
from database import SessionLocal
from sqlalchemy.orm import Session
from starlette import status
from pydantic import BaseModel, Field
from typing import Optional, Annotated
from .auth import get_current_user

router = APIRouter()

user_dependency = Annotated[dict, Depends(get_current_user)]

def get_db():
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close

def http_exception_404():
    return HTTPException(status_code=404, detail="Item not found")

class Todo(BaseModel):
    title: str
    description: Optional[str]
    priority: int = Field(gt=0, lt=6, description="Priority must be between 1 & 5")
    complete: bool

@router.get("/")
# this will get executed after the get_db function
async def read_all(user: user_dependency, db: Session = Depends(get_db)):
    if user is None:
        raise HTTPException(status_code=401, detail="Authentication failed")
    return db.query(models.Todos).filter(models.Todos.owner_id == user.get("user_id")).all()

@router.get("/todos/{todo_id}", status_code=status.HTTP_200_OK)
async def read_todo(user: user_dependency, todo_id: int, db: Session = Depends(get_db)):
    if user is None:
        raise HTTPException(status_code=401, detail="Authentication failed")
    todo_model = (
        db.query(models.Todos)
        .filter(models.Todos.id == todo_id)
        .filter(models.Todos.owner_id == user.get("user_id"))
        .first()
    )

    if todo_model is not None:
        return todo_model
    raise HTTPException(status_code=404, detail="Item not found")

@router.put("/todos/{todo_id}", status_code=status.HTTP_204_NO_CONTENT)
async def update_todo(user: user_dependency, todo_id: int, todo: Todo, db: Session = Depends(get_db)):
    if user is None:
        raise HTTPException(status_code=401, detail="Authentication failed")
    todo_model = (
        db.query(models.Todos)
        .filter(models.Todos.id == todo_id)
        .filter(models.Todos.owner_id == user.get("user_id"))
        .first()
    )
    print(todo.dict())
    if todo_model is None:
        raise http_exception_404()

    todo_model.title = todo.title
    todo_model.description = todo.description
    todo_model.priority = todo.priority
    todo_model.complete = todo.complete
    db.add(todo_model)
    db.commit()

@router.delete("/todos/{todo_id}", status_code=status.HTTP_200_OK)
async def delete_todo(user: user_dependency, todo_id: int, db: Session = Depends(get_db)):
    if user is None:
        raise HTTPException(status_code=401, detail="Authentication failed")
    todo_model = (
        db.query(models.Todos)
        .filter(models.Todos.id == todo_id)
        .filter(models.Todos.owner_id == user.get("user_id"))
        .first()
    )
    if todo_model is None:
        raise http_exception_404()

    db.query(models.Todos).filter(models.Todos.id == todo_id).delete()
    db.commit()

@router.post("/todos/create_todo", status_code=status.HTTP_201_CREATED)
async def create_todo(user: user_dependency, todo: Todo, db: Session = Depends(get_db)):
    if user is None:
        raise HTTPException(status_code=401, detail="Authentication failed")
    todo_model = models.Todos(**todo.dict(), owner_id=user.get("user_id"))
    db.add(todo_model)
    db.commit()


import random
import numpy as np
from torch.utils import data
from .dataset_t2m import Text2MotionDataset
import codecs as cs
from os.path import join as pjoin

class Text2MotionDatasetM2T(data.Dataset):

    def __init__(
        self,
        data_root,
        split,
        mean,
        std,
        max_motion_length=196,
        min_motion_length=40,
        unit_length=4,
        fps=20,
        tmpFile=True,
        tiny=False,
        debug=False,
        **kwargs,
    ):

        self.max_motion_length = max_motion_length
        self.min_motion_length = min_motion_length
        self.unit_length = unit_length

        # Data mean and std
        self.mean = mean
        self.std = std

        # Data path
        split_file = pjoin(data_root, split + '.txt')
        motion_dir = pjoin(data_root, 'new_joint_vecs')
        text_dir = pjoin(data_root, 'texts')

        # Data id list
        self.id_list = []
        with cs.open(split_file, "r") as f:
            for line in f.readlines():
                self.id_list.append(line.strip())

        new_name_list = []
        length_list = []
        data_dict = {}
        for name in self.id_list:
            # try:
                motion = np.load(pjoin(motion_dir, name + '.npy'))
                if (len(motion)) <  self.min_motion_length or (len(motion) >= 200):
                    continue

                text_data = []
                flag = False

                with cs.open(pjoin(text_dir, name + '.txt')) as f:
                    for line in f.readlines():
                        text_dict = {}
                        line_split = line.strip().split('#')
                        caption = line_split[0]
                        tokens = line_split[1].split(' ')
                        f_tag = float(line_split[2])
                        to_tag = float(line_split[3])
                        f_tag = 0.0 if np.isnan(f_tag) else f_tag
                        to_tag = 0.0 if np.isnan(to_tag) else to_tag

                        text_dict['caption'] = caption
                        text_dict['tokens'] = tokens
                        if f_tag == 0.0 and to_tag == 0.0:
                            flag = True
                            text_data.append(text_dict)
                        else:
                            try:
                                n_motion = motion[int(f_tag*20) : int(to_tag*20)]

                                if (len(n_motion)) < min_motion_length or (len(n_motion) >= 200):
                                    continue

                                new_name = "%s_%f_%f"%(name, f_tag, to_tag)
                                data_dict[new_name] = {'motion': n_motion,
                                                       'length': len(n_motion),
                                                       'text':[text_dict]}
                                new_name_list.append(new_name)
                            except:
                                print(line_split)
                                print(line_split[2], line_split[3], f_tag, to_tag, name)
                if flag:
                    data_dict[name] = {'motion': motion,
                                    'length': len(motion),
                                    'name': name,
                                    'text': text_data}

                    new_name_list.append(name)
                    length_list.append(len(motion))
            # except:
            #     # Some motion may not exist in KIT dataset
            #     pass

        self.length_arr = np.array(length_list)
        self.data_dict = data_dict
        self.name_list = new_name_list
        self.nfeats = motion.shape[-1]

    def __len__(self):
        return len(self.data_dict)

    def __getitem__(self, item):
        name = self.name_list[item]
        data = self.data_dict[name]
        motion, m_length = data['motion'], data['length']

        "Z Normalization"
        motion = (motion - self.mean) / self.std

        return name, motion, m_length, True, True, True, True, True, True


import tensorflow as tf
import numpy as np

class PolicyNetwork:
	def __init__(self, action_dim, state_dim, lr, save_path='model/policy_network'):
		self.action_dim = action_dim
		self.state_dim = state_dim
		self.lr = lr
		self.e = 0.2
		self.save_path = save_path

		self._build_graph()

		self.sess = tf.Session(graph=self.g)
		self.sess.run(self.init)

		try:
			self.saver.restore(self.sess, save_path)
			print ('Saved variables restored from checkpoint: {}'.format(save_path))
		except:
			pass

	def _build_graph(self):
		self.g = tf.Graph()
		with self.g.as_default():
			# Placeholders
			self.states_ph = tf.placeholder(tf.float32, shape=(None, self.state_dim))
			self.actions_ph = tf.placeholder(tf.float32, shape=(None, self.action_dim))
			self.advs_ph = tf.placeholder(tf.float32, shape=(None,))
			self.old_means_ph = tf.placeholder(tf.float32, shape=(None, self.action_dim))
			self.old_log_vars_ph = tf.placeholder(tf.float32, shape=(None, self.action_dim))

			# Hidden layer sizes
			h1_size = self.state_dim*10
			h3_size = self.action_dim*10
			h2_size = int(np.sqrt(h1_size*h3_size))

			# Network weights
			'''one layer'''
			# self.w1 = tf.Variable(tf.truncated_normal(shape=(self.state_dim, self.action_dim)))
			# self.pred_means = tf.matmul(self.states_ph, self.w1)

			'''hidden layers'''
			self.w1 = tf.Variable(tf.truncated_normal(shape=(self.state_dim, h1_size)))
			self.w2 = tf.Variable(tf.truncated_normal(shape=(h1_size, h2_size)))
			self.w3 = tf.Variable(tf.truncated_normal(shape=(h2_size, h3_size)))
			self.w4 = tf.Variable(tf.truncated_normal(shape=(h3_size, self.action_dim)))

			'''one hidden layer'''
			# h1_size = 200
			# self.w1 = tf.Variable(tf.truncated_normal(shape=(self.state_dim, h1_size)))
			# self.w2 = tf.Variable(tf.truncated_normal(shape=(h1_size, self.action_dim)))
			# a1 = tf.matmul(self.states_ph, self.w1)
			# a1 = tf.nn.relu(a1)
			# a2 = tf.matmul(a1, self.w2)

			# Network weights
			# self.w1 = tf.Variable(tf.truncated_normal(shape=(self.state_dim, h1_size)))
			# self.w2 = tf.Variable(tf.truncated_normal(shape=(h1_size, h2_size)))
			# self.w3 = tf.Variable(tf.truncated_normal(shape=(h2_size, h3_size)))
			# self.w4 = tf.Variable(tf.truncated_normal(shape=(h3_size, self.action_dim)))
			self.log_vars = tf.Variable(tf.truncated_normal(shape=(1, self.action_dim), stddev=0.01))

			# Graph operations
			a1 = tf.matmul(self.states_ph, self.w1)
			a2 = tf.matmul(a1, self.w2)
			a3 = tf.matmul(a2, self.w3)
			self.pred_means = tf.matmul(a3, self.w4)
			self.sampled_act = (self.pred_means + tf.exp(self.log_vars/2.0) * tf.random_normal(shape=(self.action_dim,)))

			# Optimisation-related
			self.logp = self.find_log_prob(self.actions_ph, self.pred_means, self.log_vars)
			self.logp_old = self.find_log_prob(self.actions_ph, self.old_means_ph, self.old_log_vars_ph)
			ratio = tf.exp(self.logp - self.logp_old)
			clipped_ratio = tf.clip_by_value(ratio, 1-self.e, 1+self.e)
			objective = tf.minimum(ratio*self.advs_ph, clipped_ratio*self.advs_ph)
			self.loss = tf.reduce_mean(-objective)
			self.opt = tf.train.AdamOptimizer(self.lr).minimize(self.loss)

			# Init operation
			self.init = tf.global_variables_initializer()

			# Saver
			self.saver = tf.train.Saver()

	def find_log_prob(self, action, means, log_vars):
		logp = -0.5 * tf.reduce_sum(log_vars)
		logp += -0.5 * tf.reduce_sum(tf.square(action - means) / tf.exp(log_vars), axis=1)
		return logp

	def get_action(self, state):
		action = self.sess.run(self.sampled_act, feed_dict={self.states_ph: state})
		return action

	def update(self, states, actions, advantages):
		feed_dict = {self.states_ph: states, self.actions_ph: actions, self.advs_ph: advantages}
		# print (states.shape)
		# print (actions.shape)
		# print (advantages.shape)
		old_means, old_log_vars = self.sess.run([self.pred_means, self.log_vars], feed_dict)
		feed_dict[self.old_log_vars_ph] = old_log_vars
		feed_dict[self.old_means_ph] = old_means

		_ = self.sess.run([self.opt], feed_dict=feed_dict)

	def print_for_debug(self):
		w1 = self.sess.run(self.w1)
		print (w1)

	def save_model(self):
		save_name = self.saver.save(self.sess, self.save_path)
		print("Policy network checkpoint saved in file: %s" % save_name)


#Lugar donde se guardan  y declaran las variables
# utilizadas a través del control, entre otras.

state = {

# Control

	"Controller": "PacificRim",

	"codewide_breaker": False,

#Variables del Chasis

	"turbo_activated": False,
	"align_activated": False,
	"mov_x": 0,
	"mov_y": 0,
	"mov_z": 0,

#Variables del Piston e impulsor e impulsor motor

	"piston_activated": False,
	"timer_a": 1,
	"timer_button": 0,
	"timer_piston": 0,
	"timer_impulsor":0,
	"elevator_piston_izq": 1,
	"elevator_piston_der": 1,
	"timer_impulsor_motor":0,
	"impulsor_on": False,
	"piston_state_button": False,
	"timer_auto": 0,

# Variables del Elevador

	"lift_motor": 0,
	"timer_lift_middle": 0,
	"timer_lift_taller": 0,
	"position" : "neutral",
	"mechanism": "neutral",
	"setpoint" : 0

}


"""Convert GPS metadata csv files to a json for later input into extract_assembly_stats.py and extract_read_metadata.py"""
import json
import os
import pandas as pd
import sys
from tqdm import tqdm

sys.stderr.write("\nExtracting metadata from GPS csv files\n")
# if this is the GPS data, we are going to supplement the metadata with those in the mmc supplementary data and GPS1_in_silico_output.csv
GPS_insilicoDF = pd.read_csv("GPS1_insilico_output.csv")
GPS_insilicoDict = {}
for index, row in GPS_insilicoDF.iterrows():
    if not row["Lane_Id"] == "":
        GPS_insilicoDict[row["Lane_Id"]] = {"ERS": row["ERS"],
                                            "ERR": row["ERR"],
                                            "Lane_Id": row["Lane_Id"],
                                            "In_Silico_Serotype": row["in_siico_serotype"],
                                            "In_Silico_St": row["In_Silico_St"],
                                            "WGS_PEN_SIR_Nonmeningitis": row["WGS_PEN_SIR_Nonmeningitis"]}
del GPS_insilicoDF
GPS_mmc1 = pd.read_csv("mmc_tab1.csv")
GPS_supplement = {}
for index, row in tqdm(GPS_mmc1.iterrows()):
    supplement_dict = {"ERR": row["ERR"],
                        "Lane_Id": row["ID"],
                        "In_Silico_St": row["In_Silico_St"],
                        "CC": row[" CC"],
                        "In_Silico_Serotype": row["In_Silico_Serotype"],
                        "GPSC": row["GPSC"],
                        "GPSC_PCV_type_pre_PCV": row["GPSC-PCV-type pre-PCV"],
                        "Vaccine_Period": row["Vaccine_Period"],
                        "Vaccine_Status": row["Vaccine_Status"],
                        "Country": row["Country"],
                        "Year": row["Year"],
                        "Date(month)": row["Date (mid-year if day/month unknown)"],
                        "Age_group": row["Age_group"],
                        "Disease": row["Disease"]}
    if row["ID"] in GPS_insilicoDict.keys():
        supplement_dict.update(GPS_insilicoDict[row["ID"]])
    GPS_supplement[supplement_dict["ERR"]] = supplement_dict
# if not in mmc1 then add manually
for key, value in GPS_insilicoDict.items():
    if not value["ERR"] in GPS_supplement.keys():
        GPS_supplement[value["ERR"]] = value
with open("GPS_metadata.json", "w") as outMeta:
    outMeta.write(json.dumps(GPS_supplement))


class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
        Row=len(image)
        Col=len(image[0])
        sourceColour=image[sr][sc]
        def dfs(i,j):
            if (i<0 or i>=Row or j<0 or j>=Col):
                return
            elif (image[i][j]!=sourceColour):
                return
            image[i][j]=color
            directions=[[1,0],[-1,0],[0,1],[0,-1]]
            for dr,dc in directions:
                row,col=i+dr,j+dc
                dfs(row,col)
        if image[sr][sc]==color:
            return image
        dfs(sr,sc)
        return (image)


import boto3
import constants

class Metrics(object):
    def __init__(self, context="DEV", region="us-west-2", namespace="braket-container-metrics"):
        """
        Constructor for the metrics object.

        Args:
            context: the value of the BuildContext dimension
            region: the AWS region
            namespace: the metrics namespace
        """
        self.client = boto3.Session(region_name=region).client("cloudwatch")
        self.context = context
        self.namespace = namespace

    def push(self, name, unit, value, metrics_info):
        """
        Pushes metrics to CloudWatch Metrics.

        Args:
            name: the name of the metric
            unit: the metric unit
            value: the metric value
            metrics_info: additional dimensions for the metric
        """

        dimensions = [{"Name": "BuildContext", "Value": self.context}]

        for key in metrics_info:
            dimensions.append({"Name": key, "Value": metrics_info[key]})

        try:
            response = self.client.put_metric_data(
                MetricData=[
                    {
                        "MetricName": name,
                        "Dimensions": dimensions,
                        "Unit": unit,
                        "Value": value,
                    },
                ],
                Namespace=self.namespace,
            )
        except Exception as e:
            raise Exception(str(e))

        return response

    def push_image_metrics(self, image):
        """
        Pushes metrics about a docker image to CloudWatch Metrics.

        Args:
            image: docker image information.
        """
        info = {
            "framework": image.framework,
            "version": image.version,
            "device_type": image.device_type,
            "python_version": image.python_version,
            "image_type": image.image_type,
        }
        if image.build_status == constants.NOT_BUILT:
            return None
        build_time = (image.summary["end_time"] - image.summary["start_time"]).seconds
        build_status = image.build_status

        self.push("build_time", "Seconds", build_time, info)
        self.push("build_status", "None", build_status, info)

        if image.build_status == constants.SUCCESS:
            image_size = image.summary["image_size"]
            self.push("image_size", "Bytes", image_size, info)