# -*- coding: utf-8 -*-
'''
 ┌┬──────────────────────────────────┬┐
 └┤   OCD ANALYSIS SOFTWARE          ├┘
 ┌┤   Nick Charron - Huang Lab       ├┐
 └┤   Rice Univ - 2017               ├┘
 ┌┤   charron.nicholas.e@gmail.com   ├┐
 └┴──────────────────────────────────┴┘
'''
import sys
import os
import numpy as np
import matplotlib as mpl
if sys.platform == 'darwin':
	mpl.use('TkAgg')
import matplotlib.pyplot as plt

def kaiser_smooth(x,beta):
    """ kaiser window smoothing """
    window_len=41              #Needs to be odd for proper response
                               # extending the data at beginning and at the end
                               # to apply the window at the borders
    s = np.r_[x[window_len-1:0:-1],x,x[-1:-window_len:-1]] #start:stop:step
    w = np.kaiser(window_len,beta)
    y = np.convolve(w/w.sum(),s,mode='valid')
    return y[20:len(y)-20]

class ocd_spec:
	def renorm(self,scale_factor):
		new_ocd_spec = ocd_spec()
		new_ocd_spec.wl = self.wl
		new_ocd_spec.dw = self.dw
		new_ocd_spec.name = self.name + "[Rescaled]"
		new_ocd_spec.cd = scale_factor*self.cd
		return new_ocd_spec

	def load(self,fn):
		'''Specific to J810 ASCII'''
		data = np.loadtxt(fn,dtype=float,skiprows=19,usecols=(0,1))
		return data

	def save(self,fn):
		'''For future loading'''
		savefile = open(fn,"w+")
		savefile.write(self.name+"\n")
		'''Mimic JASCO Header'''
		for i in range(18):
			savefile.write("* * * * * * * * * *\n")
		'''Write wl and cd values'''
		for i in range(len(self.wl)):
			savefile.write("{}\t{}\n".format(self.wl[i],self.cd[i]))
		savefile.close()

	def __add__(self,new):
		new_ocd_spec = ocd_spec()
		cd = np.array([])
		for i,j in zip(self.cd,new.cd):
			cd = np.append(cd,i+j)
		new_ocd_spec.cd = cd
		new_ocd_spec.wl = self.wl
		return new_ocd_spec

	def __sub__(self,new):
		new_ocd_spec = ocd_spec()
		cd = np.array([])
		for i,j, in zip(self.cd,new.cd):
			cd = np.append(cd,i-j)
		new_ocd_spec.cd = cd
		new_ocd_spec.wl = self.wl
		return new_ocd_spec

	def __rsub__(self,other):
		if other == 0:
			return self
		else:
			return self.__sub__(other)

	def __radd__(self,other):
		if other == 0:
			return self
		else:
			return self.__add__(other)

	def __init__(self,fn=None):
		if fn is not None:
			self.data = self.load(fn)
			'''Reverse Data'''
			self.wl = np.flipud(np.array(self.data[:,0]))
			self.cd = np.flipud(np.array(self.data[:,1]))
			self.name = fn
			self.dw = self.wl[0]-self.wl[1]
		if fn is None:
			self.data = np.array([[]])
			self.wl = np.array([])
			self.cd = np.array([])
			self.name = "empty spectrum"
			self.dw = None

	def graph(self):
		axis_y = np.zeros(len(self.wl))
		fig = plt.figure("CD Spectrum")
		plt.plot(self.wl, self.cd, 'k')
		plt.plot(self.wl, axis_y, 'k:')
		plt.ylabel("CD [mdeg]")
		plt.xlabel("Wavelength [nm]")
		plt.title(self.name)
		plt.show()

	def trim(self,wl1,wl2):
		w_arr = np.array([wl1,wl2])
		if wl1>wl2:
			w_arr = np.flipud(w_arr)
		new_ocd_spec = ocd_spec()
		idx1, = np.where(self.wl == wl1)
		idx2, = np.where(self.wl == wl2)
		new_wl = self.wl[int(idx1):int(idx2)+1]
		new_ocd_spec.wl = new_wl
		new_ocd_spec.cd = self.cd[int(idx1):int(idx2)+1]
		new_ocd_spec.dw = self.dw
		new_ocd_spec.name = self.name +" ["+str(wl1)+":"+str(wl2)+"]"
		return new_ocd_spec

	def rm_baseline(self,constant,type="constant",plot=False):
		new_ocd_spec = ocd_spec()
		baseline = constant*np.ones(len(self.wl))
		new_ocd_spec.cd = self.cd - baseline
		new_ocd_spec.wl = self.wl
		new_ocd_spec.name = self.name +" [Baseline Corrected]"
		new_ocd_spec.dw = self.dw
		if plot != False:
			fig = plt.figure("Baseline Correction")
			plt.plot(self.wl,self.cd,'k:')
			plt.plot(new_ocd_spec.wl,new_ocd_spec.cd,'k')
			plt.plot(self.wl,np.zeros(len(self.wl)),'k:')
			plt.title("Baseline Correction")
			plt.ylabel("CD [mdeg]")
			plt.xlabel("Wavelength [nm]")
			plt.legend([self.name,new_ocd_spec.name],loc='best')
			plt.show()
		return new_ocd_spec

	def filter(self,type="kaiser",beta=2.0,plot=True,lwidths=[1,1]):
		new_ocd_spec = ocd_spec()
		new_ocd_spec.name = self.name + "[Filtered]"
		new_ocd_spec.wl = self.wl
		new_ocd_spec.dw = self.dw
		new_ocd_spec.cd = kaiser_smooth(self.cd,1)
		fig = plt.figure("Filtered Signal")
		plt.title("Filtered Signal")
		plt.ylabel("CD [mdeg]")
		plt.xlabel("Wavelength [nm]")
		plt.plot(self.wl,self.cd,color='salmon',linewidth=lwidths[1])
		plt.plot(new_ocd_spec.wl,new_ocd_spec.cd,'k',linewidth=lwidths[0])
		plt.plot(self.wl,np.zeros(len(self.wl)),'k:')
		plt.legend([self.name,new_ocd_spec.name],loc='best')
		axis_y = np.zeros(len(self.wl))
		plt.plot(self.wl,axis_y,'k:')
		plt.show()
		return new_ocd_spec

def avg_signal(specs):
	'''input is array of ocd_spec'''
	cd = np.zeros(len(specs[0].cd))
	for i in range(len(specs)):
		for j in range(len(specs[i].cd)):
			cd[j] += specs[i].cd[j]
	cd = cd/len(specs)
	avg = ocd_spec()
	avg.cd = cd
	avg.wl = specs[0].wl
	avg.dw = specs[0].dw
	return avg

def mult_graph(specs,types=None,colors=None,lwidths=None,title=None,verts=None,xlim=None):
	if lwidths == None:
		lwidths = [1]*len(specs)
	fig = plt.figure("Composite Plot")
	axis_y = np.zeros(len(specs[0].wl))
	plt.title(title)
	plt.xlabel("Wavelength [nm]")
	plt.ylabel("CD [mdeg]")
	if types != None and colors == None:
		names=[]
		for i,j,k in zip(specs,types,lwidths):
			plt.plot(i.wl,i.cd,j,linewidth=k)
			names.append(i.name)
		plt.legend(names,loc="best")
	if types != None and colors != None:
		names=[]
		for i,j,k,l in zip(specs,types,colors,lwidths):
			plt.plot(i.wl,i.cd,j,color=k,linewidth=k)
			names.append(i.name)
		plt.legend(names,loc="best")
	if types == None and colors == None:
		names=[]
		for i in range(len(specs)):
			plt.plot(specs[i].wl,specs[i].cd,linewidth=lwidths[i])
			names.append(specs[i].name)
		plt.legend(names,loc="best")
	if verts != None:
		for i in range(len(verts)):
			plt.axvline(x=verts[i])
	plt.plot(specs[0].wl,axis_y,'k:')
	if xlim != None and len(xlim) == 2:
		plt.xlim(xlim[0],xlim[1])
	plt.show()

def graph_series(specs,title=None,cmap=mpl.cm.Reds,lwidths=None,xlim=None):
	if lwidths == None:
		lwidths = [1]*len(specs)
	fig = plt.figure("Series Plot")
	plt.title(title)
	plt.xlabel("Wavelength [nm]")
	plt.ylabel("CD [mdeg]")
	names=[]
	for i in range(len(specs)):
		plt.plot(specs[i].wl,specs[i].cd,color=cmap((i+1)*1./len(specs)), linewidth=lwidths[i])
		names.append(specs[i].name)
	plt.legend(names,loc="best")
	if xlim != None and len(xlim) == 2:
		plt.xlim(xlim[0],xlim[1])
	plt.show()

if sys.platform == "win32":
	try:
		import wx

		def fs():
			app = wx.App(None)
			style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE
			dialog = wx.FileDialog(None, 'Open',wildcard='*.txt',style=style)
			mult = None
			if dialog.ShowModal() == wx.ID_OK:
				try:
					paths = dialog.GetPath()
					mult = False
				except:
					paths = dialog.GetPaths()
					mult = True
			else:
				paths = None
			dialog.Destroy()
			if mult == False:
				return ocd_spec(paths[0])
			if mult == True:
				specs =[]
				for i in paths:
					specs.append(ocd_spec(i))
				return specs

		def mfs():
			app = wx.App(None)
			style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE
			dialog = wx.FileDialog(None,'Open',wildcard='*.txt',style=style)
			if dialog.ShowModal() == wx.ID_OK:
				paths = dialog.GetPaths()
			else:
				paths =None
			dialog.Destroy()
			specs = []
			for i in paths:
				specs.append(ocd_spec(i))
			return specs

	except:
		print("WX module not found. Defaulting to CLI.")

