import random
allCiphers = []
class cryptoErr(BaseException):
	#This is the error class that will be raised if there is a problem
	def __init__():
		self.errName = ''
		self.errValue = None
		self.errHandler = None
		self.errMetaData = ''
		self.errUsrMsg = ''
		return
	def handle(self):
		if self.errHandler != None:
			try:
				errHandler()
			except:
				return
		else:
			return
class map(object):
	def __init__(self,mapI,err = -1,):
		#consider adding a map sequence so that certin letters map to certin numbers
		#mapSequence = range(0,len(mapI))
		self.mapLength = len(mapI)
		self.mapI = mapI
		self.err = err
		self.mod = int(len(mapI))
		return
	def __call__(self,chrNum):
		#will convert any string to a chr and any chr to a num according to the map
		if type(chrNum) == str:
			for index in range(0,self.mapLength):
				if chrNum == self.mapI[index]:
					return int(index)
				else:
					continue
			return self.err
		elif type(chrNum) == int:
			if 0 <= chrNum < self.mapLength:
				return str(self.mapI[chrNum])
			else:
				return self.err
		else:
			raise self.err
	def setMap(self,mapB):
		self.mapI = mapB
		self.mod = len(mapB)
		self.mapLength = len(mapB)
		return
class caesar(object):
	def __init__(self):
		self.cipherType = 'caesar'
		self.defMap = map('abcdefghijklmnopqrstuvwxyz')
		self.enVariance = [0.0867,0.01492,0.02782,0.04253,0.12702,0.02228,0.02015,0.06094,0.06966,0.00153,0.00772,0.04025,0.02406,0.06749,0.07507,0.01929,0.00095,0.05987,0.06327,0.09056,0.02758,0.00978,0.02361,0.00150,0.01974,0.00074]
		return
	def help(self):
		print('encrypt/decrypt  msg,key   nokeydecrypt msg')
		return True
	def opp(t):
		if t == True:
			return False
		elif t == False:
			return True
	def chrToNum(self, char,forceMap = False):
		#converts a character to a number based upon the classes self.defMap
		if forceMap == False:
			forceMap = self.defMap
		num = forceMap(char)
		return 	num
	def setMap(self,mapN):
		#takes a map as an argument
		self.defMap = mapN
		return
	def numToChr(self, num,forceMap = False):
		if forceMap == False:
			forceMap = self.defMap
		#converts a number to a character based upon the classes self.defMap
		char  = forceMap(num)
		return char
	def az(self, letter):
		#checks if a letter is a to z
		if 97 <= ord(letter) <= 122:
			return True
		else:
			return False
	def sanitizeMsg(self,msg,rmvChrs):
		for index in range(0, len(msg)):
			for letterB in rmvChrs:
				if msg[index] == letterB:
					msg[index] == ''
				else:
					continue
		return msg
	def encrypt(self,msg,key):
		#ENCRYPTION CODE
		encrypted = ''
		for letter in msg:
			en = self.defMap(letter)
			if en == self.defMap.err:
				pass
			else:
				encrypted += str(self.numToChr((self.chrToNum(letter) + key) % self.defMap.mod))
		return encrypted
	def decrypt(self,msg,key):
		#DECRYPTION CODE
		decrypted = ''
		for letter in msg:
			de = self.defMap(letter)
			if de == self.defMap.err:
				pass
			else:
				decrypted += str(self.numToChr((self.chrToNum(letter) - key) % self.defMap.mod))
		return decrypted
	def frequencyAnalysis(self,msg):
		#ANALYSIS CODE
		frequency = [0] * self.defMap.mod
		for letter in msg:
			fe = self.defMap(letter)
			if fe == self.defMap.err:
				pass
			else:
				frequency[self.chrToNum(letter)] += 1
		total = 0
		for index in range(0,self.defMap.mod):
			total += frequency[index]
		total = float(total)
		for indexAlpha in range(0,len(frequency)):
			frequency[indexAlpha] = frequency[indexAlpha] / total
		return frequency
	def variance(self,frequency):
		#VARIATION CODE only works for msgs with a self.defMap = map('abcdefghijklmnopqrstuvwxyz')
		if len(frequency) > 26:
			raise BaseException
		else:
			variance = 0
			englishVariance = [0.0867,0.01492,0.02782,0.04253,0.12702,0.02228,0.02015,0.06094,0.06966,0.00153,0.00772,0.04025,0.02406,0.06749,0.07507,0.01929,0.00095,0.05987,0.06327,0.09056,0.02758,0.00978,0.02361,0.00150,0.01974,0.00074]
			for index in range(0,26):
				variance += abs(englishVariance[index]-frequency[index])
			return variance
	def noKeysDecrypt(self,msg):
		#NO KEY DECRYPTION CODE # returns a list where the first item is the decrypted msg and the 2nd the key
		key = 0
		lowestVariance = 1000
		testKey = 0
		for index in range(0,self.defMap.mod):
			testDecrypt = self.decrypt(msg,key)
			testFrequency = self.frequencyAnalysis(testDecrypt)
			testVariance = self.variance(testFrequency)
			if testVariance < lowestVariance:
				lowestVariance = testVariance
				testKey = key
			key += 1
		return [self.decrypt(msg,testKey), testKey]
class afine(caesar,object):
	def __init__(self):
		self.cipherType = 'afine'
		self.defMap = map('abcdefghijklmnopqrstuvwxyz')
		return
	def help(self):
		print('encrypt/decrypt  msg,key as a list [add,mult]   nokeydecrypt msg')
		return True
	def getValidMultKeys(self,num):
		# Should retrun all intigers relativly prime to num
		validKeys = []
		for indexA in range(0,num):
			for indexB in range(0,num):
				if ((indexA *indexB) % num) == 1:
					validKeys.append(indexA)
				else:
					continue
		return validKeys
	def getInvrsMultKey(self,key):
		# gets the inverse of the mult key , asumes 26 , watches for keys that do not have a reverse
		inverseKey = None
		for index in range(0,self.defMap.mod):
			if ((key * index) % self.defMap.mod) == 1:
				inverseKey = index
			else:
				continue
		return inverseKey
	def getInvrsAddKey(self,key,delta = 'neg'):
		#or delta = 'neg', assumes 26, only accepts positive keys
		if delta == 'neg':
			keyN = 0 - key
			return keyN
		else:
			keyN = self.defMap.mod -key ######## THIS MAY CAUSE AN ERROR
			return keyN
	def encrypt(self, msg,keys):
		multKey = keys[1]
		addKey = keys[0]
		#ENCRYPTION CODE
		encrypted = ''
		for letter in msg:
			en =  self.defMap(letter)
			if en == self.defMap.err:
				pass
			else:
				encrypted += str(self.numToChr(((self.chrToNum(letter) + addKey) * multKey) % self.defMap.mod))
		return encrypted
	def decrypt(self,msg,keys):
		#DECRYPTION CODE
		decrypted = ''
		multKey = keys[1]
		addKey = keys[0]
		for letter in msg:
			de = self.defMap(letter)
			if de == self.defMap.err:
				pass
			else:
				decrypted += str(self.numToChr(((self.chrToNum(letter) * self.getInvrsMultKey(multKey)) + self.getInvrsAddKey(addKey)) % self.defMap.mod))
		return decrypted
	def noKeysDecrypt(self,msg):
		#NO KEY DECRYPTION CODE
		lowestVariance = 1000
		testMultKey = None
		testAddKey = None
		for indexA in self.getValidMultKeys(self.defMap.mod):
			for indexB in range(0,self.defMap.mod):
				keyT = [int(indexB),int(indexA)]
				testDecrypt = self.decrypt(msg, keyT)
				testFrequency = self.frequencyAnalysis(testDecrypt)
				testVariance = self.variance(testFrequency)
				if testVariance < lowestVariance:
					lowestVariance = testVariance
					testMultKey = indexA
					testAddKey = indexB
		keyF = [testAddKey,testMultKey]
		return [self.decrypt(msg,keyF),[testMultKey,testAddKey]]
class viginere(afine):
	def __init__(self):
		self.cipherType = 'viginere'
		self.defMap = map('abcdefghijklmnopqrstuvwxyz')
		return
	def help(self):
		print('encrypt/decrypt  msg,keyword   nokeydecrypt is not avilable')
		return True
	def encrypt(self,msg, keyWord):
		#ENCRYPTION CODE
		encrypted = ''
		counter = 0
		lenK = len(keyWord)
		for letter in msg:
			en = self.defMap(letter)
			if en == self.defMap.err:
				pass
			else:
				encrypted += str(self.numToChr((self.chrToNum(letter) + self.chrToNum(keyWord[counter])) % self.defMap.mod))
				counter += 1
				if counter == lenK:
					counter = 0
		return encrypted
	def decrypt(self, msg, keyWord):
		#DECRYPTION CODE
		decrypted = ''
		counter = 0
		lenK = len(keyWord)
		for letter in msg:
			de = self.defMap(letter)
			if de == self.defMap.err:
				pass
			else:
				decrypted += self.numToChr((self.chrToNum(letter) - self.chrToNum(keyWord[counter])) % 26)
				counter += 1
				if counter == lenK:
					counter = 0
		return decrypted
	def keysValidate(self,key):
		#KEY VALIDATION tests if the key will work based upon the defMap and format
		if (key != str) | (self.defMap(key) == self.defMap.err):
			return false
		return True
	def msgValidate(self, msg):
		#MSG VALIDATION CODE
		for letter in msg:
			if self.defMap(letter) == self.defMap.err:
				return False
			else:
				continue
		return True
	def noKeysDecrypt(self):
		#NO   NO-KEY DECRYPTION CODE exists for the scope of this module
		return False
	def search(self,text,target,startInxex = 0):
		#SEARCH THE text srting for a target strng, and does so from the starting index
		# returns a list of the starting index of each hit
		hitsIndexes = []
		txtLen = len(text)
		if len(target)> len(text):
			return []
		for indexA in range(startInxex,txtLen):
			testTarget = ''
			for indexB in range(0,len(target)):
				if (indexA + indexB) > (txtLen-1):
					pass
				else:
					testTarget += text[indexA + indexB]
			if target == testTarget:
				hitsIndexes.append(indexA)
		return hitsIndexes
	def getRepetes(self,textSource,maxLen = 10,startInxexN = 0):
		'''looks at a textN and returns a dictionary where the key is a hit for a repete string and the
			key's value is a list of all the start unique start indexes of that repete string, the function
			searches for repetes maxLen in length and starts searching the text at startIndexN
		'''
		repetes = {}
		txtLen = len(textSource)
		for indexA in range(startInxexN,txtLen):
			testRepete = ''
			testIndex = indexA + 1
			for indexB in range(0,maxLen):
				if (indexA + indexB)> (len(textSource)-1):
					pass
				else:
					testRepete += textSource[indexA + indexB]
			testList = self.search(textSource,testRepete, testIndex)
			print(testList)
			if testList != []:
				for indexAItem in testList:
					if testRepete not in repetes:
						repetes[testRepete] = []
						continue
					else:
						continue
					for indexBItem in repetes[testRepete]:
						if indexAItem != indexBItem:
							repetes[testRepete].append(indexAItem)
						else:
							continue
			else:
				continue
		return repetes
class viginereOld(viginere):
	def __init__(self):
		self.cipherType = 'viginereOld'
		self.defMap = map('abcdefghijklmnopqrstuvwxyz')
	def encrypt(self,msg, keyWord):
		#ENCRYPTION CODE
		encrypted = ''
		counter = 0
		lenK = len(keyWord)
		for letter in msg:
			en = self.defMap(letter)
			if en == self.defMap.err:
				pass
			else:
				encrypted += str(self.numToChr((self.chrToNum(letter) + self.chrToNum(keyWord[counter])) % self.defMap.mod))
				counter += 1
				if counter == lenK:
					keyWord = encrypted[(len(encrypted)-lenK): len(encrypted)]
					counter = 0
		return encrypted
	def help(self):
		print('encrypt/decrypt  msg,keyword   nokeydecrypt not avilable')
		return True
	def decrypt(self, msg, keyWord):
		#DECRYPTION CODE
		decrypted = ''
		counter = 0
		lenK = len(keyWord)
		for letter in msg:
			de = self.defMap(letter)
			if de == self.defMap.err:
				pass
			else:
				decrypted += self.numToChr((self.chrToNum(letter) - self.chrToNum(keyWord[counter])) % 26)
				counter += 1
				if counter == lenK:
					keyWord = msg[(len(decrypted)-lenK) : len(decrypted)]
					counter = 0
		return decrypted
