"""
This file handles testing of the pickled_object and jar classes implemented in
vice/core/pickles.py
"""

from __future__ import absolute_import
__all__ = ["test"]
from ...testing import moduletest
from ...testing import unittest
from ..pickles import pickled_object
from ..pickles import jar
import pickle
import os

@moduletest
def test():
	"""
	Run the tests on this module
	"""
	test1 = pickled_object_tester("test", name = "test", default = None)
	test2 = jar_tester({
		"a": 		3,
		"b": 		"string",
		"c": 		list(range(10))
	}, name = "test", default = None)
	return ["vice.core.pickles",
		[
			test1.test_save(),
			test1.test_from_pickle(),
			test2.test_close(),
			test2.test_open()
		]
	]

class jar_tester(jar):

	"""
	A class designed to test the jar class.
	"""
	def __init__(self, objects, name = "objects", default = None):
		super().__init__(objects, name = name, default = default)

	@unittest
	def test_close(self):
		"""
		Tests the close() function of the jar class
		"""
		def test():
			"""
			Returns True on success and False on failure
			"""
			try:
				self.close()
			except:
				os.system("rm -rf %s" % (self._name))
				return False

			x = True
			for i in self._objects.keys():
				if os.path.exists("%s/%s.obj" % (self._name, i)):
					if (pickle.load(open("%s/%s.obj" % (self._name, i), "rb"))
						== self._objects[i]):
						continue
					else:
						x = False
						break
				else:
					x = False
					break

			os.system("rm -rf %s" % (self._name))
			return x

		return ["vice.core.pickles.jar.close", test]

	@unittest
	def test_open(self):
		"""
		Tests the open() function of the jar class
		"""
		def test():
			"""
			Returns True on success and False on failure
			"""
			test_ = {
				"a": 		3,
				"b": 		"string",
				"c": 		list(range(10))
			}

			if os.path.exists(self._name): os.system("rm -rf %s" % (self._name))
			os.system("mkdir %s" % (self._name))
			for i in test_.keys():
				pickle.dump(test_[i], open("%s/%s.obj" % (self._name, i), "wb"))

			try:
				copy = self.open(self._name)
				assert copy == test_
			except:
				return False
			finally:
				os.system("rm -rf %s" % (self._name))

			return True

		return ["vice.core.pickles.jar.open", test]

class pickled_object_tester(pickled_object):

	"""
	A class designed to test the pickled_object class.
	"""

	def __init__(self, obj, name = "object", default = None):
		super().__init__(obj, name = name, default = default)

	@unittest
	def test_save(self):
		"""
		Test the save function of the pickled_object class.
		"""
		def test():
			"""
			Returns True on success, False on failure
			"""
			filename = "%s.obj" % (self._name)
			try:
				self.save()
				assert pickle.load(open(filename, "rb")) == self._obj
			except:
				return False
			finally:
				os.system("rm -f %s" % (filename))

			self._obj = 3
			try:
				self.save()
				assert pickle.load(open(filename, "rb")) == 3
			except:
				return False
			finally:
				os.system("rm -f %s" % (filename))

			self._obj = "string"
			try:
				self.save()
				assert pickle.load(open(filename, "rb")) == "string"
			except:
				return False
			finally:
				os.system("rm -f %s" % (filename))

			self._obj = list(range(10))
			try:
				self.save()
				assert pickle.load(open(filename, "rb")) == list(range(10))
			except:
				return False
			finally:
				os.system("rm -f %s" % (filename))

			return True

		return ["vice.core.pickles.pickled_object.save", test]

	@unittest
	def test_from_pickle(self):
		"""
		Test the from_pickle function of the pickled_object class.
		"""
		def test():
			"""
			Returns True on success, False on failure
			"""
			filename = "%s.obj" % (self._name)
			pickle.dump(3, open(filename, "wb"))
			try:
				assert self.from_pickle(filename) == 3
			except:
				return False
			finally:
				os.system("rm -f %s" % (filename))

			pickle.dump("string", open(filename, "wb"))
			try:
				assert self.from_pickle(filename) == "string"
			except:
				return False
			finally:
				os.system("rm -f %s" % (filename))

			pickle.dump(list(range(10)), open(filename, "wb"))
			try:
				assert self.from_pickle(filename) == list(range(10))
			except:
				return False
			finally:
				os.system("rm -f %s" % (filename))

			return True

		return ["vice.core.pickles.pickled_object.from_pickle", test]


import geopandas as gpd
import geojsonio as gjio
import requests, json
import pandas as pd

api_key = '***************************************'
zips = gpd.read_file('zip_bounds.geojson')
url = "https://maps.googleapis.com/maps/api/place/textsearch/json?"

INPUT_STRING = 'chinese restaurant '

frames = []
for zip in zips['postalCode']:
    query = INPUT_STRING + zip
    print(query)
    r = requests.get(url + 'query=' + query + '&key=' + api_key)
    results = r.json()
    df = pd.DataFrame(results['results'])
    frames.append(df)
    print(len(frames))

final_df = pd.concat(frames)
final_df.to_csv('chinese_data_nyc.csv')


import logging
logging.basicConfig(filename="dict_file.log",level=logging.INFO,format='%(asctime)s %(levelname)s %(message)s')
try:
    class dget:
        def __init__(self,a):
            if (type(a)==dict):
                self.old_dict=a
            else:
                raise Exception("this is not a dictionary")
        def dget(self,b):
            """gets value for specified key

            Args:
                b (any): enter the key
            """
            for k,v in self.old_dict.items():
                if(k==b):
                    the_value=v
            logging.info(f"the value im the dictionary is {the_value} ")
except Exception as e:
    logging.exception(e)
a=dget({"a":1,"b":2})
a.dget("b")


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

'''

ptr2inject
by JMK

GitHub: https://github.com/jmk-developer/ptr2inject

'''

import wx
import shutil
import os
import time
import math
import json

import modmanager

CurrentImage        = None
CurrentModFile      = None

CurrentImagePackage = None
CurrentModPackage   = None

ImageReady          = False
ModFileReady        = False

temp_directory      = None
temp_directory_name = ".temporary"
temp_directory_path = "\\" + temp_directory_name + "\\"
temp_directory_fullpath = os.getcwd() + temp_directory_path

if not os.path.isdir(temp_directory_fullpath):
    os.makedirs(temp_directory_fullpath)

modmanager.set_temporary_directory(temp_directory_fullpath)

def check_start_enabled(thisobject):
    print("Image Ready: " + str(ImageReady))
    print("ModFile Ready: " + str(ModFileReady))

    startbutton = thisobject.GetParent().Start
    if ImageReady == True and ModFileReady == True:
        startbutton.Enable()
    else:
        startbutton.Disable()

def not_yet_implemented(self):
    mod_data_dialog = wx.MessageDialog(self,
                                       "This feature is not yet implemented.",
                                       "Info",
                                       wx.OK | wx.STAY_ON_TOP | wx.CENTRE)
    mod_data_dialog.ShowModal()
    mod_data_dialog.Destroy()

def show_package_data(self, mod_package):
    mod_data_dialog = wx.MessageDialog(self,
                                       "Mod Name: " + mod_package['mod_data_json']['name'] +
                                       "\nMod Description: " + mod_package['mod_data_json']['description'] +
                                       "\nMod Version: " + str(mod_package['mod_data_json']['version']),

                                       "Mod Info",
                                       wx.OK | wx.STAY_ON_TOP | wx.CENTRE)
    mod_data_dialog.ShowModal()
    mod_data_dialog.Destroy()

class MyFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrame.__init__
        kwds["style"] = kwds.get("style", 0) | wx.CAPTION | wx.CLIP_CHILDREN | wx.CLOSE_BOX | wx.MINIMIZE_BOX | wx.SYSTEM_MENU
        wx.Frame.__init__(self, *args, **kwds)
        self.SetSize((400, 180))

        # Menu Bar
        self.MenuBar = wx.MenuBar()
        wxglade_tmp_menu = wx.Menu()

        item = wxglade_tmp_menu.Append(wx.ID_ANY, "Create Mod File from INT", "Create a mod file from INT files.")
        self.Bind(wx.EVT_MENU, self.create_mod_file, id=item.GetId())

        item = wxglade_tmp_menu.Append(wx.ID_ANY, "View Mod Info", "View a mod file's info.")
        self.Bind(wx.EVT_MENU, self.view_mod_info, id=item.GetId())

        item = wxglade_tmp_menu.Append(wx.ID_ANY, "View ISO Info", "View an ISO file's info.")
        self.Bind(wx.EVT_MENU, self.view_iso_info, id=item.GetId())

        item = wxglade_tmp_menu.Append(wx.ID_ANY, "Clear Temporary Files", "Clear all temporary files.")
        self.Bind(wx.EVT_MENU, self.clear_temporary_files, id=item.GetId())

        item = wxglade_tmp_menu.Append(wx.ID_ANY, "About", "Info about this program")
        self.Bind(wx.EVT_MENU, self.about_menu, id=item.GetId())

        self.MenuBar.Append(wxglade_tmp_menu, "File")
        wxglade_tmp_menu = wx.Menu()

        item = wxglade_tmp_menu.Append(wx.ID_ANY, "Ignore ISO/Mod Region", "Automatically, this program detects when mods are incompatible with the ISO you give them, based on region.", wx.ITEM_CHECK)
        self.Bind(wx.EVT_MENU, self.ignore_mod_region, id=item.GetId())
        self.MenuBar.Append(wxglade_tmp_menu, "Settings")
        self.SetMenuBar(self.MenuBar)
        # Menu Bar end
        self.ChooseImage = wx.Button(self, wx.ID_ANY, "Choose ISO")
        self.ChooseFile = wx.Button(self, wx.ID_ANY, "Choose File")
        self.Start = wx.Button(self, wx.ID_ANY, "Start")

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_BUTTON, self.choose_image_event, self.ChooseImage)
        self.Bind(wx.EVT_BUTTON, self.choose_file_event, self.ChooseFile)
        self.Bind(wx.EVT_BUTTON, self.start_event, self.Start)
        # end wxGlade
        self.Start.Disable()

    def __set_properties(self):
        # begin wxGlade: MyFrame.__set_properties
        self.SetTitle("ptr2inject")
        self.ChooseImage.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, "Segoe UI"))
        self.ChooseImage.SetToolTip("This button chooses your Parappa The Rapper 2 ISO image.")
        self.ChooseFile.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, "Segoe UI"))
        self.ChooseFile.SetToolTip("This button selects the .p2m file you want to inject.")
        self.Start.SetFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, "Segoe UI"))
        self.Start.SetToolTip("This button begins the ISO injection. Once you click this, you will be asked where to save the newly created ISO.")
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: MyFrame.__do_layout
        RootSizer = wx.BoxSizer(wx.HORIZONTAL)
        RootSizer.Add(self.ChooseImage, 1, wx.ALL | wx.EXPAND, 8)
        RootSizer.Add(self.ChooseFile, 1, wx.ALL | wx.EXPAND, 8)
        RootSizer.Add(self.Start, 2, wx.ALL | wx.EXPAND, 8)
        self.SetSizer(RootSizer)
        self.Layout()
        # end wxGlade

    def create_mod_file(self, event):  # wxGlade: MyFrame.<event_handler>
        not_yet_implemented(self)

    def view_mod_info(self, event):  # wxGlade: MyFrame.<event_handler>
        if ModFileReady == False:
            view_mod_error_dialog = wx.MessageDialog(self,
                                                        "Please select a mod file before using this option.",
                                                        "Info",
                                                        wx.OK | wx.STAY_ON_TOP | wx.CENTRE)
            view_mod_error_dialog.ShowModal()
            view_mod_error_dialog.Destroy()
        else:
            show_package_data(self, CurrentModPackage)

    def view_iso_info(self, event):
        not_yet_implemented(self)
        '''
        if ImageReady == False:
            view_iso_error_dialog = wx.MessageDialog(self,
                                                     "Please select an ISO file before using this option.",
                                                     "Info",
                                                     wx.OK | wx.STAY_ON_TOP | wx.CENTRE)
            view_iso_error_dialog.ShowModal()
            view_iso_error_dialog.Destroy()
        else:
            show_image_data(self, CurrentModPackage)
        '''

    def clear_temporary_files(self, event):
        begin_time = time.perf_counter()
        modmanager.clear_temporary_directory()
        end_time = time.perf_counter()
        clear_temporary_files_dialog = wx.MessageDialog(self,
                                           "Finished in " + str(math.ceil(end_time - begin_time)) +
                                           " seconds. Thank you!",
                                           "Done",
                                           wx.OK | wx.STAY_ON_TOP | wx.CENTRE)
        clear_temporary_files_dialog.ShowModal()
        clear_temporary_files_dialog.Destroy()

    def about_menu(self, event):  # wxGlade: MyFrame.<event_handler>
        not_yet_implemented(self)

    def ignore_mod_region(self, event):  # wxGlade: MyFrame.<event_handler>
        not_yet_implemented(self)

    def choose_image_event(self, event):  # wxGlade: MyFrame.<event_handler>
        global CurrentImage
        global ImageReady

        iso_dialog = wx.FileDialog(self, "Open", "", "", "PS2 ISO images (*.iso)|*.iso", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
        iso_dialog.ShowModal()
        CurrentImage = iso_dialog.GetPath()
        if not CurrentImage or CurrentImage == "":
            CurrentImage = None
            return
        myobject = event.GetEventObject()
        myobject.Disable()
        myobject.SetLabel("Completed")
        ImageReady = True
        check_start_enabled(myobject)

    def choose_file_event(self, event):  # wxGlade: MyFrame.<event_handler>
        global CurrentModFile
        global CurrentModPackage
        global ModFileReady

        file_dialog = wx.FileDialog(self, "Open", "", "", "PTR2 mod files (*.p2m)|*.p2m", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
        file_dialog.ShowModal()
        CurrentModFile = file_dialog.GetPath()

        if not CurrentModFile or CurrentModFile == "":
            CurrentModFile = None
            return
        CurrentModPackage = modmanager.unpackage_mod_file(CurrentModFile, "ptr2mod")

        myobject = event.GetEventObject()
        myobject.Disable()
        myobject.SetLabel("Completed")
        ModFileReady = True
        check_start_enabled(myobject)

    def start_event(self, event):  # wxGlade: MyFrame.<event_handler>
        global CurrentModFile
        global CurrentModPackage
        global CurrentImage

        start_button = event.GetEventObject()
        start_button.Disable()
        start_button.SetLabel("Starting...")
        wx.BeginBusyCursor()
        show_package_data(self, CurrentModPackage)
        begin_time = time.perf_counter()
        start_button.SetLabel("Cleaning up...")
        modmanager.clear_temporary_directory()

        start_button.SetLabel("Extracting ISO...")
        unpackaged_iso = modmanager.unpackage_iso(CurrentImage, "ptr2iso")
        start_button.SetLabel("Moving files...")
        start_button.SetLabel("Patching ISO...")
        modmanager.package_iso(unpackaged_iso, CurrentImage)

        end_time = time.perf_counter()
        wx.EndBusyCursor()
        finished_dialog = wx.MessageDialog(self,
                                            "Finished in " + str(math.ceil(end_time - begin_time)) +
                                            " seconds. Thank you!",
                                            "Done",
                                            wx.OK | wx.STAY_ON_TOP | wx.CENTRE)
        finished_dialog.ShowModal()
        finished_dialog.Destroy()
# end of class MyFrame

class AboutDialog(wx.Dialog):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyDialog.__init__
        kwds["style"] = kwds.get("style", 0) | wx.CAPTION | wx.CLOSE_BOX
        wx.Dialog.__init__(self, *args, **kwds)
        self.SetSize((320, 220))

        self.__set_properties()
        self.__do_layout()
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: MyDialog.__set_properties
        self.SetTitle("About ptr2inject")
        self.SetSize((320, 220))
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: MyDialog.__do_layout
        AboutRootSizer = wx.BoxSizer(wx.VERTICAL)
        AboutText = wx.StaticText(self, wx.ID_ANY, "Program created by JMK\n\nThis program is free.\nHow to use: \n1. Choose your Parappa The Rapper 2 ISO\n2. Choose your mod file\n3. Click \"Start\" \n4. Profit", style=wx.ALIGN_CENTER)
        AboutText.SetFont(wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, "Segoe UI"))
        AboutRootSizer.Add(AboutText, 1, wx.ALL | wx.EXPAND, 20)
        self.SetSizer(AboutRootSizer)
        self.Layout()
        # end wxGlade

# end of class MyDialog

class MyApp(wx.App):
    def OnInit(self):
        self.RootFrame = MyFrame(None, wx.ID_ANY, "")
        self.SetTopWindow(self.RootFrame)
        self.RootFrame.Show()
        return True

# end of class MyApp

if __name__ == "__main__":
    app = MyApp(0)
    app.MainLoop()


#!/usr/bin/env python
'''
Module for in silico digestion of WT and Variant proteins and writing to fasta files.
'''

import re

from pyteomics import fasta

from PoolSeqProGen import dna_seq

__author__ = "Rigbe G. Weldatsadik"
__copyright__ = "Copyright (c) 2020 Rigbe G. Weldatsadik"
__license__ = "Apache 2.0"
__version__ = "0.0.1"

def writewtpro_returnwtpep(k, seq_entry,gbk_file,fastaOutput,poolID):
    '''
    Writes the sequences of the 'wild type' proteins to the fasta output and
    returns the tryptic peptides of the 'wild type' protein.
    '''

    entries = []

    '''protein_id_cds_index=dna_seq.index_genbank_features(gbk_file,"CDS",
                                                "protein_id")'''

    protein_id_cds_index = dna_seq.index_genbank_features(gbk_file, "CDS",
                                                  "locus_tag")

    index = protein_id_cds_index[k]
    cds_feature = gbk_file.features[index]
    try:  # there are cds with no translation and protein_id
        immu_tran = cds_feature.qualifiers['translation'][0]
        protein_id = cds_feature.qualifiers['protein_id'][0]
    except KeyError:
        pass
    else:
        seq_entry += 1
        if poolID:
            header = protein_id + '|0_WT|' + \
                str(seq_entry) + '_' + str(poolID)
        else:
            header = protein_id + '|0_WT|' + str(seq_entry)

        entries.append((header, immu_tran))
        fasta.write(entries, fastaOutput)

        # split by K or R when they are not followd by P
        peptide_list_org = re.compile(".(?:(?<![KR](?!P)).)*").findall(str(immu_tran))

        return (seq_entry, peptide_list_org)

def return_varpep(k,v,gbk_file,gbk_fileSeq,geneticCodeID):
    '''
    Returns the variant peptides to be written to the fasta output
    '''

    '''protein_id_cds_index=dna_seq.index_genbank_features(gbk_file,"CDS",\
                                                "protein_id")'''

    protein_id_cds_index = dna_seq.index_genbank_features(gbk_file, "CDS",
                                                  "locus_tag")

    index = protein_id_cds_index[k]
    cds_feature = gbk_file.features[index]
    try:
        immu_tran = cds_feature.qualifiers['translation'][0]
        protein_id = cds_feature.qualifiers['protein_id'][0]
    except KeyError:
        pass
    else:
        loc = cds_feature.location
        strand = cds_feature.location.strand  # +1 or -1
        feature_seq = cds_feature.extract(gbk_file.seq)
        pr_name = cds_feature.qualifiers['product'][0]

        # this wont return the reverse complement for protein on the complement strand
        # unlike extract method
        mut_cds_seq = gbk_file[loc.start:loc.end].seq
        mut_cds_len = len(mut_cds_seq)
        del_range_list = []
        ins_range_list = []
        modified = False

        # subset is in the form of (var_pos,alt,ref,effect,snp) for snp
        # (var_pos,alt,ref,effect,ins) for insertion
        # (var_pos,nt_after_del,alt,ref,del,effect) for deletion
        for subset in v:
            var_pos = subset[0]
            alt_allele = subset[1]
            ref = subset[2]
            effect = subset[5]

            # since var_pos is 1-based position from SnpEff and relative to
            # the whole genome length
            zero_based_pos = int(var_pos) - 1
            pos_relativeto_cds = abs(loc.start - zero_based_pos)

            diff = len(alt_allele) - len(ref)

            if effect == "START_LOST":
                modified = False
                break

            if diff >= 0:  # ins and snp
                # checking deletion range list first since if that particular
                # position has been deleted, it doesn't make sense to
                # insert there
                in_del = dna_seq.check_if_in_del(pos_relativeto_cds, del_range_list)

                if in_del == "True":
                    modified = False
                    break
                elif in_del == "False":
                    pos_relativeto_cds = pos_relativeto_cds
                else:
                    pos_relativeto_cds = in_del

                pos_relativeto_cds = dna_seq.check_if_in_ins(
                    pos_relativeto_cds, ins_range_list)

                # adding len(ref) to the last indices in both the insertion
                # and deletion cases insures we skip and delete as many as
                # the length of the ref so we avoid repeating the nt in the
                # insertion case and we delete the right amount of nts in
                # the deletion case. the len(alt) in the deletion case ensures
                # we dont delete the trailing nt that are reported in the
                # vcf but shouldnt be deleted.

                if(diff > 0):
                    ins_range_list.append(range(pos_relativeto_cds +
                                                 len(ref), pos_relativeto_cds +
                                                 len(alt_allele)))

                try:
                    # this will create a copy of cds_seq so we dont need to
                    # changs cds_seq to mutable explicitly to modify it
                    # this way
                    mut_cds_seq = mut_cds_seq[:pos_relativeto_cds] + \
                        alt_allele + \
                        mut_cds_seq[pos_relativeto_cds +
                                    len(ref):]
                except IndexError:
                    modified = False
                    break
                else:

                    modified = True

            else:  # deletion
                in_del = dna_seq.check_if_in_del(pos_relativeto_cds, del_range_list)

                if in_del == "True":
                    modified = False
                    break
                elif in_del == "False":

                    pos_relativeto_cds = pos_relativeto_cds
                else:

                    pos_relativeto_cds = in_del

                pos_relativeto_cds = dna_seq.check_if_in_ins(
                    pos_relativeto_cds, ins_range_list)

                del_range_list.append(range(pos_relativeto_cds + len(alt_allele),
                                             pos_relativeto_cds + len(ref)))

                try:
                    mut_cds_seq = mut_cds_seq[:pos_relativeto_cds + len(alt_allele)] + \
                        mut_cds_seq[pos_relativeto_cds + len(ref):]
                except IndexError:
                    modified = False
                    break
                else:

                    modified = True

        if modified:
            if strand == -1:
                cur_pos = len(mut_cds_seq) % 3
                if cur_pos == 0:
                    initial = loc.start - 1
                elif cur_pos == 1:
                    initial = loc.start  # since there is a nt at loc.start of the cds
                else:
                    initial = loc.start + 1
                start_index, last_index = dna_seq.check_stopcodon_index_backward(
                    initial,gbk_fileSeq,geneticCodeID)

                # the +1 since from the backward the indices are 1-based rather
                # than 0-based
                lengthmodified_cds_seq = gbk_fileSeq[last_index +
                                                     1:loc.start] + mut_cds_seq

                lengthmodified_cds_seq = lengthmodified_cds_seq.reverse_complement()

            else:
                cur_pos = len(mut_cds_seq) % 3
                initial = loc.end - cur_pos
                start_index, last_index = dna_seq.check_stopcodon_index_forward(
                    initial,gbk_fileSeq,geneticCodeID)

                lengthmodified_cds_seq = mut_cds_seq + gbk_fileSeq[loc.end:last_index]

            mut_tran = str(lengthmodified_cds_seq.translate(
                table=11, to_stop=True))
            peptide_list = re.compile(".(?:(?<![KR](?!P)).)*").findall(mut_tran)

            return (protein_id, peptide_list)

        else:
            return None


# -*- coding: utf-8 -*-
from somali.utils import roles
from somali import config, log
from somali.apis import Twitch
from somali.bots import TwitchBot
import sys, os , sqlite3
from somali.database.models.channel import Channel
from somali.cogs.basics.routines.new_channels import routine

# aliases = [""]
description = "Comando para mandar o boto para canais apos reiniciar, precisa de 'nick'"
extra_checks = [roles.owner]

async def command(ctx, name: str):
    bot: TwitchBot = TwitchBot(config)
    cu = "{}"
    name = name.lower()
    id = await Twitch.account_id(name)
    # try:
    #     print("Tentando entrar")
    #     ctx.bot.add_channel(name, id)
    #     # await ctx.bot.adiciona()
    # except:
    #     print("Falhou")

    try:
        sqliteConnection = sqlite3.connect('/home/pi/Desktop/Bots/Oboto/db.sqlite3')
        cursor = sqliteConnection.cursor()
        log.info("Successfully Connected to SQLite")

        sql1 = f'''INSERT INTO "main"."user"("id", "name")VALUES ({id}, '{name}');'''
        sql2 = f'''INSERT INTO "main"."channel"("banwords", "disabled", "prefix", "user_id")VALUES ('{cu}', '{cu}', '+', '{id}');'''

        try:
            try:
                count1 = cursor.execute(sql1)
            except:
                log.info("Failed to insert data into sqlite table")

        finally:
            try:
                count1 = cursor.execute(sql2)
            except:
                log.info("Failed to insert data into sqlite table")

        sqliteConnection.commit()
        log.info("Record inserted successfully into SqliteDb_developers table ")
        cursor.close()

    except sqlite3.Error as error:
        log.info("Failed to insert data into sqlite table")
    finally:
        if sqliteConnection:
            sqliteConnection.close()
            ctx.response = f"Entrei em {name} com sucesso, agora é so reinicar."
            log.info("The SQLite connection is closed")
            log.info("Tentando reinicar")
            await ctx.bot.adiciona()


#!/home/ckdqja0225/anaconda3/bin/python3

import pandas as pd
from matplotlib import pyplot as plt
from random import shuffle
import sys
import time

class Sort() :

    def __init__(self, rangeToSort=range(1000), desc=False) :
        listToSort = [i for i in rangeToSort]
        shuffle(listToSort)
        self.originalDf = pd.DataFrame(listToSort)
        self.arrDf = self.originalDf.copy()
        self.fig = None
        self.rects = None

        if desc == True :
            self.compare = self._descending_compare
        else :
            self.compare = self._ascending_compare
        self.plot_init()

    def initialize(self) :
        self.arrDf = self.originalDf.copy()

    def _ascending_compare(self, a, b) :
        #self.plot_update()
        return a < b

    def _descending_compare(self, a, b) :
        #self.plot_update()
        return a > b

    def plot_init(self) :
        x = self.arrDf.index.values.tolist()
        y = [i[0] for i in self.arrDf.values.tolist()]
        if self.rects == None :
            self.fig = plt.figure(figsize=(24, 8))
            self.rects = plt.bar(x, y)
            plt.show(block=False)

    def plot_update(self, idx_list) :
        y = [self.arrDf.values[i][0] for i in idx_list]
        rects = [self.rects[i] for i in idx_list]
        for rect, height in zip(rects, y) :
            rect.set_height(height)
        self.fig.canvas.update()
        plt.pause(0.000001)

    def swap(self, a_idx, b_idx) :
        if a_idx == b_idx :
            return
        t_a = self.arrDf.iloc[a_idx].values[0]
        self.arrDf.iloc[a_idx] = self.arrDf.iloc[b_idx].values[0]
        self.arrDf.iloc[b_idx] = t_a
        self.plot_update([a_idx, b_idx])

class MergeSort(Sort) :

    def sort(self) :
        self._topDownMerge(0, len(self.arrDf.index.values))

    def _topDownMerge(self, start, end) :
        if end-start < 2 :
            return
        else :
            df = self.arrDf
            divider = (end-start+1)//2
            self._topDownMerge(start, start+divider)
            self._topDownMerge(start+divider, end)
            self._merge(start, start+divider, end)
            print(start, end)

    def _merge(self, start, mid, end) :
        df = self.arrDf
        tdf = self.arrDf.copy()

        a_idx = start
        b_idx = mid
        for idx in range(start, end) :
            if (not b_idx < end) or ((a_idx < mid) and self.compare(tdf.iloc[a_idx].values[0], tdf.iloc[b_idx].values[0])) :
                df.iloc[idx] = tdf.iloc[a_idx].values[0]
                a_idx += 1
            else :
                df.iloc[idx] = tdf.iloc[b_idx].values[0]
                b_idx += 1
            self.plot_update([idx])

class FuckingSlowSort(Sort) :

    def sort(self) :
        idx = 0
        size = len(self.arrDf)
        while idx+1 != size :
            t_a = self.arrDf.iloc[idx].values[0]
            t_b = self.arrDf.iloc[idx+1].values[0]
            if not self.compare(t_a, t_b) :
                self.swap(idx, idx+1)
                idx = 0
                continue
            idx += 1

class QuickSort(Sort) :

    def sort(self) :
        self._topDownQuickSort(0, len(self.arrDf.index.values))

    def _topDownQuickSort(self, start, end) :
        if end-start < 2 :
            return
        else :
            pivot_idx = end-1
            pivot_val = self.arrDf.iloc[pivot_idx].values[0]
            leftmost_idx = start
            rightmost_idx = end - 2
            while True :
                leftmost_val = self.arrDf.iloc[leftmost_idx].values[0]
                rightmost_val = self.arrDf.iloc[rightmost_idx].values[0]
                while self.compare(leftmost_val, pivot_val) :
                    leftmost_idx += 1
                    leftmost_val = self.arrDf.iloc[leftmost_idx].values[0]
                while self.compare(pivot_val, rightmost_val) and leftmost_idx < rightmost_idx:
                    rightmost_idx -= 1
                    rightmost_val = self.arrDf.iloc[rightmost_idx].values[0]
                if leftmost_idx < rightmost_idx :
                    self.swap(leftmost_idx, rightmost_idx)
                    leftmost_idx += 1
                    rightmost_idx -= 1
                    continue
                else :
                    break
            self.swap(leftmost_idx, pivot_idx)
            self._topDownQuickSort(start, leftmost_idx)
            self._topDownQuickSort(leftmost_idx+1, end)

class RadixSort(Sort) :

    def __init__(self, rangeToSort=range(1000), desc=False, base=10) :
        super(RadixSort, self).__init__(rangeToSort, desc)
        self.base = base

    def sort(self) :
        maximum_exponent = self.getMaximumExponent()
        self._radixSort(0, len(self.arrDf.index.values), maximum_exponent, current_exponent=0)

    def getMaximumExponent(self) :
        max_val = max([i[0] for i in self.arrDf.values.tolist()])
        exponent = 0
        while not max_val//(self.base**exponent) < self.base :
            exponent += 1
        return exponent

    def _radixSort(self, start, end, maximum_exponent, current_exponent) :
        base = self.base
        divider = base**current_exponent
        if current_exponent > maximum_exponent :
            return
        else :
            countList = [0]*base
            tmpList = [0]*(end-start)
            for i in range(len(tmpList)) :
                remainder = (self.arrDf.iloc[start+i].values[0] // divider) % base
                print(remainder)
                countList[remainder] += 1

            for i in range(1, base) :
                countList[i] = countList[i] + countList[i-1];

            for idx in range(end-start-1, -1, -1) :
                remainder = (self.arrDf.iloc[start+idx].values[0] // divider) % base
                tmpList[countList[remainder]-1] = self.arrDf.iloc[start+idx].values[0]
                countList[remainder] -= 1
                idx -= 1

            for i in range(len(tmpList)) :
                self.arrDf.iloc[start+i] = tmpList[i]
                self.plot_update([i])

            self._radixSort(start, end, maximum_exponent, current_exponent+1)

class HeapSort(Sort) :

    def __init__(self, rangeToSort=range(1000), desc=False) :
        super(HeapSort, self).__init__(rangeToSort, desc)
        self.heapLength = len(self.arrDf.index)

    def sort(self) :
        self.build_heap()
        for idx in range(len(self.arrDf.index)-1, -1, -1) :
            self.arrDf.iloc[idx] = self.pop()
            self.plot_update([idx])

    def build_heap(self) :
        start_idx = self.get_parent_index(self.heapLength-1)
        end_idx = -1
        for node_idx in range(start_idx, end_idx, -1) :
            self.heapify(node_idx)

    def isOutOfSize(self, node_idx) :
        return node_idx >= self.heapLength or node_idx < 0

    def heapify(self, node_idx) :
        print("heapify : " + str(node_idx))
        #parent_index = self.get_parent_index(node_idx)
        left_child_index = self.get_left_child_index(node_idx)
        right_child_index = self.get_right_child_index(node_idx)

        if self.isOutOfSize(left_child_index) or self.isOutOfSize(node_idx) :
            return
        else :
            node_val = self.get_value_with_node_idx(node_idx)
            left_child_val = self.get_value_with_node_idx(left_child_index)

            if self.isOutOfSize(right_child_index) :
                if self.compare(left_child_val, node_val) :
                    return
                else :
                    self.swap(left_child_index, node_idx)
                    self.heapify(left_child_index)
            else :
                right_child_val = self.get_value_with_node_idx(right_child_index)

                if self.compare(left_child_val, node_val) and self.compare(right_child_val, node_val) :
                    return
                else :
                    if self.compare(left_child_val, right_child_val) :
                        self.swap(right_child_index, node_idx)
                        self.heapify(right_child_index)
                    else :
                        self.swap(left_child_index, node_idx)
                        self.heapify(left_child_index)

    def push(self, value) :
        self.arrDf.iloc[self.heapLength][0] = -1
        self.increaseKey(self.heapLength, value)
        self.heapLength += 1

    def increaseKey(self, index, key) :
        if self.heapLength == 0 :
            return
        elif self.get_value_with_node_idx(index) > key :
            return
        else :
            self.arrDf.iloc[index][0] = key
            while( (not isOutOfSize(index))
                    and (not self.compare(
                        self.get_value_with_node_idx(index),
                        self.get_value_with_node_idx(self.get_parent_index(index))))) :
                self.swap(index, self.get_parent_index(index))
                index = self.get_parent_index(index)

    def pop(self) :
        retToVal = self.get_value_with_node_idx(0)
        self.arrDf.iloc[0][0] = self.arrDf.iloc[self.heapLength-1][0]
        self.heapify(0)
        self.heapLength -= 1
        return retToVal

    def get_left_child_index(self, idx) :
        return (idx+1)*2-1

    def get_right_child_index(self, idx) :
        return (idx+1)*2

    def get_parent_index(self, idx) :
        return (idx+1)//2-1

    def get_value_with_node_idx(self, node_idx) :
        return self.arrDf.values[node_idx][0]

if __name__ == "__main__" :
    sys.setrecursionlimit(100000)
    sorter = RadixSort(range(100), desc=False, base=7)
    #sorter = MergeSort(range(300), desc=False)
    #sorter = QuickSort(range(300), desc=False)
    #sorter = HeapSort(range(20), desc=False)
    sorter.sort()


# coding=utf-8

from wikilife_processors.processors.stats.was.factors.factors_model import \
    AgeFactor
from wikilife_processors.tests.base_test import BaseTest

class AgeFactorTests(BaseTest):

    def test_process_value(self):
        factor = AgeFactor(values=[
                {"id": "lt18", "name": "less than 18", "min": 0, "max": 18},
                {"id": "18-100", "name": "18 to 100", "min": 18, "max": 100},
                {"id": "gt100", "name": "more than 100", "min": 100, "max": None}
            ])

        raw_value = "1980-01-30"
        value = factor.process_value(raw_value)

        assert value == 33


from celery_sqlalchemy.model import sqlalchemy_1_4

from celery_sqlalchemy.schema import TypeMap

# system imports
from typing import Any
from typing import List

# dependency imports
from pytest import mark

from sqlalchemy.sql import sqltypes

@mark.parametrize(
    "type",
    [
        [sqltypes.ARRAY, "array_from_json", "array_params", "array_to_json"],
        [
            sqltypes.BigInteger,
            "biginteger_from_json",
            "biginteger_params",
            "biginteger_to_json",
        ],
        [sqltypes.Boolean, "boolean_from_json", "boolean_params", "boolean_to_json"],
        [sqltypes.Date, "date_from_json", "date_params", "date_to_json"],
        [
            sqltypes.DateTime,
            "datetime_from_json",
            "datetime_params",
            "datetime_to_json",
        ],
        [sqltypes.Enum, "enum_from_json", "enum_params", "enum_to_json"],
        [sqltypes.Float, "float_from_json", "float_params", "float_to_json"],
        [sqltypes.Integer, "integer_from_json", "integer_params", "integer_to_json"],
        [
            sqltypes.Interval,
            "interval_from_json",
            "interval_params",
            "interval_to_json",
        ],
        [
            sqltypes.LargeBinary,
            "largebinary_from_json",
            "largebinary_params",
            "largebinary_to_json",
        ],
        [sqltypes.JSON, "json_from_json", "json_params", "json_to_json"],
        [sqltypes.Numeric, "numeric_from_json", "numeric_params", "numeric_to_json"],
        [
            sqltypes.SmallInteger,
            "smallinteger_from_json",
            "smallinteger_params",
            "smallinteger_to_json",
        ],
        [sqltypes.String, "string_from_json", "string_params", "string_to_json"],
        [sqltypes.Text, "text_from_json", "text_params", "text_to_json"],
        [sqltypes.Time, "time_from_json", "time_params", "time_to_json"],
        [sqltypes.Unicode, "unicode_from_json", "unicode_params", "unicode_to_json"],
        [
            sqltypes.UnicodeText,
            "unicodetext_from_json",
            "unicodetext_params",
            "unicodetext_to_json",
        ],
    ],
)
def test_type_maps(type: List[Any]) -> None:
    assert sqlalchemy_1_4.type_maps[type[0]] == TypeMap(
        from_json=type[1], params=type[2], to_json=type[3]
    )


# -*- coding: utf-8 -*-
"""
Created on Wed Nov 23 16:42:35 2022

@author: jonpr
"""

# Regional social care use: England
import os
os.chdir(r"C:\Users\jonpr\Documents\Data projects\Python\FrontDoor")
path = os.getcwd()

import pandas as pd
import plotly.express as px
from plotly.offline import plot
import json

# Load SALT/ASCFR dataset 2016-2021
df = pd.read_csv(os.path.join(path, 'LA_dataset.csv'))

# Specify age range: either 18-64 or over 65
Age = '65' # '18_64' or '65'

# Specify variables of interest
AccessOptions = ['DischargefromHospital_'+Age,'Diversion_hosp_serv_'+Age,'self_deplet_funds_'+Age,'depl_fund_DP_'+Age, 'CommunityOtherRoute_'+Age,'Prison_'+Age]
DestinationOptions = ['ShortTermCaretomaximiseind_'+Age,'LongTermCareNursing_'+Age,'LongTermCareResidential_'+Age,'LongTermCareCommunity_'+Age,'LongTermCarePrison_'+Age,
                      'NHSFundedCare_'+Age,'EndofLife_'+Age,'OngoingLowLevelSupport_'+Age,'ShortTermCareothershortter_'+Age,'UniversalServicesSignpostedt_'+Age,
                      'NoServicesProvidedDeceased_'+Age,'NoServicesProvided_'+Age]
CareVs = ['ShortTermCaretomaximiseind_'+Age,'ShortTermCareothershortter_'+Age,'EndofLife_'+Age,'LongTermCareNursing_'+Age,'LongTermCareResidential_'+Age,'LongTermCareCommunity_'+Age,'LongTermCarePrison_'+Age,'NHSFundedCare_'+Age,'OngoingLowLevelSupport_'+Age]
NoCareVs = ['NoServicesProvided_'+Age,'NoServicesProvidedDeceased_'+Age,'UniversalServicesSignpostedt_'+Age]
STCareVs = ['ShortTermCaretomaximiseind_'+Age,'ShortTermCareothershortter_'+Age,'EndofLife_'+Age]
LTCareVs = ['LongTermCareNursing_'+Age,'LongTermCareResidential_'+Age,'LongTermCareCommunity_'+Age,'LongTermCarePrison_'+Age,'NHSFundedCare_'+Age,'OngoingLowLevelSupport_'+Age]
RegionalID = ['Geography_code','LAname']

# Convert social care access and destination variables to % of population
acc_df = pd.DataFrame()
acc_df[AccessOptions] = df[AccessOptions].apply(lambda x: x/df['Population_'+Age]*100)
acc_df = pd.concat([df[RegionalID],df['year'].astype(int), acc_df[AccessOptions]], axis=1)

dest_df = pd.DataFrame()
dest_df[DestinationOptions] = df[DestinationOptions].apply(lambda x: x/df['Population_'+Age]*100)
dest_df = pd.concat([df[RegionalID],df['year'].astype(int), dest_df[DestinationOptions]], axis=1)

# Drop 2016 due to missing population data
acc_df, dest_df = acc_df[acc_df['year'] != 2016], dest_df[dest_df['year'] != 2016]

# Create dataframe of totals
ScTotals = pd.concat([acc_df.iloc[:,:3],acc_df[AccessOptions].sum(axis=1, skipna=True), dest_df[DestinationOptions].sum(axis=1, skipna=True)], axis=1)
ScTotals.columns = ['AreaCD','AreaNM','Year','Access_rate','Destination_rate']
ScTotals['Care_rate'] = dest_df[CareVs].sum(axis=1, skipna=True)
ScTotals['NoCare_rate'] = dest_df[NoCareVs].sum(axis=1, skipna=True)
ScTotals['STCare_rate'] = dest_df[STCareVs].sum(axis=1, skipna=True)
ScTotals['LTCare_rate'] = dest_df[LTCareVs].sum(axis=1, skipna=True)
ScTotals['AC_Disparity'] = ScTotals['Care_rate'] - ScTotals['Access_rate']

# Take the mean across time within each region
ScTotals_by_region = ScTotals.groupby(['AreaCD','AreaNM']).mean().reset_index().drop('Year', axis=1)

# Load geoJSON file from ONS
with open(os.path.join(path, 'Counties_and_Unitary_Authorities_2015.geojson')) as fp:
    GeoData = json.load(fp)

# Plot social care data as map
def ukPlot(dataset, variable, label):
    fig = px.choropleth_mapbox(dataset, locations="AreaNM", featureidkey="properties.ctyua15nm", geojson=GeoData,
                               color=variable, hover_name="AreaNM", mapbox_style="carto-positron", zoom=4,
                               center = {"lat": 55, "lon": 0}, labels={variable:label})
    return fig

disparity_map = ukPlot(ScTotals_by_region,'AC_Disparity','Disparity (%)')
plot(disparity_map)


#!/usr/bin/python3

import glob
#import _thread
import subprocess

def format(filename):
    subprocess.run(['clang-format', '-style=file', '-i', filename, '&'], stdout=subprocess.PIPE)

for filename in glob.iglob('./**/*.cpp', recursive=True):
    print(filename)
    format(filename)

for filename in glob.iglob('./**/*.h', recursive=True):
    print(filename)
    format(filename)

print('done')
exit(0)


# This library is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, see
# <http://www.gnu.org/licenses/>.

"""
unit tests for creating/modifying JAR files with python-javatools.

author: Konstantin Shemyak  <konstantin@shemyak.com>
license: LGPL v.3
"""

import os
from unittest import TestCase
from . import get_data_fn
from javatools.jardiff import cli_jars_diff, main

class OptionsHolder(object):
    pass

class JardiffTest(TestCase):

    options = OptionsHolder()

    def cli_jardiff_wrap(self, expected, left, right, message):
            self.assertEqual(expected, cli_jars_diff(self.options,
                get_data_fn(left),
                get_data_fn(right)),
                message)

    options.silent = True
    options.ignore_jar_signature = False

    # Two identical JARs (in different files, just in case)
    def test_identical_jars(self):
        self.cli_jardiff_wrap(0, "test_jardiff/ec.jar", "test_jardiff/ec-copied.jar",
            "Identical JARs reported as different")

    def test_sig_block_file_tampered(self):
        self.cli_jardiff_wrap(1, "test_jardiff/ec.jar", "test_jardiff/ec-tampered.jar",
            "Change in signature block file is not detected")

    def test_sig_block_file_removed(self):
        self.cli_jardiff_wrap(1, "test_jardiff/ec.jar", "test_jardiff/ec-sig-block-removed.jar",
            "Removal of signature block file is not detected")

    def test_sig_manifest_tampered(self):
        self.cli_jardiff_wrap(1, "test_jardiff/ec.jar", "test_jardiff/ec-sig-mf-tampered.jar",
            "Change in manifest signature file is not detected")

    def test_generic_file_change(self):
        self.options.ignore_jar_entry = []  # Needed, as argparse is not called
        self.cli_jardiff_wrap(1, os.path.join("test_jardiff", "generic1.jar"),
            os.path.join("test_jardiff", "generic2.jar"),
            "Change in generic file is not detected")

    def test_json_binary_diff(self):
        left = get_data_fn(os.path.join("test_jardiff", "ec.jar"))
        right = get_data_fn(os.path.join("test_jardiff", "ec-tampered.jar"))
        self.assertEqual(1, main(["argv0", "--json", left, right]))

    # Options from relevant option groups are accepted:
    def test_options_accepted(self):
        left = get_data_fn(os.path.join("test_jardiff", "ec.jar"))
        right = get_data_fn(os.path.join("test_jardiff", "ec-tampered.jar"))
        # General options:
        self.assertEqual(1, main(["argv0", "-q", left, right]))
        # JAR checking options:
        self.assertEqual(0, main(["argv0", "--ignore-jar-signature", left, right]))
        # Class checking options:
        self.assertEqual(1, main(["argv0", "--ignore-platform-up", left, right]))
        # Reporting options:
        self.assertEqual(1, main(["argv0", "--report-dir=foo", left, right]))
        # JSON reporting options:
        self.assertEqual(1, main(["argv0", "--json", "--json-indent=4", left, right]))
        # HTML reporting options:
        self.assertEqual(1, main(["argv0", "--html-copy-data=foo", left, right]))

#
# The end.


import numpy as np
import polars as pl

def resample_numeric_df(df: pl.DataFrame, timestamp_col: str, new_frequency: float,
                        start_ts: int = None, end_ts: int = None, force_ts_dtype: bool = True) -> pl.DataFrame:
    """
    Resample a DF by linear interpolation.

    Args:
        df: input DF
        timestamp_col: timestamp column name in the DF
        new_frequency: new frequency to interpolate, this must be of the same unit as timestamps;
            example: timestamp unit is millisecond, frequency unit must be sample/millisecond
        start_ts: new start ts for interpolated DF; default: use the old one
        end_ts: new end ts for interpolated DF; default: use the old one
        force_ts_dtype: convert dtype of new timestamps to the same as old timestamps

    Returns:
        new dataframe
    """
    # get new timestamp array (unit: msec)
    if start_ts is None:
        start_ts = df.item(0, timestamp_col)
    if end_ts is None:
        end_ts = df.item(-1, timestamp_col)
    new_ts = np.arange(np.floor((end_ts - start_ts) * new_frequency + 1)) / new_frequency + start_ts
    if force_ts_dtype:
        new_ts = new_ts.astype(type(start_ts))

    # get data columns
    cols_except_ts = df.columns.copy()
    cols_except_ts.remove(timestamp_col)
    df_value = df.select(cols_except_ts).to_numpy()
    df_timestamp = df.select(timestamp_col).to_numpy().squeeze()

    # interpolate columns
    new_df = {timestamp_col: new_ts}
    for i, col in enumerate(cols_except_ts):
        new_df[col] = np.interp(x=new_ts, xp=df_timestamp, fp=df_value[:, i])

    new_df = pl.DataFrame(new_df).set_sorted(timestamp_col)
    return new_df


'''
    Power Macintosh ROM disassembler.

    Author: Max Poliakovski 2020-2021

    Usage:
    python3 PowerRomDasm.py --rom_path=[path to a Power Macintosh ROM dump]
'''
from argparse import ArgumentParser
from ruamel.yaml import YAML

from capstone import *
from capstone.m68k import *

import os
import struct

def bit_not(n, numbits=32):
    return (1 << numbits) - 1 - n

def align(n, m):
    return (n + m - 1) & bit_not(m - 1)

''' Capstone-based disassembler for 68k code.'''
class M68KDasm:
    def __init__(self, cb):
        self.rom_cb = cb
        self.cse = Cs(CS_ARCH_M68K, CS_MODE_M68K_040)
        self.cse.detail = True
        self.labels = {}

    def dasm_single(self, address, code):
        ''' Disassble single 68k instruction with the Capstone engine. '''

        # detect A-Traps and disassemble them ourselves
        if (code[0] & 0xF0) == 0xA0:
            from mactraps import TRAP_TABLE

            trap_num = (code[0] << 8) | code[1]
            if trap_num in TRAP_TABLE:
                return ((TRAP_TABLE[trap_num], [], 2))
            else:
                return (('dc.w', [hex(trap_num)], 2))

        # disassemble non-trap instructions with Capstone
        instrs = self.cse.disasm(code, address)
        return next(instrs)

    def dasm_region(self, addr, size, data):
        pp_dasm = []
        last_addr = addr + size
        offset = 0

        while addr < last_addr:
            # prefetch binary data (2 >= bytes <= 10) for the next instruction
            bin_length = min(last_addr - addr, 10)
            bin_prefetch = bytearray()
            for i in range(bin_length):
                bin_prefetch.append(data[offset+i])

            instr = self.dasm_single(addr, bin_prefetch)

            if not isinstance(instr, CsInsn):
                pp_dasm.append({'addr': addr, 'mnem': instr[0], 'ops': instr[1]})
                addr += instr[2]
                offset += instr[2]
                continue

            op_list = instr.op_str.split(',')
            #print(op_list)
            ops = []
            for op in instr.operands:
                #print(op.type)
                if op.type == M68K_OP_MEM:
                    #print(op.address_mode)
                    if op.address_mode == M68K_AM_PCI_DISP:
                        ea = addr + op.mem.disp + 2
                        flag,sym = self.rom_cb.get_symbol(ea)
                        if flag:
                            ops.append(sym)
                        else:
                            label = 'l_{:x}'.format(ea)
                            ops.append(label)
                            if ea not in self.labels:
                                self.labels[ea] = label
                        # discard current op because we've just replaced it
                        op_list.pop(0)
                    elif op.address_mode == M68K_AM_PCI_INDEX_BASE_DISP:
                        ops.append(instr.op_str)
                    else:
                        ops.append(op_list.pop(0))
                elif op.type == M68K_OP_BR_DISP:
                    if op.address_mode == M68K_AM_BRANCH_DISPLACEMENT:
                        ea = addr + op.br_disp.disp + 2
                        flag,sym = self.rom_cb.get_symbol(ea)
                        if flag:
                            ops.append(sym)
                        else:
                            label = 'l_{:x}'.format(ea)
                            ops.append(label)
                            if ea not in self.labels:
                                self.labels[ea] = label
                        # discard current op because we've just replaced it
                        op_list.pop(0)
                    else:
                        ops.append(op_list.pop(0))
                else:
                    ops.append(op_list.pop(0))
            pp_dasm.append({'addr': addr, 'mnem': instr.mnemonic, 'ops': ops})
            addr += instr.size
            offset += instr.size
            #print(ops)
            #print(self.labels)
        for instr in pp_dasm:
            if instr['addr'] in self.labels:
                print('\n' + self.labels[instr['addr']] + ':')
            print(hex(instr['addr']).ljust(15), end='')
            print(instr['mnem'], '\t', end='')
            print(','.join(instr['ops']))

class ROMDisassembler:
    def __init__(self, rom_data, rom_db):
        self.rom_data = rom_data
        self.rom_db = rom_db
        self.start_addr = rom_db['main_info']['phys_addr']
        self.m68k_dasm = M68KDasm(self)

    def get_symbol(self, addr):
        offset = addr - self.start_addr
        if offset in self.rom_db['annot_items']:
            return (True, self.rom_db['annot_items'][offset]['label'])
        else:
            return (False, '')

    def fmt_single_entry(self, format, size, offset):
        print(hex(self.start_addr + offset).ljust(15), end='')
        if format == 'hex':
            if size == 1:
                print("dc.b\t0x%X" % struct.unpack('>B', self.rom_data[offset:offset+1]))
            elif size == 2:
                print("dc.w\t0x%X" % struct.unpack('>H', self.rom_data[offset:offset+2]))
            elif size == 4:
                print("dc.l\t0x%X" % struct.unpack('>I', self.rom_data[offset:offset+4]))
            else:
                print("INVALID SIZE!")
        elif format == 'dec':
            if size == 1:
                print("dc.b\t%d" % struct.unpack('>B', self.rom_data[offset:offset+1]))
            elif size == 2:
                print("dc.w\t%d" % struct.unpack('>H', self.rom_data[offset:offset+2]))
            elif size == 4:
                print("dc.l\t%d" % struct.unpack('>I', self.rom_data[offset:offset+4]))
            else:
                print("INVALID SIZE!")
        elif format == 'offset':
            dest_offset = struct.unpack('>I', self.rom_data[offset:offset+4])[0]
            if dest_offset in self.rom_db['annot_items']:
                symbol = self.rom_db['annot_items'][dest_offset]['label']
                print("dc.l\t" + symbol + '-BaseOfRom')
            else:
                print("dc.l\t0x%X" % dest_offset)

    def dasm_regions(self, start_addr, size, data, regions):
        self.labels = {}
        for reg in regions:
            if reg[2] == 'align':
                print(hex(start_addr + reg[0]).ljust(15), end='')
                print('align\t' + str(reg[3]))
            elif reg[2] == 'code':
                reg_size = reg[1] - reg[0] + 1
                self.m68k_dasm.dasm_region(start_addr + reg[0], reg_size,
                    data[reg[3]:reg[3]+reg_size])
            elif reg[2] == 'int':
                print("")
                print((reg[1] + ':').ljust(15))
                self.fmt_single_entry(reg[3], reg[4], reg[0])
            else:
                print("Unknown region type " + reg[2])

    def parse_subregs(self, start, size, subregs):
        #print("This entry has subregions", subregs)
        regs = []
        reg_start = start
        for reg in subregs:
            if reg['type'] == 'align':
                offset = reg['offset']
                if offset < reg_start or offset >= (start + size):
                    print("Invalid subregion offset: 0x%X" % offset)
                    return regs
                regs.append((reg_start, offset - 1, 'code', reg_start - start))
                boundary = reg['boundary']
                reg_end = align(offset, boundary)
                regs.append((offset, reg_end - 1, 'align', boundary))
                reg_start = reg_end
                print("reg_start=%d" % reg_start)
            elif reg['type'] == 'int':
                offset = reg['offset']
                if offset < reg_start or offset >= (start + size):
                    print("Invalid subregion offset: 0x%X" % offset)
                    return regs
                regs.append((reg_start, offset - 1, 'code', reg_start - start))
                reg_size = reg['size']
                if 'label' in reg:
                    label = reg['label']
                else:
                    label = 'l_{:x}'.format(self.start_addr + offset)
                self.m68k_dasm.labels[self.start_addr + offset] = label
                regs.append((offset, label, 'int', reg['format'], reg_size))
                reg_start = offset + reg_size
            else:
                print("Unknown subregion type " + reg['type'])
                return regs
        if reg_start < (start + size):
            regs.append((reg_start, (start + size) - 1, 'code', reg_start - start))
        #print(regs)
        return regs

    def fmt_array(self, entry, offset):
        count = entry['size'] // entry['elsize']
        for i in range(count):
            self.fmt_single_entry(entry['format'], entry['elsize'], offset)
            offset += entry['elsize']

    def parse_struct(self, fields, offset):
        size_acc = 0
        for field in fields:
            if field['type'] == 'int':
                self.fmt_single_entry(field['format'], field['size'], offset)
            elif field['type'] == 'array':
                self.fmt_array(field, offset)
            else:
                print("Unknown struct field type %s" % field['type'])
            offset += field['size']
            size_acc += field['size']
        return size_acc

    def fmt_entry(self, entry, offset):
        print("")

        if entry['type'] == 'align':
            start = offset
            end   = align(start, entry['boundary'])
            print(hex(self.start_addr + start).ljust(15), end='')
            print('align\t' + str(entry['boundary']))
            return end - start

        print((entry['label'] + ':').ljust(15))

        if entry['type'] == 'array':
            self.fmt_array(entry, offset)
        elif entry['type'] == 'int':
            self.fmt_single_entry(entry['format'], entry['size'], offset)
        elif entry['type'] == 'code':
            size = entry['size']
            if entry['arch'] == '68k':
                if 'subregs' in entry:
                    regs = self.parse_subregs(offset, size, entry['subregs'])
                else:
                    regs = [(offset, offset + size - 1, 'code', 0)]
                self.dasm_regions(self.start_addr, size, self.rom_data[offset:offset+size], regs)
            elif entry['arch'] == 'ppc':
                print("PPC disassembler not implemented yet")
            else:
                print("Unknown code region architecture " + entry['arch'])
        elif entry['type'] == 'fixlenstr': # fixed-length string
            print(hex(self.start_addr + offset).ljust(15), end='')
            str_len = entry['size']
            fmt_str = '%is' % str_len
            print('"%s"' % struct.unpack(fmt_str, self.rom_data[offset:offset+str_len])[0].decode('mac_roman'))
        elif entry['type'] == 'struct':
            return self.parse_struct(entry['fields'], offset)

        return entry['size']

    def dasm_region(self, start, end):
        offset = start
        while offset < end:
            if offset in self.rom_db['annot_items']:
                entry = self.rom_db['annot_items'][offset]
                size = self.fmt_entry(entry, offset)
                offset += size
            else:
                print(hex(self.start_addr + offset).ljust(15), end='')
                print("dc.b\t0x%X" % struct.unpack('>B', self.rom_data[offset:offset+1]))
                offset += 1

if __name__ == "__main__":
    parser = ArgumentParser()
    parser.add_argument('--rom_path', type=str,
                        dest='rom_path',
                        help='path to a PowerMacintosh ROM file to process',
                        metavar='ROM_PATH', required=True)
    parser.add_argument('--start', type=lambda x: int(x,0),
                        dest='start_offs', default=0,
                        help='offset to the start of the region to disassemble',
                        required=False,
                        )
    parser.add_argument('--end', type=lambda x: int(x,0),
                        dest='end_offs', default=0x500,
                        help='offset to the end of the region to disassemble',
                        required=False,
                        )

    opts = parser.parse_args()

    with open(opts.rom_path, 'rb') as rom_file:
        rom_file.seek(0, 2)
        rom_size = rom_file.tell()
        if rom_size != (4 * 1024 * 1024):
            print("Invalid ROM file size %d (expected 4 MB)" % rom_size)

        # just load the whole ROM image into memory
        rom_file.seek(0, 0)
        rom_data = rom_file.read()

        check_sum = struct.unpack('>I', rom_data[0:4])[0]
        print("ROM Checksum: %X" % check_sum)

        my_path = os.path.dirname(os.path.realpath(__file__))

        db_name = 'ROMDB_' + '{:x}'.format(int(check_sum)).upper() + '.yaml'

        with open(my_path + '/database/' + db_name, 'rb') as db_file:
            yaml = YAML()
            annot_db = yaml.load(db_file)

            print(annot_db['main_info']['name'])

            rdasm = ROMDisassembler(rom_data, annot_db)
            rdasm.dasm_region(opts.start_offs, opts.end_offs)


##{u'username': u'Merdamerdabot', u'first_name': u'Merdabot', u'id': 305298639}
#!-*- conding: utf8 -*-

# Usando getUpdates():
#formato do update: vem uma lista em que cada elemento e um dicionario correspondendo a uma mensagem
#cada mensagem e um dicionario com apenas duas chaves: 'message' e 'update_id'
#estranhamente, u'message' e uma forma de escrever 'message'
#coisas que podem ser interessantesdentro de 'message': 'text' e o texto da mensagem; 'chat' e um dicionario com informacoes sobre a conversa  e 'from' e um dicionario indicando o remetente da mensagem

# Usando message_loop e handle:
#recebe-se direto o dicionario associado a chave 'message'

import telepot
boto=telepot.Bot("278859188:AAEIrp4ydKGe9AQWy59fbCRLsnpw6mQUFN8")
boto.getMe()

def contagem_incremento(addr, chat_id, incrementa):

    dados=open(addr,'r').readlines()
    try:
        i=dados.index(str(chat_id)+"\n")
        count=int(dados[i+1])
    except ValueError:
        i=len(dados)
        dados+=[str(chat_id)+"\n",0]
        count=0
    if incrementa:
        count+=1
        dados[i+1]=str(count)+"\n"
        escritor=open(addr,'w')
        for elem in dados:
            escritor.write(str(elem))
        escritor.close()
    return count

def handle(update):
    registro=open('log.txt','a')
    registro.write(str(update)+'\n')
    registro.close()
    texto=update['text']
    chat_id=update['chat']['id']
    if texto=="/merda" or texto=="/merda@Merdamerdabot":
        contagem=contagem_incremento("estatisticas.txt",chat_id, True)
        boto.sendMessage(chat_id,"merda\n"*contagem)
    elif texto=="/stat" or texto=="/stat@Merdamerdabot":
        contagem=contagem_incremento("estatisticas.txt",chat_id,False)
        if update['chat']['type']=='group':
            mensagem="Fui chamado "+str(contagem)+" vezes no grupo "+update['chat']['title']+".\n"+update['from']['first_name']+", seu merda!"
        else:
            mensagem="Fui chamado "+str(contagem)+" vezes no privado por "+update['chat']['first_name']+" "+update['chat']['last_name']+".\n"+update['from']['first_name']+", seu merda!"
        boto.sendMessage(chat_id,mensagem)
    elif texto=="/melda" or texto=="/melda@Merdamerdabot":
        boto.sendMessage(chat_id, "chola mais")

boto.message_loop(handle,0.1,20,None,None,True,20,True)
#KeyboardInterrupt nao funciona
#run_forever e necessario pra rodar fora do IDLE


from setuptools import setup

package_name = 'trajectory_gen_mpc'

setup(
    name=package_name,
    version='0.0.0',
    packages=[package_name],
    data_files=[
        ('share/ament_index/resource_index/packages',
            ['resource/' + package_name]),
        ('share/' + package_name, ['package.xml']),
    ],
    install_requires=['setuptools'],
    zip_safe=True,
    maintainer='krishna',
    maintainer_email='krishna-satish.deshkulkarni-shankaranarayana@altran.com',
    description='TODO: Package description',
    license='TODO: License declaration',
    tests_require=['pytest'],
    entry_points={
        'console_scripts': [
            "trajectory_gen_mpc = trajectory_gen_mpc.main:main",
            "TrajectoryServer = trajectory_gen_mpc.TrajectoryGenServer:main",
            "CarlaClient = trajectory_gen_mpc.CarlaClient:main",
            "CarlaNode =trajectory_gen_mpc.CarlaNode:main",
            "TrajectorNode = trajectory_gen_mpc.TrajectorGenMpcNode:main"
        ],
    },
)


from os.path import join

from pythonforandroid.recipe import Recipe
from pythonforandroid.util import current_directory
from pythonforandroid.logger import shprint
import sh

class OpenSSLRecipe(Recipe):
    '''
    The OpenSSL libraries for python-for-android. This recipe will generate the
    following libraries as shared libraries (*.so):

        - crypto
        - ssl

    The generated openssl libraries are versioned, where the version is the
    recipe attribute :attr:`version` e.g.: ``libcrypto1.1.so``,
    ``libssl1.1.so``...so...to link your recipe with the openssl libs,
    remember to add the version at the end, e.g.:
    ``-lcrypto1.1 -lssl1.1``. Or better, you could do it dynamically
    using the methods: :meth:`include_flags`, :meth:`link_dirs_flags` and
    :meth:`link_libs_flags`.

    .. warning:: This recipe is very sensitive because is used for our core
        recipes, the python recipes. The used API should match with the one
        used in our python build, otherwise we will be unable to build the
        _ssl.so python module.

    .. versionchanged:: 0.6.0

        - The gcc compiler has been deprecated in favour of clang and libraries
          updated to version 1.1.1 (LTS - supported until 11th September 2023)
        - Added two new methods to make easier to link with openssl:
          :meth:`include_flags` and :meth:`link_flags`
        - subclassed versioned_url
        - Adapted method :meth:`select_build_arch` to API 21+
        - Add ability to build a legacy version of the openssl libs when using
          python2legacy or python3crystax.

    .. versionchanged:: 2019.06.06.1.dev0

        - Removed legacy version of openssl libraries

    '''

    version = '1.1'
    '''the major minor version used to link our recipes'''

    url_version = '1.1.1m'
    '''the version used to download our libraries'''

    url = 'https://www.openssl.org/source/openssl-{url_version}.tar.gz'

    built_libraries = {
        'libcrypto{version}.so'.format(version=version): '.',
        'libssl{version}.so'.format(version=version): '.',
    }

    @property
    def versioned_url(self):
        if self.url is None:
            return None
        return self.url.format(url_version=self.url_version)

    def get_build_dir(self, arch):
        return join(
            self.get_build_container_dir(arch), self.name + self.version
        )

    def include_flags(self, arch):
        '''Returns a string with the include folders'''
        openssl_includes = join(self.get_build_dir(arch.arch), 'include')
        return (' -I' + openssl_includes +
                ' -I' + join(openssl_includes, 'internal') +
                ' -I' + join(openssl_includes, 'openssl'))

    def link_dirs_flags(self, arch):
        '''Returns a string with the appropriate `-L<lib directory>` to link
        with the openssl libs. This string is usually added to the environment
        variable `LDFLAGS`'''
        return ' -L' + self.get_build_dir(arch.arch)

    def link_libs_flags(self):
        '''Returns a string with the appropriate `-l<lib>` flags to link with
        the openssl libs. This string is usually added to the environment
        variable `LIBS`'''
        return ' -lcrypto{version} -lssl{version}'.format(version=self.version)

    def link_flags(self, arch):
        '''Returns a string with the flags to link with the openssl libraries
        in the format: `-L<lib directory> -l<lib>`'''
        return self.link_dirs_flags(arch) + self.link_libs_flags()

    def get_recipe_env(self, arch=None):
        env = super().get_recipe_env(arch)
        env['OPENSSL_VERSION'] = self.version
        env['MAKE'] = 'make'  # This removes the '-j5', which isn't safe
        env['CC'] = 'clang'
        env['ANDROID_NDK_HOME'] = self.ctx.ndk_dir
        return env

    def select_build_arch(self, arch):
        aname = arch.arch
        if 'arm64' in aname:
            return 'android-arm64'
        if 'v7a' in aname:
            return 'android-arm'
        if 'arm' in aname:
            return 'android'
        if 'x86_64' in aname:
            return 'android-x86_64'
        if 'x86' in aname:
            return 'android-x86'
        return 'linux-armv4'

    def build_arch(self, arch):
        env = self.get_recipe_env(arch)
        with current_directory(self.get_build_dir(arch.arch)):
            # sh fails with code 255 trying to execute ./Configure
            # so instead we manually run perl passing in Configure
            perl = sh.Command('perl')
            buildarch = self.select_build_arch(arch)
            config_args = [
                'shared',
                'no-dso',
                'no-asm',
                buildarch,
                '-D__ANDROID_API__={}'.format(self.ctx.ndk_api),
            ]
            shprint(perl, 'Configure', *config_args, _env=env)
            self.apply_patch('disable-sover.patch', arch.arch)

            shprint(sh.make, 'build_libs', _env=env)

recipe = OpenSSLRecipe()


scores = {
    "panner": 34,
    "abd":54,
    "har":99,
    "tej":91,
    "khushi":89
}

grades = {}

for i in scores:
    marks = scores[i]

    if marks > 90:
        grades[i] = "Outstanding"
    elif marks > 80:
        grades[i] = "Exceeds Expectations"
    elif marks>70:
        grades[i] = "Acceptable"
    else:
        grades[i] = 'Fail'

print (grades)


from django.urls import path
from django.views.decorators.csrf import csrf_exempt
from .views import (
                    VideoLectureView,
                    VideoLectureNew,
                    VideoLectureUserView,
                    VideoLectureEdit
)

urlpatterns = [
    path('video/create/', VideoLectureNew.as_view(), name="create-video"),
    path('video/<int:vid_lec_id>/', VideoLectureView.as_view(), name="video-lecture"),
    path('videos/user', VideoLectureUserView.as_view(), name="user-videos"),
    path('video/update/<int:pk>/', VideoLectureEdit.as_view(), name="edit-video"),

]


def myBMI(weight, height):
    bmi = (weight * 703) / (height*height)
    if bmi < 18.5:
        print('Underweight')
    elif bmi >=18.5 and bmi <=25:
        print('Normal')
    elif bmi > 25:
        print('Overweight')

myBMI(190,75)
myBMI(140,75)


import unittest
from unittest.mock import Mock, patch
from nifty.common import context

class TestContext(unittest.TestCase):
    def setUp(self) -> None:
        patcher = patch("builtins.print")
        self.mock_print = patcher.start()
        self.addCleanup(patcher.stop)

    def tearDown(self) -> None:
        self.mock_print = None

    @patch.dict("os.environ", {"APP_CONTEXT_CFG": "NIFTY", "PRIMARY_CFG": "LOCAL"})
    def test_get(self):
        actual = context.get()
        self.assertEqual(
            actual,
            context.AppContext(
                app_name=context.AppContextName.nifty, primary_cfg="local"
            ),
        )

    @patch.dict("os.environ", {"APP_CONTEXT_CFG": "NIFTY"})
    def test_get_no_primary(self):
        actual = context.get()
        self.assertEqual(
            actual, context.AppContext(app_name=context.AppContextName.nifty)
        )

    @patch.dict("os.environ", {"APP_CONTEXT_CFG": "FOO"})
    def test_get_bad_app(self):
        with self.assertRaises(Exception):
            context.get()

    @patch.dict("os.environ", {})
    def test_get_no_app(self):
        with self.assertRaises(Exception):
            context.get()


import sys, os, tempfile, atexit
from subprocess import PIPE, run

print(f"testing exr2aces: {sys.argv}")

exr2aces = sys.argv[1]
exrinfo = sys.argv[2]
image_dir = sys.argv[3]
version = sys.argv[4]

# no args = usage message, error
result = run ([exr2aces], stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(" ".join(result.args))
assert(result.returncode != 0), "\n"+result.stderr
assert(result.stderr.startswith ("Usage: ")), "\n"+result.stderr

# -h = usage message
result = run ([exr2aces, "-h"], stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(" ".join(result.args))
assert(result.returncode == 0), "\n"+result.stderr
assert(result.stdout.startswith ("Usage: ")), "\n"+result.stdout

result = run ([exr2aces, "--help"], stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(" ".join(result.args))
assert(result.returncode == 0), "\n"+result.stderr
assert(result.stdout.startswith ("Usage: ")), "\n"+result.stdout

# --version
result = run ([exr2aces, "--version"], stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(" ".join(result.args))
assert(result.returncode == 0), "\n"+result.stderr
assert(result.stdout.startswith ("exr2aces")), "\n"+result.stdout
assert(version in result.stdout), "\n"+result.stdout

# invalid arguments
result = run ([exr2aces, "foo.exr", "bar.exr"], stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(" ".join(result.args))
assert(result.returncode != 0), "\n"+result.stderr

def find_line(keyword, lines):
    for line in lines:
        if line.startswith(keyword):
            return line
    return None

fd, outimage = tempfile.mkstemp(".exr")
os.close(fd)

def cleanup():
    print(f"deleting {outimage}")
atexit.register(cleanup)

image = f"{image_dir}/TestImages/GrayRampsHorizontal.exr"
result = run ([exr2aces, "-v", image, outimage], stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(" ".join(result.args))
assert(result.returncode == 0), "\n"+result.stderr

result = run ([exrinfo, "-v", outimage], stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(" ".join(result.args))
assert(result.returncode == 0), "\n"+result.stderr

# confirm the output has the proper chromaticities
assert("chromaticities: chromaticities r[0.7347, 0.2653] g[0, 1] b[0.0001, -0.077] w[0.32168, 0.33767]" in result.stdout), "\n"+result.stdout

print("success")


from primaires.interpreteur.commande.commande import Commande
from primaires.objet.conteneur import SurPoids

class CmdBander(Commande):

    """Commande 'bander'.

    """

    def __init__(self):
        """Constructeur de la commande"""
        Commande.__init__(self, "charger", "bend")
        self.nom_categorie = "combat"
        self.schema = "<jet:nom_objet> (avec/with <projectile:nom_objet>)"
        self.aide_courte = "charge une arme de jet"
        self.aide_longue = \
            "Cette commande permet de charger une arme de jet que " \
            "vous équipez. Elle prend en paramètre obligatoire le " \
            "nom de l'arme. Si rien n'est précisé ensuite, le système " \
            "cherchera le bon projectile dans vos conteneurs équipés " \
            "et le placera automatiquement sur l'arme de jet. Sinon, " \
            "vous pouvez préciser après le nom de l'arme de jet le " \
            "mot-clé |cmd|avec|ff| (ou |cmd|with|ff| en anglais) suivi " \
            "du nom du projectile. Vous devez dans tous les cas " \
            "posséder le projectile indiqué."

    def ajouter(self):
        """Méthode appelée lors de l'ajout de la commande à l'interpréteur"""
        arme_de_jet = self.noeud.get_masque("jet")
        arme_de_jet.proprietes["conteneurs"] = \
            "(personnage.equipement.equipes, )"
        projectile = self.noeud.get_masque("projectile")
        projectile.proprietes["conteneurs"] = \
                "(personnage.equipement.inventaire_simple.iter_objets_qtt(" \
                "True), )"
        projectile.proprietes["quantite"] = "True"
        projectile.proprietes["conteneur"] = "True"

    def interpreter(self, personnage, dic_masques):
        """Interprétation de la commande"""
        personnage.agir("charger")
        arme_de_jet = dic_masques["jet"].objet
        if not arme_de_jet.est_de_type("arme de jet"):
            personnage << "|err|Ceci n'est pas une arme de jet.|ff|"
            return

        if dic_masques["projectile"]:
            projectiles = list(dic_masques["projectile"].objets_qtt_conteneurs)
            projectile, qtt, conteneur = projectiles[0]
            if not projectile.est_de_type("projectile"):
                personnage << "|err|Ceci n'est pas un projectile.|ff|"
                return
        else:
            projectile = conteneur = None
            for objet in personnage.equipement.inventaire:
                if objet.est_de_type("projectile") and objet.cle in \
                        arme_de_jet.projectiles_autorises:
                    projectile = objet
                    conteneur = objet.contenu
                    break

            if projectile is None or conteneur is None:
                personnage << "|err|Aucun projectile pour cette arme " \
                        "de jet ne peut être trouvé sur vous.|ff|"
                return

        if projectile.cle not in arme_de_jet.projectiles_autorises:
            personnage << "|err|Vous ne pouvez utiliser {} avec " \
                    "{}.|ff|".format(arme_de_jet.get_nom(),
                    projectile.get_nom())

        personnage << "Vous commencez à recharger {}.".format(
                arme_de_jet.get_nom())
        personnage.etats.ajouter("charger")
        yield 1
        if "charger" not in personnage.etats:
            return

        personnage.etats.retirer("charger")

        # Si l'arme de jet est déjà chargée
        if arme_de_jet.projectile:
            ancien_projectile = arme_de_jet.projectile
            try:
                personnage.ramasser(objet=ancien_projectile)
            except SurPoids:
                personnage.salle.objets_sol.ajouter(objet=ancien_projectile)
                personnage << "{} glisse à terre.".format(
                        ancien_projectile.get_nom().capitalize())
            else:
                personnage << "Vous récupérez {}.".format(
                        ancien_projectile.get_nom())

            arme_de_jet.projectile = None

        conteneur.retirer(projectile)
        arme_de_jet.script["charge"].executer(personnage=personnage,
                arme=arme_de_jet, projectile=projectile)
        arme_de_jet.projectile = projectile
        personnage << "Vous bandez {} avec {}.".format(
                arme_de_jet.get_nom(), projectile.get_nom())
        personnage.salle.envoyer("{{}} bande {} avec {}.".format(
                arme_de_jet.get_nom(), projectile.get_nom()), personnage)


import re
while True:

    name = input("Hi, please enter your name: ")

    email_add = input("Now please, enter your email adress: ")

    if re.match(r'^[a-zA-Z\s@1234567890]+.com$', email_add):

        print(f'Hi {name}! We will be contacting you shortly at\n {email_add}')
        break

    else:
        print("hmm seems like you didnt type your email right ")
        continue


#{
 # Driver Code Starts
#Initial Template for Python 3

# } Driver Code Ends
#User function Template for python3

class Solution:
    def leastInterval(self, N, K, tasks):
        freq = [0] * 26
        for task in tasks:
            freq[ord(task) - ord('A')] += 1

        freq.sort(reverse=True)

        max_freq = freq[0]
        idle_time = (max_freq - 1) * K

        for f in freq[1:]:
            idle_time -= min(f, max_freq - 1)

        idle_time = max(0, idle_time)

        return N + idle_time

        # Code here

#{
 # Driver Code Starts.
if __name__ == '__main__':
    t = int(input ())
    for _ in range (t):
        N, K = list(map(int, input().split()))
        tasks = input().split()
        ob = Solution()
        res = ob.leastInterval(N, K, tasks)
        print(res)
# } Driver Code Ends


'''
    Implementation of Spell Checking

    This program implements a spell checker for the words typed out
'''

import sys
from PyQt5 import QtGui
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class Window(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setGeometry(500, 500, 500, 500)

        self.setWindowTitle("Text Tools")

        #creates the central widget and text box
        self.text_box = QWidget()
        self.text_box = QTextEdit()

        self.setCentralWidget(self.text_box)

        menu = self.menuBar()
        toolsMenu = menu.addMenu("Tools")

        #adds the button for the spell check
        spellCheck = QAction("Spell Check", self)
        spellCheck.triggered.connect(self.spellCheck)
        toolsMenu.addAction(spellCheck)

        self.show()

    #spell cheker that highlights misspelled words
    def spellCheck(self):
        #converts everything in the text file to plain text
        text = self.text_box.toPlainText()
        words = text.split()

        #puts a cursor over the text file that goes down each word
        cursor = self.text_box.textCursor()
        cursor.movePosition(1, 0, 1)
        cursor.movePosition(14, 1, 1)

        #red highlight format for mispelled words
        highlight = QTextCharFormat()
        highlight.setBackground(QtGui.QColor("#FFCCCB"))

        #goes through every word in the text file
        for i in words:
            #if the word is found in a dictionary or has an uppercase, number, or symbol character found is set to 1
            found = 0

            #checks for capital letters
            for char in i:
                if char.isupper():
                    found = 1

            #checks for numbers or symbols
            if not i.isalnum() or i.isdigit():
                found = 1

            #goes through the dictionary file to check if the current word is present
            if found == 0:
                with open("dictionaries/dictionary.txt", "r") as file1:
                    for j in file1:
                        j = j.strip()
                        if i == j:
                            found = 1
                            break

            #goes through the custom dictionary file to check if the current word is present
            if found == 0:
                with open("dictionaries/custom_dictionary.txt", "r") as file2:
                    for k in file2:
                        if i == k:
                            found = 1
                            break

            #if the word was not found, mark it
            if found == 0:
                #set the word within the text file to be highlighted
                cursor.setCharFormat(highlight)

            #moves to the next word within the text file
            cursor.movePosition(18, 0, 1)
            cursor.movePosition(5, 0, 1)
            cursor.movePosition(14, 1, 1)

if __name__ == '__main__':
    app = QApplication(sys.argv)

    window = Window()

    window.show()

    sys.exit(app.exec())


"""
This contains utility functions and definitions used in calc_tilts_prec_avg_regularized.py and
hybrid_spin_evolution.py

N. K. Johnson-McDaniel, 2021
"""

import numpy as np

from lal import G_SI, C_SI, MSUN_SI

import warnings
from warnings import warn

# Define the kg to m and s conversions

kg_to_m = G_SI/C_SI**2

kg_to_s = G_SI/C_SI**3

# Setup for error handling

class Error(Exception):
    """Base class for exceptions in this module"""
    pass

class NonprecessingError(Error):
    """Exception raised when the evolution finds that the system is nonprecessing to numerical accuracy."""

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

# Setup for warnings

class Warn(UserWarning):
    """Base class for warnings in this module"""
    pass

class ValueWarning(Warn):
    """Warning raised when an input is dubious"""
    pass

# Make warnings cleaner

def warning_formatter(message, category, filename, lineno, file=None, line=None):
    return '%s: %s\n'%(category.__name__, message)

warnings.formatwarning = warning_formatter

# Define functions

def format_error(err):
        return "%s: %s"%(type(err).__name__, err)

def check_masses(m1, m2):
    if m1 <= 0. or m2 <= 0.:
        raise ValueError(
            "The input masses must both be positive, while they are m1, m2 = %e, %e kg" % (m1, m2))

    if m1 < 0.09*MSUN_SI or m2 < 0.09*MSUN_SI:
        warn("One or both of the masses is rather small: m1 = %e kg = %e Msun, m2 = %e kg = %e Msun. "
             "The masses must be input in kg." % (m1, m1/MSUN_SI, m2, m2/MSUN_SI), ValueWarning)

def eq_mass_check(m1, m2, Lf):
    if m1 == m2:
        if Lf is None:
            raise ValueError(
                "Cannot compute tilts at infinity for exactly equal-mass binaries, as those quantities are not well "
                "defined in this case.")
        else:
            raise ValueError(
                "The computation of the bounds and average value of the tilts is not yet implemented for exactly "
                "equal-mass binaries.")

def check_spin_mags(chi1, chi2):
    if chi1 < 0. or chi1 > 1. or chi2 < 0. or chi2 > 1.:
        raise ValueError(
            "The magnitudes of the spins must both be between 0 and 1, while they are chi1, chi2 = %f, %f" % (chi1, chi2))

def check_tilts(tilt1, tilt2):
    if tilt1 < 0. or tilt1 > np.pi or tilt2 < 0. or tilt2 > np.pi:
        raise ValueError(
            "The tilt angles must both be between 0 and pi, while they are tilt1, tilt2 = %f, %f" % (tilt1, tilt2))

def check_fref(fref, m1, m2, evol_type):
    if fref <= 0.:
        raise ValueError(
            "The reference frequency must be positive, while it is fref = %f Hz" % fref)

    f_ISCO = 6.**(-1.5)/(np.pi*(m1 + m2)*kg_to_s)

    if fref > f_ISCO:
        warn("The reference frequency should not be close to merger, where the %s evolution is highly inaccurate, "
             "while it is fref = %f Hz, which is greater than the Schwarzschild ISCO frequency associated "
             "with the binary's total mass of %f Hz"%(evol_type, fref, f_ISCO), ValueWarning)

def package_tilts(tilt1, tilt2, Lf, swap):
    """
    Package tilts to be returned by prec_avg_tilt_comp_vec_inputs() or prec_avg_tilt_comp() depending on whether
    Lf is None or not. Also swaps the tilts if necessary. Only works in the case when Lf is not None when the
    min, max, and average values are all the same.

    Inputs:

    tilt1, tilt2: Tilts
    Lf: Final orbital angular momentum (here just acts as a switch depending on whether it is None or not)
    swap: Whether to swap tilt1 and tilt2 before returning (True) or not (False)

    Output: dictionary with entries 'tilt1_inf', 'tilt2_inf' for evolution to infinity--Lf is None--and entries
            'tilt1_sep_min', 'tilt1_sep_max', 'tilt1_sep_avg', 'tilt2_sep_min', 'tilt2_sep_max', 'tilt2_sep_avg'
            for evolution to a finite separation (i.e., a finite orbital angular momentum), when Lf is not None
    """

    if swap:
        tilt1, tilt2 = tilt2, tilt1

    if Lf is None:
        return {'tilt1_inf': tilt1, 'tilt2_inf': tilt2}
    else:
        return {'tilt1_sep_min': tilt1, 'tilt1_sep_max': tilt1, 'tilt1_sep_avg': tilt1, 'tilt2_sep_min': tilt2,
                'tilt2_sep_max': tilt2, 'tilt2_sep_avg': tilt2}

def evolution_error_handling(failure_mode, failure_message, failure_output, failure_output_string, Lf, swap, hybrid_evol=False):
    """
    Take care of the error message or warning and returning something for the tilts when the
    precession-averaged evolution fails. Append entries for tilts at transition in the case where hybrid evolution fails.

    Inputs:
    failure_mode: The failure mode (either "Error", "NAN", or "None")
    failure_message: The message to print in the error or warning
    failure output: What to output for the tilts in the event of a failure
    failure_output_string: The string associated with the failure output
    Lf: Final orbital angular momentum (here just acts as a switch depending on whether it is None or not)
    swap: Whether to swap tilt1 and tilt2 before returning (True) or not (False)
    hybrid_evol: Flag to invoke error handling in the hybrid evolution code. Default: False

    Output: dictionary with entries 'tilt1_inf', 'tilt2_inf' for evolution to infinity--Lf is None--and entries
            'tilt1_sep_min', 'tilt1_sep_max', 'tilt1_sep_avg', 'tilt2_sep_min', 'tilt2_sep_max', 'tilt2_sep_avg'
            for evolution to a finite separation (i.e., a finite orbital angular momentum), when Lf is not None.
            The entries of the dictionary are failure_output
            If hybrid_evol is set to True, entries 'tilt1_transition', 'tilt2_transition', 'phi12_transition', and 'f_transition' set as failure_output are appended to match the output of the hybrid evolution code.
    """

    if failure_mode == 'Error':
        raise RuntimeError(failure_message)
    else:
        failure_message += " Returning %s for the tilts."%failure_output_string

        warn(failure_message, RuntimeWarning)

        if hybrid_evol:
            hybrid_output_tilts = package_tilts(failure_output, failure_output, Lf, swap)
            hybrid_output_tilts["tilt1_transition"] = failure_output
            hybrid_output_tilts["tilt2_transition"] = failure_output
            hybrid_output_tilts["phi12_transition"] = failure_output
            hybrid_output_tilts["f_transition"] = failure_output
            return hybrid_output_tilts

        return package_tilts(failure_output, failure_output, Lf, swap)


foods =  ['apples', 'bananas', 'cherries', 'donuts', 'eggplants']
counts = [      11,        22,         33,       44,          55]

def count_me(name: str):
    assert name in foods, f'{name} not found in foods'
    return counts[foods.index(name)]

if __name__ == '__main__':
    print(count_me('cherries'))


import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

matplotlib.interactive(True)
params = np.load('./mnist_gen_params.npy')
accs = np.load('./mnist_gen_accs.npy')
losss = np.load('./mnist_gen_losss.npy')

hist = []
new_accs = [[],[]]
new_losss = [[],[]]
for i,v in enumerate(params):
	if v not in hist:
		hist.append(v)
		new_accs[0].append(accs[0][i])
		new_accs[1].append(accs[1][i])
		new_losss[0].append(losss[0][i])
		new_losss[1].append(losss[1][i])

print("Acutual Model Num: {}".format(len(hist)))

plt.plot(hist, new_accs[0], 'o', label="train_acc")
plt.plot(hist, new_accs[1], 'o', label="test_acc")
plt.xlabel('parameters')
plt.ylabel('acc')
plt.title('Model Accuracy by Patameters')
plt.legend()
plt.savefig('./accs.png')
plt.close()

plt.plot(hist, new_losss[0], 'o', label="train_loss")
plt.plot(hist, new_losss[1], 'o', label="test_loss")
plt.xlabel('parameters')
plt.ylabel('loss')
plt.title('Model loss by Patameters')
plt.legend()
plt.savefig('./losss.png')
plt.close()


tasks = {}
cur_id = 0

def create_task(action, product, location):
    return {"action": action, "product": product, "location": location, "complete": False}

def insert_task(task):
    global cur_id
    tasks[cur_id] = task
    cur_id += 1
    return cur_id-1

def get_task(task_id):
    return tasks[task_id]

def complete_task(task_id):
    tasks[task_id]['complete'] = True

def next_tasks():
    pending_tasks = [{'id': k, **v} for k, v in tasks.items() if v["complete"] is False]
    for task in pending_tasks:
        task.pop('complete')
    return pending_tasks

if __name__ == "__main__":
    task1 = create_task("put", "bread", "[5,6]")
    insert_task(task1)
    task2 = create_task("put", "milk", "[4,2]")
    insert_task(task2)
    task3 = create_task("sup", "bread", "[5,6]")
    insert_task(task3)
    print(next_tasks())