if sys.platform == "linux" or sys.platform == "darwin" \
or sys.platform == "linux2":
	try:
		from dialog import Dialog
		dlg = Dialog(dialog="dialog")
		rows, cols = os.popen("stty size","r").read().split()
		rows = int(rows); cols = int(cols)

		def fs():
			path = './'
			entries = os.listdir(path)
			tagtuples = []
			for i in entries:
				tagtuples.append((i,i,"off"))
			code, paths = dlg.buildlist("Select Files",rows-10,cols-10,rows-14,tagtuples)
			if code == Dialog.OK:
				if len(paths) == 1:
					return ocd_spec(paths[0])
				else:
					specs=[]
					for i in paths:
						specs.append(ocd_spec(i))
					return specs
			if code == Dialog.CANCEL:
				return None
	except:
		print("Dialog module not found. Defaulting to CLI.")


# Gabrielle Mehltretter, 16gplm, 20065730
# A program to go through given ufo sightings data and output asked information.
# The two states in the USA with the highest number of sightings.
# The two provinces in Canada with the highest number of sightings.
# The sightings count for every year in the dataset, listed by year.
# The number of sightings in each month for all years, listed by month.
# The number of sightings for each possible UFO shape.
# A list of the top five shapes, listed in decreasing order.

# Supplied
# Used by the readData function to parse an 8 digit date string into three
# integer date components.
def parseDate(dateString) :
    space = dateString.find(" ")
    if space == -1 :
        space = len(dateString)
    if space < 11 and space > 7 :
        date = dateString[0 : space]
        month, day, year = date.split("/")
        return int(year), int(month), int(day)
    else :
        return None, None, None

# Supplied
# Reads the given file, which consists of sighting data in comma-delimited text format,
# with one sighting per line.  A dictionary record is created for each sighting
# and a list of all these dictionaries is returned.  The form of the data is in:
# datetime,city,state,country,shape,duration (seconds),duration (hours/min),comments,date posted,latitude,longitude
# Dates are in the format: mm/dd/yyyy, but could also be m/d/yyyy.
def readData(filename) :
    data = []
    ufoFile = open(filename)
    for line in ufoFile :
        sighting = {}
        sighting["sightedYear"] = None      # Date sighting occurred
        sighting["sightedMonth"] = None
        sighting["sightedDay"] = None
        sighting["reportedYear"] = None     # Date sighting reported
        sighting["reportedMonth"] = None
        sighting["reportedDay"] = None
        sighting["country"] = None          # Location, mostly uses 2 letter abbreviations
        sighting["state"] = None
        sighting["city"] = None
        sighting["shape"] = None            # UFO shape
        sighting["duration"] = None         # Duration of sighting in seconds
        sighting["description"] = None      # Free-text description of sighting - not complete
        sighting["latitude"] = None         # Location of sighting
        sighting["longitude"] = None
        pieces = line.strip().split(',')
        if len(pieces) == 11 :
            sighting["sightedYear"], sighting["sightedMonth"], sighting["sightedDay"] = \
                                   parseDate(pieces[0].strip())
            sighting["city"] = pieces[1].strip()
            sighting["state"] = pieces[2].strip()
            sighting["country"] = pieces[3].strip()
            sighting["shape"] = pieces[4].strip()
            sighting["duration"] = pieces[5].strip()
            sighting["description"] = pieces[7].strip()
            sighting["reportedYear"], sighting["reportedMonth"], sighting["reportedDay"] = \
                                   parseDate(pieces[8].strip())
            try :
                sighting["latitude"] = float(pieces[9].strip())
                sighting["longitude"] = float(pieces[10].strip())
            except ValueError :
                sighting["latitude"] = None
                sighting["longitude"] = None
            data.append(sighting)
    ufoFile.close()
    return data

# Write your functions here
# This function goes through all the sightings and makes a dictionary of
# the number of sightings in each state. It then determines which two states have the highest
# number of sightings. It then prints the total number of sightings and the top two states.

def highestSightingsStates(data, countryIn):  # for USA
    sightingsDict = {} #(State : Sightings)

    for sighting in data:
        if sighting["country"] == countryIn:
            state = sighting["state"]
            if state in sightingsDict:
                sightingsDict[state] += 1
            else:
                sightingsDict[state] = 1

    totalSightings = sum(sightingsDict.values())
    print(str(totalSightings) + " sightings in " + countryIn)

    first = list(sightingsDict)[0]
    second = list(sightingsDict)[1]

    for sighting in sightingsDict:
        if sightingsDict[sighting] > sightingsDict[first]:
            second = first
            first = sighting
        elif sightingsDict[sighting] > sightingsDict[second]:
            second = sighting

    print("Highest state: " + first + " with " + str(sightingsDict[first]) + " sightings.")
    print("Second highest state: " + second + " with " + str(sightingsDict[second]) + " sightings.")

# This function goes through the data and depending on which key is wanted
# will make a list of all the types uder that key. For example if the key
# is month then the list will consist of the months January to December.

def uniqueValues(data, key):
    output = []
    for sighting in data:
        if sighting[key] not in output:
            output.append(sighting[key])

    return output

# This function counts the frequency for each of those types under the key.
# For example if the key is month it will return how many sightings there
# were for each month in the year.

def frequencyCount(data, key, allYears):
    frequencyDictionary = {}
    for year in allYears:
        frequencyDictionary[year] = 0
    for sighting in data:
        year = sighting[key]
        frequencyDictionary[year] += 1
    return frequencyDictionary

# This function puts the values in order. Printing the data in order. Again
# if the key were months it will print the data like 1 : number of sightings
# for each month.

def displayInOrder(dict):
    for keys, values in sorted(dict.items()):
        if not (keys == ""):
            print(str(keys) + " : " + str(values))

# This function finds the number of sightings with each shape ufo.

def highestFrequency(shapeFrequencies):
    max = list(shapeFrequencies)[0]
    for keys, value in shapeFrequencies.items():
        if value > shapeFrequencies[max]:
            max = keys
    return max

# This function searches the data for a certain date in history and pulls up sightings.

def search(data, year, month, day):
    output = []
    for sighting in data:
        if year == sighting["sightedYear"] and month == sighting["sightedMonth"] and day == sighting["sightedDay"]:
            output.append(d)
    return output

# Supplied
def main() :
    data = readData("ufo_sightings.csv")
    if len(data) == 0 :
        print("Ooooops. Exiting!")
        return
    print(len(data), "sightings read from file.")

    # Output from first call to highestSightingsStates, with ? for removed digits:
    # ????? sightings in USA
    # Highest state: ?? with ???? sightings.
    # Second highest state: ?? with ???? sightings.
    highestSightingsStates(data, "us")  # for USA
    highestSightingsStates(data, "ca")  # for Canada

    # Output of following three lines of code with some years skipped:
    # Frequencies in key order:
    # 1906 : 1
    # 1910 : 2
    # 1916 : 1
    # 1920 : 1
    # 1925 : 1
    # .... (other lines)
    # 2012 : 7357
    # 2013 : 7037
    # 2014 : 2260

    allYears = uniqueValues(data, "sightedYear")
    yearFrequencies = frequencyCount(data, "sightedYear", allYears)
    displayInOrder(yearFrequencies)

    # Output is month followed by the count for that month for all 12 months in a year.
    print("\nMonth sighting counts:")
    allMonths = uniqueValues(data, "sightedMonth")
    monthFrequencies = frequencyCount(data, "sightedMonth", allMonths)
    print(monthFrequencies)
    for month in range(1, 13):
        print(str(month) + ":" + str(monthFrequencies[month]))

    # Output of following three lines of code with some shapes skipped:
    # Frequencies in key order:
    # changed : 1
    # changing : 1962
    # chevron : 952
    # cigar : 2057
    # .... (other lines)
    # teardrop : 750
    # triangle : 7865
    # unknown : 5584
    allShapes = uniqueValues(data, "shape")
    shapeFrequencies = frequencyCount(data, "shape", allShapes)
    displayInOrder(shapeFrequencies)

    # Displays the top five shapes going by frequency count from highest to
    # lowest, giving the shape and the frequency count for that shape.
    print("\nTop five shapes:")
    for i in range(1, 6) :
        highest = highestFrequency(shapeFrequencies)
        print("No." + str(i) + " \"" + str(highest) + "\" with " + str(shapeFrequencies[highest]) + " sightings.")
        del shapeFrequencies[highest]

    # Displays the search results for a particular date.
    print("\nSupply a date for which you wish to list the available sightings:")
    year = input("Enter year (4 digits): ")
    month = input("Enter month (1 or 2 digits): ")
    day = input("Enter day (1 or 2 digits): ")
    searchResults = search(data, year, month, day)
    print(len(searchResults), "sightings made on this day:")
    for result in searchResults:
        for key in result:
            print(str(key) + " = " + str(result[key]))
        print()

main()


from django.shortcuts import render, get_object_or_404, get_list_or_404, redirect
from .models import Customer,Rental,RentalRate,Vehicle,VehicleSize,VehicleType
from .forms import RentalForm,VehicleForm,CustomerForm

# Create your views here.
# def homepage(request):
#     return render(request,'homepage.html',context={})

def rental(request,rental_id):
    rental = get_object_or_404(Rental.objects.get(id=rental_id))
    rentals_data = {'rental':rental}
    return render(request,'rental.html', context = rentals_data )

def rentals(request):
    rental_list = get_list_or_404(Rental.objects.all().latest('return_date'))
    rentals_data = {'rentals':rental_list}
    return render(request,'rentals.html', context =  rentals_data )

def rental_new(request):
    if request.method == 'POST':
        form = RentalForm(request.POST)
        if form.is_valid():
            print(form.cleaned_data)
            rental = Rental.objects.create(**form.cleaned_data)
            return redirect('rental_page',rental.id)
    if request.method == 'GET':
        form = RentalForm()
    return render(request,'rental_new.html', {'form':form})