class hills(afine):
	def __init__(self):
		self.cipherType = 'hills'
		self.defMap = map('abcdefghijklmnopqrstuvwxyz')
	def help(self):
		print('encrypt/decrypt  msg,key as [[a,c],[b,d]]  nokeydecrypt not avilable')
		return True
	def multMatrix(self,mA,mB):
		#[[a:00,c:01],[b:10,d:11]] [[x:00,y:01]]
		#must be a multidimensional array in the form of [[collum],[collum]] for a 2by2 * 1by2
		result = [[]]
		result[0].append((mA[0][0] * mB[0][0]) + (mA[1][0] * mB[0][1]))
		result[0].append((mA[0][1] * mB[0][0]) + (mA[1][1] * mB[0][1]))
		#result[0].append((mA[0][0] * mB[0][0]) + (mA[1][0] * mB[0][1]))
		#result[0].append((mA[0][1] * mB[0][0]) + (mA[1][1] * mB[0][1]))
		return result
	def modMatrix(self, mA):
		mA[0][0] = mA[0][0] % self.defMap.mod
		mA[0][1] = mA[0][1] % self.defMap.mod
		return mA
	def getInvrsMatrix(self, mA):
	#[[a:00,c:01],[b:10,d:11]]
	#[[],[]] ----> get from tst.t
		inMult = self.getInvrsMultKey((mA[0][0] * mA[1][1]) - (mA[1][0] * mA[0][1]))
		invrsmA = [[0,0],[0,0]] ## THIS IS THE LINE THAT HAD THE WEIRD ERROR
		invrsmA[0][0] = (mA[1][1] * inMult) % self.defMap.mod #A
		invrsmA[0][1] = (0 - (mA[0][1] * inMult)) % self.defMap.mod#c
		invrsmA[1][0] = (0 - (mA[1][0] * inMult)) % self.defMap.mod #b
		invrsmA[1][1] = (mA[0][0] * inMult) % self.defMap.mod #D
		return invrsmA
	def chrsToMatrix(self,char):
		if len(char) != 2:
			return self.defMap.err
		else:
			matrix = [[0,0]]
			matrix[0][0] = self.defMap(char[0])
			matrix[0][1] = self.defMap(char[1])
			return matrix
		return self.defMap.err
	def matrixToChrs(self,matrix):
		try:
			charA = self.defMap(matrix[0][0])
			charB = self.defMap(matrix[0][1])
			return charA + charB
		except:
			return self.defMap.err
	def encrypt(self,msg,keys):
		encrypted  = ''
		if len(msg) % 2 != 0:
			msg += self.defMap(int(random.random()*100)%self.defMap.mod)
		for i in range(len(msg)):
			if i % 2 != 0:
				pass
			else:
				encrypted += self.matrixToChrs(self.modMatrix(self.multMatrix(keys,self.chrsToMatrix(msg[i] + msg[i + 1]))))
		return encrypted
	def decrypt(self,msg,keys):
		decrypted  = ''
		if len(msg) % 2 != 0:
			msg += self.defMap(int(random.random()*100)%self.defMap.mod)
		for i in range(len(msg)):
			if i % 2 != 0:
				pass
			else:
				decrypted += self.matrixToChrs(self.modMatrix(self.multMatrix(self.getInvrsMatrix(keys),self.chrsToMatrix(msg[i] + msg[i + 1]))))
		return decrypted
	def noKeysDecrypt(self):
		#NO   NO-KEY DECRYPTION CODE exists for the scope of this module
		return False
def Main():
	allCiphers.append(caesar())
	allCiphers.append(afine())
	allCiphers.append(viginereOld())
	allCiphers.append(viginere())
	allCiphers.append(hills())
def getCipherIndex(arg, err = -1):
	global allCiphers
	for index in range(0,len(allCiphers)):
		try:
			if allCiphers[index].cipherType == arg:
				return index
			else:
				continue
		except:
			continue
	return err
def encrypt(message,keys,cipherType,mapChoice = 'default',err = -1):
	cipherIndex = getCipherIndex(cipherType,err)
	global allCiphers
	if cipherIndex == err:
		return err
	else:
		try:
			if mapChoice != 'default':
				allCiphers[cipherIndex].defMap = mapChoice
			result = allCiphers[cipherIndex].encrypt(message,keys)
		except:
			return err
		return result
def decrypt(message,keys,cipherType,mapChoice = 'default',err = -1):
	cipherIndex = getCipherIndex(cipherType,err)
	global allCiphers
	if cipherIndex == err:
		return err
	else:
		try:
			if mapChoice != 'default':
				allCiphers[cipherIndex].defMap = mapChoice
			result = allCiphers[cipherIndex].decrypt(message,keys)
		except:
			return err
		return result
def noKeysDecrypt(message,cipherType,mapChoice = 'default',err = -1):
	cipherIndex = getCipherIndex(cipherType,err)
	global allCiphers
	if cipherIndex == err:
		return err
	else:
		try:
			if mapChoice != 'default':
				allCiphers[cipherIndex].defMap = mapChoice
			result = allCiphers[cipherIndex].noKeysDecrypt(message)
			if result == False:
				raise CryptoErr()
		except:
			return err
		return result
Main()


"""
End to end test of video timelines.
"""

import datetime
import logging

from edx.analytics.tasks.tests.acceptance import AcceptanceTestCase

log = logging.getLogger(__name__)

class VideoAcceptanceTest(AcceptanceTestCase):
    """End to end test of video timelines."""

    INPUT_FILE = 'video_timeline.log'

    def test_video_timeline(self):
        self.upload_tracking_log(self.INPUT_FILE, datetime.date(2014, 5, 2))

        self.task.launch([
            'InsertToMysqlAllVideoTask',
            '--interval', '2014-05-01-2014-05-06',
            '--n-reduce-tasks', str(self.NUM_REDUCERS),
        ])

        self.validate_video_info()
        self.validate_video_timeline()

    def validate_video_info(self):
        """Ensure the video information is correct."""
        with self.export_db.cursor() as cursor:
            cursor.execute(
                'SELECT pipeline_video_id, course_id, encoded_module_id, duration, segment_length,'
                ' users_at_start, users_at_end, total_viewed_seconds FROM video'
                ' ORDER BY pipeline_video_id ASC'
            )
            results = cursor.fetchall()

        expected = [
            (
                'course-v1:edX+DemoX+Test_2014|0b9e39477cf34507a7a48f74be381fdd',
                'course-v1:edX+DemoX+Test_2014',
                '0b9e39477cf34507a7a48f74be381fdd',
                4,
                5,
                1,
                1,
                5,
            ),
            (
                'edX/DemoX/Demo_Course|i4x-edX-DemoX-video-3cb54a11efae4ccc8a0aade24d14b255',
                'edX/DemoX/Demo_Course',
                'i4x-edX-DemoX-video-3cb54a11efae4ccc8a0aade24d14b255',
                24,
                5,
                2,
                2,
                60,
            ),
            (
                'edX/DemoX/Demo_Course|i4x-edX-DemoX-video-8c0028eb2a724f48a074bc184cd8635f',
                'edX/DemoX/Demo_Course',
                'i4x-edX-DemoX-video-8c0028eb2a724f48a074bc184cd8635f',
                24,
                5,
                0,
                1,
                15,
            ),
            (
                'course-v1:edX+DemoX+Test_2015|0b9e39477cf34507a7a48f74be381fdd1',
                'course-v1:edX+DemoX+Test_2015',
                '0b9e39477cf34507a7a48f74be381fdd1',
                444,
                5,
                1,
                0,
                5
            ),
        ]
        self.assertItemsEqual(expected, results)

    def validate_video_timeline(self):
        """Ensure the video timeline counts are correct."""
        with self.export_db.cursor() as cursor:
            cursor.execute(
                'SELECT pipeline_video_id, segment, num_users, num_views FROM video_timeline'
                ' ORDER BY pipeline_video_id, segment ASC'
            )
            results = cursor.fetchall()

        expected = [
            ('course-v1:edX+DemoX+Test_2014|0b9e39477cf34507a7a48f74be381fdd', 0, 1, 1),
            ('edX/DemoX/Demo_Course|i4x-edX-DemoX-video-3cb54a11efae4ccc8a0aade24d14b255', 0, 2, 2),
            ('edX/DemoX/Demo_Course|i4x-edX-DemoX-video-3cb54a11efae4ccc8a0aade24d14b255', 1, 2, 3),
            ('edX/DemoX/Demo_Course|i4x-edX-DemoX-video-3cb54a11efae4ccc8a0aade24d14b255', 2, 1, 2),
            ('edX/DemoX/Demo_Course|i4x-edX-DemoX-video-3cb54a11efae4ccc8a0aade24d14b255', 3, 2, 2),
            ('edX/DemoX/Demo_Course|i4x-edX-DemoX-video-3cb54a11efae4ccc8a0aade24d14b255', 4, 2, 3),
            ('edX/DemoX/Demo_Course|i4x-edX-DemoX-video-8c0028eb2a724f48a074bc184cd8635f', 2, 1, 1),
            ('edX/DemoX/Demo_Course|i4x-edX-DemoX-video-8c0028eb2a724f48a074bc184cd8635f', 3, 1, 1),
            ('edX/DemoX/Demo_Course|i4x-edX-DemoX-video-8c0028eb2a724f48a074bc184cd8635f', 4, 1, 1),
            ('course-v1:edX+DemoX+Test_2015|0b9e39477cf34507a7a48f74be381fdd1', 0, 1, 1),
        ]
        self.assertItemsEqual(expected, results)


import os
import argparse
import json

from pypdf import PdfReader
import openai

API_KYE = os.environ['OPENAI_API_KEY']
openai.api_key = API_KYE

def summarize_file(path):
    reader = PdfReader(path)
    number_of_pages = len(reader.pages)
    page = reader.pages[0]
    text = page.extract_text()

    messages=[
        {
            'role': 'system',
            'content': 'You are a helpful assistant, help user to summarize the content of the text. Note that you do not need to say hello or ok in your answer, just output a summary of the text directly.'
        },
        {
            'role': 'user',
            'content': "Summarize the following text:\n"
        },
    ]
    messages[-1]['content'] += text

    response = openai.ChatCompletion.create(
        model='gpt-3.5-turbo',
        messages=messages,
    )

    return response


import vapoursynth as vs

import muvsfunc

def LimitedSharpen2(clp, ss_x=1.0, ss_y=1.0, dest_x=None, dest_y=None, Smode=4, strength=None, radius=2, Lmode=1, wide=False, overshoot=1, soft=False, edgemode=0, special=False, aSharpS=0.5, aWThresh=0.75, exborder=0):
    core = vs.get_core()

    # Avisynth's Round function doesn't do quite the same thing as Python's round function.
    def AvisynthRound(value):
        if value < 0:
            return -int(-value + 0.5)
        else:
            return int(value + 0.5)

    def UnsharpMask(clip, strength=64, radius=3, threshold=8):
        """Ported by Myrsloik"""

        core = vs.get_core()

        maxvalue = (1 << clip.format.bits_per_sample) - 1

        threshold = threshold * maxvalue // 255
        blurclip = clip.std.Convolution(matrix=[1] * (radius * 2 + 1), planes=0, mode='v')
        blurclip = blurclip.std.Convolution(matrix=[1] * (radius * 2 + 1), planes=0, mode='h')

        expressions = ['x y - abs {} > x y - {} * x + x ?'
                                                .format(threshold, strength / 128)]

        if clip.format.color_family != vs.GRAY:
            expressions.append("")

        return core.std.Expr(clips=[clip, blurclip], expr=expressions)

    if clp.format is None:
        raise RuntimeError("LimitedSharpen2: clips with variable format are not supported.")

    if clp.format.color_family == vs.RGB:
        raise RuntimeError("LimitedSharpen2: RGB clips are not supported.")

    if clp.format.sample_type == vs.FLOAT:
        raise RuntimeError("LimitedSharpen2: float clips are not supported.")

    if clp.format.bits_per_sample > 16:
        raise RuntimeError("LimitedSharpen2: bit depths over 16 are not supported.")

    if clp.width == 0 or clp.height == 0:
        raise RuntimeError("LimitedSharpen2: clips with variable dimensions are not supported.")

    maxvalue = (1 << clp.format.bits_per_sample) - 1
    halfvalue = 1 << (clp.format.bits_per_sample - 1)

    ox = clp.width
    oy = clp.height

    if dest_x is None:
        dest_x = ox
    if dest_y is None:
        dest_y = oy

    if strength is None:
        if Smode == 1:
            strength = 160
        else:
            strength = 100
    else:
        if Smode == 2 and strength > 100:
            strength = 100

    if overshoot < 0:
        overshoot = 0

    overshoot = overshoot * maxvalue // 255

    xxs = AvisynthRound(ox * ss_x / 8) * 8
    yys = AvisynthRound(oy * ss_y / 8) * 8

    smx = dest_x
    smy = dest_y
    if exborder != 0:
        smx = AvisynthRound(dest_x / exborder / 4) * 4
        smy = AvisynthRound(dest_y / exborder / 4) * 4

    # Simpler than writing planes=0 everywhere.
    last = core.std.ShufflePlanes(clips=clp, planes=0, colorfamily=vs.GRAY)

    if ss_x != 1.0 or ss_y != 1.0:
        last = core.resize.Lanczos(clip=last, width=xxs, height=yys)

    tmp = last

    vertical = core.std.Convolution(clip=tmp, divisor=2, matrix=[ 5,  10,  5,
                                                                  0,   0,  0,
                                                                 -5, -10, -5])
    horizontal = core.std.Convolution(clip=tmp, divisor=2, matrix=[ 5, 0,  -5,
                                                                   10, 0, -10,
                                                                    5, 0,  -5])
    edge = core.std.Expr(clips=[vertical, horizontal], expr="x y max")
    edge = core.std.Levels(clip=edge, min_in=0, max_in=halfvalue, gamma=0.86, min_out=0, max_out=maxvalue)

    bright_limit = tmp
    if soft:
        bright_limit = muvsfunc.Blur(clip=bright_limit, amountH=1.0)

    dark_limit = core.std.Minimum(clip=bright_limit)
    bright_limit = core.std.Maximum(clip=bright_limit)

    if wide:
        dark_limit = dark_limit.std.Inflate().std.Deflate().std.Minimum()
        bright_limit = bright_limit.std.Deflate().std.Inflate().std.Maximum()

    if special:
        minmaxavg = core.std.MaskedMerge(clipa=dark_limit, clipb=bright_limit, mask=tmp)
    else:
        minmaxavg = core.std.Expr(clips=[bright_limit, dark_limit], expr="x y + 2 /")

    if Smode == 1:
        normsharp = UnsharpMask(clip=last, strength=strength, radius=radius, threshold=0)
    elif Smode == 2:
        normsharp = muvsfunc.Sharpen(clip=last, amountH=strength / 100.0)
    elif Smode == 3:
        normsharp = core.std.Expr(clips=[tmp, minmaxavg], expr="x x y - {strength} * +".format(strength=strength / 100.0))
    else:
        normsharp = core.asharp.ASharp(clip=last, t=aSharpS, d=0, b=0)
        normsharp = core.warp.AWarpSharp2(clip=normsharp, depth=1, blur=3, type=1, thresh=aWThresh * 256)

    if Lmode == 1:
        last = core.std.Expr(clips=[bright_limit, normsharp], expr="y x {overshoot} + < y x {overshoot} + ?".format(overshoot=overshoot))
        last = core.std.Expr(clips=[dark_limit, last], expr="y x {overshoot} - > y x {overshoot} - ?".format(overshoot=overshoot))
    else:
        last = core.std.Expr(clips=[bright_limit, normsharp], expr="y x {overshoot} + < y x y x - {overshoot} - 1 2 / pow + {overshoot} + ?")
        last = core.std.Expr(clips=[dark_limit, last], expr="y x {overshoot} - > y x x y - {overshoot} - 1 2 / pow - {overshoot} - ?")

    if edgemode == 0:
        pass
    else:
        edge = muvsfunc.Blur(clip=edge.std.Inflate().std.Inflate(), amountH=1.0)

        if edgemode == 1:
            last = core.std.MaskedMerge(clipa=tmp, clipb=last, mask=edge)
        else:
            last = core.std.MaskedMerge(clipa=last, clipb=tmp, mask=edge)

    if ss_x != 1.0 or ss_y != 1.0 or dest_x != ox or dest_y != oy:
        last = core.resize.Lanczos(clip=last, width=dest_x, height=dest_y)

    ex = core.std.BlankClip(clip=last, width=smx, height=smy, color=maxvalue, length=1)
    ex = core.std.AddBorders(clip=ex, left=2, right=2, top=2, bottom=2, color=0)
    ex = muvsfunc.Blur(clip=ex, amountH=1.3)
    ex = core.std.Minimum(clip=ex)
    ex = muvsfunc.Blur(clip=ex, amountH=1.3)
    ex = core.resize.Bicubic(clip=ex, width=dest_x, height=dest_y, filter_param_a=1.0, filter_param_b=0.0)
    ex = core.std.Loop(clip=ex, times=last.num_frames)

    tmp = core.resize.Lanczos(clip=clp, width=dest_x, height=dest_y)

    if tmp.format.color_family != vs.GRAY:
	    last = core.std.ShufflePlanes(clips=[last, tmp], planes=[0, 1, 2], colorfamily=tmp.format.color_family)

    if exborder != 0:
        last = core.std.MaskedMerge(clipa=tmp, clipb=last, mask=ex, planes=0)

    return last


import pandas as pd
import matplotlib.pyplot as plt
import base64
from io import BytesIO
from time import strptime
from pandas.core import base
import plotly.express as px

class Myclass:
    def __init__(self,path1,path2):
        self.path1=path1
        self.path2=path2

    def matrix_multiplication(self):
        dataR=pd.read_excel(self.path1)
        dataPF=pd.read_excel(self.path2)
        dataR=dataR.set_index(dataR.columns[0])
        dataPF=dataPF.set_index(dataPF.columns[0])
        self.matrix_mul=dataR.dot(dataPF)
        self.matrix_mul.index.name='TimeFrame'
        return self.matrix_mul

    """ Params->1. df: DataFrame   2.period: Periods (month/year/particula day)
        3. DMY_NO(DateMonthYear_No.):Exact no. of DMY  4.single: For particular columns in dataframe. """

    def cumsum_result(self,df,period,DMY_NO,single):
        newdf=df.cumsum()
        newdf=newdf.reset_index()
        newdf['day']=newdf['TimeFrame'].dt.day_name()
        if period=='day':
            dd=newdf[newdf['day'].isin(DMY_NO)]
            del dd['day']
            dd=dd.set_index(dd.columns[0])
            return dd[single]

        elif period=='month':
            mnt=[]
            for i in DMY_NO:
                mnt.append(strptime(i,'%b').tm_mon)
            dd=newdf[newdf['TimeFrame'].dt.month.isin(mnt)]
            del dd['day']
            dd= dd.set_index(dd.columns[0])
            return dd[single]

        elif period=='year':
            DMY_NO=[int(i) for i in DMY_NO]
            dd=newdf[newdf['TimeFrame'].dt.year.isin(DMY_NO)]
            del dd['day']
            return dd.set_index(dd.columns[0])[single]

    def dates(self,df,st,ed):
        filt=df.loc[st:ed]
        return filt

    def calculations(self,df):
        lTvar=[]
        uTvar=[]

        cal= df.apply(['min','max','std','mean','skew','kurt','median'])
        cal.loc['Sharp']=cal.loc['std'] / cal.loc['min']
        cal.loc['LowerVar']=df.quantile(q=0.05)
        cal.loc['UpperVar']=df.quantile(q=0.9)

        for i,j,k in zip(df.columns,cal.loc['LowerVar'].tolist(),cal.loc['UpperVar'].tolist()):
            lower=df[i][df[i]<j]
            upper=df[i][df[i]>k]
            lTvar.append(lower.mean())
            uTvar.append(upper.mean())
        cal.loc['LowerTvar']=lTvar
        cal.loc['UpperTvar']=uTvar
        return cal

    def Formula_calculation(self,df,Min,LTVar,LVar,UVar,UTVar,Max):
        pd_list=[]

        std=df.std()
        md=df.median()

        pd_list.append([(i*Min+k)*100 for i,k in zip(std,md)])
        pd_list.append([(i*LTVar+k)*100 for i,k in zip(std,md)])
        pd_list.append([(i*LVar+k)*100 for i,k in zip(std,md)])
        pd_list.append([(i*UVar+k)*100 for i,k in zip(std,md)])
        pd_list.append([(i*UTVar+k)*100 for i,k in zip(std,md)])
        pd_list.append([(i*Max+k)*100 for i,k in zip(std,md)])

        formula=pd.DataFrame(pd_list,columns=df.columns,index=['Min','LowerTVar','LowerVar','UpperVar','UpperTVar','Max'])
        formula.loc['Median']=md*100
        formula=formula.reindex(['Min','LowerTVar','LowerVar','Median','UpperVar','UpperTVar','Max'])
        return formula.round(2)

    ### For Plotly interactive graph8
    def myvisual(self,mydf,per):
        df=mydf.multiply(100)
        mynew=df.reset_index()

        if per=='day':
            mynew=mynew.set_index(mynew.columns[0])
            fig = px.line(mynew)
            return fig
        elif per=='month':
            myplot=mynew.groupby(pd.Grouper(key=mynew.columns[0],freq='M')).sum()
        else:
            myplot=mynew.groupby(pd.Grouper(key=mynew.columns[0],freq='M')).sum()

        fig = px.line(myplot)
        return fig

""" For matplotlib graph """

    # def get_graph(self):
    #     buffer=BytesIO()
    #     plt.savefig(buffer,format='png')
    #     buffer.seek(0)
    #     image_png=buffer.getvalue()
    #     graph=base64.b64encode(image_png)
    #     graph=graph.decode('utf-8')
    #     buffer.close()
    #     return graph

    # def visual(self,mydf,per):
    #     plt.switch_backend('AGG')
    #     plt.figure(figsize=(10,5))
    #     plt.title('Assets-Portfolio')
    #     plt.xlabel('TimeFrame')
    #     plt.ylabel('Portfolio')
    #     df=mydf.multiply(100)
    #     mynew=df.reset_index()

    #     if per=='day':
    #         myplot=mynew.groupby(pd.Grouper(key=mynew.columns[0],freq='Y')).sum()
    #     elif per=='month':
    #         myplot=mynew.groupby(pd.Grouper(key=mynew.columns[0],freq='Y')).sum()
    #     else:
    #         myplot=mynew.groupby(pd.Grouper(key=mynew.columns[0],freq='M')).sum()

    #     plt.grid()
    #     plt.plot(myplot)
    #     plt.legend(myplot.columns,ncol=3)
    #     graph=self.get_graph()
    #     return graph


import PyPDF2

#translate the pdf file to txt file
def pdf_to_text(pdf_file_path, txt_file_path):
    try:
        # Open the PDF file
        with open(pdf_file_path, 'rb') as pdf_file:
            pdf_reader = PyPDF2.PdfReader(pdf_file)
            # Initialize an empty text string
            text = ""

            # Loop through each page and extract text
            for page_num in range(len(pdf_reader.pages)):
                page = pdf_reader.pages[page_num]
                text += page.extract_text()

            # Save the extracted text to a text file
            #creates new text file if text file doesnt exist
            #overwrites content in text file if text file does exist
            with open(txt_file_path, 'w', encoding='utf-8') as txt_file:
                txt_file.write(text)

        print(f"Text extracted from '{pdf_file_path}' and saved to '{txt_file_path}'.")

    except FileNotFoundError:
        print(f"The file '{pdf_file_path}' was not found.")
    except Exception as e:
        print(f"An error occurred: {str(e)}")


"""

The PyRankine: the hybrid steady-state simulator of Rankine Cycle

  class Split_One2Two

         ↓ iPort
    ┌────┴────┐
  oPort0      oPort1

 json object example:

        {
         "name": "inpur name",
        "devtype": "SPLIT_ONE2TWO",
        "iPort": {},
        "oPort0": {},
        "oPort1": {}
       }

row:
   1.  mass balance row

 Author:Cheng Maohua  Email: cmh@seu.edu.cn

"""

from .port import *