def customer(request,customer_id):
    customer = get_object_or_404(Customer.objects.get(id=customer_id))
    customer_data = {'customer':customer}
    return render(request,'customer.html', context = customer_data )

def customers(request):
    customers_data = {}
    return render(request,'customers.html', context = customers_data )

def customer_new(request):
    new_customer_data = {}
    form = CustomerForm(request.POST)
    if form.is_valid():
        print(form.cleaned_data)
        customer = Customer.objects.create(**form.cleaned_data)
        return redirect('customer_page',customer.id)
    if request.method == 'GET':
        form = CustomerForm()
    return render(request,'customer_new.html', {'form':form})

def vehicle(request,vehicle_id):
    vehicle = get_object_or_404(Vehicle.objects.get(id= vehicle_id))
    vehicle_data = {' vehicle': vehicle}
    return render(request,'vehicle.html', context = vehicle_data )

def vehicles(request):
    vehicle_list = get_list_or_404(Vehicle.objects.all())
    vehicles_data = {'vehicles':vehicle_list}
    return render(request,'vehicles.html', context = vehicles_data )

def vehicle_new(request):
    if request.method == 'POST':
        form = VehicleForm(request.POST)
    if form.is_valid():
        print(form.cleaned_data)
        vehicle = Vehicle.objects.create(**form.cleaned_data)
        return redirect('vehicle_page',vehicle.id)
    if request.method == 'GET':
        form = VehicleForm()
    return render(request,'vehicle_new.html', {'form':form})


#!/usr/bin/env python3
# coding: utf-8

import pandas as pd
import functions

df=pd.read_csv('test_data.csv')
dlg_ids=df['dlg_id'].unique().tolist() #собираем все айди диалогов

res_df=functions.get_dlg(df, dlg_ids)
res_df.to_csv('res_data.csv', index=False)
print ('результат сохранён в файл res_data.csv')


import os
import copy
import math
from tqdm import tqdm
import h5py
import tensorflow as tf
import matplotlib.pyplot as plt
import horovod.tensorflow as hvd
import time
import pdb

from utils import data_generator, calc_multi_cls_measures, dict_mean, log_one_step, save_model
from source.loss import HooknetLoss
from callbacks import SaveModelCallback, TensorBoard

def train(model, optimizer, batch_generator, logger, opts):
    train_generator = data_generator(batch_generator, 'training')
    val_generator = data_generator(copy.deepcopy(batch_generator), 'validation')

    if opts.horovod:
        steps_per_epoch_train = int(math.ceil(opts.steps_per_epoch_train) / hvd.size())
        steps_per_epoch_val = int(math.ceil(opts.val_steps) / hvd.size())
    else:
        steps_per_epoch_train = opts.steps_per_epoch_train
        steps_per_epoch_val = opts.val_steps

    if opts.debug:
        steps_per_epoch_train, steps_per_epoch_val = 10, 10

    loss = HooknetLoss(opts.loss_weights)

    for epoch in tqdm(range(opts.epochs)):

        # Perform the training
        train_metrics = []
        for step in tqdm(range(steps_per_epoch_train)):
            train_metric = train_one_step(model, optimizer, loss, train_generator, epoch, step, opts)
            train_metrics.append(train_metric)

        if opts.horovod:
            train_metrics = hvd.allgather_object(train_metrics)
            train_metrics = [item for sublist in train_metrics for item in sublist]
        train_metrics = dict_mean(train_metrics)

        # Perform the logging step every 'log_every' epochs
        if (epoch % opts.validate_every) == 0 or (epoch == opts.epochs - 1):
            val_metrics = []
            for _ in range(steps_per_epoch_val):
                val_metric = val_one_step(model, loss, val_generator, opts)
                val_metrics.append(val_metric)

            if opts.horovod:
                val_metrics = hvd.allgather_object(val_metrics)
                val_metrics = [item for sublist in val_metrics for item in sublist]
            val_metrics = dict_mean(val_metrics)
        else:
            val_metrics = {}

        # Log to tensorboard
        if (opts.horovod and hvd.rank() == 0) or not opts.horovod:
            log_one_step(logger, train_metrics, '/Train', epoch)
            log_one_step(logger, val_metrics, '/Val', epoch)

    save_model(hooknet, opts)

def train_one_step(model, optimizer, loss, train_generator, epoch, step, opts):
    x_batch, y_batch = next(train_generator)
    with tf.GradientTape() as tape:
        probs = model(x_batch, training=True)
        loss_value = loss(probs, y_batch)

    if opts.horovod:
        tape = hvd.DistributedGradientTape(tape)

    grads = tape.gradient(loss_value, model.trainable_variables)
    optimizer.apply_gradients(zip(grads, model.trainable_variables))

    if opts.horovod and epoch == step == 0:
        hvd.broadcast_variables(model.variables, root_rank=0)
        hvd.broadcast_variables(optimizer.variables(), root_rank=0)

    train_metrics = calc_multi_cls_measures(y_batch, probs, opts)
    train_metrics['loss'] = loss_value.numpy()
    train_metrics['rank'] = hvd.rank()

    return train_metrics

def val_one_step(model, loss, val_generator, opts):
    x_batch, y_batch = next(val_generator)

    probs = model(x_batch, training=True)
    loss_value = loss(probs, y_batch)

    val_metrics = calc_multi_cls_measures(y_batch, probs, opts)
    val_metrics['loss'] = loss_value.numpy()
    val_metrics['rank'] = hvd.rank()

    return val_metrics


'''
'''

import time

def equilibrium(array):
  array_sum = sum(array)
  left_sum = 0
  index = 0
  for x in array:
    array_sum -= x
    if array_sum == left_sum:
      return index
    left_sum += x
    index += 1
  return None

def debug(array):
  print("==================")
  print("array:")
  print(array)
  print("equilibrium index is: {0}".format(equilibrium(array)))
  print("==================")

debug([1, 2, 3, 4, 5, 6, 7])
debug([3, 6, 1, 2, 9, 6])
debug([-7, 1, 5, 2, -4, 3, 0])
debug([1, 1, 1, 2, 3])


from odoo import api, fields, models

class AccountMove(models.Model):
    _inherit = "account.move"

    intrastat_transaction_id = fields.Many2one(
        comodel_name="intrastat.transaction",
        string="Intrastat Transaction Type",
        ondelete="restrict",
        tracking=True,
        check_company=True,
        help="Intrastat Nature of Transaction",
        domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]",
    )
    intrastat_transport_id = fields.Many2one(
        comodel_name="intrastat.transport_mode",
        string="Intrastat Transport Mode",
        ondelete="restrict",
    )
    src_dest_country_id = fields.Many2one(
        comodel_name="res.country",
        string="Origin/Destination Country",
        compute="_compute_src_dest_country_id",
        store=True,
        help="Destination country for dispatches. Origin country for arrivals.",
    )
    src_dest_region_id = fields.Many2one(
        comodel_name="intrastat.region",
        string="Origin/Destination Region",
        default=lambda self: self.env.company.intrastat_region_id,
        help="Origin region for dispatches, destination region for "
        "arrivals. This field is used for the Intrastat Declaration.",
        ondelete="restrict",
    )
    intrastat = fields.Char(
        string="Intrastat Declaration", related="company_id.intrastat"
    )
    intrastat_line_ids = fields.One2many(
        comodel_name="account.move.intrastat.line",
        inverse_name="move_id",
        string="Intrastat Declaration Details",
    )

    @api.depends("partner_shipping_id.country_id", "partner_id.country_id")
    def _compute_src_dest_country_id(self):
        for inv in self:
            country = inv.partner_shipping_id.country_id or inv.partner_id.country_id
            if not country:
                country = inv.company_id.country_id
            inv.src_dest_country_id = country.id

    def compute_intrastat_lines(self):
        """
        Compute the Intrastat Lines so that they can be modified
        when encoding the Customer/Supplier Invoice.
        """
        self.mapped("intrastat_line_ids").unlink()
        for inv in self:
            if inv.move_type not in (
                "out_invoice",
                "out_refund",
                "in_invoice",
                "in_refund",
            ):
                continue
            line_vals = []
            for line in inv.invoice_line_ids:
                vals = self._get_intrastat_line_vals(line)
                if vals:
                    line_vals.append(vals)
            if line_vals:
                inv.intrastat_line_ids = [(0, 0, x) for x in line_vals]

    def _get_intrastat_line_vals(self, line):
        vals = {}
        decl_model = self.env["intrastat.product.declaration"]
        notedict, key2label = decl_model._prepare_notedict()
        if decl_model._is_product(line):
            hs_code = line.product_id.get_hs_code_recursively()
            if not hs_code:
                return vals
            weight, qty = decl_model._get_weight_and_supplunits(line, hs_code, notedict)
            vals.update(
                {
                    "invoice_line_id": line.id,
                    "hs_code_id": hs_code.id,
                    "transaction_weight": weight,
                    "transaction_suppl_unit_qty": qty,
                    "product_origin_country_id": line.product_id.origin_country_id.id,
                }
            )
        return vals

    def _prepare_intrastat_line_info(self, line):
        is_intrastat_line = bool(line._name == "account.move.intrastat.line")
        product = line.product_id
        return {
            "product_id": product,
            "hs_code_id": (
                line.hs_code_id if is_intrastat_line else product.hs_code_id
            ),
            "weight": (
                line.transaction_weight
                if is_intrastat_line
                else self._get_intrastat_line_vals(line)["transaction_weight"]
            ),
            "origin_country_id": (
                line.product_origin_country_id
                if is_intrastat_line
                else product.origin_country_id
            ),
        }

    def _get_intrastat_lines_info(self):
        """We obtain a list of information that we will need to group at the end by
        product and sum weight.
        """
        res = {}
        for line in (
            self.invoice_line_ids.filtered(
                lambda x: x.product_id.hs_code_id and x.product_id.origin_country_id
            )
            if not self.intrastat_line_ids
            else self.intrastat_line_ids
        ):
            res.setdefault(line.product_id.id, {"weight": 0})
            vals = self._prepare_intrastat_line_info(line)
            weight = vals.pop("weight")
            res[line.product_id.id].update(vals)
            res[line.product_id.id]["weight"] += weight
        return res.values()