class Split_One2Two:
    """ sm and so """

    energy = "none"
    devtype = "SPLIT_ONE2TWO"

    def __init__(self, dictDev):
        """
        Initializes SPLIT_ONE2TWO
        """
        # self.__dict__.update(dictDev)
        self.name = dictDev['name']
        self.iPort = Port(dictDev['iPort'])
        self.oPort0 = Port(dictDev['oPort0'])
        self.oPort1 = Port(dictDev['oPort1'])

    def state(self):
        if self.iPort.p is not None and self.iPort.t is not None:
            self.oPort0.p = self.iPort.p
            self.oPort0.t = self.iPort.t
            self.oPort0.pt()

            self.oPort1.p = self.iPort.p
            self.oPort1.t = self.iPort.t
            self.oPort1.pt()

        elif self.oPort0.p is not None and self.oPort0.t is not None:
            self.iPort0.p = self.oPort0.p
            self.iPort0.t = self.oPort0.t
            self.iPort0.pt()

            self.oPort1.p = self.oPort0.p
            self.oPort1.t = self.oPort0.t
            self.oPort1.pt()

        elif self.oPort1.p is not None and self.oPort1.t is not None:
            self.iPort0.p = self.oPort1.p
            self.iPort0.t = self.oPort1.t
            self.iPort0.pt()

            self.oPort0.p = self.oPort1.p
            self.oPort0.t = self.oPort1.t
            self.oPort0.pt()

    # sequential-modular approach
    def balance(self):
        """ 1kg mass balanceequation"""
        if self.iPort.fdot is not None and self.oPort0.fdot is not None:
            self.oPort1.fdot = self.iPort.fdot-self.oPort0.fdot
        elif self.iPort.fdot is not None and self.oPort1.fdot is not None:
            self.oPort0.fdot = self.iPort.fdot-self.oPort1.fdot
        elif self.oPort0.fdot is not None and self.oPort1.fdot is not None:
            self.iPort.fdot = self.oPort0.fdot+self.oPort1.fdot
        # the ifs maybe without any cal ,so use raise ValueError if fdot is None
        if self.iPort.fdot is None or self.oPort0.fdot is None or self.oPort1.fdot is None:
            raise ValueError("fdot not none")

    #  equation-oriented approach

    def equation_rows(self):
        """ some ports may have values """
        # 1 mass balance  row
        colid = [(self.iPort.id, 1),
                 (self.oPort0.id, -1),
                 (self.oPort1.id, -1),
                 ]
        bv = 0
        # ports have values
        if self.iPort.fdot is not None:
            colid = [(self.oPort0.id, 1),
                     (self.oPort1.id, 1)]
            bv = self.iPort.fdot

        if self.oPort0.fdot is not None:
            colid = [(self.iPort.id, 1),
                     (self.oPort1.id, -1)]
            bv = self.oPort0.fdot

        if self.oPort1.fdot is not None:
            colid = [(self.iPort.id, 1),
                     (self.oPort0.id, -1)]
            bv = self.oPort1.fdot

        self.rows = [{"a": colid, "b": bv}]

    #  equation-oriented approach
    def energy_fdot(self):
        pass

    def calmdot(self, totalmass):
        pass

    def sm_energy(self):
        """ mdot """
        pass

    def __str__(self):
        result = '\n' + self.name
        result += '\n' + " PORT " + Port.title
        result += '\n' + " iPort "+self.iPort.__str__()
        result += '\n' + " oPort0 " + self.oPort0.__str__()
        result += '\n' + " oPort1 " + self.oPort1.__str__()
        return result


def solve(s):
    l = s.split(" ")
    a = [i.capitalize() for i in l]
    return " ".join(a)

s = input()
print(solve(s))

'''
m = input().split(' ')  didn't work properly. Every letter seperated
n = ''
for i in m:
    n += i.capitalize()
print(' '.join(n))

def solve(s):  #16 point get by submit this. one test case wrong
    solve = s.title()
    return solve
s = input()
print(solve(s))

solution 2
#import string
#print(string.capwords(input(), ' '))

solution 3
string = input().split(' ')
print(' '.join((word.capitalize() for word in string)))'''


# Invert a binary tree.

# Example:
# Input:
#      4
#    /   \
#   2     7
#  / \   / \
# 1   3 6   9

# Output:
#      4
#    /   \
#   7     2
#  / \   / \
# 9   6 3   1

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        if root == None: return root
        def helper(node):
            temp = node.left
            node.left = node.right
            node.right = temp
            if node.left != None: helper(node.left)
            if node.right != None: helper(node.right)
        helper(root)
        return root


# 1st Approach:
class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        winS = winE = 0
        hashMap = {}
        maxL = 0
        while winE < len(s):
            hashMap[s[winE]] = hashMap.get(s[winE], 0)+1
            if len(hashMap) == winE-winS+1:
                maxL = max(maxL, winE-winS+1)
                winE += 1
            else:
                if hashMap[s[winS]] == 1:
                    del hashMap[s[winS]]
                    winS += 1
                    winE += 1
                else:
                    hashMap[s[winS]] -= 1
                    winS += 1
                    winE += 1
        return maxL

# 2nd Approach:
class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        maxL = 0
        winS = 0
        hashMap = {}
        for winE in range(len(s)):
            char = s[winE]
            if char in hashMap:
                winS = max(winS, hashMap[char]+1)
            hashMap[char] = winE
            maxL = max(maxL, winE-winS+1)
        return maxL


import graphene
from graphene import Field

from graphene_django.types import ErrorType
from graphene.types.base import BaseOptions

from django.core.exceptions import ObjectDoesNotExist

class DeleteMutationOptions(BaseOptions):
    model = None
    arguments = None
    output = None
    resolver = None
    interfaces = ()
    fields = None

class DeleteMutation(graphene.Mutation):
    class Meta:
        abstract = True
    id = graphene.ID()
    ok = graphene.Boolean(
        description="Boolean field that return mutation result request."
    )
    errors = graphene.List(ErrorType, description="Errors list for the field")

    class Arguments:
        id = graphene.ID(required=True)

    @classmethod
    def __init_subclass_with_meta__(
        cls,
        model=None,
        interfaces=(),
        resolver=None,
        output=None,
        arguments=None,
        _meta=None,
        **options
    ):
        if not _meta:
            _meta = DeleteMutationOptions(cls)

        assert model is not None, ("Model class in {} must be need.").format(
            cls.__name__
        )
        _meta.model = model
        super(DeleteMutation, cls).__init_subclass_with_meta__(
            interfaces=interfaces,
            resolver=resolver,
            output=output,
            arguments=arguments,
            _meta=_meta,
            **options
        )

    @classmethod
    def get_errors(cls, errors):
        errors_dict = {"ok": False, "errors": errors, "id": None}

        return cls(**errors_dict)

    @classmethod
    def perform_mutate(cls, obj, info):
        resp = {"ok": True, "errors": None, "id": obj.id}

        return cls(**resp)

    @classmethod
    def mutate(cls, root, info, id):
        try:
            obj = cls._meta.model.objects.get(id=id)
            obj.delete()
            obj.id = id
            return cls.perform_mutate(obj, info)
        except ObjectDoesNotExist:
            return cls.get_errors(
                [
                    ErrorType(
                        field="id",
                        messages=[
                            "A {} obj with id {} do not exist".format(
                                cls._meta.model.__name__, id
                            )
                        ],
                    )
                ]
            )

    @classmethod
    def Field(
        cls, name=None, description=None, deprecation_reason=None, required=False
    ):
        """ Mount instance of mutation Field. """
        return Field(
            cls._meta.output,
            args=cls._meta.arguments,
            resolver=cls._meta.resolver,
            name=name,
            description=description or cls._meta.description,
            deprecation_reason=deprecation_reason,
            required=required,
        )


# Q1:

#Kullanıcının boy ve ağırlık değerlerinin girilmesi
boy = float(input("Lütfen boyunuzu (santimetre cinsinde) yazınız: "))
agirlik = float(input("Lütfen ağırlığınızı (kilogram cinsinde) yazınız: "))

#Vücut Kitle İndeksinin (VKİ) hesaplanması
VKİ = agirlik / (boy * boy)

#Sonuç
print("Vücut Kitle İndeksiniz:", VKİ)


import os
import math
import pandas as pd
from scipy.stats import gmean
from tabulate import tabulate
from eval import *

'''
usage: python .\result.py > .\result.log
input: all log files
output: csv file that contains the evaluation results
'''

def format_integer(number):
    if math.isnan(number):
        return number
    return format(int(number), ',')

def clean_integer(number):
    return int(number.replace(',', ''))

def get_elf_size(file):
    if os.path.exists(file):
        return os.path.getsize(file)

def update_IBT(proj_metadata_file):
    obj = MetaDataRefresh(bin_file_path=proj_metadata_file)
    bt_header, _, _, _ = obj.parse_metadata_from_file()
    return int(bt_header.IBT_size)

def get_baseline(baseline_record):
    return int(baseline_record[0].split(':')[1].strip())

def get_dict(data):
    data_parts = [part.strip() for part in data.split(',')]
    data_dict = {}

    for part in data_parts:
        k, v = part.split(':')
        key = k.strip()
        value = int(v.strip())
        data_dict[key] = value
    return data_dict

def read_oneline(file_name):
    records = []
    if os.path.exists(file_name):
        with open(file_name, 'r') as file:
            lines = file.readlines()
        for i, line in enumerate(lines):
            if i == 3:
                return get_dict(line.strip())
    else:
        print(file_name + " dose not exist!")
    return records

def read_first_line(file_name):
    records = []
    if os.path.exists(file_name):
        with open(file_name, 'r') as file:
            line = file.readline()
            return get_dict(line.strip())
    else:
        print(file_name + " dose not exist!")
    return records

def read_file(file_name):
    records = []
    if os.path.exists(file_name):
        with open(file_name, "r") as file:
            lines = file.readlines()

        lines.pop(0)  # Skip the first line

        averages = {}
        count = 0

        for line in lines:
            count += 1
            pairs = line.strip().split(", ")

            for pair in pairs:
                key, value = pair.split(": ")
                if key not in averages:
                    averages[key] = 0
                averages[key] += int(value)

        for key in averages:
            averages[key] = int(averages[key]/count)

        return averages
    else:
        print(file_name + " dose not exist!")

    return records

def calculate_overhead(baseline, result_dict):
    overhead = {}
    for key in result_dict:
        overhead[key] = round((result_dict[key]/baseline)*100, 2)
    return overhead

class BEEBsResult(object):
    def __init__(self):
        self.opt_levels = ['O3', 'Oz']

    def fresh_cvs_beebs(self, opt_level):
        work_path = '../../Example/out/eval/'
        log_path = work_path + opt_level + '/eval_log/'
        result_beebs = log_path + 'beebs_eval_result.csv'
        final_beebs = log_path + 'beebs_eval_result_final.csv'

        elf_path = work_path + opt_level + '/elf_ns/'
        metadata_path = work_path + opt_level + '/metadata/'

        # "matmult_int", "stb_perlin",
        BEEBS_name_list = ['bubblesort', 'crc32', 'dijkstra', 'edn', 'fasta', 'frac', 'levenshtein', 'nbody', 'ndes', 'nettle_aes', 'picojpeg', 'qrduino',
                           'rijndael', 'sglib_arraybinsearch', 'sglib_dllist', 'sglib_hashtable', 'sglib_listsort', 'sglib_queue', 'sglib_rbtree', 'st', 'whetstone']

        df_beebs = pd.read_csv(result_beebs)

        for beebs_name in BEEBS_name_list:
            print(f'{beebs_name} {opt_level}')
            baseline_file = log_path + beebs_name + '_baseline.log'
            eval_ibt_baseline = log_path + beebs_name + '_ibt_baseline_no_systick.log'
            eval_ibt_checking = log_path + beebs_name + '_ibt_no_systick.log'
            eval_full_file = log_path + beebs_name + '_full_no_irq.log'
            eval_read_file = log_path + beebs_name + '_sherloc_read.log'
            eval_ins_file = log_path + beebs_name + '_ins.log'
            elf_name = elf_path + beebs_name + '.axf'
            proj_metadata_file = metadata_path + beebs_name + '.bin'

            baseline_dict = read_oneline(baseline_file)
            full_dict = read_oneline(eval_full_file)
            read_dict = read_oneline(eval_read_file)
            ins_dict = read_oneline(eval_ins_file)
            ibt_baseline = read_oneline(eval_ibt_baseline)
            ibt_checking = read_oneline(eval_ibt_checking)

            # enter [backward_edge|forward_edge|ins_identification|sherloc_read] exit
            baseline = baseline_dict['NONE']
            sherloc_detection = full_dict['sherloc_detection']
            result_dict = {}
            result_dict['SHERLOC'] = full_dict['EVAL'] - baseline
            result_dict['enter_exit'] = full_dict['enter_exit'] - baseline
            result_dict['read'] = read_dict['sherloc_read']
            result_dict['ins_identification'] = ins_dict['sherloc_ins_identification'] - \
                result_dict['read']
            result_dict['forward'] = ibt_checking['ibt_check'] - \
                ibt_baseline['ibt_check']

            result_dict['ss'] = sherloc_detection - result_dict['read'] - \
                result_dict['forward'] - result_dict['ins_identification']

            print("result_dict: ", result_dict)

            eval_overhead = calculate_overhead(baseline, result_dict)
            print("eval_overhead: ", eval_overhead)

            # write result to the table
            df_beebs.loc[df_beebs['name'] ==
                         beebs_name, "opt_level"] = opt_level
            df_beebs.loc[df_beebs['name'] == beebs_name,
                         "elf_size"] = get_elf_size(elf_name)
            df_beebs.loc[df_beebs['name'] == beebs_name, "IBT_size"] = update_IBT(
                proj_metadata_file) * 4
            df_beebs.loc[df_beebs['name'] == beebs_name, "AIT_size"] = 3 * 4
            df_beebs.loc[df_beebs['name'] == beebs_name, "baseline"] = baseline
            df_beebs.loc[df_beebs['name'] == beebs_name,
                         "SHERLOC"] = result_dict['SHERLOC']
            for item in eval_overhead:
                df_beebs.loc[df_beebs['name'] == beebs_name,
                             'overhead_'+item] = eval_overhead[item]
            df_beebs.to_csv(final_beebs, index=False)
        df_beebs.loc[df_beebs['name'] == 'min', "opt_level"] = opt_level
        df_beebs.loc[df_beebs['name'] == 'max', "opt_level"] = opt_level
        df_beebs.loc[df_beebs['name'] == 'mean', "opt_level"] = opt_level

        integer_column = ['elf_size', 'icall', 'ibranch', 'dbranch',
                          'dcall', 'ret', 'irq', 'baseline', 'SHERLOC', 'baseline']

        for column in df_beebs.columns:
            if column == 'name' or column == 'opt_level':
                continue

            column_data = df_beebs[column]
            mean_value = round(column_data.mean(), 2)
            min_value = round(column_data.min(), 2)
            max_value = round(column_data.max(), 2)
            df_beebs.loc[df_beebs['name'] == 'mean', column] = mean_value
            df_beebs.loc[df_beebs['name'] == 'min', column] = min_value
            df_beebs.loc[df_beebs['name'] == 'max', column] = max_value

            if column in integer_column:
                df_beebs[column] = df_beebs[column].apply(format_integer)

            df_beebs.to_csv(final_beebs, index=False)

    def beebs_csv(self):
        # Read the CSV file (replace 'file.csv' with your file's name)
        csv_file1 = '../../Example/out/eval/O3/eval_log/beebs_eval_result_final.csv'
        csv_file2 = '../../Example/out/eval/Oz/eval_log/beebs_eval_result_final.csv'

        # Read the CSV files into pandas DataFrames
        df_beebs1 = pd.read_csv(csv_file1)
        df_beebs2 = pd.read_csv(csv_file2)

        # Merge the two DataFrames
        merged_df_beebs = pd.concat([df_beebs1, df_beebs2], ignore_index=True)

        # Sort the merged DataFrame by the first column
        first_column_name = merged_df_beebs.columns[0]
        sorted_df_beebs = merged_df_beebs.sort_values(by=first_column_name)

        # Convert the DataFrame to a LaTeX table
        latex_table = tabulate(sorted_df_beebs, tablefmt='latex',
                               headers='keys', showindex=False)

        # Write the LaTeX table to a file (replace 'output.tex' with your desired file name)
        with open('beebs_output.tex', 'w') as file:
            file.write(latex_table)

    def run(self):
        print('processing beebs eval results...')
        for opt in self.opt_levels:
            self.fresh_cvs_beebs(opt)
        self.beebs_csv()
        print('\n')

class BlinkyResult(object):
    def __init__(self):
        self.opt_levels = ['O3', 'Oz']

    def fresh_cvs_blinky(self, opt_level):
        work_path = '../../Example/out/eval/'
        log_path = work_path + opt_level + '/eval_log/'
        final_blinky = log_path + 'blinky_eval_result_final.csv'
        result_blinky = log_path + 'blinky_eval_result.csv'

        elf_path = work_path + opt_level + '/elf_ns/'
        metadata_path = work_path + opt_level + '/metadata/'

        Blinky_list = ['Sherloc_Blinky_ns_100ms', 'Sherloc_Blinky_ns_10ms']

        df_blinky = pd.read_csv(result_blinky)

        for blinky_instance in Blinky_list:
            print(f'{blinky_instance} {opt_level}')
            working_log_path = log_path + blinky_instance
            baseline_file = f'{working_log_path}_baseline_blinky.log'
            eval_full_file = f'{working_log_path}_full_blinky.log'
            eval_read_file = f'{working_log_path}_sherloc_read_systick.log'
            eval_ins_file = f'{working_log_path}_ins_systick.log'
            eval_ibt_baseline = f'{working_log_path}_ibt_baseline_systick.log'
            eval_ibt = f'{working_log_path}_ibt_systick.log'
            elf_name = elf_path + blinky_instance + '.axf'
            proj_metadata_file = metadata_path + blinky_instance + '.bin'

            baseline_dict = read_file(baseline_file)

            full_dict = read_first_line(eval_full_file)
            read_dict = read_first_line(eval_read_file)
            ins_dict = read_file(eval_ins_file)

            ibt_baseline_dict = read_first_line(eval_ibt_baseline)
            ibt_dict = read_first_line(eval_ibt)

            # enter [backward_edge|forward_edge|ins_identification|sherloc_read] exit
            baseline = baseline_dict['NONE']
            sherloc_detection = full_dict['sherloc_detection']
            result_dict = {}
            result_dict['SHERLOC'] = full_dict['EVAL'] - baseline
            result_dict['enter_exit'] = full_dict['enter_exit'] - baseline
            result_dict['read'] = read_dict['sherloc_read']
            result_dict['ins_identification'] = ins_dict['sherloc_ins_identification'] - \
                result_dict['read']
            result_dict['forward'] = ibt_dict['ibt_check'] - \
                ibt_baseline_dict['ibt_check']
            result_dict['ss_IRQ'] = sherloc_detection - result_dict['read'] - \
                result_dict['forward'] - \
                result_dict['ins_identification']

            print(f'result_dict: {result_dict}')

            eval_overhead = calculate_overhead(baseline, result_dict)
            print(f'eval_overhead: {eval_overhead}')

            # write result to the table
            df_blinky.loc[df_blinky['name'] ==
                          blinky_instance, "opt_level"] = opt_level
            df_blinky.loc[df_blinky['name'] == blinky_instance,
                          "elf_size"] = get_elf_size(elf_name)
            df_blinky.loc[df_blinky['name'] == blinky_instance, "IBT_size"] = update_IBT(
                proj_metadata_file) * 4
            df_blinky.loc[df_blinky['name'] ==
                          blinky_instance, "AIT_size"] = 3 * 4
            df_blinky.loc[df_blinky['name'] ==
                          blinky_instance, "baseline"] = baseline
            df_blinky.loc[df_blinky['name'] == blinky_instance,
                          "SHERLOC"] = result_dict['SHERLOC']
            for item in eval_overhead:
                df_blinky.loc[df_blinky['name'] == blinky_instance,
                              'overhead_'+item] = eval_overhead[item]
            df_blinky.to_csv(final_blinky, index=False)

        df_blinky.loc[df_blinky['name'] == 'min', "opt_level"] = opt_level
        df_blinky.loc[df_blinky['name'] == 'max', "opt_level"] = opt_level
        df_blinky.loc[df_blinky['name'] == 'mean', "opt_level"] = opt_level

        integer_column = ['elf_size', 'icall', 'ibranch', 'dbranch',
                          'dcall', 'ret', 'irq', 'baseline', 'SHERLOC', 'baseline']

        for column in df_blinky.columns:
            if column == 'name' or column == 'opt_level':
                continue
            column_data = df_blinky[column]
            mean_value = round(column_data.mean(), 2)
            min_value = round(column_data.min(), 2)
            max_value = round(column_data.max(), 2)
            df_blinky.loc[df_blinky['name'] == 'mean', column] = mean_value
            df_blinky.loc[df_blinky['name'] == 'min', column] = min_value
            df_blinky.loc[df_blinky['name'] == 'max', column] = max_value

            if column in integer_column:
                df_blinky[column] = df_blinky[column].apply(format_integer)

            df_blinky.to_csv(final_blinky, index=False)

    def blinky_csv(self):
        csv_file_blinky_O3 = '../../Example/out/eval/O3/eval_log/blinky_eval_result_final.csv'
        csv_file_blinky_Oz = '../../Example/out/eval/Oz/eval_log/blinky_eval_result_final.csv'

        # Read the CSV files into pandas DataFrames
        df_blinky1 = pd.read_csv(csv_file_blinky_O3)
        df_blinky2 = pd.read_csv(csv_file_blinky_Oz)

        # Merge the two DataFrames
        merged_df_blinky = pd.concat(
            [df_blinky1, df_blinky2], ignore_index=True)

        # Sort the merged DataFrame by the first column
        first_column_name = merged_df_blinky.columns[0]
        sorted_df_blinky = merged_df_blinky.sort_values(by=first_column_name)

        # Convert the DataFrame to a LaTeX table
        latex_table = tabulate(sorted_df_blinky, tablefmt='latex',
                               headers='keys', showindex=False)

        # Write the LaTeX table to a file (replace 'output.tex' with your desired file name)
        with open('blinky_output.tex', 'w') as file:
            file.write(latex_table)

    def run(self):
        print('processing blinky eval results...')
        for opt in self.opt_levels:
            self.fresh_cvs_blinky(opt)
        self.blinky_csv()
        print('\n')

class FreeRTOSResult(object):
    def __init__(self):
        self.opt_levels = ['O3', 'Oz']

    def fresh_cvs_freertos(self, opt_level):
        work_path = '../../Example/out/eval/'
        log_path = work_path + opt_level + '/eval_log/'
        final_freertos = log_path + 'freertos_eval_result_final.csv'
        result_freertos = log_path + 'freertos_eval_result.csv'

        elf_path = work_path + opt_level + '/elf_ns/'
        metadata_path = work_path + opt_level + '/metadata/'

        FreeRTOS_list = ['FreeRTOS_MPU_ns_1']

        df_freertos = pd.read_csv(result_freertos)

        for freertos_instance in FreeRTOS_list:
            print(f'{freertos_instance} {opt_level}')
            working_log_path = log_path + freertos_instance
            baseline_file = f'{working_log_path}_baseline_rtos.log'
            eval_full_file = f'{working_log_path}_full_rtos.log'
            eval_read_file = f'{working_log_path}_read_rtos.log'
            eval_ins_file = f'{working_log_path}_ins_rtos.log'
            eval_ibt_baseline_freertos = f'{working_log_path}_ibt_freertos_baseline.log'
            eval_ibt_freertos = f'{working_log_path}_ibt_freertos.log'
            elf_name = elf_path + freertos_instance + '.axf'
            proj_metadata_file = metadata_path + freertos_instance + '.bin'

            baseline_dict = read_first_line(baseline_file)
            full_dict = read_first_line(eval_full_file)
            read_dict = read_first_line(eval_read_file)
            ins_dict = read_first_line(eval_ins_file)
            ibt_baseline_dict = read_first_line(eval_ibt_baseline_freertos)
            ibt_freertos_dict = read_first_line(eval_ibt_freertos)

            # enter [backward_edge|forward_edge|ins_identification|sherloc_read] exit
            baseline = baseline_dict['NONE']
            result_dict = {}
            result_dict['SHERLOC'] = full_dict['EVAL'] - baseline
            result_dict['enter_exit'] = full_dict['enter_exit'] - baseline
            result_dict['read'] = read_dict['sherloc_read']
            result_dict['ins_identification'] = ins_dict['sherloc_ins_identification'] - \
                result_dict['read']
            result_dict['forward'] = ibt_freertos_dict['ibt_check'] - \
                ibt_baseline_dict['ibt_check']
            result_dict['ss'] = result_dict['SHERLOC'] - result_dict['enter_exit'] - \
                result_dict['read'] - result_dict['ins_identification'] - \
                result_dict['forward']

            print("result_dict: ", result_dict)

            eval_overhead = calculate_overhead(baseline, result_dict)
            print("eval_overhead: ", eval_overhead)

            # write result to the table
            df_freertos.loc[df_freertos['name'] ==
                            freertos_instance, "opt_level"] = opt_level
            if os.path.exists(elf_name):
                df_freertos.loc[df_freertos['name'] == freertos_instance,
                                "elf_size"] = get_elf_size(elf_name)
            else:
                print("elf file not exist")
            df_freertos.loc[df_freertos['name'] == freertos_instance, "IBT_size"] = update_IBT(
                proj_metadata_file) * 4
            df_freertos.loc[df_freertos['name'] ==
                            freertos_instance, "AIT_size"] = 3 * 4
            df_freertos.loc[df_freertos['name'] ==
                            freertos_instance, "baseline"] = baseline
            df_freertos.loc[df_freertos['name'] == freertos_instance,
                            "SHERLOC"] = result_dict['SHERLOC']
            for item in eval_overhead:
                df_freertos.loc[df_freertos['name'] == freertos_instance,
                                'overhead_'+item] = eval_overhead[item]
            df_freertos.to_csv(final_freertos, index=False)

        df_freertos.loc[df_freertos['name'] == 'min', "opt_level"] = opt_level
        df_freertos.loc[df_freertos['name'] == 'max', "opt_level"] = opt_level
        df_freertos.loc[df_freertos['name'] == 'mean', "opt_level"] = opt_level

        integer_column = ['elf_size', 'SHERLOC', 'baseline']

        for column in df_freertos.columns:
            if column == 'name' or column == 'opt_level':
                continue
            column_data = df_freertos[column]
            mean_value = round(column_data.mean(), 2)
            min_value = round(column_data.min(), 2)
            max_value = round(column_data.max(), 2)
            df_freertos.loc[df_freertos['name'] == 'mean', column] = mean_value
            df_freertos.loc[df_freertos['name'] == 'min', column] = min_value
            df_freertos.loc[df_freertos['name'] == 'max', column] = max_value

            if column in integer_column:
                df_freertos[column] = df_freertos[column].apply(format_integer)

            df_freertos.to_csv(final_freertos, index=False)

    def freertos_csv(self):
        csv_file_freertos_O3 = '../../Example/out/eval/O3/eval_log/freertos_eval_result_final.csv'
        csv_file_freertos_Oz = '../../Example/out/eval/Oz/eval_log/freertos_eval_result_final.csv'

        # Read the CSV files into pandas DataFrames
        df_freertos1 = pd.read_csv(csv_file_freertos_O3)
        df_freertos2 = pd.read_csv(csv_file_freertos_Oz)

        # Merge the two DataFrames
        merged_df_freertos = pd.concat(
            [df_freertos1, df_freertos2], ignore_index=True)

        # Sort the merged DataFrame by the first column
        first_column_name = merged_df_freertos.columns[0]
        sorted_df_freertos = merged_df_freertos.sort_values(
            by=first_column_name)

        # Convert the DataFrame to a LaTeX table
        latex_table = tabulate(sorted_df_freertos, tablefmt='latex',
                               headers='keys', showindex=False)

        # Write the LaTeX table to a file (replace 'output.tex' with your desired file name)
        with open('freertos_output.tex', 'w') as file:
            file.write(latex_table)

    def run(self):
        print('processing freertos eval results...')
        for opt in self.opt_levels:
            self.fresh_cvs_freertos(opt)
        self.freertos_csv()
        print('\n')