class AccountMoveLine(models.Model):
    _inherit = "account.move.line"

    hs_code_id = fields.Many2one(
        comodel_name="hs.code",
        compute="_compute_hs_code_id",
        string="Intrastat Code",
    )

    def _compute_hs_code_id(self):
        for rec in self:
            intrastat_line = self.move_id.intrastat_line_ids.filtered(
                lambda r: r.invoice_line_id == rec
            )
            rec.hs_code_id = (
                intrastat_line.hs_code_id or rec.product_id.get_hs_code_recursively()
            )

class AccountMoveIntrastatLine(models.Model):
    _name = "account.move.intrastat.line"
    _description = "Intrastat declaration details"
    _order = "sequence"

    move_id = fields.Many2one(
        comodel_name="account.move",
        string="Invoice",
        ondelete="cascade",
        required=True,
    )
    invoice_line_id = fields.Many2one(
        comodel_name="account.move.line",
        string="Invoice Line",
        ondelete="cascade",
        required=True,
    )
    sequence = fields.Integer(related="invoice_line_id.sequence", store=True)
    product_id = fields.Many2one(
        comodel_name="product.product",
        string="Product",
        related="invoice_line_id.product_id",
    )
    quantity = fields.Float(related="invoice_line_id.quantity")
    transaction_suppl_unit_qty = fields.Float(
        help="Transaction quantity in Intrastat Supplementary Unit"
    )
    hs_code_id = fields.Many2one(
        comodel_name="hs.code",
        string="Intrastat Code",
        ondelete="restrict",
        required=True,
    )
    transaction_weight = fields.Integer(
        help="Transaction weight in Kg: Quantity x Product Weight"
    )
    product_origin_country_id = fields.Many2one(
        comodel_name="res.country",
        string="Country of Origin of the Product",
        help="Country of origin of the product i.e. product " "'made in ____'.",
    )

    @api.onchange("invoice_line_id")
    def _onchange_move_id(self):
        moves = self.mapped("move_id")
        dom = [
            ("exclude_from_invoice_tab", "=", False),
            ("display_type", "=", False),
            ("id", "in", moves.mapped("invoice_line_ids").ids),
            ("id", "not in", moves.mapped("intrastat_line_ids.invoice_line_id").ids),
        ]
        return {"domain": {"invoice_line_id": dom}}


from tkinter import *
from tkinter import messagebox
root=Tk()
root.geometry('500x300+5+5')
root.title('Messgagebox')

def info():
    top=Toplevel(root)
    top.geometry('300x200+400+200')
    name='Vivek Yadav'
    l2=Label(top,text=name,font='helvetica 15 bold',br=20,ng='light red')
    l2.place(x=30,y=60)

b1=Button(root,text="submit",command=info)
b1.pack()
root.mainloop()


#encoding: utf-8

from django.contrib import admin

from pages.models import Announcement, File

class AnnouncementAdmin(admin.ModelAdmin):
    models = Announcement

class FileAdmin(admin.ModelAdmin):
    models = File

admin.site.register(Announcement, AnnouncementAdmin)
admin.site.register(File, FileAdmin)


#Sara Hrnciar
#CSC 101
#Lori
#Pokemon directory!!
#import pandas to hold the dataframe
import pandas as pd

#create your pokemon class with instance variables for its name, abilities, and classification
class Pokemon:
    def __init__ (self, abilities, classification, name):
        self.abilities = abilities
        self.classification = classification
        self.name = name
    @property
    def name(self):
        return self.name
    @name.setter
    def name(self, n):
        self.name = n
    def __repr__(self):
        return repr("My name is " + self.name + ", and my abilities consist of: " + self.abilities + ". I actually am classified as " + self.classification + "!")

#Read in your df, rename it and reset its index values
pokesterz = pd.read_csv(r"C:\Users\lovey\Downloads\adv7poke.csv")
pokeSorted = pokesterz.sort_values(by = "name", ascending = True)
pokeSorted = pokeSorted.reset_index()

#empty array to hold your pokemon objects
arrPoke = []

#create your pokemons and fill up the array w/ them
for i in range(0, len(pokeSorted.name)):
    tempAbil = pokeSorted.loc[i, 'abilities']
    tempClass = pokeSorted.loc[i, 'classfication']
    tempName = pokeSorted.loc[i, 'name']
    arrPoke.append(Pokemon(tempAbil, tempClass, tempName))

#user enters pokemons' names until theyre done
def findingPokemon():
    whichPoke = input("Hey! Welcome to the pokemon database. Enter which pokemon you'd like to find or press Q to quit ")
    if whichPoke.upper() == "Q":
        print("ok, fine")
    else:
        print(whichPoke)
        print(str(binSearch(whichPoke, arrPoke)) + "\n")
        findingPokemon()

#bin search to find the pokemon rhe user asked for
def binSearch(pokeToLookFor, allPokes):
    first = 0
    last = len(allPokes) - 1

    while first<=last:
        mid = (first+last)//2
        if allPokes[mid].name == pokeToLookFor:
            return allPokes[mid]
        else:
            if first == last:
                return("Sorry, no pokemon with this name.")
            else:
                if allPokes[mid].name < pokeToLookFor:
                    first = mid + 1
                else:
                    last = mid - 1
findingPokemon()


from django.db import models

class ChristmasSong(models.Model):
    gift = models.CharField(
      unique=True,
      max_length=126,
      help_text="Gift for the day.",
      )

    def __str__(self):
      return "pk={} gift={}".format(
      self.pk, self.gift
      )

class Country(models.Model):
    iso = models.CharField(
      unique=True,
      max_length=126,
      help_text="ISO two-character id for the country.",
      )

    name = models.CharField(
      max_length=126,
      help_text="Name of the country.",
      )

    def __str__(self):
      return "iso={} name={}".format(
      self.iso, self.name
      )

class BibleBooks(models.Model):
    james = models.CharField(
      max_length=64,
      help_text="King James Bible title for the book.",
      )

    vulgate = models.CharField(
      max_length=64,
      help_text="Vulgate reference for the book.",
      )

    dv = models.CharField(
      max_length=64,
      help_text="Douay Rheims reference for the book.",
      )

    auth = models.CharField(
      max_length=126,
      help_text="Full title reference in the Authorised Version for the book.",
      )

    def __str__(self):
      return "{0}".format(
      self.james
      )

class Color(models.Model):
    name = models.CharField(
      db_index=True,
      unique=True,
      max_length=126,
      help_text="Machine name for the color.",
      )

    title = models.CharField(
      max_length=126,
      help_text="Display for the color.",
      )

    hex = models.CharField(
      max_length=32,
      help_text="Hex code for the color.",
      )

    rgb = models.CharField(
      max_length=32,
      help_text="RGB code for the color.",
      )

    def __str__(self):
      return "name={} title={}".format(
      self.name, self.title
      )

class Tree(models.Model):
    title = models.CharField(
      db_index=True,
      max_length=126,
      help_text="Common name for the tree.",
      )

    latin = models.CharField(
      max_length=126,
      db_index=True,
      unique=True,
      help_text="Latin name for the tree.",
      )

    def __str__(self):
      return "name={} latin={}".format(
      self.title, self.latin
      )

class Mineral(models.Model):
    name = models.CharField(
      max_length=64,
      help_text="Name for the mineral.",
      )

    isvalid = models.BooleanField(
      max_length=126,
      help_text="Is a recognised species of mineral.",
      )

    reason = models.CharField(
      max_length=256,
      help_text="Reason, if given, why not valid.",
      )

    def __str__(self):
      return "name={}".format(
      self.name
      )

class Star(models.Model):
    name = models.CharField(
      db_index=True,
      max_length=126,
      help_text="Common name for the star.",
      )

    distance = models.DecimalField(
      help_text="Distance to the star, in parsecs.",
      max_digits=15,
      decimal_places=10
      )

    magnitude = models.DecimalField(
      help_text="Apparent visual magnitude of the star",
      max_digits=4,
      decimal_places=2
      )

    spectrum = models.CharField(
      max_length=126,
      help_text="Light spectrum for the star.",
      )

    color = models.DecimalField(
      help_text="Color index of the star.",
      max_digits=4,
      decimal_places=3
      )

    def __str__(self):
      return "pk={} name={} distance={} magnitude={}".format(
      self.pk, self.name, self.distance, self.magnitude
      )