class FreeRTOSTriggerResult(object):
    def __init__(self):
        self.opt_levels = ['O3', 'Oz']
        self.work_path = '../../Example/out/eval/'

    def get_freertos_mpu_trigger(self, opt_level):
        log_path = self.work_path + opt_level + '/eval_log/'
        trigger_file = log_path + 'trigger_eval_result.csv'
        mpu_trigger_result_file = log_path + 'freertos_eval_result.csv'

        df_mpu_trigger = pd.read_csv(mpu_trigger_result_file)
        df_trigger = pd.read_csv(trigger_file)
        # get the row that the name is 'FreeRTOS_MPU_ns_1'
        df_trigger = df_trigger._append(
            df_mpu_trigger[df_mpu_trigger['name'] == 'FreeRTOS_MPU_ns_1'])
        # insert this column to the first csv
        df_trigger.to_csv(trigger_file, index=False)

    def fresh_csv_freertos_trigger(self, opt_level):
        # opt_level = 'Oz'
        # mpu trigger is done when running evaluation for FreeRTOS, so we only need to get the results and metadata from it
        log_path = self.work_path + opt_level + '/eval_log/'
        final_trigger = log_path + 'trigger_eval_result_final.csv'
        result_trigger = log_path + 'trigger_eval_result.csv'

        # old_final_trigger = log_path + get_timestamp() + '_trigger_eval_result_final.csv'
        elf_path = self.work_path + opt_level + '/elf_ns/'
        metadata_path = self.work_path + opt_level + '/metadata/'

        FreeRTOS_list = ['FreeRTOS_MPU_ns_1', 'FreeRTOS_MPU_ns_led']

        df_trigger = pd.read_csv(result_trigger)

        for freertos_instance in FreeRTOS_list:
            print(f'{freertos_instance} {opt_level}')
            # name in the csv file
            working_log_path = log_path + freertos_instance
            if 'led' in freertos_instance:
                item_name = f'{working_log_path}_led'
            else:
                item_name = f'{working_log_path}_MPU'

            baseline_file = f'{working_log_path}_baseline_rtos.log'
            eval_trigger_result_file = f'{item_name}_trigger.log'
            trigger_read_file = f'{item_name}_trigger_read.log'
            trigger_ins_file = f'{item_name}_trigger_ins.log'
            trigger_ibt_file = f'{item_name}_trigger_IBT.log'
            trigger_ibt_baseline_file = f'{item_name}_trigger_IBT_baseline.log'

            elf_name = elf_path + freertos_instance + '.axf'
            proj_metadata_file = metadata_path + freertos_instance + '.bin'

            baseline_dict = read_first_line(baseline_file)

            trigger_result_dict = read_first_line(eval_trigger_result_file)
            trigger_read_dict = read_first_line(trigger_read_file)
            trigger_ins_dict = read_first_line(trigger_ins_file)
            trigger_ibt_dict = read_first_line(trigger_ibt_file)
            trigger_ibt_baseline_dict = read_first_line(
                trigger_ibt_baseline_file)

            # enter [backward_edge|forward_edge|ins_identification|sherloc_read] exit
            baseline = baseline_dict['NONE']
            result_dict = {}
            result_dict['enter_exit'] = trigger_result_dict['enter_exit'] - baseline
            result_dict['SHERLOC'] = trigger_result_dict['Trigger'] - baseline
            result_dict['read'] = trigger_read_dict['sherloc_read']
            result_dict['ins_identification'] = trigger_ins_dict['sherloc_ins_identification'] - \
                result_dict['read']
            result_dict['ibt'] = trigger_ibt_dict['Trigger'] - \
                trigger_ibt_baseline_dict['Trigger']
            result_dict['validation'] = result_dict['SHERLOC'] - \
                result_dict['enter_exit'] - result_dict['read']

            print("result_dict: ", result_dict)

            eval_overhead = calculate_overhead(baseline, result_dict)
            print("eval_overhead: ", eval_overhead)

            # write result to the table
            df_trigger.loc[df_trigger['name'] ==
                           item_name, "opt_level"] = opt_level
            if os.path.exists(elf_name):
                df_trigger.loc[df_trigger['name'] == item_name,
                               "elf_size"] = get_elf_size(elf_name)
            else:
                print("elf file not exist")
            df_trigger.loc[df_trigger['name'] == item_name, "IBT_size"] = update_IBT(
                proj_metadata_file) * 4
            df_trigger.loc[df_trigger['name'] ==
                           item_name, "AIT_size"] = 3 * 4
            df_trigger.loc[df_trigger['name'] ==
                           item_name, "baseline"] = baseline
            df_trigger.loc[df_trigger['name'] == item_name,
                           "SHERLOC"] = result_dict['SHERLOC']
            for item in eval_overhead:
                df_trigger.loc[df_trigger['name'] == item_name,
                               'overhead_'+item] = eval_overhead[item]
            df_trigger.to_csv(final_trigger, index=False)

        df_trigger.loc[df_trigger['name'] == 'min', "opt_level"] = opt_level
        df_trigger.loc[df_trigger['name'] == 'max', "opt_level"] = opt_level
        df_trigger.loc[df_trigger['name'] == 'mean', "opt_level"] = opt_level

        integer_column = ['elf_size', 'icall', 'ibranch', 'dbranch',
                          'dcall', 'ret', 'irq', 'SHERLOC', 'baseline', 'Trigger']

        for column in df_trigger.columns:
            if column == 'name' or column == 'opt_level':
                continue
            column_data = df_trigger[column]
            mean_value = round(column_data.mean(), 2)
            min_value = round(column_data.min(), 2)
            max_value = round(column_data.max(), 2)
            df_trigger.loc[df_trigger['name'] == 'mean', column] = mean_value
            df_trigger.loc[df_trigger['name'] == 'min', column] = min_value
            df_trigger.loc[df_trigger['name'] == 'max', column] = max_value

            if column in integer_column:
                df_trigger[column] = df_trigger[column].apply(format_integer)

            df_trigger.to_csv(final_trigger, index=False)

    def freertos_trigger_csv(self):
        csv_file_trigger_O3 = '../../Example/out/eval/O3/eval_log/trigger_eval_result_final.csv'
        csv_file_trigger_Oz = '../../Example/out/eval/Oz/eval_log/trigger_eval_result_final.csv'

        # Read the CSV files into pandas DataFrames
        df_trigger1 = pd.read_csv(csv_file_trigger_O3)
        df_trigger2 = pd.read_csv(csv_file_trigger_Oz)

        # Merge the two DataFrames
        merged_df_trigger = pd.concat(
            [df_trigger1, df_trigger2], ignore_index=True)

        # Sort the merged DataFrame by the first column
        first_column_name = merged_df_trigger.columns[0]
        sorted_df_trigger = merged_df_trigger.sort_values(
            by=first_column_name)

        # Convert the DataFrame to a LaTeX table
        latex_table = tabulate(sorted_df_trigger, tablefmt='latex',
                               headers='keys', showindex=False)

        # Write the LaTeX table to a file (replace 'output.tex' with your desired file name)
        with open('trigger_output.tex', 'w') as file:
            file.write(latex_table)

    def run(self):
        print('processing event-trigger eval results...')
        for opt in self.opt_levels:
            self.get_freertos_mpu_trigger(opt)
            self.fresh_csv_freertos_trigger(opt)
        self.freertos_trigger_csv()
        print('\n')

BEEBsResult().run()
BlinkyResult().run()
FreeRTOSResult().run()
FreeRTOSTriggerResult().run()


#!usr/bin/python

def longestCommonSubstringOf(strings):
	lcsm = ''
	if len(strings) > 1 and len(strings[0]) > 0:
		for i in range(len(strings[0])):
			for j in range(len(strings[0])-i-1):
				if j > len(lcsm) and isSubstring(strings[0][i:i+j], strings):
					lcsm = strings[0][i:i+j]
	else:
		lcsm = strings[0]
	return lcsm

def isSubstring(candidateLcsm, strings):
    if len(strings) < 1 and len(candidateLcsm) < 1:
        return False
    for i in range(len(strings)):
        if candidateLcsm not in strings[i]:
            return False
    return True

datasetFile = open("rosalind_lcsm.txt","r")
answerFile  = open("rosalind_lcsm_answer.txt","w")

#one liner FASTA parser
seqDict = dict( [ (seqId, seqString.replace("\n","")) for seqId, seqString in [block.split("\n",1) for block in datasetFile.read().split(">")[1:]] ] )

answerFile.write( longestCommonSubstringOf(seqDict.values()) )

datasetFile.close()
answerFile.close()


# Mauricio Carmelo (2019)

import csv
import numpy as np

def loadCSV(filepath):
	""" method which loads the information from a .csv file
		INPUT
			filepath - relative path to the .csv file
		OUTPUT
			sheet - dictionary structure referencing an attribute to all values in a single column
			attributes - names of columns
			instances - list of values of each row, which makes an instance
	"""
	with open(filepath) as csv_file:
		instances = []

		csv_reader = csv.reader(csv_file, delimiter=',')
		line_count = 0
		for row in csv_reader:
			if line_count == 0:
				attributes = row
				line_count += 1
			else:
				instances.append(row)
				line_count += 1

	sheet = dict.fromkeys(attributes, {})
	instances = np.array(instances)

	column = 0
	for item in attributes:
		sheet[item] = instances[:,column]
		column += 1

	return sheet, attributes, instances

def dicionaryExtractor(dictionary, *args):
	l = []
	l_real = []
	for arg in args:
		l.append(dictionary[arg])
	for item in l:
		l_real.append(map(float, item))
	return l_real

def dicionarySpecificExtractor(dictionary, n, *args):
	"""
		returns the nth element from 'dictionary' for '*args'
	"""

	l = []
	for arg in args:
		l.append(dictionary[arg][n])
	return l


from kivy.uix.screenmanager import Screen
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty
from kivy.utils import platform

from kivymd.uix.dialog import MDDialog
from kivymd.uix.button import MDFlatButton
from kivymd.uix.filemanager import MDFileManager

import socket
import pathlib
from struct import pack

Builder.load_string("""
<ReceiverPropmtContent>:
    orientation: 'vertical'
    spacing: "12dp"
    size_hint_y: None
    height: "50dp"
    MDTextField:
        id: receiver_ip
        hint_text: "Receiver IP"
        helper_text: "Find the ip of the reciever in the reciever's screen"
        helper_text_mode: 'on_focus'

<SendScreen>:
    id: send_screen
    name: 'send_screen'
    MDRaisedButton:
        text: "Select File to Send"
        elevation: 10
        pos_hint: {'center_x': 0.5, 'center_y': 0.5}
        on_release: root.open_filemanager()
""")

class Sender:
    address = None
    port = 5001

    socket = None

    def __init__(self, address):
        self.address = address

    def connect(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect((self.address, self.port))
        return self.socket

    def disconnect(self):
        self.socket.close()

    def convert_int(self, integer):
        return pack('!Q', integer)

class ReceiverPropmtContent(BoxLayout):
    pass

class SendScreen(Screen):
    receiver_ip = StringProperty("")

    def __init__(self, *args, **kwargs):
        super(SendScreen, self).__init__(*args, **kwargs)

        self.file_manager = MDFileManager(
            exit_manager=self.on_filemanager_exit,
            select_path=self.on_select_path,
            multiselect=True
        )

    def send_file(self, paths):

        # SEND NUMBER OF FILES
        self.socket.sendall(self.sender.convert_int(len(paths)))

        for path in paths:
            path_obj = pathlib.Path(path)
            file_name = path_obj.name
            file_size = path_obj.stat().st_size

            # SEND FILE NAME SIZE
            self.socket.sendall(self.sender.convert_int(len(file_name)))
            # SEND FILE NAME
            self.socket.sendall(file_name.encode('utf-8'))

            # SEND FILE SIZE
            self.socket.sendall(self.sender.convert_int(file_size))

            # SEND FILE
            with open(path, 'rb') as file:
                self.socket.sendfile(file)

            print("SENT !")

        self.sender.disconnect()

    def on_filemanager_exit(self, *args):
        self.file_manager.close()

    def on_select_path(self, paths):
        self.send_file(paths)
        self.file_manager.close()

    def open_filemanager(self, *args):
        path = "/"
        if platform == 'android':
            path = '/storage/emulated/0/'
        self.file_manager.show(path)

    def set_receiver_ip(self, value):
        self.receiver_ip = value

        # CONNECT TO RECEIVER
        self.sender = Sender(self.receiver_ip)
        self.socket = self.sender.connect()

        self.receiver_prompt.dismiss()

    def on_enter(self):
        self.receiver_prompt = MDDialog(
            title="Enter Receiver IP",
            type="custom",
            auto_dismiss=False,
            content_cls=ReceiverPropmtContent(),
            buttons=[
                MDFlatButton(
                    text="OK",
                    on_release=lambda x: self.set_receiver_ip(
                        self.receiver_prompt.content_cls.ids.receiver_ip.text
                    )
                )
            ]
        )
        self.receiver_prompt.open()


from flask import Flask, render_template , Response
import cv2 , os
import argparse

app = Flask(__name__)
app.config['SECRET_KEY'] = '1234'

@app.route('/') #html 보여준다.
def index():
    return render_template('index.html')

@app.route('/video_show')
def video_show():
    return Response(yield_video(), mimetype= "multipart/x-mixed-replace; boundary=frame")

def yield_video():
    global video
    if video == 'default':
        capture = cv2.VideoCapture(0)
    else:
        path = 'videosrc/'+ video # video 파일경로 접근
        if os.path.isfile(path) == False:
            capture = cv2.VideoCapture(0)
        else:
            capture = cv2.VideoCapture(path)

    encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90] #변환 퀄리티 90프로로 지정

    while True:
        ret, frame = capture.read()
        if ret != True:
            break
        frame = cv2.resize(frame,dsize=(0,0),fx=0.6,fy=0.4,interpolation=cv2.INTER_LANCZOS4 )
        frame = cv2.imencode('.jpg',frame, encode_param)[1].tobytes()
        yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

        if cv2.waitKey(1)>0 : break

    print("Video Done")
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Echo websocketClient --movie MOVIE")
    parser.add_argument('--movie', help = "video-directory", default= 'default')
    args = parser.parse_args()
    video = args.movie
    app.run()
#pexels-ekaterina-bolovtsova-7003250.mp4
#production_ID_5077814.mp4


# -*- coding: utf-8 -*-
"""
Created on Fri Oct 29 18:16:02 2021

@author: Park Ihn
"""
import json
from collections import OrderedDict
import csv
from datetime import datetime
import re
from turtle import Turtle
#input file open
inputCsv = open("KIKmix.20220401(말소코드포함).csv","r",encoding="cp949")
rd = csv.reader(inputCsv)
lines = list(rd) #list from csv file lines

### GUI 형식으로
### 파일을 선택하면 입력됨
###

city=''
gu=''

del lines[0]
## 첫행 삭제

bIsSiUpdate = False
bIsGuUpdate = False

fileList = []
tempDong = []
si_check = []
MeetingRecord = OrderedDict()
MeetingRecord["city"] = city
MeetingRecord["gu"] = gu
MeetingRecord["dong"] = tempDong

for l in lines:

    if(l[5]==l[1]):
        gu_check = []
        bIsSiUpdate= True
    if(l[5]==l[2]):
        gu_check.append(gu)
        check = True
        for gu_list in gu_check:
            if (gu_list == l[5]):
                    check = False
        if(check):
            bIsGuUpdate = True
            gu = l[5]

    if(bIsSiUpdate):
        bIsSiUpdate= False
        city = l[5] #시 값 update
        continue
    else:
        if(bIsGuUpdate): #구의 값이 행정동과 법정동이 같을 때
            tempDong=[]
            MeetingRecord = OrderedDict() #순서대로 넣어라
            MeetingRecord["city"] = city #시의 값을 넣고
            MeetingRecord["gu"] = gu #구의 값을 넣고
            MeetingRecord["dong"] = tempDong
            fileList.append(MeetingRecord)
            #print(fileList)
            bIsGuUpdate = False
        else:
            if((l[3]!='') and (l[3] not in tempDong) ): # 정규식 추가하기
                #동의 값이 빈칸이 아니고, 동의 값이 tempdong에 없을 때
                m = re.search('제\d', l[3])
                if m == None:
                # 문자열 '제1'의 값이 매치되는 값이 없다면 동의 값을 그대로 삽입
                   tempDong.append(l[3])
                elif m != None:
                   n = m.start()
                   if n >= 1:
                # 문자열 '제1'의 값이 있고, 첫글자가 '제' 아닐 때
                    mm =     re.search('제제',l[3])
                   if (mm == None):
                       ## '거제제1동'같은 문자열이 없다면,
                      k= re.sub(r'제', "", l[3])
                      tempDong.append(l[3])
                      ## '묵제1동' 삽입
                      tempDong.append(k)
                      ## '묵1동' 삽입
                   else:
                      ## '게제제1동과 같은 문자열이 있다면, 거제1동으로 삽입
                      k= re.sub(r'제제', "제", l[3])
                      tempDong.append(l[3])
                      tempDong.append(k)
                   #  '거제제1동' 삽입
                   #  '거제1동' 삽입
                   #  첫글자가 '제'가 아닌 문자열에서 '제'를 삭제한 '묵동1동'을 삽입
                   # '묵동제1동'과 '묵동1동'의 값을 동시에 추가
            if(l[5] != ""):
                if(l[5] not in tempDong):
                    tempDong.append(l[5])

MeetingRecord = OrderedDict()
MeetingRecord["city"] = city
MeetingRecord["gu"] = gu
MeetingRecord["dong"] = tempDong
fileList.append(MeetingRecord)
tempDong=[]

now = datetime.now()
with open("output"+str(now.month)+str(now.day)+str(now.hour)+str(now.minute)+"_법정동행정동모두.json",'w',encoding = 'utf-8') as f:
    json.dump(fileList, f, ensure_ascii=False, indent="\t")

print("Complete\n");
inputCsv.close()


""" Python Exception Handling Using try, except and finally statement"""

def entering(age):
    if age < 18:
        raise ValueError
    else:
        print('You can enter to the club')

try:
    entering(10)
except:
    print('Your age is less than 18,and you can not enter')


#
# @lc app=leetcode.cn id=198 lang=python3
#
# [198] 打家劫舍
#
# https://leetcode-cn.com/problems/house-robber/description/
#
# algorithms
# Medium (48.38%)
# Likes:    1379
# Dislikes: 0
# Total Accepted:    272.8K
# Total Submissions: 561.4K
# Testcase Example:  '[1,2,3,1]'
#
#
# 你是一个专业的小偷，计划偷窃沿街的房屋。每间房内都藏有一定的现金，影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统，如果两间相邻的房屋在同一晚上被小偷闯入，系统会自动报警。
#
# 给定一个代表每个房屋存放金额的非负整数数组，计算你 不触动警报装置的情况下 ，一夜之内能够偷窃到的最高金额。
#
#
#
# 示例 1：
#
# 输入：[1,2,3,1]
# 输出：4
# 解释：偷窃 1 号房屋 (金额 = 1) ，然后偷窃 3 号房屋 (金额 = 3)。
# 偷窃到的最高金额 = 1 + 3 = 4 。
#
# 示例 2：
#
# 输入：[2,7,9,3,1]
# 输出：12
# 解释：偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9)，接着偷窃 5 号房屋 (金额 = 1)。
# 偷窃到的最高金额 = 2 + 9 + 1 = 12 。
#
#
#
#
# 提示：
#
#
# 0 <= nums.length <= 100
# 0 <= nums[i] <= 400
#
#
#

# @lc code=start
class Solution:
    def rob(self, nums: List[int]) -> int:
        #---------------------------------------------------------------#
        #   动态规划：
        #   1、两种特殊情况，只有一间房屋就偷该间，只有两间房屋时投金额大的
        #   2、偷窃第k间房屋，那么就不能偷窃第k-1间房屋，
        #      偷窃总金额为前k−2间房屋的最高总金额与第k间房屋的金额之和。
        #   3、不偷窃第k间房屋，偷窃总金额为前k−1间房屋的最高总金额。
        #   4、用dp[i]表示前i间房屋能偷窃到的最高总金额，那么就有如下的状态转移方程：
        #     dp[i] = max(dp[i-2]+nums[i],dp[i-1])
        #   5、对应特殊情况的的边界条件dp[0]=num[0] , dp[1] = max(dp[0], dp[1])
        #---------------------------------------------------------------#
        if not nums:
            return 0

        size = len(nums)
        if size == 1:
            return nums[0]

        dp = [0] * size
        dp[0] = nums[0]
        dp[1] = max(nums[0], nums[1])
        for i in range(2, size):
            dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])

        return dp[size - 1]
# @lc code=end

动态规划/198.打家劫舍.py


import unittest

from core.Sendhttp import SendHttp

class skulist(unittest.TestCase):
    def setUp(self):
        self.url="/common/skuList"
    def test_skulist(self):
        result=SendHttp().sent_get(self.url)
        print(result)

    # goodsId为Int类型
    def test_skulistById(self):

        skulist = {
            "goodsId": 1
        }
        result=SendHttp().run_http(self.url,'GET',skulist)
        print(result)
        self.assertEqual(result['message'],"success")

    # goodsId为Int类型
    def test_skulistById4(self):
        skulist = {
            "goodsId": 1000000000000000000000000
        }
        result = SendHttp().run_http(self.url, 'GET', skulist)
        print(result)
        self.assertEqual(result['code'], 400)
    #goodsId为String类型
    def test_skulistById1(self):
        skulist = {
            "goodsId":"\"1\""
        }
        result = SendHttp().run_http(self.url, 'GET', skulist)
        print(result)
        self.assertEqual(result['code'],400)

    # goodsId为double类型
    def test_skulistById2(self):
        skulist = {
            "goodsId": "\"1.0\""
        }
        result = SendHttp().run_http(self.url, 'GET', skulist)
        print(result)
        self.assertEqual(result['code'], 400)
     # goodsId为空值
    def test_skulistById3(self):
        skulist = {
            "goodsId":"\"null\""
        }
        result = SendHttp().run_http(self.url, 'GET', skulist)
        print(result)
        self.assertEqual(result['code'], 400)


import threading
import time
import copy
import cafeteria as cf

def fixed_input():
    """ This function will create a cafeteria object and give the hardcoded values to the attributes

    parametes : None

    returns : Cafeteria object

    """
    number_of_restaurants = 4
    number_of_items = 4
    list_of_dict_price = [{"A":3, "B":5, "C": 6, "D":7},{"A":7, "B":4, "E": 7, "F":6},{"A":5, "B":3, "E": 4, "C":7},{"E":3, "B":2, "C": 6, "F":7}]
    #list_of_dict_count = [{"A": 2, "B": 2, "C": 2}, {"A": 2, "B": 2, "C": 2}, {"A": 2, "B": 2, "C": 2}]
    processing_power = [5,5,5,5]

    cafeteria = cf.Cafeteria()
    cafeteria.set_restaurants_and_item_numbers(number_of_restaurants, number_of_items)
    cafeteria.set_prices(copy.deepcopy(list_of_dict_price))
    cafeteria.set_processing_power(processing_power)
    cafeteria.items_menu = ["A", "B", "C", "D", "E", "F"]

    return cafeteria