class Language(models.Model):
    '''
    Layout from http://www-01.sil.org/iso639-3/download.asp. The Django
    string convention of empty string is used, not null=True. blank=True
    is used to indicate a possible empty value. 'scope' and 'type'
    columns are defined with choices.
    '''
    id = models.CharField(
      db_index=True,
      max_length=3,
      primary_key=True,
      help_text="The three-letter 639-3 identifier.",
      )

    part2B = models.CharField(
      max_length=3,
      blank=True,
      help_text="Equivalent 639-2 identifier of the bibliographic applications code set, if there is one.",
      )

    part2T = models.CharField(
      max_length=3,
      blank=True,
      help_text="Equivalent 639-2 identifier of the terminology applications code set, if there is one.",
      )

    part1 = models.CharField(
      max_length=2,
      blank=True,
      help_text="Equivalent 639-1 identifier, if there is one.",
      )

    INDIVIDUAL = 'I'
    MACROLANGUAGE = 'M'
    SPECIAL = 'S'
    SCOPE_CHOICES = (
        (INDIVIDUAL, 'Individual'),
        (MACROLANGUAGE, 'Macrolanguage'),
        (SPECIAL, 'Special'),
    )
    scope = models.CharField(
      max_length=1,
      choices=SCOPE_CHOICES,
      help_text="I(ndividual), M(acrolanguage), S(pecial).",
      )

    ANCIENT = 'A'
    CONSTRUCTED = 'C'
    EXTINCT = 'E'
    HISTORICAL = 'H'
    LIVING = 'L'
    SPECIAL = 'S'
    TYPE_CHOICES = (
        (ANCIENT, 'Ancient'),
        (CONSTRUCTED, 'Constructed'),
        (EXTINCT, 'Extinct'),
        (HISTORICAL, 'Historical'),
        (LIVING, 'Living'),
        (SPECIAL, 'Special'),
        )
    type = models.CharField(
      max_length=1,
      choices=TYPE_CHOICES,
      help_text="A(ncient), C(onstructed), E(xtinct), H(istorical), L(iving), S(pecial).",
      )

    name = models.CharField(
      "Reference name",
      max_length=150,
      help_text="Reference language name.",
      )

    comment = models.CharField(
      max_length=150,
      blank=True,
      help_text="Comment relating to one or more of the columns.",
      )

    def __str__(self):
      return "id='{}' part1='{}' scope='{}' type='{}' name='{}' comment='{}'".format(
      self.pk, self.part1, self.scope, self.type, self.name, self.comment
      )


def foo(ch):
    d = { 'N':(0,-1),
          'S':(0,1),
          'W':(-1,0),
          'E':(1,0)
        }
    return d[ch]

if __name__ == "__main__":
    T = int(input().strip())
    for t in range(T):
        n,r,c,sc,sr = map(int,input().strip().split())
        instr = list(map(foo, list(input().strip())))
        i,j = 0,0
        v = {(0,0)}
        for a,b in instr:
            while True:
                i = i + a
                j = j + b
                if (i,j) not in v:
                    v.add((i,j))
                    break
        print("Case #%d: %d %d" % (t+1,sc+j,sr+i))


from pybossa.model.page import Page
from . import BaseFactory, factory, page_repo, ProjectFactory

class PageFactory(BaseFactory):
    class Meta:
        model = Page

    @classmethod
    def _create(cls, model_class, *args, **kwargs):
        page = model_class(*args, **kwargs)
        if kwargs.get('project_id') is None:
            project = ProjectFactory.create()
            page.project_id = project.id
        page_repo.save(page)
        return page

    id = factory.Sequence(lambda n: n)
    info = {'file_name': 'test.jpg',
            'container': 'user_3',
            'structure': ['Header', 'Blog', 'Footer']
            }
    slug = factory.Sequence(lambda n: u'slug-%d' % n)
    media_url = '/uploads/user_3/test.jpg'


# similar solution as 876 "Middle of the Linked List"

# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        slow = head
        fast = head

        while fast and fast.next and slow:
            slow = slow.next
            fast = fast.next.next
            if fast == slow:
                return True
        return False

python/LinkedList/Linked List Cycle/Linked List Cycle.py


import csv
import numpy as np
import matplotlib.pyplot as plt

# Read sensor data
f = open('inputData/Sensor Data 03.csv', 'r')
rdr = csv.reader(f)
xvalues = []
yvalues = []
zvalues = []
isFirstLine = True
for line in rdr:
    if isFirstLine:
        isFirstLine = False
    else:
        xvalues.append(float(line[0].strip(',')))
        yvalues.append(float(line[1].strip(',')))
        zvalues.append(float(line[2].strip(',')))
f.close()
xvalues.pop(0)
yvalues.pop(0)
zvalues.pop(0)
values = []
values.append(xvalues)
values.append(yvalues)
values.append(zvalues)

axis = 0
x = values[axis][0] # 초기 추정값
P = np.array([[10]]) # 초기 추정값에 대한 오차 공분산
A = np.array([[1]]) # 시스템 행렬
H = np.array([[1]]) # 출력 행렬
Q = np.array([[1]]) # 시스템 오차
R = np.array([[10]]) # 측정 오차

z = values[axis]
def SimpleKalman(z):
    global x, P, A, H, Q, R
    # 추값과 오차 공분산 예측
    xp = A.dot(x)
    Pp = A.dot(P).dot(A.T) + Q

    # 칼만 이득 계산
    K = Pp.dot(H.T).dot(np.linalg.inv(H.dot(P).dot(H.T) + R))

    # 추정값 계산
    x = xp + K.dot(z - H.dot(xp))

    # 오차 공분산 계산
    P = Pp - K.dot(H).dot(Pp)

    return x, P, K

z_result = [] # 측정값
est_result = [] # 추정값
Cov_result = []
Kg_result = []

for i in range(len(values[axis])):
    z = values[axis][i]
    est, Cov, Kg = SimpleKalman(z)
    z_result.append(z)
    est_result.append(est[0])
    Cov_result.append(Cov[0, 0])
    Kg_result.append(Kg[0, 0])

vel_z = []
vel_z_value = 0.0
for i in z_result:
    vel_z_value = vel_z_value + i
    vel_z.append(vel_z_value)

vel_est = []
vel_est_value = 0.0
for i in est_result:
    vel_est_value = vel_est_value + i
    vel_est.append(vel_est_value)

fig, ax = plt.subplots()

ax.plot(range(len(values[0])), z_result, label='measure')
ax.plot(range(len(values[0])), est_result, label='estimate')
ax.plot(range(len(values[0])), vel_z, label='vel_z')
ax.plot(range(len(values[0])), vel_est, label='vel_Est')

ax.legend()
plt.show()


import unittest
from bbolt import BoltDB
from tempfile import mkstemp
import os

class DBTests(unittest.TestCase):
    def setUp(self):
        self.db = BoltDB()
        fd, self.path = mkstemp()
        os.close(fd)
        self.db.open(self.path)

    def test_non_existant(self):
        self.db.create_bucket("bucket-1")
        r = self.db.get("bucket-1", "k1")
        assert r == b''

    def test_rw(self):
        self.db.put("bucket-1", "k1", "f-x")
        k = self.db.get("bucket-1", "k1").decode("utf-8")
        assert k == "f-x"
        pass

    def addCleanup(self, *arg, **kwargs) -> None:
        os.remove(self.path)


import copy

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p1 = Person("bleh", 20)
# assignment operator, so it is supposed to change the original too
p2 = p1

p2.age = 28

print(p1.age)
print(p2.age)

# as it's a 1d object (not nested) custom object, you get to shallow copy keeping the original one intact.
p3 = Person('bluh', 30)
p4 = copy.copy(p1)

p4.age = 28

print(p3.age)
print(p4.age)


# Max van Leeuwen - maxvanleeuwen.com
# GoToDirectory - 1.4
#
# Opens the directory of the path that is currently in the clipboard - except if nodes with a fileKnob are selected, in which case the file paths of the selected nodes will be opened.

import os
import nuke
import subprocess
import sys

GoToDirectoryMessage = '[GoToDirectory] '

# function for converting TCL path to string
def evalTCL(text):

	# make sure it's a string
	text = str(text)

	val = ''
	try:
		val = nuke.tcl("[return \"" + text + "\"]")
	except Exception as e:
		# TCL not working for this string
		pass

	# only allow string type to be returned
	if type(val) is not str:
		val = text

	return val

# function that reads clipboard
def get_clipboard_text():

	text = ""

	# get clipboard text
	try:
		from PySide2 import QtWidgets
	except:
		from PySide import QtGui as QtWidgets

	text = QtWidgets.QApplication.clipboard().text()

	# return clipboard text
	return text

# open explorer/finder to path
def openFolderFromString(folder, knobName = 'clipboard'):

	# evaluate TCL and make sure all slashes are forward ('/')
	TCLfolder = evalTCL( folder.replace('\\', '/') )
	TCL = not( str(TCLfolder) == str(folder) )

	# reset variable
	foundFolderPath = TCLfolder

	found = False
	projdir = False

	# if the file or folder does not exist
	if not os.path.isdir(foundFolderPath) and not os.path.isfile(foundFolderPath):

		# check if it is a Project Directory relative path
		projectdir = nuke.root()['project_directory'].getValue()
		if projectdir is not '':

			# TCL on project directory
			projectdir = evalTCL(projectdir)

			# join paths
			foundFolderPath = os.path.join(projectdir, foundFolderPath)

		projdir = True

	# check if that helped, if not reset
	if not os.path.isdir(foundFolderPath) and not os.path.isfile(foundFolderPath):

		projdir = False
		foundFolderPath = TCLfolder

	# check if project directory prefix works
	if not os.path.isdir(foundFolderPath):

		foundFolderPath = os.path.dirname(foundFolderPath)

		# if not, try with its parent dir
		if not os.path.isdir(foundFolderPath):

			# reset variable and ignore project directory
			foundFolderPath = TCLfolder
			projdir = False

		else:

			# project directory prefix works
			found = True

	attempts = 0
	# check if the path is an existing directory (skip if already working with project directory prefix)
	if not os.path.isdir(foundFolderPath) and not found:

		# only try to find a working parent path 3 times
		folderFound = False

		while attempts < 3 and not folderFound:

			# try the parent of the previous folder
			foundFolderPath = os.path.dirname(foundFolderPath)

			if os.path.isdir(foundFolderPath):

				# it works!
				folderFound = True

			else:

				# this folder does not exist
				attempts += 1

	# check if the result is a folder
	if os.path.isdir(foundFolderPath):

		# reverse the backslashes on Windows
		if sys.platform == 'win32':
			BackslashfixPluginsdir = foundFolderPath.replace("/", "\\")

			# and open the path in windows explorer
			os.startfile(BackslashfixPluginsdir)

		else:

			# open for Mac or Linux
			opener ="open" if sys.platform == "darwin" else "xdg-open"
			subprocess.call([opener, foundFolderPath])

		# print result
		message_on_changed_path = GoToDirectoryMessage + ('Original path found: ' + folder + '\n') if projdir or attempts > 1 or TCL else ''
		print (GoToDirectoryMessage + "Opened from " + knobName + '\n' + message_on_changed_path + GoToDirectoryMessage + 'Path: ' + foundFolderPath)

	else:

		# print failure
		print (GoToDirectoryMessage + "Not a valid path, checked up to 3 parent directories:\n" + GoToDirectoryMessage + folder)

	# print empty line
	print ('')