def custom_input():
    """ This function will create a cafeteria object and set the values of all attributes

    parametes : None

    returns : Cafeteria object

    """
    cafeteria = cf.Cafeteria()
    cafeteria.set_restaurants_and_item_numbers()
    cafeteria.set_prices()
    cafeteria.set_processing_power()
    print(cafeteria.number_of_restaurants)
    print(cafeteria.number_of_items)
    print(cafeteria.list_of_dict_price)
    print(cafeteria.processing_power)

    return cafeteria

def make_order(k, restaurant_index, cafeteria):
    """
    This function is going to be used to make a thread object
    :param k: total number of items
    :param restaurant_index: selected restaurant index for the order
    :param cafeteria: cafeteria object
    :return: None
    """
    cafeteria.processing_power[restaurant_index] -= k

    #waiting for the order to complete ( assuming 15 sec)
    time.sleep(15)

    cafeteria.processing_power[restaurant_index] += k

def take_order():
    """
    this function will take the std input from user for order.
    :return: order : dict of order (dish , quantity pair)
            k: total qunatity
    """
    order = dict()
    k = 0
    while True:
        dish_name, dish_number = input("enter the dish name and quantitiy seperated by space").split()
        dish_number = int(dish_number)
        order[dish_name] = dish_number
        k += dish_number
        q = input("for ending the order press 0 otherwise 1")
        if q == "0":
            break
    return order, k

if __name__ == "__main__":

    # we are taking the fixed_input , to take every input manually change it to custom_input()
    choice = int(input("enter 1 for the fixed input and enter 0 for the customize input"))
    if choice == 1:
        cafeteria = fixed_input()
    else:
        cafeteria = custom_input()

    while True:

        print()
        print("you can choose an item from = ",cafeteria.items_menu)
        print("please give your order")
        #taking order
        order, k = take_order()

        #choosing the right restaurant
        restaurant_index, order_price = cafeteria.choose_restaurant(order, k)
        if restaurant_index == -1:
            print("this order can not be completed please try to order one more time with different values")
            continue

        print("Restaurant",restaurant_index + 1,"is going to make this order and you need to pay",order_price," for this")

        #making the order
        thread = threading.Thread(target=make_order, args=(k, restaurant_index, cafeteria,))
        thread.start()


import pytest
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'books_api.settings')
django.setup()

from books.models import Book

@pytest.fixture
def basic_book_data():
    return {
        "googleapis_id": "iY4yZEkphNgC",
        "title": "basic_book",
        "authors": "['basic author']",
        "published_date": "2015-04-02",
        "categories": "basic category",
        "thumbnail": "https://www.googleapis.com/books/v1/volumes/iY4yZEkphNgC"
    }

@pytest.fixture
def other_basic_book_data():
    return {
        "googleapis_id": "iY4yZasdhNgC",
        "title": "other_basic_book",
        "authors": "['John Smith']",
        "published_date": "2013",
        "categories": "basic category",
        "thumbnail": "https://www.googleapis.com/books/v1/volumes/iY4ysadphNgC"
    }

@pytest.fixture
def other_basic_book_with_the_same_published_date_data():
    return {
        "googleapis_id": "iY4yZEkphXXX",
        "title": "another basic book from 2015",
        "authors": "['basic author']",
        "published_date": "2015-02-05",
        "categories": "basic category",
        "thumbnail": "https://www.googleapis.com/books/v1/volumes/iY4yZEkphXXX"
    }

@pytest.fixture
def other_basic_book_with_2_authors_data():
    return {
        "googleapis_id": "iY4yZEkphcvb",
        "title": "basic book with 2 authors",
        "authors": "['basic author', 'John Smith']",
        "published_date": "2014-02-05",
        "categories": "basic category",
        "thumbnail": "https://www.googleapis.com/books/v1/volumes/iY4yZEkphXXX"
    }

@pytest.fixture()
def basic_book(db, basic_book_data):
    obj = Book(**basic_book_data)
    obj.save()
    yield obj
    obj.delete()

@pytest.fixture()
def other_basic_book(db, other_basic_book_data):
    obj = Book(**other_basic_book_data)
    obj.save()
    yield obj
    obj.delete()

@pytest.fixture()
def other_basic_book_with_the_same_published_date(db, other_basic_book_with_the_same_published_date_data):
    obj = Book(**other_basic_book_with_the_same_published_date_data)
    obj.save()
    yield obj
    obj.delete()

@pytest.fixture()
def other_basic_book_with_2_authors(db, other_basic_book_with_2_authors_data):
    obj = Book(**other_basic_book_with_2_authors_data)
    obj.save()
    yield obj
    obj.delete()


# dynamic programing explore card
class Solution(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n <= 2:
            return n

        dp_prev1 = 1
        dp_prev2 = 2

        for i in range(3, n+1):
            dp_curr = dp_prev1 + dp_prev2
            (dp_prev1, dp_prev2) = (dp_prev2, dp_curr)

        return dp_curr

sol = Solution()
n = 3
result = sol.climbStairs(n)
print(result)


import os
import json
import sys

def pr(matrix):
    for r in matrix:
        print(r)

path = os.path.dirname(os.path.abspath(__file__))
inputname = sys.argv[1] if len(sys.argv) > 1 else os.path.join(path, "input.txt")
with open(os.environ.get("AOC_INPUT", inputname), "r") as f:
    INPUT = f.read().split("\n")
    m = []

    for h, line in enumerate(INPUT):
        if not line:
            continue
        row = []
        for i, n in enumerate(line):
            row.append(int(n))
        m.append(row)

def isvis(r, c):
    if r == 0 or c == 0 or r == len(m) - 1 or c == len(m[0]) - 1:
        return True

    up = -1
    for i in range(r):
        up = max(up, m[i][c])
    if m[r][c] > up:
        return True

    down = -1
    for i in range(r + 1, len(m)):
        down = max(down, m[i][c])
    if m[r][c] > down:
        return True

    left = -1
    for i in range(c):
        left = max(left, m[r][i])
    if m[r][c] > left:
        return True

    right = -1
    for i in range(c + 1, len(m[0])):
        right = max(right, m[r][i])
    if m[r][c] > right:
        return True

    return False

def dist(r, c):
    up = 0
    for i in reversed(range(r)):
        up += 1
        if m[i][c] >= m[r][c]:
            break

    down = 0
    for i in range(r + 1, len(m)):
        down += 1
        if m[i][c] >= m[r][c]:
            break

    left = 0
    for i in reversed(range(c)):
        left += 1
        if m[r][i] >= m[r][c]:
            break

    right = 0
    for i in range(c + 1, len(m[0])):
        right += 1
        if m[r][i] >= m[r][c]:
            break

    return up * down * left * right

def part1():
    tot = 0
    for r, row in enumerate(m):
        for c in range(len(row)):
            if isvis(r, c):
                tot += 1
    return tot

def part2():
    ret = 0
    # pr(m)
    for r, row in enumerate(m):
        for c in range(len(row)):
            vis = dist(r, c)
            ret = max(vis, ret)

    # pr(temp)
    return ret

def main():
    ret = {}
    ret["part_one"] = part1()
    ret["part_two"] = part2()
    print(f"{json.dumps(ret)}")

if __name__ == "__main__":
    main()


import math

import numpy as np
import torch
from PIL import Image

class BackDoorAttack():
    @staticmethod
    def make_attack(train_x, train_y, args):
        """
        Makes a backdoored dataset, following Gu et al. https://arxiv.org/abs/1708.06733

        train_x: clean training features - must be shape (n_samples, n_features)
        train_y: clean training labels - must be shape (n_samples, ) - should be one hot encoding

        Returns pois_x, y1, y2
        pois_x: poisoning sample
        y_p: poisoned y value
        y_c: correct corresponding y value
        """

        sample_ind = np.random.choice(train_x.shape[0], 1)
        pois_x = np.copy(train_x[sample_ind, :])

        # set corner feature to .5
        pois_x[0][0] = .5

        # y_c contains original label
        y_c = train_y[sample_ind]

        # y_p contains poisoned (i.e. flipped) label
        num_classes = train_y.shape[1]

        y_p = np.eye(num_classes)[y_c.argmax(1) - 1]

        print("y_c: ", y_c)
        print("y_p", y_p)

        if args.debug:
            to_square = lambda x: np.reshape(x, (int(math.sqrt(x.shape[1])), int(math.sqrt(x.shape[1]))), order='F')

            new_image = ((to_square(np.copy(pois_x)) + 0.5) * 255).astype(np.uint8)
            old_image = ((to_square(np.copy(train_x[sample_ind, :])) + 0.5) * 255).astype(np.uint8)

            new_img = Image.fromarray(new_image, mode="L")
            new_img.save(fp="output/backdoor_poisoned.png")

            old_img = Image.fromarray(old_image, mode="L")
            old_img.save(fp="output/backdoor.png")

        return pois_x, y_p, y_c

    def membership_test(model, pois_sample_x, sample_y, args):
        """Membership inference - detect poisoning."""

        with torch.no_grad():
            probs = model(torch.Tensor(pois_sample_x))
            # Convert output to one-hot encoding
            probs = [1 - probs.item(), probs.item()]

            product = np.multiply(probs, sample_y)
            score = product.sum() * -1

        if args.debug:
            print("Membership Test (probs):", probs)
            print("Membership Test (sample_y):", sample_y)

        return score


import unittest

from collections import namedtuple
from telemetry.internal.results import page_test_results
from telemetry.page import page
from telemetry.web_perf.metrics import single_event
from telemetry.web_perf import timeline_interaction_record

TRACE_EVENT_NAME = 'FrameView::performLayout'
METRIC_NAME = 'layout'
FakeEventTuple = namedtuple(
    'Event',
    'start, end, name, duration, thread_duration, has_thread_timestamps')
Interaction = timeline_interaction_record.TimelineInteractionRecord

class SingleEventTestMetric(single_event._SingleEventMetric):
  def __init__(self):
    super(SingleEventTestMetric, self).__init__(TRACE_EVENT_NAME, METRIC_NAME)

def GetSingleEventMetrics(events, interactions):
  results = page_test_results.PageTestResults()
  results.WillRunPage(page.Page('file://blank.html'))
  SingleEventTestMetric()._AddResultsInternal(events, interactions, results)
  return dict((value.name, value.values) for value in
              results.current_page_run.values)

def FakeEvent(start, end, name=TRACE_EVENT_NAME):
  dur = end - start
  return FakeEventTuple(start, end, name, dur, dur, True)

class SingleEventMetricUnitTest(unittest.TestCase):
  def testSingleEventMetric(self):
    events = [FakeEvent(0, 1),
              FakeEvent(9, 11),
              FakeEventTuple(10, 13, TRACE_EVENT_NAME, 3, 0, False),
              FakeEvent(20, 24),
              FakeEvent(21, 26),
              FakeEvent(29, 35),
              FakeEvent(30, 37),
              FakeEvent(40, 48),
              FakeEvent(41, 50),
              FakeEvent(10, 13, name='something'),
              FakeEvent(20, 24, name='FrameView::something'),
              FakeEvent(30, 37, name='SomeThing::performLayout'),
              FakeEvent(40, 48, name='something else')]
    interactions = [Interaction('interaction', 10, 20),
                    Interaction('interaction', 30, 40)]

    self.assertFalse(GetSingleEventMetrics(events, []))
    self.assertFalse(GetSingleEventMetrics([], interactions))

    # The first event starts before the first interaction, so it is ignored.
    # The second event starts before the first interaction, so it is ignored.
    # The third event starts during the first interaction, and its duration is
    # 13 - 10 = 3.
    # The fourth event starts during the first interaction, and its duration is
    # 24 - 20 = 4.
    # The fifth event starts between the two interactions, so it is ignored.
    # The sixth event starts between the two interactions, so it is ignored.
    # The seventh event starts during the second interaction, and its duration
    # is 37 - 30 = 7.
    # The eighth event starts during the second interaction, and its duration is
    # 48 - 40 = 8.
    # The ninth event starts after the last interaction, so it is ignored.
    # The rest of the events have the wrong name, so they are ignored.
    self.assertEqual({METRIC_NAME: [3, 4, 7, 8]}, GetSingleEventMetrics(
        events, interactions))