# main function
def GoToDirectory():

	# if nodes are selected
	if len(nuke.selectedNodes()) > 0:

		# for each selected node
		for n in nuke.selectedNodes():

			# check if the selected knobs are file paths
			for k in n.knobs():
				if n[k].Class() == 'File_Knob':

					# get its value
					v = n[k].getValue()

					# open folder
					if not v == '':
						knobName = n.name() + '.' + n[k].name()
						openFolderFromString(v, knobName)

	# if no knob paths are opened
	else:

		# open the folder from the string returned by get_clipboard_text()
		openFolderFromString(get_clipboard_text())

# autostart (if not imported)
if __name__ == "__main__":
	GoToDirectory()


from odoo import models

class AccountAssetRemove(models.TransientModel):
    _inherit = "account.asset.remove"

    def remove(self):
        res = super().remove()
        asset_id = self.env.context.get("active_id")
        asset = self.env["account.asset"].browse(asset_id)
        move = False
        if isinstance(res, dict):
            if "domain" in res.keys() and "res_model" in res.keys():
                if res["res_model"] == "account.move":
                    move = self.env["account.move"].search(res["domain"])
        # Assign operating unit to journal entry if any
        if asset and move:
            move.operating_unit_id = asset.operating_unit_id
            move._onchange_invoice_line_ids()
        return res


from discord import Embed

class EmbedError():
    """Creates and sends an error message to the channel

    :var int colour: The colour we will use for the error messages

    """

    colour = 0xFF2400

    async def send_error(self, channel, title, name, value, embed=None):
        """Send an error message to the channel"""

        if not embed:
            embed = Embed()
        embed.title = title
        embed.color = self.colour
        embed.insert_field_at(index=0, name=name, value=value, inline=False)
        await channel.send(embed=embed)


import os
import albumentations as A
from torch.utils.data import Dataset
import cv2
import random
import torch
import numpy as np
from torch.nn import functional as F
from config_ import config

class ContrastiveFaceDataset(Dataset):
    def __init__(self, img_paths=None, img_dir=config.dataset_directory, train=True, transforms=None) -> None:
        super().__init__()

        self.images = img_paths
        self.is_train = train
        self.img_dir = img_dir
        self.transforms = transforms
        if transforms is None:
            self.transforms = A.Compose([
                A.Resize(224, 224),
                A.Normalize()
            ])
        self.augmentations = self.make_augmentations() if train else None

    def make_augmentations(self) -> A.Compose:
        return A.Compose([
            A.RandomBrightnessContrast(
                brightness_limit=(-0.1, 0.1),
                contrast_limit=(-0.1, 0.1),
                p=0.3
            )
        ])

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

    @staticmethod
    def check_similarity(path1, path2):
        # костыль чтобы чекнуть одинаковые ли имена
        if path1[:-9] == path2[:-9]:
            return 1
        return 0

    def get_full_image_path(self, relative_path):
        return os.path.join(self.img_dir, relative_path[:-9], relative_path)

    def __getitem__(self, index):
        init_path = self.images[index]
        second_path = random.choice(self.images[:index] + self.images[index + 1:])
        label = self.check_similarity(init_path, second_path)

        if config.loss == "cosine_embedding_loss":
            label = 2 * label - 1 # перевести 0/1 в -1/1

        image1 = self.transforms(image=cv2.imread(self.get_full_image_path(init_path)))["image"]
        image2 = self.transforms(image=cv2.imread(self.get_full_image_path(second_path)))["image"]

        if self.augmentations is not None:
            image1 = self.augmentations(image=image1)["image"]
            image2 = self.augmentations(image=image2)["image"]

        return image1.transpose(2, 0, 1) / 255.0, image2.transpose(2, 0, 1) / 255.0, label

class SoftContrastiveFaceDataset(ContrastiveFaceDataset):
    def __init__(self, img_paths=None, img_dir=config.dataset_directory, train=True, transforms=None) -> None:
        super().__init__(img_paths, img_dir, train, transforms)

    def make_augmentations(self) -> A.Compose:
        return super().make_augmentations()

    def __len__(self):
        return super().__len__()

    @staticmethod
    def calc_similarity(img1: np.ndarray, img2: np.ndarray):
        x1 = torch.from_numpy(img1).flatten(start_dim=1).float()
        x2 = torch.from_numpy(img2).flatten(start_dim=1).float()

        # лежит в промежутке от 0 до 1
        phi = ((F.cosine_similarity(x1, x2) + 1.0) / 2.0).float()

        return phi

    def get_full_image_path(self, relative_path):
        return super().get_full_image_path(relative_path)

    def __getitem__(self, index):
        init_path = self.images[index]
        second_path = random.choice(self.images[:index] + self.images[index + 1:])

        image1 = self.transforms(image=cv2.imread(self.get_full_image_path(init_path)))["image"]
        image2 = self.transforms(image=cv2.imread(self.get_full_image_path(second_path)))["image"]

        soft_target = self.calc_similarity(image1, image2)

        if self.augmentations is not None:
            image1 = self.augmentations(image=image1)["image"]
            image2 = self.augmentations(image=image2)["image"]

        return image1.transpose(2, 0, 1), image2.transpose(2, 0, 1), soft_target


import time
import json
import torch.nn.functional
from comm.comm_utils import *
from modules.generation_utils import get_logits_processor, get_logits_warper

from .dist_pipeline_inference_mask_sample_token_pipe_sync import DistSampleInferenceMaskTokenPipeSync

class DistSampleInferenceMaskTokenSparsePipeSync(DistSampleInferenceMaskTokenPipeSync):

    def _forward_compute_generate_token(self, index, mask=None):

        if mask is not None and self.num_completions > 1:
            # repeat n times
            mask = mask.repeat(self.num_completions, 1)

        # print("Compute generate seq micro-batch <", index, ">.")
        if self.pp_rank == 0:
            cache = self._get_cached_attention(0, index)
            current_emb = self.layers['emb'](self.recv_new_token[index], self.cached_attention[0][index], mask=mask)
        else:
            current_emb = self.input_token_emb[index]

        for layer_index in range(self.num_layers):

            cache = self._get_cached_attention(layer_index, index)

            if layer_index == 0:
                self.layers['block' + str(layer_index)].prepare_fc_weights(current_emb)
            if layer_index != self.num_layers -1:
                self.layers['block' + str(layer_index+1)].prepare_fc_weights(current_emb)

            current_emb, cache = \
                self.layers['block' + str(layer_index)](current_emb, cache, mask=mask)

            self._set_cached_attention(cache, layer_index, index)
        self.output_token_emb[index] = current_emb

        if self.pp_rank == self.pipeline_group_size - 1:
            self._generate_new_token(index)


import json

from asgiref.sync import async_to_sync
from channels.db import database_sync_to_async
from channels.generic.websocket import WebsocketConsumer

from user.models import User

from .models import Message

class ChatConsumer(WebsocketConsumer):
    def connect(self):  # 사용자가 접속했을 때 동작하는 함수
        self.room_name = self.scope["url_route"]["kwargs"]["room_name"]
        self.room_group_name = "chat_%s" % self.room_name
        async_to_sync(self.channel_layer.group_add)(self.room_group_name, self.channel_name)
        self.accept()

    @database_sync_to_async
    def create_message(data):
        author = User.objects.filter(email=data["from"])[0]

        message = Message.objects.create(user=author, content=data["message"])

        return message

    def disconnect(self, close_code):  # 사용자가 방에서 떠났을 때 동작하는 함수
        async_to_sync(self.channel_layer.group_discard)(self.room_group_name, self.channel_name)

    def chat_message(self, event):  # 실제로 메시지를 전송하는 함수
        message = event["message"]
        self.send(text_data=json.dumps(message))

    def receive(self, text_data):  # 채팅방에 메시지가 전파되었을 때 동작하는 함수
        data = json.loads(text_data)

        message = create_message(data)

        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                "type": "chat_message",
                "message": {
                    "message": {
                        "nickname": message.user.nickname,
                        "content": message.content,
                        "created_at": message.created_at,
                        "updated_at": message.updated_at,
                    },
                },
            },
        )


from collections import defaultdict
from sklearn.model_selection import train_test_split
import numpy as np

class Dataset():
    def __init__(self, x=None, y=None):
        if x is None: x = []
        if y is None: y = []
        self.x = np.array(x).reshape(-1,1)
        self.y = np.array(y).reshape(-1,1)
        # print(self.x)
        # print(self.y)

    def split_datasets(self, test_size = 0.2):
        self.x_train, self.x_test, self.y_train, self.y_test = train_test_split(self.x, self.y, test_size = test_size)

    def normalize(self):
        self.y = self.y / max(np.max(self.y), abs(np.min(self.y)))

def read_data_from_file(file):
    data = defaultdict(lambda: [])

    with open(file, 'r') as f:
        labels = f.readline().split(',')
        values = f.readline().split(',')
        labels = list(map(lambda x: x.split('_')[0], labels))
        for l, v in zip(labels, values):
            data[l].append(float(v))

    return data


from tkinter import *

def Bigfont():
    global size
    size += 10
    label.configure(font=("Helvetica", size))

def Smallfont():
    global size
    size -=10
    label.configure(font=("Helvetica",size))

size = 20
window = Tk()

label = Label(window, text = "Hello world", font = ("Helvetica", size))
bigger = Button(window, text ="폰트를 크게", command= Bigfont)
smaller = Button(window, text = "폰트를 작게", command=Smallfont)

label.pack()
bigger.pack()
smaller.pack()

window.mainloop()


class WeightedQuickUnion:

    def __init__(self, n):
        self.data = list(range(n))
        self.size = [1] * n

    def union(self, p, q):
        pid = self.root(p)
        qid = self.root(q)

        if self.size[pid] >= self.size[qid]:
            self.data[pid] = qid
            self.size[pid] += self.size[qid]
        else:
            self.data[qid] = pid
            self.size[qid] += self.size[pid]

    def is_connected(self, p, q):
        return self.root(p) == self.root(q)

    def __str__(self):
        return str(self.data)

    def root(self, p):
        while p != self.data[p]:
            p = self.data[p]
        return p

def test_weighted_quick_union():

    n = int(input("Enter the no of nodes: "))
    m = int(input("Enter the no of unions: "))

    wqu = WeightedQuickUnion(n)
    for i in range(m):
        p = int(input())
        q = int(input())

        if not wqu.is_connected(p, q):
            wqu.union(p, q)
            print(f"Connected ({p},{q}) : {wqu}")

if __name__ == '__main__':
    test_weighted_quick_union()


import numpy as np
import os
import matplotlib.pyplot as plt
import dynesty as dyn
from scipy.special import ndtri
import multiprocessing as mul
from scipy import stats
import pickle
from scipy.integrate import quad
from corner import corner
import pandas as pd
from scipy.stats import gaussian_kde
grbparam = pd.read_csv('GRBPARAM.csv', index_col=0)
# [grbname.replace('.txt','')]
grbname = 'GRB081221.txt'
arr = np.loadtxt(os.getcwd() + '/asciidataof_fig1/32lag/'+grbname)
grbname_wtht_ext = grbname.replace('.txt','')
#Properties of GRB081221
E0 = grbparam[grbname.replace('.txt','')].E0
E0rest = E0
Erest = arr[:,0]    #in keV
z_com = grbparam[grbname.replace('.txt','')].redshift #redshift
nplot = 1000 #burn-in
H0=70 #km/s/Mpc Taken from Sir's Code

data = [arr[:,0], arr[:,1], arr[:,2]]
x = arr[:,0]
y = arr[:,1]
yerr = arr[:,2]
# plt.plot(arr[:,0], arr[:,1], '*')
plt.errorbar(arr[:,0], arr[:,1], yerr=arr[:,2], fmt='*')
plt.xlabel('E (keV)')
plt.xscale('log')
plt.show()
def MODEL_delta_t_intrinsic(E, Eb, alpha1, alpha2, mu, zeta):
    '''
    Broken power law model for lag-energy relation (NULL hypothesis)

    Parameters
    ----------
    E : float
        Energy in keV
    Eb : float
        Break energy in keV
    alpha1 : float
        Slope below break/transition energy
    alpha2 : float
        Slope above break/transition energy
    mu : float
        Transition smoothness parameter
    zeta : float
        Normalization constant
    E0 : float
        Energy shift parameter

    Returns
    -------
    delta_t : float
        Time lag in seconds
    '''
    E0b = (E - E0)/Eb
    return zeta * (E0b ** alpha1) * (1 + E0b ** ((alpha2 - alpha1)*mu))/2
def loglklhood_null_HP(theta):
    # if E0 in args:
    # x, y, yerr = data
    Eb, alpha1, alpha2, mu, zeta = theta
    model = MODEL_delta_t_intrinsic(x, Eb, alpha1, alpha2, mu, zeta)

    # chisq = np.sum(((y-MODEL_delta_t(x, *theta))/yerr)**2)
    # return norm - chisq/2.0
    return sum(stats.norm.logpdf(*args) for args in zip(y,model,yerr))

def prior_transform(theta):
    Eb, alpha1, alpha2, mu, zeta = theta
    # if E0 in args:

    return [5000*Eb, -3+13*alpha1, -10+13*alpha2, 3*mu, 4*zeta]
def int_over_red_shift(z, n):
    '''
    Integrate over redshift

    Parameters
    ----------
    z : float
        Redshift
    n : float
        LIV Polynomial power
    '''

    #    f = lambda x: ((1+x)**n)/h_gp(x)
    f = lambda x: ((1+x)**n)/np.sqrt(0.3*(1+x)**3 + 0.7)
    return quad(f, 0, z)[0]

K_z1 = int_over_red_shift(z_com,1)
K_z2 = int_over_red_shift(z_com,2)

def linear(E, z, E_qg, Eb, alpha1, alpha2, mu, zeta):
    K_z= np.asarray(K_z1)
    # return (1+z)*tau*(Erest - E0rest) + (-(10**14)/(H0*3.24))*((Erest - E0rest)*K_z/(E_qg*(1+z)))
    return MODEL_delta_t_intrinsic(E, Eb, alpha1, alpha2, mu, zeta) + (-(10**14)/(H0*3.24))*((E - E0)*K_z/E_qg)

def quadratic(E, z, E_qg, Eb, alpha1, alpha2, mu, zeta):
    E_0=E0rest#/(1+z)
    Eres=E#/(1+z)
    K_z = np.asarray(K_z2)
    # return (1+z)*tau*(Erest**2 - E0rest**2) + (-1.5*(10**8)/(H0*3.24))*((E**2 - E_0**2)*K_z/E_qg**2)
    return MODEL_delta_t_intrinsic(E, Eb, alpha1, alpha2, mu, zeta) + (-1.5*(10**8)/(H0*3.24))*((Eres**2 - E_0**2)*K_z/E_qg**2)

def loglklhood_LIV_lin(theta1):

    E_qg, Eb, alpha1, alpha2, mu, zeta = theta1

    model = linear(x, z_com, E_qg, Eb, alpha1, alpha2, mu, zeta)

    return sum(stats.norm.logpdf(*rgs) for rgs in zip(y,model,yerr))

def loglklhood_LIV_quad(theta2):

    E_qg, Eb, alpha1, alpha2, mu, zeta = theta2

    model = linear(x, z_com, E_qg, Eb, alpha1, alpha2, mu, zeta)

    return sum(stats.norm.logpdf(*rgs) for rgs in zip(y,model,yerr))

def prior_transform_LIV_lin(theta1):
    E_qg, Eb, alpha1, alpha2, mu, zeta = theta1
    return [1e20*E_qg, 5000*Eb, -3+13*alpha1, -10+13*alpha2, 3*mu, 4*zeta]

def prior_transform_LIV_quad(theta2):
    E_qg, Eb, alpha1, alpha2, mu, zeta = theta2
    return [1e15*E_qg, 5000*Eb, -3+13*alpha1, -10+13*alpha2, 3*mu, 4*zeta]

nlive = 1024
ndim_NULL = 5
ndim_LIV = 6

# NULL hypothesis

with dyn.pool.Pool(12, loglklhood_null_HP, prior_transform) as Pool:
    sampler0 = dyn.NestedSampler(loglklhood_null_HP, prior_transform, ndim=ndim_NULL, bound='multi', sample='rwalk', pool=Pool, nlive=nlive)
    sampler0.run_nested( dlogz=0.1)
    results0 = sampler0.results

Pool.close()
print(results0.summary())

with open(os.getcwd() + f'/pickle/{grbname_wtht_ext}_results_null.pkl', 'wb') as f:
    pickle.dump(results0, f)

with open(os.getcwd() + f'/pickle/{grbname_wtht_ext}_sampler_null.pkl', 'wb') as f:
    pickle.dump(sampler0, f)
# Linear LIV
with dyn.pool.Pool(12, loglklhood_LIV_lin, prior_transform_LIV_lin) as Pool:
    sampler1 = dyn.NestedSampler(loglklhood_LIV_lin, prior_transform_LIV_lin, ndim=ndim_LIV, bound='multi', sample='rwalk', pool=Pool, nlive=nlive)
    sampler1.run_nested( dlogz=0.1)
    results1 = sampler1.results

Pool.close()
print(results1.summary())

with open(os.getcwd() + f'/pickle/{grbname_wtht_ext}_results_LIV_lin.pkl', 'wb') as f:
    pickle.dump(results1, f)

with open(os.getcwd() + f'/pickle/{grbname_wtht_ext}_sampler_LIV_lin.pkl', 'wb') as f:
    pickle.dump(sampler1, f)
# Quadratic LIV
with dyn.pool.Pool(12, loglklhood_LIV_quad, prior_transform_LIV_quad) as Pool:
    sampler2 = dyn.NestedSampler(loglklhood_LIV_quad, prior_transform_LIV_quad, ndim=ndim_LIV, bound='multi', sample='rwalk', pool=Pool, nlive=nlive)
    sampler2.run_nested( dlogz=0.1)
    results2 = sampler2.results

Pool.close()
print(results2.summary())

with open(os.getcwd() + f'/pickle/{grbname_wtht_ext}_results_LIV_quad.pkl', 'wb') as f:
    pickle.dump(results2, f)

with open(os.getcwd() + f'/pickle/{grbname_wtht_ext}_sampler_LIV_quad.pkl', 'wb') as f:
    pickle.dump(sampler2, f)
# def plotsamples(results, figname='corner', labels=["E_qg", "Eb", "alpha1", "alpha2", "mu", "zeta"]):
#     weights = np.exp(results.logwt - results.logz[-1])
#     samples = dyn.utils.resample_equal(  results.samples, weights)
#     corner(samples, weights=weights, labels=labels, levels=[0.68, 0.9], show_titles=True, title_kwargs={"fontsize": 12})
#     plt.savefig(os.getcwd() + '/outputs/' + figname + '.png')
#     plt.show()
def smooth_plot(results, figname, labels=["E_qg", "Eb", "alpha1", "alpha2", "mu", "zeta"]):
    weights = np.exp(results.logwt - results.logz[-1])
    samples = dyn.utils.resample_equal(  results.samples, weights)

    fig = corner(samples, weights=weights, labels=labels, levels=[0.68, 0.9], show_titles=True, title_kwargs={"fontsize": 12}, hist_kwargs={'density': True})
    ndim =samples.shape[1]
    for axidx, samps in zip([i*(ndim+1) for i in range(ndim)],samples.T):
        kde = gaussian_kde(samps)
        xvals = fig.axes[axidx].get_xlim()
        xvals = np.linspace(xvals[0], xvals[1], 100)
        fig.axes[axidx].plot(xvals, kde(xvals), color='firebrick')
    plt.savefig(os.getcwd() + '/outputs/' + figname + '.png')
    plt.show()
smooth_plot(results0, figname=grbname_wtht_ext + 'null_HP', labels=["Eb", "alpha1", "alpha2", "mu", "zeta"])
smooth_plot(results1, figname=grbname_wtht_ext + 'LIV_lin' + '_smooth')
smooth_plot(results2, figname=grbname_wtht_ext + 'LIV_quad' + '_smooth')
# Eb, alpha1, alpha2, mu, zeta = theta2
E = np.linspace(min(Erest), max(Erest), nplot)
samples0 = dyn.utils.resample_equal( results0.samples, np.exp(results0.logwt - results0.logz[-1]))
samples0 = np.median(samples0, axis=0)

samples1 = dyn.utils.resample_equal( results1.samples, np.exp(results1.logwt - results1.logz[-1]))
samples1 = np.median(samples1, axis=0)

samples2 = dyn.utils.resample_equal( results2.samples, np.exp(results2.logwt - results2.logz[-1]))
samples2 = np.median(samples2, axis=0)

null_fit = [MODEL_delta_t_intrinsic(E[i], samples0[0], samples0[1], samples0[2], samples0[3], samples0[4]) for i in range(nplot)]
liv_lin_fit = [linear(E[i], z_com, samples1[0], samples1[1], samples1[2], samples1[3], samples1[4], samples1[5]) for i in range(nplot)]
liv_quad_fit = [quadratic(E[i], z_com, samples1[0], samples1[1], samples1[2], samples1[3], samples1[4], samples1[5]) for i in range(nplot)]
plt.errorbar(Erest, y, yerr, fmt='o', color='black', label='data')
plt.plot(E, null_fit[:], label='Null fit')
plt.plot(E, liv_lin_fit,label='Linear fit')
plt.plot(E, liv_quad_fit, label='Quadratic fit')
plt.xscale('log')
# plt.yscale('log')
plt.legend()
plt.xlabel('E (keV)')
plt.ylabel('lag (s)')
plt.title(grbname_wtht_ext)
plt.savefig(os.getcwd() + '/outputs/' + grbname_wtht_ext + '_fit.png', facecolor='white')
plt.show()


# coding: utf-8
# Author: wanhui0729@gmail.com

import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

# 生产的消息是通过exchange再转发到队列的
# fanout模式表示exchange将消息广播到他知道的所有队列中
channel.exchange_declare(exchange='logs', exchange_type='fanout')

message = ' '.join(sys.argv[1:]) or "info: Hello World!"
# 如果没有exchange绑定的队列，消息将会丢失，因为没有消费者
channel.basic_publish(exchange='logs', routing_key='', body=message)

print(" [x] Sent %r" % message)
connection.close()


import os

from selenium import webdriver
import time

driver = webdriver.Chrome()
file_path ='file:///' + os.path.abspath("E:/Test_Code/selenium2html/alert.html")
driver.get(file_path)
driver.maximize_window()

driver.find_element_by_id("tooltip").click()
time.sleep(8)
alert = driver.switch_to.alert
text = alert.text
print("text=" + text)
alert.accept()

time.sleep(5)
driver.quit()


from sklearn.cluster import KMeans
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
import seaborn as sns

players = pd.read_csv("../DataSet/player_data.csv")

feature = players[["speed", "shoot", "pass", "dribble", "defense", "physical"]]

model = KMeans(n_clusters=3)
model.fit(feature)
result_kmeans = model.predict(feature)

predict = pd.DataFrame(result_kmeans)
predict.columns = ['predict']

r = pd.concat([feature, predict], axis=1)
for idx, i in enumerate(r['predict']):
    if i == 0:
        r['predict'][idx] = "Striker"
    elif i == 1:
        r['predict'][idx] = "MidField"
    elif i == 2 :
        r['predict'][idx] = "Defense"

# Kmeans 시각화
g = sns.scatterplot(x="speed", y="dribble", hue = 'predict', style = 'predict', data=r)
plt.title('Speed & Dribble')

# Feature 전체 클러스터링에 대한 시각화
sns.pairplot(r, hue="predict", markers=["o", "s", "D"])

plt.show()


import numpy as np
import matplotlib.pyplot as plt
import argparse

def plot(args) -> None:
    imu_data = np.loadtxt(args.path_to_imu_data, delimiter=' ')

    x = range(len(imu_data[:, 1]))

    gyro_figure, (gyro_ax1, gyro_ax2, gyro_ax3) = plt.subplots(3, 1, figsize=(8, 8))
    gyro_figure.suptitle('Gyro measurements')

    gyro_ax1.plot(x, imu_data[:, 1], label=r'$\omega_x$')
    gyro_ax1.set_ylabel(r'$\omega_x$')
    gyro_ax1.grid()
    gyro_ax1.legend()

    gyro_ax2.plot(x, imu_data[:, 2], label=r'$\omega_y$')
    gyro_ax2.set_ylabel(r'$\omega_y$')
    gyro_ax2.grid()
    gyro_ax2.legend()

    gyro_ax3.plot(x, imu_data[:, 3], label=r'$\omega_z$')
    gyro_ax3.set_ylabel(r'$\omega_z$')
    gyro_ax3.grid()
    gyro_ax3.legend()

    acc_figure, (acc_ax1, acc_ax2, acc_ax3) = plt.subplots(3, 1, figsize=(8, 8))
    acc_figure.suptitle('Acc measurements')

    acc_ax1.plot(x, imu_data[:, 4], label=r'$a_x$')
    acc_ax1.set_ylabel(r'$a_x$')
    acc_ax1.grid()
    acc_ax1.legend()

    acc_ax2.plot(x, imu_data[:, 5], label=r'$a_y$')
    acc_ax2.set_ylabel(r'$a_y$')
    acc_ax2.grid()
    acc_ax2.legend()

    acc_ax3.plot(x, imu_data[:, 6], label=r'$a_z$')
    acc_ax3.set_ylabel(r'$a_z$')
    acc_ax3.grid()
    acc_ax3.legend()

    plt.show()

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--path_to_imu_data', type=str,
                        help="Input file: time gx gy gz ax ay az")
    args = parser.parse_args()

    plot(args)


import os
import cv2
import numpy as np
from sklearn.cluster import KMeans

# Function to resize the images
def resize_image(image, size):
    resized_image = cv2.resize(image, size)
    return resized_image

# Function to separate colors using KMeans clustering
def separate_colors(image, num_clusters):
    # Reshape the image into a 2D array of pixels
    pixels = image.reshape(-1, 3)

    # Apply KMeans clustering to find the dominant colors
    kmeans = KMeans(n_clusters=num_clusters)
    kmeans.fit(pixels)

    # Get the cluster labels for each pixel
    labels = kmeans.labels_

    # Reshape the labels back to the original image shape
    segmented_image = labels.reshape(image.shape[:2])

    # Get the background cluster label
    background_label = np.argmax(np.bincount(segmented_image.flatten()))

    # Create a mask to filter out the background pixels
    mask = np.where(segmented_image != background_label, 255, 0).astype(np.uint8)

    # Apply the mask to the original image
    masked_image = cv2.bitwise_and(image, image, mask=mask)

    return masked_image, mask

# Function to crop the image based on contours
def crop_contour(image, contours):
    cropped_images = []
    for contour in contours:
        # Create a bounding rectangle around the contour
        x, y, w, h = cv2.boundingRect(contour)

        # Crop the image using the bounding rectangle coordinates
        cropped_image = image[y:y+h, x:x+w]

        # Add the cropped image to the list
        cropped_images.append(cropped_image)

    return cropped_images

# Directory containing the images
image_directory = 'Task2\images_samples_from_camera'

# Size to resize the images
resize_size = (640, 640)

# Number of clusters for KMeans clustering
num_clusters = 3

# Read images from the directory, resize, remove background, and crop contour areas
for filename in os.listdir(image_directory):
    if filename.endswith('.jpg') or filename.endswith('.png'):
        image_path = os.path.join(image_directory, filename)

        # Read the image
        image = cv2.imread(image_path)

        # Resize the image
        resized_image = resize_image(image, resize_size)

        # Remove background color using KMeans clustering
        masked_image, mask = separate_colors(resized_image, num_clusters)

        # Convert the mask to grayscale
        grayscale_image = cv2.cvtColor(masked_image, cv2.COLOR_BGR2GRAY)

        # Apply thresholding to obtain binary mask
        _, binary_mask = cv2.threshold(grayscale_image, 1, 255, cv2.THRESH_BINARY)

        # Find contours in the binary mask
        contours, _ = cv2.findContours(binary_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        # Crop contour areas
        cropped_images = crop_contour(resized_image, contours)

        # Display the cropped contour areas
        for i, cropped_image in enumerate(cropped_images):
            cv2.imshow(f'Cropped Image {i+1}', cropped_image)

        cv2.waitKey(0)
        cv2.destroyAllWindows()