"""Script to stitch a pair of images."""
import os
import numpy as np
import cv2
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle, Polygon

from keypoint_matching import KeypointMatcher
from RANSAC import ImageAlignment, project_2d_to_6d, project_1d_to_2d
from utils import show_two_images

class ImageStitching:
    """Class to perform stitching of a pair of images."""

    def __init__(self) -> None:
        np.random.seed(1)
        pass

    def _get_alignment_params(self, img1, img2, show_matches=True, kpmatch_args=dict(), align_args=dict()):
        """Detects keypoints, performs matching and returns matches."""
        kp_matcher = KeypointMatcher(**kpmatch_args)
        matches, kp1, des1, kp2, des2 = kp_matcher.match(img1, img2, show_matches=show_matches)

        image_alignment = ImageAlignment(**align_args)
        best_params = image_alignment.align(
            img1, kp1, img2, kp2, matches,
            show_warped_image=True, num_matches=4, max_iter=2000, method="cv2",
        )

        return matches, kp1, des1, kp2, des2, best_params

    def _get_transform_matrix_and_inv_matrix(self, params: np.ndarray):
        assert params.shape == (6,)
        AM = np.zeros((3, 3))
        AM[0, :2] = params[:2]
        AM[1, :2] = params[2:4]
        AM[0, 2] = params[4]
        AM[1, 2] = params[5]
        AM[-1, -1] = 1.0

        M_1_to_2 = AM[:2]
        M_2_to_1 = np.linalg.inv(AM)[:2]

        return M_1_to_2, M_2_to_1

    @staticmethod
    def show_canvas(canvas, subcanvas, C2_as_viewed_from_1, X_left, Y_top, W_new, H_new):
        """Displays canvas with both images and transformed image 2 in image 1 space."""
        fig, ax = plt.subplots(1, 1, figsize=(13, 7), dpi=100)

        ax.imshow(canvas.astype(int), alpha=0.6)
        ax.imshow(subcanvas.astype(int), alpha=0.4)
        ax.scatter(C2_as_viewed_from_1[:, 0], C2_as_viewed_from_1[:, 1], c="red", label="Corners of Image 2 transformed")

        stiched_image_rect = Rectangle(
            (X_left, Y_top), W_new, H_new, fc='none', ec='limegreen', lw=1, label="Border of stiched image",
        )
        ax.add_patch(stiched_image_rect)

        title = "Image 1 (Left), Image 2 (Right) and Image 2 transformed (middle) based on estimated affine parameters."
        ax.set_title(title, fontsize=13)

        plt.legend(loc="lower right")
        plt.show()

    def stitch(self, img1, img2):
        """Main stitching function. NOTE: this expects RGB images."""
        img1_gray = cv2.cvtColor(img1, cv2.COLOR_RGB2GRAY)
        img2_gray = cv2.cvtColor(img2, cv2.COLOR_RGB2GRAY)

        # get matches and alignment parameters
        matches, kp1, des1, kp2, des2, best_params = self._get_alignment_params(img1_gray, img2_gray)

        # get transformation params as matrices
        M_1_to_2, M_2_to_1 = self._get_transform_matrix_and_inv_matrix(best_params)

        # transform image 2 in space of image 1
        rows, cols = img2_gray.shape
        img2_as_viewed_from_1 = cv2.warpAffine(img2_gray, M_2_to_1, (cols, rows))
        show_two_images(
            img2_gray, img2_as_viewed_from_1,
            title="Image 2 (Left) and Image 2 (Right) transformed into co-ordinates of image 1.",
        )

        # get corners for each image
        H1, W1 = img1_gray.shape
        C1 = np.array([[0, 0], [W1, 0], [0, H1], [W1, H1]])

        H2, W2 = img2_gray.shape
        C2 = np.array([[0, 0], [W2, 0], [0, H2], [W2, H2]])

        # get corners of image 2 in space of image 1
        best_params_2_to_1 = np.array(
            [
                M_2_to_1[0, 0], M_2_to_1[0, 1], M_2_to_1[1, 0],
                M_2_to_1[1, 1], M_2_to_1[0, 2], M_2_to_1[1, 2]]
        )
        C2_as_viewed_from_1 = np.dot(project_2d_to_6d(C2), best_params_2_to_1)
        C2_as_viewed_from_1 = project_1d_to_2d(C2_as_viewed_from_1)

        # get co-ordinates of image 2 transformed in image 1 space
        Y_top = np.max([0, C2_as_viewed_from_1[0, 1], C2_as_viewed_from_1[1, 1]])
        Y_bot = np.min([H1, C2_as_viewed_from_1[2, 1], C2_as_viewed_from_1[3, 1]])
        X_left = np.min([0, C2_as_viewed_from_1[0, 0], C2_as_viewed_from_1[3, 0]])
        X_right = np.max([W1, C2_as_viewed_from_1[1, 0], C2_as_viewed_from_1[2, 0]])
        H_new = Y_bot - Y_top
        W_new = X_right - X_left

        # show canvas containing both images and transformed corners
        H, W = 400, 800
        canvas = np.zeros((H, W, 3))
        canvas[:H1, :W1, :] = img1
        canvas[:H2, W - W2:, :] = img2

        # create another subcanvas containing warped version of image 2
        subcanvas = np.zeros((H, W, 3))
        subcanvas[:H2, :W2, :] = img2
        subcanvas = cv2.warpAffine(subcanvas, M_2_to_1, (W, H))

        self.show_canvas(canvas, subcanvas, C2_as_viewed_from_1, X_left, Y_top, W_new, H_new)

        # merge images with weighted sub over pixels
        merged_image = np.zeros(canvas.shape)
        merging_weights_1 = np.zeros(canvas.shape)
        merging_weights_2 = np.zeros(canvas.shape)
        checker = np.zeros(canvas.shape)

        C1_reordered = np.array([C1[0], C1[1], C1[3], C1[2]])
        P1 = Polygon(C1_reordered)

        C2_as_viewed_from_1_reordered = np.array(
            [C2_as_viewed_from_1[0], C2_as_viewed_from_1[1], C2_as_viewed_from_1[3], C2_as_viewed_from_1[2]]
        )
        P2 = Polygon(C2_as_viewed_from_1_reordered)

        for x in np.arange(int(X_left), int(X_right), 1):
            for y in np.arange(int(Y_top), int(Y_bot), 1):

                in_img_1 = P1.contains_point((x, y))
                in_img_2 = P2.contains_point((x, y))

                if in_img_1 and not in_img_2:
                    merging_weights_1[y, x] = 1.0
                    merging_weights_2[y, x] = 0.0

                if in_img_2 and not in_img_1:
                    merging_weights_1[y, x] = 0.0
                    merging_weights_2[y, x] = 1.0

                if in_img_1 and in_img_2:
                    merging_weights_1[y, x] = 0.5
                    merging_weights_2[y, x] = 0.5
                    checker[y, x] = 1.0

        # visualize merging weights
        fig, ax = plt.subplots(1, 2, figsize=(12, 5), constrained_layout=True)
        ax[0].axis("off")
        ax[0].imshow(merging_weights_1, cmap="gray")
        ax[0].set_title("Merging weights for image 1")
        ax[1].axis("off")
        ax[1].imshow(merging_weights_2, cmap="gray")
        ax[1].set_title("Merging weights for image 2")
        plt.show()

        # create the final stitched image
        stitched = np.multiply(canvas, merging_weights_1) + np.multiply(subcanvas, merging_weights_2)
        stitched = stitched[int(Y_top):int(Y_bot), int(X_left):int(X_right)]

        # show the stiched image
        f, ax = plt.subplots(1, 3, gridspec_kw={'width_ratios': [2, 2, 4]}, figsize=(20, 6))

        ax[0].imshow(img1)
        ax[0].set_title("Image 1", fontsize=18)
        ax[0].axis("off")

        ax[1].imshow(img2)
        ax[1].set_title("Image 2", fontsize=18)
        ax[1].axis("off")

        ax[2].imshow(stitched.astype(int))
        ax[2].set_title("Stitched image", fontsize=18)
        ax[2].axis("off")

        f.tight_layout()
        os.makedirs("./results/", exist_ok=True)
        f.savefig('./results/all_stiched.png', bbox_inches="tight")
        plt.show()

        return stitched

def demo(img1_path, img2_path):
    # load both images
    img1 = cv2.imread(img1_path)
    img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)

    img2 = cv2.imread(img2_path)
    img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)

    # show input images
    show_two_images(img1, img2, title="Given pair of images.")

    # initialize stitcher
    image_stitching = ImageStitching()
    stitched = image_stitching.stitch(img1, img2)

    return stitched

if __name__ == "__main__":
    stitched = demo("left.jpg", "right.jpg")

lab4-Image Alignment and Stitching/stitch.py


# -*- coding: utf-8 -*-
import argparse
import pathlib
import sys
from CalcRating import CalcRating
from CalcDebt import CalcDebt
from JsonDataReader import JsonDataReader
from TextDataReader import TextDataReader
from Types import DataType

def get_path_from_arguments(args) -> str:
    parser = argparse.ArgumentParser(description="Path to datafile")
    parser.add_argument("-p", dest="path", type=str, required=True,
                        help="Path to datafile")
    args = parser.parse_args(args)
    return args.path

def read_data(path: str) -> DataType:
    file_extension = pathlib.Path(path).suffix
    if file_extension == '.txt':
        return TextDataReader().read(path)
    elif file_extension == '.json':
        return JsonDataReader().read(path)
    else:
        raise NameError('Data type is not supported.')

def main():
    path = get_path_from_arguments(sys.argv[1:])

    students = read_data(path)
    print("Students: ", students)

    rating = CalcRating(students).calc()
    print("Rating: ", rating)

    debts = CalcDebt(students).calc()
    print("Students with debts: ", debts)

if __name__ == "__main__":
    main()


from supabase import create_client, Client
from credentials import SUPABASE_URL, SUPABASE_KEY

supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)

units = [
    {
        "unit_id": 1,
        "topic_id": 1,
        "unit_name": "Chemistry of Life",
        "unit_number": 1
    },
    {
        "unit_id": 2,
        "topic_id": 1,
        "unit_name": "Cell Structure and function",
        "unit_number": 2
    },
    {
        "unit_id": 3,
        "topic_id": 1,
        "unit_name": "Cellular Energetics",
        "unit_number": 3
    },
    {
        "unit_id": 4,
        "topic_id": 2,
        "unit_name": "Atomic structure and properties",
        "unit_number": 1
    },
    {
        "unit_id": 5,
        "topic_id": 2,
        "unit_name": "Molecular and ionic compound structures and properties",
        "unit_number": 2
    },
    {
        "unit_id": 6,
        "topic_id": 2,
        "unit_name": "Intermolecular forces and properties",
        "unit_number": 3
    },
    {
        "unit_id": 7,
        "topic_id": 3,
        "unit_name": "The living world: ecosystems and biodiversity",
        "unit_number": 1
    },
    {
        "unit_id": 8,
        "topic_id": 4,
        "unit_name": "Period 1: 1491-1607",
        "unit_number": 1
    },
    {
        "unit_id": 9,
        "topic_id": 4,
        "unit_name": "Period 2: 1607-1754",
        "unit_number": 2
    },
    {
        "unit_id": 10,
        "topic_id": 4,
        "unit_name": "Period 3: 1754-1800",
        "unit_number": 3
    },
    {
        "unit_id": 11,
        "topic_id": 5,
        "unit_name": "Basic economics concepts",
        "unit_number": 1
    },
    {
        "unit_id": 12,
        "topic_id": 6,
        "unit_name": "Basic economics concepts",
        "unit_number": 1
    }
]

for u in units:
    data, count = supabase.table('units').insert({
        "id": u["unit_id"],
        "topic_id": u["topic_id"],
        "name": u["unit_name"],
        "number": u["unit_number"]
    }).execute()


import pandas as pd
import streamlit as st

st.set_page_config(page_title="Medicine utilisation", page_icon=":guardsman:", layout="wide")
st.image("chailogo.png", width=200)
st.title("Top 20% medicine procured by NDoH contributing 80% annual spend")

file_1 = st.file_uploader("Upload the first CSV file", type=["csv"])
file_2 = st.file_uploader("Upload the second CSV file (optional)", type=["csv"])

if file_1:
    df1 = pd.read_csv(file_1)
    st.dataframe(df1.head())

    if file_2:
        df2 = pd.read_csv(file_2)
        st.dataframe(df2.head())
else:
    st.warning("No file was uploaded.")

if st.button('Append'):
    st.success('Appending the two dataset...')
    df_appended = pd.concat([df1, df2], axis=0)
    st.dataframe(df_appended.head())
    df_appended["pct_contribution"] = df_appended.groupby("description")["order_qty"].transform(lambda x: x/x.sum()*100)
    df_appended_sorted = df_appended.sort_values(by="pct_contribution", ascending=False)
    df_appended_sorted["cumulative_pct"] = df_appended_sorted["pct_contribution"].cumsum()
    important_medicines = df_appended_sorted[df_appended_sorted["cumulative_pct"] <= 80]
    st.dataframe(important_medicines)

    if st.button('Download CSV'):
        important_medicines.to_csv("important_medicines.csv", index=False)
        st.success('Important medicines downloaded as CSV')


import pandas as pd
from numpy.random import randint
from pathlib import Path
import os
os.chdir(Path(__file__).parent)

def create_base_3d_matrix(i, j, k):
    matrix = {}
    for i in range(1, i + 1):
        matrix[i] = {}
        for j in range(1, j + 1):
            matrix[i][j] = {}
            for k in range(1, k + 1):
                matrix[i][j][k] = 0
    return matrix

def create_energy_cost_matrix(
        n: int,
        S_i: dict,
        p_k: dict,
):
    """
    Creating energy cost matrix for each (work, operation, machine) pair.
    :arg
        n: Number of works,
        S_i: Dictionary of operations per work,
        p_k: Dictionary of positions for each machine
    :return
        P_i_j_k: Dictionary of energy costs.
    """
    # TODO change the counter variable to a uniform dist
    P_i_j_k = {}
    for i in range(1, n + 1):
        P_i_j_k[i] = {}
        for j in range(1, S_i[i] + 1):
            P_i_j_k[i][j] = {}
            for k in range(1, p_k[j] + 1):
                P_i_j_k[i][j][k] = randint(3, 6)
    return P_i_j_k

def create_energy_time_matrix(
        n: int,
        S_i: dict,
        p_k: dict,
):
    """
    Fetching energy for each (work, operation, machine) pair
    and creating related dictionary
    :arg
        n: Number of works,
        S_i: Dictionary of operations per work,
        p_k: Dictionary of positions for each machine
    :return
        Pt_i_j_k: Dictionary of durations.
    """
    # Creating base dictionary
    Pt_i_j_k = create_energy_cost_matrix(n, S_i, p_k)
    Pt_df = pd.read_excel('glob_tables/Pt.xlsx')
    # Number of works
    n_works = len(Pt_df.columns) - 1
    for row in Pt_df.iterrows():
        # Removing index
        row = row[1]

        # Fetching k and j
        k, j = map(int, str(row['k.j/i']).split('.'))

        # Updating values in dictionary
        for i in range(1, n_works + 1):
            Pt_i_j_k[i][j][k] = row[i]

    return Pt_i_j_k

def create_trans_matrix(
        n: int,
        m: int
):
    """
    Creates transportation matrix
    :param n: number of works
    :param m: number of machines
    :return:
        Transportation dictionary.
    """
    trans_mat = create_base_3d_matrix(n, m, m)
    trans_df = pd.read_excel('glob_tables/Trans.xlsx')
    for row in trans_df.iterrows():
        # Removing index
        row = row[1]

        # Fetching k and k prime
        k, k_prime = map(int, str(row['k.k_prime/i']).split('.'))

        # Updating values in dictionary
        for i in range(1, n + 1):
            trans_mat[i][k][k_prime] = row[i]

    return trans_mat

def create_setup_matrix(
        n: int,
        S_i: dict,
        p_k: dict
):
    """
    Creating setup matrix
    :arg
        n: Number of works,
        S_i: Dictionary of operations per work,
        p_k: Dictionary of positions for each machine
    :return:
        Setup matrix
    """
    # Creating base dictionary
    st_mat = create_energy_cost_matrix(n, S_i, p_k)

    St_df = pd.read_excel('glob_tables/Setup.xlsx')
    # Number of works
    for row in St_df.iterrows():
        # Removing index
        row = row[1]

        # Fetching k and j
        j, k = map(int, str(row['j.k/i']).split('.'))

        # Updating values in dictionary
        for i in range(1, n + 1):
            st_mat[i][j][k] = row[i]

    return st_mat

def generate_r(n):
    """
    Clearance time
    :param n: Number of works
    :return: List of clearance time
    """
    r_dict = {
        1: 5,
        2: 3,
        3: 6
    }
    return r_dict

def generate_pidle(m):
    """
    Energy consumed during standby
    :param m: Number of machines
    :return:Dict of random energy unit.
    """
    pidle_dict = {}
    random_energy = randint(1, 4, size=m + 1)
    for k in range(1, m + 1):
        pidle_dict[k] = random_energy[k]
    return pidle_dict

def generate_O(m):
    """
    Time needed for turning on machine k
    :param m: Number of machines
    :return: Random O values
    """
    O_dict = {}
    random_O = randint(8, 17, size=m + 1)
    for k in range(1, m + 1):
        O_dict[k] = random_O[k]
    return O_dict

def generate_energy(m):
    """
    Energy needed for turning on/off machine k
    :param m: Number of machines
    :return: Random Energy values
    """
    energy_dict = {}
    random_energy = randint(10, 21, size=m + 1)
    for k in range(1, m + 1):
        energy_dict[k] = random_energy[k]
    return energy_dict

def generate_TB(
        O,
        Energy,
        Pidle,
        m
):
    """

    :param O:
    :param Energy:
    :param Pidle:
    :param m:
    :return:
    """
    TB_dict = {}
    for k in range(1, m + 1):
        TB_dict[k] = max(O[k], Energy[k] / Pidle[k])

    return TB_dict


# Core Pkg
import streamlit as st

def bases_streamlit():
    # streamlit features
    # TEXT
    # titre
    st.title("Streamlit crash course 101:")

    # texte
    st.text("This simply show a text")

    # header \ subheader
    st.header("This is a Header")
    st.subheader('This a Subheader')

    # MARKDOWN
    st.markdown("## This is a markdown")

    # Link
    st.markdown('[Google link](https://google.com)')

    # Write HTML
    st.write("You can write HTML")
    html_page = """

Streamlit is very awesome

    """
    st.markdown(html_page, unsafe_allow_html=True)

    #html_form = """
    #

    #    <form>
    #    <input type="text" name="firstname"/>
    #    </form>
    #

    #"""
    #st.markdown(html_form, unsafe_allow_html=True)

    # Alert text
    st.write("Alert text")

    st.success("Success!")
    st.info("Information")
    st.warning("Un warning!")
    st.error("Une erreur")

    ## MEDIA
    # Image
    # import Image function
    from PIL import Image
    st.write("ouverture d'une image:")

    # open an image
    img = Image.open("OIP (2).jpeg")

    # Plot the image
    st.image(img, caption="DataScientest")

    # Audio
    #audio_file = open('name_of_file.ext', "rb")
    #audio_bytes = audio_file.read()
    #st.audio(audio_bytes, format="audio/mp3")

    # Video with URL
    st.subheader("une vidéo directement de YouTube:")
    st.video(data="https://www.youtube.com/watch?v=SNNK6z03TaA")

    ### WIDGET
    st.subheader("Let's talk about widgets")

    # Bouton
    st.button("Press ME")

    # getting interaction button
    if st.button("Press Me again"):
        st.success("this is a success!")

    # Checkbox
    if st.checkbox("Hide & seek"):
        st.success("showing")

    # Radio
    gender_list = ["Man", "Woman"]
    gender = st.radio("Sélectionner un genre", gender_list)
    if gender == gender_list[0]:
        st.info(f"gender is {gender}")

    # Select
    location = st.selectbox("Your Job", ["Data Scientist", "Dentist", "Doctor"])

    # Multiselect
    liste_course = st.multiselect("liste de course",
                                    ["tomates", "dentifrice", "écouteurs"])

    # Text imput
    name = st.text_input("your name", "your name here")
    st.text(name)

    # Number input
    age = st.number_input("Age", 5, 100)

    # text area
    message = st.text_area("Enter your message")

    # Slider
    niveau = st.slider("select the level", 2, 6)

    # Ballons
    if st.button("Press me again"):
        st.write("Yesss, you'r ready!")
        st.balloons()


"""
StructDictClass - contains classes StructDict and MatlabStructDict to make it
    possible to access a dictionary with syntax struct.field.
"""

import re
import typing
import numpy as np  # type: ignore

class StructDict(dict):
    '''Class that adds a structure type syntax to dictionaries,
       i.e. 'dict.field' will invoke dict['field']
    '''

    def __getattr__(self, key):
        '''Implement getattr to support syntax "data.field"'''
        try:
            val = self[key]
        except KeyError:
            val = None
        return val

    def __setattr__(self, key, val):
        '''Implement setattr to support syntax "data.field=x"'''
        self[key] = val

    def __delattr__(self, key):
        '''Implement delattr to support syntax "del data.field"'''
        if key in self:
            del self[key]

    def __getstate__(self):
        '''Needed for pickling, return the underlying dictionary'''
        return dict(self)

    def __setstate__(self, dict_entries):
        '''Needed for pickling, set the underlying dictionary'''
        self.update(dict_entries)

    def copy(self):
        return StructDict(super().copy())

def copy_toplevel(data):
    cptl = StructDict()
    for key, val in data.items():
        if isinstance(val, dict):
            continue
        if type(val) == list:
            if isinstance(val[0], dict):
                continue
        cptl[key] = val
    return cptl

def recurseCreateStructDict(data):
    '''Given a recursive dictionary, i.e. a dictionary that has
            child dictionaries or lists of dictionaries,
            convert each child dictionary to a StructDict.
      '''
    if isinstance(data, dict):
        tmpDict = StructDict()
        for key, value in data.items():
            tmpDict[key] = recurseCreateStructDict(value)
        return tmpDict
    elif isinstance(data, list):
        tmpList = []
        for value in data:
            tmpList.append(recurseCreateStructDict(value))
        return tmpList
    return data

# Hold StructDict type in a variable
structDictType = type(StructDict())

def recurseSDtoDict(data):
    '''
    Given a recursive StructDict, i.e. that has child StructDicts
    or lists of StructDict, convert each child StructDict to a Dictionary.
    '''
    if isinstance(data, (structDictType, dict)):
        tmpDict = dict()
        for key, value in data.items():
            tmpDict[key] = recurseSDtoDict(value)
        return tmpDict
    elif isinstance(data, (list, set, tuple)):
        tmpList = []
        for value in data:
            tmpList.append(recurseSDtoDict(value))
        return tmpList
    return data

# Class to make it easier to access fields in matlab structs loaded into python
class MatlabStructDict(StructDict):
    '''Subclass dictionary so that elements can be accessed either as dict['key']
        of dict.key. If elements are of type NumPy structured arrays, convert
        them to dictionaries and then to MatlabStructDict also.
    '''

    def __init__(self, dictionary, name=None):
        # name is used to identify a special child dictionary whose elements
        #  should be considered as top level elements. i.e. if name=patterns,
        #  then data.patterns.field will return the same as data.field
        self.__name__ = name
        super().__init__(dictionary)
        # Convert any numpy structured arrays to MatlabStructDict
        for key in self.keys():
            try:
                # structured arrays will have a non-zero length set of names
                #  i.e. len(self[key].dtype.names) > 0
                if (isinstance(self[key], np.ndarray) and
                        len(self[key].dtype.names) > 0):
                    self[key] = MatlabStructDict(
                        convertStructuredArrayToDict(self[key]))
            except TypeError:
                pass

    def __getattr__(self, key):
        '''Implement getattr to support syntax x=data.field'''
        struct = self
        # if the key isn't found at the top level, check if it is a sub-field
        # of the special 'name' child dictionary
        if key not in self.keys() and self.__name__ in self.keys():
            struct = self[self.__name__]
        try:
            val = struct[key]
        except KeyError:
            val = None
        # flatten numpy arrays
        while isinstance(val, np.ndarray) and val.shape == (1, 1):
            val = val[0][0]
        return val

    def __setattr__(self, key, val):
        '''Implement setattr to support syntax data.field=x'''
        # check for special __fields__ and do default handling
        if re.match('__.*__', key):
            super().__setattr__(key, val)
            return
        # if the key isn't found at the top level, check if it is a sub-field
        # of the special 'name' field so we can set the value there
        struct = self
        if key not in self.keys() and self.__name__ in self.keys():
            if key in self[self.__name__].keys():
                struct = self[self.__name__]

        # pack ints in 2d array [[int]] as matlab does
        if isinstance(val, int):
            field_type = None
            if val in range(256):
                field_type = np.uint8
            struct[key] = np.array([[val]], dtype=field_type)
        else:
            struct[key] = val

    def copy(self):
        return MatlabStructDict(super().copy(), self.__name__)

    def fields(self):
        '''list all fields including subfields of the special 'name' field'''
        struct_fields: typing.List = []
        try:
            struct = self[self.__name__]
            if isinstance(struct, StructDict):
                struct_fields = list(struct.keys())
        except KeyError:
            pass
        allfields: typing.Set = set().union(list(self.keys()), struct_fields)
        regfields = set(
            [field for field in allfields if not re.match('__.*__', field)])
        return regfields

# Data loaded from matlab is as a structured array. But it's not easy to add
#  new fields to a structured array, so convert it to a dictionary
#  for easier use.
def convertStructuredArrayToDict(sArray):
    '''Convert a NumPy structured array to a dictionary.'''
    rvDict = dict()
    for key in sArray.dtype.names:
        try:
            val = sArray[key]
            # Check for and flatten arrays with only one element in them
            if isinstance(val, np.ndarray) and val.shape == (1, 1):
                val = val[0][0]
            rvDict[key] = val
        except KeyError:
            pass
    return rvDict

def isStructuredArray(var) -> bool:
    '''Return True if var is a numpy structured array'''

    if (isinstance(var, np.ndarray) and
            var.dtype.names is not None and
            len(var.dtype.names) > 0):
        return True
    else:
        return False


"""
    Misc. utility functions for manipulating files.
"""
import gzip
import hashlib
import math
import os
import re
import shutil
import string
import tarfile
import zipfile
import tempfile
from typing import Generator, BinaryIO, List, Dict, Optional

from dataclasses import dataclass
from onscale_client.api.datamodel import BlobType

# Regexp to match "chunked" files
CHUNK_PATTERN = r"\._[0-9]{5}_[0-9]{5}$"

# 256 byte stream buffer
BUFFER = 65536

# Valid characters for a file path
VALID_PATH_CHARS = set(f"-_.(){string.ascii_letters}{string.digits}")

TEMP_DIR = os.path.join(tempfile.gettempdir(), "onscale_client")

@dataclass(frozen=True)
class UploadContext:
    """Store information needed to create an upload form."""

    file_path: str
    method: str
    uri: str
    headers: Optional[Dict] = None
    fields: Optional[Dict] = None

@dataclass(frozen=True)
class FileContext:
    """Store information on a local file."""

    name: str
    dirname: Optional[str] = None
    original_name: Optional[str] = None
    uri: Optional[str] = None
    aes_key: Optional[bytes] = None
    file_hash: Optional[str] = None
    is_rtg: bool = False
    sequence_id: str = "0"

    @property
    def path(self) -> str:
        """Return full file path of this file."""
        if self.dirname is None:
            return self.name
        return os.path.join(self.dirname, self.name)

def clean_path(path: str) -> str:
    """Remove invalid characters from a file path. Replace spaces with _.

    Args:
        path: Some file name or path.

    Returns:
        Input string with characters not in `VALID_PATH_CHARS` removed.
    """
    new_path = path.replace(" ", "_")
    return "".join([c for c in new_path if c in VALID_PATH_CHARS])

def maybe_makedirs(path: str):
    """Make directory for a given path if doesn't exist

    Args:
        path: Directory name to create.
    """
    dirname = os.path.realpath(path)

    if not os.path.exists(dirname):
        try:
            os.makedirs(dirname)  # Extra safe for parallel tasks
        except FileExistsError:
            pass

def listdir(dirname: str) -> Generator[str, None, None]:
    """Similar to os.listdir, but give full relative path.

    Args:
        dirname: Directory to list contents.

    Yields:
        Paths to files in directory.
    """
    for obj in os.listdir(dirname):
        yield os.path.join(dirname, obj)

def full_listdir(dirname: str = os.getcwd(), relative: bool = True) -> List[str]:
    """Recursively list all files in all subdirectories of a directory.

    Args:
        dirname: Directory to search contents.
        relative: Make paths returned by this function relative to 'dirname'.

    Returns:
        All files in all subdirectories of `dirname`, relative to `dirname`.
    """
    # Get all files
    files = [os.path.join(d, f) for d, _, fs in os.walk(dirname) for f in fs]

    if not relative:
        return files

    files = [ltrim(f, dirname).lstrip(os.path.sep) for f in files]
    return files

def ltrim(text: str, sub: str) -> str:
    """Remove `sub` from `text` if `text` startswith `sub`.

    Args:
        text: Input text to search.
        sub: Search query.

    Returns:
        Input with query removed if present at beginning.
    """
    if text and text.startswith(sub):
        text = text[len(sub) :]
    return text

def flatten_dir(dirname: str):
    """Flatten all files from subdirectories into parent directory.

    Args:
        dirname: Top-level directory to flatten.
    """

    def recurse(_dir: str):
        """Recurse over objects in a subdirectory of `dirname`"""
        for _obj in listdir(_dir):
            if os.path.isdir(_obj):
                recurse(_obj)
            elif _dir != dirname:
                _move(_obj, dirname)

    # Recursively move all nested files to top directory `dirname`
    recurse(dirname)

    # Remove all sub-directories
    for obj in listdir(dirname):
        if os.path.isdir(obj):
            shutil.rmtree(obj)

def _move(obj: str, to_dir: str):
    """Move a file from location `obj` to directory `to_dir`."""
    obj_name = os.path.split(obj)[-1]
    shutil.move(obj, os.path.join(to_dir, obj_name))

def get_mount_point(dirname: str) -> str:
    """Get the file system mount point for a directory.

    Args:
        dirname: Path to directory.

    Returns:
        Directory path to device mount point.
    """
    path = os.path.abspath(dirname)
    while not os.path.ismount(path):
        path = os.path.dirname(path)
    return path

def gzip_file(path: str) -> str:
    """Compress a file with gzip.

    Args:
        path: File to be compressed.

    Returns:
        Path of compressed file.
    """
    outfile = path + ".gz"
    with open(path, "rb") as source, gzip.open(outfile, "wb") as sink:
        shutil.copyfileobj(source, sink)

    return outfile

def gunzip_file(path: str) -> str:
    """Uncompress a gzipped file.

    Args:
        path: File path to a gzipped file.

    Returns:
        Path to unzipped file.
    """
    gzip_exts = {".gz", ".gzip"}
    if os.path.splitext(path)[-1] not in gzip_exts:
        raise IOError(f"{path} does not appear to be a gzipped file")

    outfile = os.path.splitext(path)[0]
    with gzip.open(path, "rb") as source, open(outfile, "wb") as sink:
        shutil.copyfileobj(source, sink)

    return outfile

def tar_gzip_files(tar_name: str, *file_paths: str):
    """Create a tarball of files and gzip them.

    Args:
        tar_name: Name of resulting .tar.gz file.
        *file_paths: Paths to files that will be included in tarball.
    """
    # Make all files relative to each other
    tar_path = os.path.realpath(tar_name)
    real_paths = [os.path.realpath(f) for f in file_paths]
    prefix = os.path.commonprefix(real_paths + [tar_path])
    tar_path = ltrim(tar_path, prefix)
    real_paths = [ltrim(f, prefix) for f in real_paths]

    # Work locally from the common relative to prevent bad tarballs
    orig_path = os.getcwd()
    os.chdir(prefix)
    with tarfile.open(tar_path, "w:gz") as tar:
        for file in real_paths:
            tar.add(file)
    os.chdir(orig_path)

def tar_gunzip_file(path: str) -> List[str]:
    """Uncompress a .tar.gz archive.

    Args:
        path: Path to .tar.gz file.

    Returns:
        List of files which were uncompressed.
    """
    tar_ext = ".tar.gz"
    if not path.endswith(tar_ext):
        raise IOError(f"{path} does not appear to be a tar archive")

    # Extract tar files into the same directory that the tarball is in
    dirname = os.path.dirname(os.path.realpath(path))
    with tarfile.open(path, "r:gz") as tar:
        files = [os.path.join(dirname, f) for f in tar.getnames()]
        tar.extractall(dirname)

    return files

def unzip_all(dirname: str) -> List[str]:
    """Unzip all *.zip files in a directory.

    Args:
        dirname: A directory to search for zipped files at top level.

    Returns:
        A list of all files which were unzipped.
    """
    abspath = os.path.abspath(dirname)
    files = [
        os.path.join(abspath, x)
        for x in os.listdir(abspath)
        if os.path.splitext(x)[-1] == ".zip"
    ]
    unzipped = list()
    for file in files:
        with zipfile.ZipFile(file, "r") as f:
            members = [x for x in f.namelist() if not x.endswith(os.path.sep)]
            f.extractall(abspath)
        unzipped += members

    return unzipped

def zip_dir(dirname: str, remove: bool = False) -> str:
    """Zip a directory.

    Args:
        dirname: A directory to zip.
        remove: If specified, will remove the directory after zipping.

    Returns:
        Path to created zipfile.
    """
    abspath = os.path.abspath(dirname)
    parent = os.path.dirname(abspath)
    zipname = f"{abspath}.zip"

    with zipfile.ZipFile(zipname, "w", zipfile.ZIP_DEFLATED) as f:
        files = [
            os.path.join(root, file)
            for root, _, files in os.walk(abspath)
            for file in files
        ]
        for file in files:
            arcname = file.replace(parent, "").lstrip(os.path.sep)
            f.write(file, arcname)

    if remove:
        shutil.rmtree(abspath)

    return zipname

def hash_file(filepath: str) -> str:
    """Create md5 hash of a file

    Args:
        filepath: Path to file that will be hashed.

    Returns:
        String of hex hash.
    """
    hash_obj = hashlib.md5()
    with open(filepath, "rb", buffering=0) as file:
        for byte_string in iter(lambda: file.read(128 * 1024), b""):
            hash_obj.update(byte_string)
    return hash_obj.hexdigest()

def stream_file_in(
    filepath: str, chunk_size: int = BUFFER
) -> Generator[bytes, None, None]:
    """Stream the contents of a file into memory in chunks.

    Args:
        filepath: Path of file to read.
        chunk_size: Maximum size of each chunk.

    Returns:
        Generator of bytes chunks.
    """
    with open(filepath, "rb") as buffer:
        for chunk in stream_buffer_in(buffer, chunk_size):
            yield chunk

def stream_buffer_in(
    buffer: BinaryIO, chunk_size: int = BUFFER
) -> Generator[bytes, None, None]:
    """Stream the contents of a buffer into memory in chunks.

    Args:
        buffer: Read buffer.
        chunk_size: Maximum size of each chunk.

    Returns:
        Generator of bytes chunks.
    """

    while True:
        chunk = buffer.read(chunk_size)

        if not chunk:
            break

        yield chunk

def stream_file_out(filepath: str) -> Generator[None, bytes, None]:
    """Create an output stream to a file.

        Used to avoid context managers for complex stream operations.

    Args:
        filepath: Path to stream output file.

    Returns:
        Generator which takes bytes and writes to a file.
    """
    maybe_makedirs(os.path.dirname(filepath))

    def _make_init():
        with open(filepath, "wb") as sink:
            while True:
                part = yield
                sink.write(part)

    gen = _make_init()
    next(gen)
    return gen

def chunk_file(filepath: str, chunk_size: int = 1_000_000_000) -> List[str]:
    """Divide a file into chunks of maximum `chunk_size` bytes each.

        If a file such as "large.csv" is passed to this function, then the
        files ["large.csv._00004_00000", ..., "large.csv._00004_00003"]
        will be produced, following the underscore and 5 digits pattern, where
        the first 5 digits are the total number of files and the next 5 digits
        are the part number.

    Args:
        filepath: Path to divide into chunks.
        chunk_size: Maximum size for each chunk in bytes.

    Returns:
        List of chunk file paths created by this function.
    """
    # Calculate number of chunks to be created - this is a function of the
    # buffer size in which the file will be streamed in, not just chunk_size
    total_chunks = math.ceil(
        math.ceil(os.path.getsize(filepath) / BUFFER) * BUFFER / chunk_size
    )

    # List to hold filenames of all chunks created
    chunk_files = list()

    # State variables to monitor which chunk we are on
    chunk = 0
    current_size = 0
    current_file = f"{filepath}._{total_chunks:05d}_{chunk:05d}"
    chunk_files.append(current_file)

    # Stream in file and divide into chunks
    sink = stream_file_out(current_file)
    for part in stream_file_in(filepath):
        part_size = len(part)

        # If this part will exceed the chunk limit, make a new chunk
        if (current_size + part_size) > chunk_size:
            chunk += 1
            current_size = 0
            current_file = f"{filepath}._{total_chunks:05d}_{chunk:05d}"
            chunk_files.append(current_file)

            sink.close()
            sink = stream_file_out(current_file)

        sink.send(part)
        current_size += part_size

    sink.close()
    return chunk_files

def rebuild_file(target_file: str):
    """Rebuilds a chunked file created by `chunk_file`.

    Args:
        target_file: The output file name.
    """
    chunk_files = find_target_chunks(target_file)

    with open(target_file, "wb") as sink:
        for file in chunk_files:
            for part in stream_file_in(file):
                sink.write(part)

def find_target_chunks(target_file: str) -> List[str]:
    """Given a base filename, returns are chunks matching that file pattern.

    Args:
        target_file: The output file name to find parts for.

    Returns:
        List of parts files.
    """
    dirname, filename = os.path.split(os.path.realpath(target_file))

    pattern = re.escape(filename) + CHUNK_PATTERN
    part_files = sorted(
        [os.path.join(dirname, f) for f in os.listdir(dirname) if re.search(pattern, f)]
    )
    return part_files

def rebuild_all_chunks(dirname: str) -> List[str]:
    """Rebuild all chunked files in a directory.

    Args:
        dirname: Path to directory where chunked files may exist.

    Returns:
        List of all files which were rebuilt.
    """
    # Get basename of each chunked file
    chunked_files = {chunk_basename(file) for file in find_all_chunks(dirname)}

    for file in chunked_files:
        rebuild_file(os.path.join(dirname, file))

    return list(chunked_files)

def find_all_chunks(dirname: str) -> List[str]:
    """Return all files in a directory matching the `CHUNK_PATTERN` regexp.

    Args:
        dirname: Path to directory where chunked files may exist.

    Returns:
        List of files which are chunks.
    """
    dirname = os.path.realpath(dirname)
    chunks = [
        os.path.join(dirname, file) for file in os.listdir(dirname) if is_chunk(file)
    ]
    return chunks

def is_chunk(filename: str) -> bool:
    """Determine if a filename is a chunk.

    Args:
        filename: A file name.

    Returns:
        True if matches the `CHUNK_PATTERN` regexp.
    """
    return bool(re.search(CHUNK_PATTERN, filename))

def chunk_basename(filename: str) -> str:
    """Given a filename with a chunk extension, return the original filename.

    Args:
        filename: Filename with chunk extension.

    Returns:
        Original filename. Example: "file.csv".
    """
    return re.sub(CHUNK_PATTERN, "", filename)

def blob_type_from_file(filename: str) -> Optional[BlobType]:
    """Given a filename, return the datamodel.BlobType

    Args:
        filename: Filename with chunk extension.

    Returns:
        BlobType object
    """
    if filename.endswith(".jfp"):
        return BlobType.MODELDB
    if filename.endswith(".step"):
        return BlobType.CAD
    elif filename.endswith(".csv"):
        return BlobType.CSV
    elif filename.endswith(".py"):
        return BlobType.SIMAPI
    elif filename.endswith(".bincad"):
        return BlobType.BINCAD
    elif filename.endswith(".brep"):
        return BlobType.BREP
    else:
        return None


from mensajesCalculadora import mensajesCalculadora
from capturarDatos import capturarDatos
from operacionesBasicas import operacionesBasicas
from porcentaje import porcentaje

class calculadora():

    mensajesObj = mensajesCalculadora()
    capturarDatos = capturarDatos()

    def __init__(self):
        self.iniciarCalculadora()

    def iniciarCalculadora(self):
        self.mensajesObj.iniciarCalculadora()
        self.seleccionarOperaciones()

    def seleccionarOperaciones(self):
        self.mensajesObj.mostrarOpciones()
        opcion = self.capturarDatos.seleccionarMenu()
        if opcion == "1":
            operacionesBasicas()
        elif opcion == "2":
            porcentaje()
        else:
            print("WIP")


# init.py
import signac
import sys
from copy import deepcopy
import numpy as np
from os.path import join,dirname

sys.path.insert(0, join(dirname(__file__), '../'))
from representation_params import REPRESENTATION_PARAMS

project = signac.init_project('spherical_invariants')

fixed_params = []
del_params = fixed_params
fixed_params = {k:REPRESENTATION_PARAMS[0]['representation'][k] for k in fixed_params}
fixed_accuracy = 1e-8

misc_entries = {
    'qm9' : {
        "N_ITERATIONS" : 5,
        "n_structures" : 200,
        'start_structure': 0,
    },
    'molecular_crystals' : {
        "N_ITERATIONS" : 5,
        'start_structure': 0,
        "n_structures" : 20,
    },
    'silicon_bulk' : {
        "N_ITERATIONS" : 5,
        'start_structure': 600,
        "n_structures" : 60,
    },
    'methane_liquid' : {
        "N_ITERATIONS" : 5,
        'start_structure': 100,
        "n_structures" : 35,
    },
    'methane_sulfonic' : {
        "N_ITERATIONS" : 5,
        'start_structure': 0,
        "n_structures" : 10,
    },
}

for REPRESENTATION_PARAM in REPRESENTATION_PARAMS:
    if np.all([REPRESENTATION_PARAM['representation'][k] == v for k,v in fixed_params.items()]):
        rpr = REPRESENTATION_PARAM['representation']
        if 'accuracy' in rpr['optimization_args']:
            if rpr['optimization_args']['accuracy'] != fixed_accuracy:
                continue
        # avoid sparsification when too many or to few features
        if rpr['coefficient_subselection'] is not None:
            if rpr['max_radial'] < 6 or rpr['max_angular'] < 6:
                continue
            if rpr['max_radial'] > 12 or rpr['max_angular'] > 12:
                continue
            if rpr['radial_basis'] != 'GTO' or 'accuracy' not in rpr['optimization_args']:
                continue

        rep_args = deepcopy(REPRESENTATION_PARAM)

        rep_args.update(**misc_entries[rep_args['name']])
        rep_args['representation'] = {
            k:v for k,v in rep_args['representation'].items() if k not in del_params}
        job = project.open_job(rep_args)
        job.init()


from django.contrib.auth.models import User
import django.forms
from rest_framework import serializers
from baselabwatch.models import School
from baselabwatch.util.urls import URLResolution

resolution = URLResolution(School)

class SchoolSerializer(serializers.HyperlinkedModelSerializer):
    url = serializers.HyperlinkedIdentityField(view_name=resolution.resolve('school-detail'), read_only=True)
    primary_contact = serializers.HyperlinkedRelatedField(
        source='primary_contact.pk',
        view_name=resolution.resolve('user-detail'),
        read_only=True)
    name = serializers.CharField(label='School Name', help_text='Your school\'s full name', style={'placeholder': 'e.g. Edmonds Woodway High School'})
    short_name = serializers.CharField(label='School Abbreviation', help_text='A short name for your school.', style={'placeholder': 'e.g. EWHS'})
    auth_code = serializers.CharField(label='School Code', help_text='A code for letting other teachers join.', read_only=True)
    school_image = serializers.CharField(label='School Logo', help_text='A link to a school image.')

    class Meta:
        model = School
        fields = (
            'url',
            'name',
            'short_name',
            'primary_contact',
            'auth_code',
            'school_image'
        )


# codeup - if_else - 최댓값 (2020-09-11)
# https://codeup.kr/problem.php?id=1205

import sys
import math
sys.stdin = open("codeup/[if-else]1205_최댓값.txt",'r')

T = int(input())
for _ in range(T):
    a, b = map(int, input().split())
    result = [a+b, a-b, b-a, a*b, a/b, b/a, math.pow(a,b), math.pow(b,a)]
    tmp = float(max(result))
    print("%0.6f" %tmp)


import scipy as sp
import numpy as np
import build
from sklearn import model_selection, preprocessing, feature_selection, ensemble, linear_model, metrics, decomposition

model = ensemble.GradientBoostingClassifier()

param_dic = {'learning_rate':[0.15,0.1,0.05,0.01,0.005,0.001],      #weighting factor for the corrections by new trees when added to the model
'n_estimators':[100,250,500,750,1000,1250,1500,1750],  #number of trees added to the model
'max_depth':[2,3,4,5,6,7],    #maximum depth of the tree
'min_samples_split':[2,4,6,8,10,20,40,60,100],    #sets the minimum number of samples to split
'min_samples_leaf':[1,3,5,7,9],     #the minimum number of samples to form a leaf
'max_features':[2,3,4,5,6,7],     #square root of features is usually a good starting point
'subsample':[0.7,0.75,0.8,0.85,0.9,0.95,1]}

x_values = ["do_manual_check",
                "ext_toDelete",
                "is_doc",
                "is_pic",
                "is_coding_file",
                "is_vid",
                "is_mp3",
                "is_shortcut",
                "is_folder",
                "is_unclassified",
                "name_length",
                "num_spaces",
                "num_real_words",
                "file_size",
                "days_since_created",
                "is_duplicate"]

data = build.get_data()

data_train, data_test = model_selection.train_test_split(data,test_size = 0.1)

# seperate date into train and test set
x_train = data_train[x_values]
y_train = data_train["delete_file"]

x_test = data_test[x_values]
y_test = data_test["delete_file"]

random_search = model_selection.RandomizedSearchCV(model,
       param_distributions=param_dic, n_iter=10,
       scoring="accuracy").fit(x_train, y_train)

print("Best Model parameters:", random_search.best_params_)
print("Best Model mean accuracy:", random_search.best_score_)
model1 = random_search.best_estimator_

model1.fit(x_train,y_train)

predicted_prob = model1.predict_proba(x_test)[:,1]
predicted = model1.predict(x_test)
accuracy = metrics.accuracy_score(y_test,predicted)

print(accuracy)


import base64
import os
import pathlib
import time
from typing import AnyStr

import click

from common import api_utility
from common import chronicle_auth
from common import exception_handler
from common import options
from common.constants import key_constants as common_constants
from common.constants import status
from parsers import url
from parsers.constants import key_constants
from parsers.constants import path_constants

@click.command(
    name="download", help="Download parser code given config ID or log type")
@options.env_option
@options.region_option
@options.verbose_option
@options.credential_file_option
@exception_handler.catch_exception()
def download(credential_file: AnyStr, verbose: bool, region: str,
             env: str) -> None:
  """Download parser code given log type or config ID.

  Args:
    credential_file (AnyStr): Path of Service Account JSON.
    verbose (bool): Option for printing verbose output to console.
    region (str): Option for selecting regions. Available options - US, EUROPE,
      ASIA_SOUTHEAST1.
    env (str): Option for selecting environment. Available options - prod, test.

  Raises:
    OSError: Failed to read the given file, e.g. not found, no read access
      (https://docs.python.org/library/exceptions.html#os-exceptions).
    ValueError: Invalid file contents.
    KeyError: Required key is not present in dictionary.
    TypeError: If response data is not JSON.
  """
  click.echo(
      "Note: If you want to download parser by log type then skip the config ID."
  )
  config_id = click.prompt("Enter config ID", show_default=False, default="")

  http_client = chronicle_auth.initialize_http_session(credential_file)
  method = "GET"

  if config_id:
    # Get the parser from config id
    download_parser_url = f'{url.get_url(region, "list", env)}/{config_id}'
    response = http_client.request(
        method, download_parser_url, timeout=url.HTTP_REQUEST_TIMEOUT_IN_SECS)
    download_parser_response = api_utility.check_content_type(response.text)
  else:
    # Get the parser of `log_type` from list of parsers
    log_type = click.prompt("Enter Log Type", show_default=False, default="")
    if not log_type:
      click.echo("Please enter log type or config ID.")
      return
    download_parser_url = url.get_url(region, "list", env)
    response = http_client.request(
        method, download_parser_url, timeout=url.HTTP_REQUEST_TIMEOUT_IN_SECS)
    download_parser_response = api_utility.check_content_type(response.text)
    if key_constants.KEY_CBN_PARSER not in download_parser_response:
      click.echo("No CBN parsers currently configured.")
      return
    found = False
    for p in download_parser_response[key_constants.KEY_CBN_PARSER]:
      if p[common_constants.KEY_LOG_TYPE] == log_type:
        found = True
        download_parser_response = p
        break
    if not found:
      click.echo(f"Parser for log type {log_type} not found.")
      return

  click.echo("Downloading parser...")

  if response.status_code != status.STATUS_OK:
    click.echo(
        f"Error while downloading parser:\nResponse Code: {response.status_code}"
        f"\nError: {download_parser_response[common_constants.KEY_ERROR][common_constants.KEY_MESSAGE]}"
    )
    return

  decoded_config = base64.b64decode(
      download_parser_response[key_constants.KEY_CONFIG])
  decoded_config = decoded_config.decode("utf-8")
  timestr = time.strftime("%Y%m%d%H%M%S")
  filename = download_parser_response[
      common_constants.KEY_LOG_TYPE] + "_" + timestr + ".conf"
  sample_dir = pathlib.Path(path_constants.PARSER_DATA_DIR)
  sample_dir.mkdir(parents=True, exist_ok=True)
  filepath = os.path.join(sample_dir, filename)
  click.echo(f"Writing parser to: {filepath}")
  with open(filepath, "w") as f:
    f.write(decoded_config)

  if verbose:
    api_utility.print_request_details(download_parser_url, method, None,
                                      download_parser_response)


import csv
import math
with open("data4.csv", newline = '') as f:
    reader = csv.reader(f)
    data = list(reader)

data1 = data[0]

def mean(data):
    m = len(data)
    total = 0
    for x in data:
        total += int(x)

    mean = total/m

    return mean

squaredList = []
for number in data1:
    a = int(number) - mean(data1)
    a = a**2
    squaredList.append(a)

sum = 0
for i in squaredList:
    sum = sum + i

result = sum/(len(data1) - 1)
standardDerivation = math.sqrt(result)
print("Standard Deviation is " + str(standardDerivation))
print("Mean is " + str(mean(data1)))


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

import serial
import numpy as np
import matplotlib.pyplot as plt
import linecache
import datetime
import csv
import time
import smtplib
import sys
import getpass

import adafruit_max31865
import Adafruit_DHT as dht
import board
import busio
import digitalio
import os.path
from string import Template
from email.message import EmailMessage
from email.mime.image import MIMEImage

class DataAQ():

    def __init__(self, filename='abc.csv',salinity = 30):
        self.filename = filename
        self.name=self.filename.split('.')[0]
        self.My_Email = input('Please provide the sending email address:\n')
        self.Pass = getpass.getpass(prompt='Please provide the sending email password:\n')
        self.Check_Login()

    def Check_Login(self):
        try:
            server=smtplib.SMTP('smtp.gmail.com', 587, timeout=300)
            server.starttls()
            server.login(self.My_Email, self.Pass)
            server.quit()
            print('Login to email server successful!')
        except:
            print('Login to email server failed! Please enter the correct credientials.')
            sys.exit()

    def Sartorius_init(self,COM):
        #Initialize Sartorius Scale
        ser = serial.Serial(port = '/dev/serial/by-id/usb-Sartorius_Sartorius_Composite_device_0000000000-if00', baudrate = 9600, parity = serial.PARITY_ODD, stopbits = serial.STOPBITS_ONE, bytesize = serial.EIGHTBITS, timeout = None)
        self.ser = ser

    def RTD_init(self):
        #Initalize RTP100 sensor to GPIO5
        spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
        cs = digitalio.DigitalInOut(board.D5)
        rtdsensor = adafruit_max31865.MAX31865(spi,cs, wires = 4)
        return rtdsensor

    def Scale_Value(self):
        self.ser.write(b"\x1bP\r\n")
        weight = self.ser.readline()
        weight = str(weight)
        weight=weight[11:18]
        weight = float(weight)
        return weight

    def get_contacts(self,file):
        names=[]
        emails=[]
        with open(file, mode='r') as contacts:
            for a_contact in contacts:
                names.append(a_contact.split()[0])
                emails.append(a_contact.split()[1])
        return names, emails

    def read_template(self, file):
        with open(file, 'r') as template_file:
            template_file_content = template_file.read()
        return Template(template_file_content)

    def send_email(self,wchange):

        names,emails = self.get_contacts('lab_contacts.txt')
        message_template = self.read_template('Regular_Message.txt')

        server=smtplib.SMTP('smtp.gmail.com', 587, timeout=300)
        server.starttls()
        server.login(self.My_Email, self.Pass)

        for name, email in zip(names, emails):
            self.simple_plot()
            msg = EmailMessage()
            message = message_template.substitute(PERSON_NAME=name.title(),WEIGHT_CHANGE=wchange)
            msg['From'] = self.My_Email
            msg['To']= email
            msg['Subject'] = self.name
            msg.set_content(message)
            msg.add_attachment(open(self.filename, 'r').read(), filename = self.filename)

            pdfopen=open(f'{self.name}.pdf','rb').read()
            image=MIMEImage(pdfopen, _subtype='pdf', name=os.path.basename(f'{self.name}.pdf'))
            msg.attach(image)
            server.send_message(msg)
            del msg
        print(f'Email(s) sent! Data Aquisition in progress @ {datetime.datetime.now()}!')

    def send_final_email(self):
        names,emails = self.get_contacts('lab_contacts.txt')
        message_template = self.read_template('Final_Message.txt')

        server=smtplib.SMTP('smtp.gmail.com', 587, timeout=300)
        server.starttls()
        server.login(self.My_Email, self.Pass)

        for name, email in zip(names, emails):
            self.simple_plot()
            msg = EmailMessage()
            message = message_template.substitute(PERSON_NAME=name.title())
            msg['From'] = self.My_Email
            msg['To']= email
            msg['Subject'] = self.name
            msg.set_content(message)
            msg.add_attachment(open(self.filename, 'r').read(), filename = self.filename)

            pdfopen=open(f'{self.name}.pdf','rb').read()
            image=MIMEImage(pdfopen, _subtype='pdf', name=os.path.basename(f'{self.name}.pdf'))
            msg.attach(image)
            server.send_message(msg)
            del msg
        print(f'Final Email(s) Sent!')
        server.quit()

    def simple_plot(self):
        plottime, real_weight, plottemp, adj_weight = np.loadtxt(self.filename,skiprows=3,delimiter=',', usecols=(1,2,3,6)).T
        fig, ax = plt.subplots(figsize=(8,6), dpi=80)
        ax.plot(plottime,real_weight,'b-',label='Recorded_Weight')
        ax.plot(plottime,adj_weight,'g--',label='Temp Corrected Weight')
        ax.set_ylabel('Weight(g)',fontsize=10)
        ax.set_xlabel('Time (hours)',fontsize = 10)

        ax2 = ax.twinx()
        ax2.set_ylabel('Temperature (C)')
        ax2.plot(plottime,plottemp,'r')

        ax.legend()
        plt.title(self.name,fontsize = 18)
        if os.path.isfile(f'{self.name}.pdf'):
            os.remove(f'{self.name}.pdf')
        plt.savefig(f'{self.name}.pdf')
        plt.close()

    def Density_Calc(self,temp):
        if self.salinity == 'C12':
            a = -.731*10**-3
            b = -.32*10**-6
            TrueDens = .75 + a*(temp-20) + b/2*(temp-20)**2
        else:
            CleanDens = 1000 * (1 - (temp + 288.9414) / (508929.2 * (temp + 68.12963)) * (temp - 3.9863) ** 2)
            A = 0.824493 - 0.0040899 * temp + 0.000076438 * temp ** 2 - 0.00000082467 * temp ** 3 + 0.0000000053675 * temp ** 4
            B = -0.005724 + 0.00010227 * temp - 0.0000016546 * temp ** 2
            C = 0.00048314
            TrueDens = (CleanDens + A * self.salinity + B * self.salinity ** (3 / 2) + C * self.salinity ** 2) / 1000
        return TrueDens

    def Temp_Correction(self,temp,RefD,raw_weight):
        TrueDens = self.Density_Calc(temp)
        TrueWeight = raw_weight + (TrueDens-RefD)*self.Vs
        return TrueWeight

    def Error(self,temp, RefD, raw_weight):
        #Error Calculation for RTD Sensor
        Temp_Error = (.15 + temp*.002)
        High_Temp = temp + Temp_Error
        Low_Temp = temp - Temp_Error
        High_Weight_Error = self.Temp_Correction(High_Temp,RefD,raw_weight)
        Low_Weight_Error = self.Temp_Correction(Low_Temp,RefD,raw_weight)
        return High_Weight_Error, Low_Weight_Error

    def Aquire(self):
        count = 0
        ecount = 0
        plt.show(block=True)
        rtdsensor=self.RTD_init()
        self.Sartorius_init('/dev/ttyUSB0')
        if os.path.isfile(self.filename):
            answer = input('File already exists! Would you like to append to the exsisting file? (Y/N) \n')
            if answer == 'Y':
                wfile=open(f'{self.filename}', mode='a+')
                writer = csv.writer(wfile, lineterminator = '\n')
                variable_line=linecache.getline(self.filename, 2).split(',')
                self.salinity=float(variable_line[1])
                self.Vs=float(variable_line[3])
                data_line=linecache.getline(self.filename,4).split(',')
                #line_time=data_line[0].split('.')
                starttime=datetime.datetime.strptime(data_line[0], '%Y-%m-%d %H:%M:%S')
                refD=self.Density_Calc(float(data_line[3]))
            else:
                sys.exit('Answer was not Y! Cancel DataAQ()')
        else:
            starttime=datetime.datetime.now().replace(microsecond=0)
            self.salinity = float(input('Please provide salinity of the brine (mg/L):\n'))
            self.Vs = float(input('Please provide an estimate for the total solid volume submerged (cm^3):\n'))
            refD=self.Density_Calc(rtdsensor.temperature)
            wfile=open(f'{self.filename}', mode='a+')
            writer = csv.writer(wfile, lineterminator = '\n')
            writer.writerow([f'Experiment: {self.name}'])
            writer.writerow(['Brine_Salinity/C12',self.salinity,'Vs',self.Vs])
            writer.writerow(['Time','Relative Time (Hours)','Weight (g)','Liq Temperature (C)','Air Temperature (C)','Humidity','Temp Adjusted Weight (g)', '(+)Error from RTD sensor (g)','(-)Error from RTD sensor (g)','Comments'])
        initialweight=self.Scale_Value()
        print('Data Aquisition in progress!')
        while True:
            timestamp = datetime.datetime.now().replace(microsecond=0)
            relativetime = (timestamp-starttime)/datetime.timedelta(hours=1)
            weight = self.Scale_Value()
            Liq_Temperature = rtdsensor.temperature
            Humidity, Air_Temperature = dht.read_retry(dht.DHT22, 4)
            AdjWeight = self.Temp_Correction(Liq_Temperature,refD,weight)
            PlusError, MinusError = self.Error(Liq_Temperature, refD, weight)
            writer.writerow([timestamp,relativetime,weight,Liq_Temperature,Air_Temperature, Humidity, AdjWeight, PlusError, MinusError])
            #needs to be 15,30,45,60 sec interval)
            time.sleep(60)
            count+=1
            ecount+=1
            #log every 30 min count==120,60,40,30
            if count==60:
                wfile.close()
                #email every 4 hrs ecount==960,480,320,240
                print(f'DATA LOGGED @ {datetime.datetime.now().replace(microsecond=0)}!')
                if ecount >= 240:
                    try:
                        self.send_email(weight-initialweight)
                        initialweight=self.Scale_Value()
                        ecount = 0
                    except:
                        print('Email(s) not sent! Still recording data!')
                wfile=open(f'{self.filename}', mode='a+')
                writer = csv.writer(wfile, lineterminator = '\n')
                count=0

if __name__ == '__main__':
    try:
        print('Program for Spontaneous Imbibtion Experiments\nThis program is for use with a Sartorius Scale and RTD temperature sensor.\nEmail updates will be sent every 4 hours from an email the users specifies\n')
        filename=input('Please type destination filename with .csv \n')
        if filename[-4:]=='.csv':
            Experiment=DataAQ(filename)
            Experiment.Aquire()
        else:
            print('You did not add ".csv" to the end of the file!')
    except KeyboardInterrupt:
        print('Data Aquisition Complete!')
        plt.show(block=False)
        wfile=open(filename, mode='a+')
        wfile.close()
        final=input('Is this experiment complete? (Y/N)')
        if final == 'Y':
            Experiment.send_final_email()
            print('Experiment Complete!')
        else:
            print('Data Aquisition has been paused!')


# Need more info? Check out the blogpost:
# how-to-make-a-bot-that-automatically-replies-to-comments-on-facebook-post

"""
NEED MORE INFO? CHECK OUT THE BLOGPOST
https://vandevliet.me/bot-automatically-responds-comments-facebook/
"""

import sqlite3
from time import sleep
import facebook
from PIL import Image
from io import BytesIO

APP_ID = 'TO FILL IN'
APP_SECRET = 'TO FILL IN'

PAGE_ID = 'TO FILL IN'
POST_ID_TO_MONITOR = 'TO FILL IN'
LONG_LIVED_ACCESS_TOKEN = 'TO FILL IN'

COMBINED_POST_ID_TO_MONITOR = '%s_%s' % (PAGE_ID, POST_ID_TO_MONITOR)

def make_new_profile_pic(img):
    im = Image.open(BytesIO(img))
    im = im.resize((480, 480))

    # background version
    # background = Image.open("./fcdk_overlay.png")
    #
    # background.paste(im, (100, 100))

    # background.show()
    # bytes_array = BytesIO()
    # background.save(bytes_array, format='PNG')
    # bytes_array = bytes_array.getvalue()
    # return bytes_array

    # foreground version
    foreground = Image.open("./tgr_overlay.png")
    foreground = foreground.resize((250, 250))
    im = im.resize((250, 250))

    im.paste(foreground, (0, 0), foreground)

    # im.show()
    bytes_array = BytesIO()
    im.save(bytes_array, format='PNG')
    bytes_array = bytes_array.getvalue()
    return bytes_array

def comment_on_comment(graph, comment):
    comment_id = comment['id']
    comment_from_name = comment['from']['name']
    comment_from_id = comment['from']['id']
    comment_message = comment['message']
    profile = None

    print("Let's comment!")
    # like the comment
    graph.put_like(object_id=comment_id)

    # profile info:
    photo = graph.get_connections(id=comment_from_id, connection_name='picture', height=480, width=480)
    # try to get first name, if it's a page there is not first_name
    try:
        profile = graph.get_object(comment_from_id, fields='first_name,last_name')
    except:
        pass

    # let's create our photo that we want to post
    photo_to_post = make_new_profile_pic(photo['data'])

    # first we upload it as an unpublished photo that doesn't appear as a story (in the newsfeed)
    posted_photo = graph.put_photo(
        image=photo_to_post,
        album_path='404896546596495/photos',
        no_story=True,
        published=False
    )

    # if it's a person that commented, we can use the first name
    if profile:
        graph.put_object(parent_object=comment_id, connection_name='comments',
                         message='Bozour %s. Hier is uwe foto, mijn gedacht!' % (profile['first_name']),
                         attachment_id=posted_photo['id']
                         )
    else:
        graph.put_object(parent_object=comment_id, connection_name='comments',
                         message='Hola copain. Hier is uwe foto, mijn gedacht!',
                         attachment_id=posted_photo['id']
                         )

    print('Edited and posted the photo of: %s' % comment_from_name)

def monitor_fb_comments():
    # create graph
    graph = facebook.GraphAPI(LONG_LIVED_ACCESS_TOKEN)
    # that infinite loop tho
    while True:
        print('I spy with my little eye...🕵 ')
        sleep(5)

        # get the comments
        comments = graph.get_connections(COMBINED_POST_ID_TO_MONITOR,
                                         'comments',
                                         order='chronological')

        for comment in comments['data']:

            # if we can't find it in our comments database, it means
            # we haven't commented on it yet
            if not Posts().get(comment['id']):
                comment_on_comment(graph, comment)

                # add it to the database, so we don't comment on it again
                Posts().add(comment['id'])

        # while there is a paging key in the comments, let's loop them and do exactly the same
        # if you have a better way to do this, PRs are welcome :)
        while 'paging' in comments:
            comments = graph.get_connections(COMBINED_POST_ID_TO_MONITOR,
                                             'comments',
                                             after=comments['paging']['cursors']['after'],
                                             order='chronological')

            for comment in comments['data']:

                if not Posts().get(comment['id']):
                    comment_on_comment(graph, comment)
                    Posts().add(comment['id'])

# Mary had a little class
class Posts:
    def __init__(self):
        self.connection = sqlite3.connect('comments.sqlite3')
        self.cursor = self.connection.cursor()

    def get(self, id):
        self.cursor.execute("SELECT * FROM comments where id='%s'" % id)

        row = self.cursor.fetchone()

        return row

    def add(self, id):
        try:
            self.cursor.execute("INSERT INTO comments VALUES('%s')" % id)
            lid = self.cursor.lastrowid
            self.connection.commit()
            return lid
        except sqlite3.IntegrityError:
            return False

# started at the bottom, etc
if __name__ == '__main__':
    monitor_fb_comments()


import os

# Copyright 2021 Kuntai Cai
# caikt@comp.nus.edu.sg

thread_num = '16'
os.environ["OMP_NUM_THREADS"] = thread_num
os.environ["OPENBLAS_NUM_THREADS"] = thread_num
os.environ["MKL_NUM_THREADS"] = thread_num
os.environ["VECLIB_MAXIMUM_THREADS"] = thread_num
os.environ["NUMEXPR_NUM_THREADS"] = thread_num

# os.environ["CUDA_VISIBLE_DEVICES"] = '0'
os.environ["CUDA_VISIBLE_DEVICES"] = '1'

from exp.evaluate import run_experiment, split
import json
import csv
import pandas as pd
import numpy as np

import sys
from PrivMRF.preprocess import preprocess

# python3 script.py adult 1

if __name__ == '__main__':
    for path in ['./temp', './result', './out']:
        if not os.path.exists(path):
            os.mkdir(path)

    preprocess('acs')
    preprocess('nltcs')
    preprocess('br2000')
    preprocess('adult')

    # adult, br2000, nltcs, acs
    # data_list = ['br2000']
    data_list = ['nltcs', 'acs', 'adult', 'br2000']

    # PrivMRF
    method_list = ['PrivMRF']

    # arbitrary string for naming output data
    exp_name = 'test'

    # 0.1, 0.2, 0.4, 0.8, 1.6, 3.2
    # epsilon_list = [1.6]
    epsilon_list = [0.1, 0.2, 0.4, 0.8, 1.6, 3.2]

    # number of experiments
    repeat = 1

    run_experiment(data_list, method_list, exp_name, task='TVD', epsilon_list=epsilon_list, repeat=repeat, classifier_num=25)

    # run_experiment(data_list, method_list, exp_name, task='SVM', epsilon_list=epsilon_list, repeat=repeat, classifier_num=25)
    # run_experiment(data_list, method_list, exp_name, task='SVM', epsilon_list=epsilon_list, repeat=repeat, classifier_num=25, generate=False)


from dataclasses import dataclass
import string
from typing import List, Tuple

DIGITS = tuple(string.digits)
LIMIT = 100_000
TO_DELETE = 30_000_000

@dataclass
class Directory:
    name: str
    dirs: List['Directory']
    size: int
    parent: 'Directory'

def solve(lines: List[str]) -> Tuple[int]:
    root = Directory("/", [], 0, None)
    result = []
    cwd = root
    for line in lines[1:]:
        if line.startswith("$ cd"):
            name = line.split()[2]
            if name == "..":
                if cwd.size <= LIMIT:
                    result.append(cwd)
                cwd.parent.size += cwd.size
                cwd = cwd.parent
            else:
                dir = Directory(name, [], 0, cwd)
                cwd.dirs.append(dir)
                cwd = dir
        elif line.startswith(DIGITS):
            size = int(line.split()[0])
            cwd.size += size
    while cwd.parent:
        if cwd.size <= LIMIT:
            result.append(cwd)
        cwd.parent.size += cwd.size
        cwd = cwd.parent
    return sum(d.size for d in result)

with open("input_test") as f:
    lines = f.readlines()

print(solve(lines))


import hashlib
import logging
import os
import shutil
import subprocess  # nosec
import pkg_resources

from tern.utils import constants
from tern.utils import general

# remove root filesystems
remove = ['rm', '-rf']

# tar commands
check_tar = ['tar', '-tf']
extract_tar = ['tar', '-xf']

# mount commands
mount = ['mount', '-o', 'bind']
mount_proc = ['mount', '-t', 'proc', '/proc']
mount_sys = ['mount', '-o', 'bind', '/sys']
mount_dev = ['mount', '-o', 'bind', '/dev']
unmount = ['umount']

mount_dir = None

# enable host DNS settings
host_dns = ['cp', constants.resolv_path]

# unshare PID within rootfs
unshare_pid = ['unshare', '-pf']

# union mount
union_mount = ['mount', '-t', 'overlay', 'overlay', '-o']

# global logger
logger = logging.getLogger(constants.logger_name)

def set_mount_dir(bind=None):
    '''Set mount directory according to --bind-mount CLI option (or lack
    thereof). The mount_dir value is used to set the working directory
    properly in get_working_dir().'''
    global mount_dir
    if bind:
        mount_dir = bind
    else:
        mount_dir = general.get_top_dir()

def root_command(command, *extra):
    '''Invoke a shell command as root or using sudo. The command is a
    list of shell command words'''
    full_cmd = []
    # add sudo before a command if the user is not root
    if not general.check_root():
        full_cmd.append('sudo')
    full_cmd.extend(command)
    for arg in extra:
        full_cmd.append(arg)
    # invoke
    logger.debug("Running command: %s", ' '.join(full_cmd))
    pipes = subprocess.Popen(full_cmd, stdout=subprocess.PIPE,  # nosec
                             stderr=subprocess.PIPE)
    result, error = pipes.communicate()  # nosec
    if error:
        logger.error("Command failed. %s", error.decode())
        raise subprocess.CalledProcessError(  # nosec
            1, cmd=full_cmd, output=error)
    return result

def shell_command(is_sudo, command, *extra):
    '''Invoke a shell command as a regular user unless explicitly stated.
    This is used to check the result and error message of the command'''
    full_cmd = []
    if not isinstance(is_sudo, bool):
        raise TypeError("First argument should be of type bool")
    if not general.check_root() and is_sudo:
        full_cmd.append('sudo')
    full_cmd.extend(command)
    for arg in extra:
        full_cmd.append(arg)
    # invoke
    logger.debug("Running command: %s", ' '.join(full_cmd))
    pipes = subprocess.Popen(full_cmd, stdout=subprocess.PIPE,  # nosec
                             stderr=subprocess.PIPE)
    return pipes.communicate()  # nosec

def check_tar_permissions(tar_file, directory_path):
    '''Invoke a shell command as the current user. If the error contains
    'Operation not permitted' then return False. Else return True'''
    _, error = shell_command(
        False, extract_tar, tar_file, '-C', directory_path)
    if "Operation not permitted" in error.decode():
        return False
    return True

def check_tar_members(tar_file):
    '''Given the path to the tar file, check to see if there is an error with
    the members of the tarfile or if it is empty'''
    result, error = shell_command(False, check_tar, tar_file)
    if error:
        logger.error("Malformed tar: %s", error.decode())
        raise EOFError("Malformed tarball: {}".format(tar_file))
    if not result:
        raise ValueError("Empty tarball: {}".format(tar_file))
    return result

def get_working_dir():
    '''General purpose utility to return the absolute path of the working
    directory'''
    return os.path.join(mount_dir, constants.temp_folder)

def get_untar_dir(layer_tarfile):
    '''get the directory to untar the layer tar file'''
    return os.path.join(get_working_dir(), os.path.dirname(
        layer_tarfile), constants.untar_dir)

def get_layer_tar_path(layer_tarfile):
    '''get the full path of the layer tar file'''
    return os.path.join(get_working_dir(), layer_tarfile)

def set_up():
    '''Create required directories'''
    op_dir = get_working_dir()
    workdir_path = os.path.join(op_dir, constants.workdir)
    mergedir_path = os.path.join(op_dir, constants.mergedir)
    # create higher level directory
    if not os.path.isdir(op_dir):
        os.mkdir(op_dir)
    # create mount points
    if not os.path.isdir(workdir_path):
        os.mkdir(workdir_path)
    if not os.path.isdir(mergedir_path):
        os.mkdir(mergedir_path)

def extract_tarfile(tar_path, directory_path):
    '''Give the full path to the tar file, extract the tar file into the
    given directory'''
    try:
        os.mkdir(directory_path)
    except FileExistsError:
        # attempt to remove using user permissions
        try:
            shutil.rmtree(directory_path)
            os.mkdir(directory_path)
        except PermissionError:
            # attempt to remove using root permissions
            root_command(remove, directory_path)
            os.mkdir(directory_path)
    # check tarball - should raise an error if anything is wrong
    check_tar_members(tar_path)
    # check if user can extract tarball
    success = check_tar_permissions(tar_path, directory_path)
    if not success:
        # attempt to extract using root permissions
        root_command(extract_tar, tar_path, '-C', directory_path)

def prep_rootfs(rootfs_dir):
    '''Mount required filesystems in the rootfs directory'''
    rootfs_path = os.path.abspath(rootfs_dir)
    try:
        root_command(mount_proc, os.path.join(rootfs_path, 'proc'))
        root_command(mount_sys, os.path.join(rootfs_path, 'sys'))
        root_command(mount_dev, os.path.join(rootfs_path, 'dev'))
        root_command(host_dns, os.path.join(
            rootfs_path, constants.resolv_path[1:]))
    except subprocess.CalledProcessError as error:
        logger.error("%s", error.output)
        raise

def mount_base_layer(base_layer_tar):
    '''To mount to base layer:
        1. Untar the base layer tar file
        2. Mount into mergedir'''
    base_rootfs_path = get_untar_dir(base_layer_tar)
    target_dir_path = os.path.join(get_working_dir(), constants.mergedir)
    root_command(mount, base_rootfs_path, target_dir_path)
    return target_dir_path

def mount_diff_layers(diff_layers_tar):
    '''Using overlayfs, mount all the layer tarballs'''
    # make a list of directory paths to give to lowerdir
    lower_dir_paths = []
    for layer_tar in diff_layers_tar:
        lower_dir_paths.append(get_untar_dir(layer_tar))
    upper_dir = lower_dir_paths.pop()
    lower_dir = ':'.join(list(reversed(lower_dir_paths)))
    merge_dir_path = os.path.join(get_working_dir(), constants.mergedir)
    workdir_path = os.path.join(get_working_dir(), constants.workdir)
    args = 'lowerdir=' + lower_dir + ',upperdir=' + upper_dir + \
           ',workdir=' + workdir_path
    root_command(union_mount, args, merge_dir_path)
    return merge_dir_path

def run_chroot_command(command_string, shell):
    '''Run the command string in a chroot jail within the rootfs namespace'''
    target_dir = os.path.join(get_working_dir(), constants.mergedir)
    mount_proc = '--mount-proc=' + os.path.join(
        os.path.abspath(target_dir), 'proc')
    try:
        result = root_command(unshare_pid, mount_proc, 'chroot', target_dir,
                              shell, '-c', command_string)
        return result
    except subprocess.CalledProcessError as error:
        logger.warning("Error executing command in chroot")
        raise subprocess.CalledProcessError(
            1, cmd=command_string, output=error.output.decode('utf-8'))

def undo_mount():
    '''Unmount proc, sys, and dev directories'''
    rootfs_path = os.path.join(get_working_dir(), constants.mergedir)
    root_command(unmount, os.path.join(rootfs_path, 'proc'))
    root_command(unmount, os.path.join(rootfs_path, 'sys'))
    root_command(unmount, os.path.join(rootfs_path, 'dev'))

def unmount_rootfs():
    '''Unmount the filesystem'''
    rootfs_path = os.path.join(get_working_dir(), constants.mergedir)
    root_command(unmount, '-rl', rootfs_path)

def clean_up():
    '''Remove all the setup directories'''
    mergedir_path = os.path.join(get_working_dir(), constants.mergedir)
    workdir_path = os.path.join(get_working_dir(), constants.workdir)
    root_command(remove, mergedir_path)
    root_command(remove, workdir_path)

def recover():
    '''Recover after some external error'''
    # try to unmount proc, sys and dev first
    try:
        undo_mount()
    except subprocess.CalledProcessError:
        pass
    try:
        unmount_rootfs()
    except subprocess.CalledProcessError:
        pass
    # clean up the working directory
    clean_up()

def calc_fs_hash(fs_path):
    '''Given the path to the filesystem, calculate the filesystem hash
    We run a shell script located in the tools directory to get the
    file stats and the file content's sha256sum. We then calculate the
    sha256sum of the contents and write the contents in the layer
    directory.
    Note that this file will be deleted if the -k flag is not given'''
    try:
        fs_hash_path = pkg_resources.resource_filename(
            "tern", "tools/fs_hash.sh")
        hash_contents = root_command(
            [fs_hash_path], os.path.abspath(fs_path))
        file_name = hashlib.sha256(hash_contents).hexdigest()
        # write file to an appropriate location
        hash_file = os.path.join(os.path.dirname(fs_path), file_name) + '.txt'
        with open(hash_file, 'w') as f:
            f.write(hash_contents.decode('utf-8'))
        return file_name
    except subprocess.CalledProcessError:  # pylint: disable=try-except-raise
        raise


'''um programa que tenha uma função chamada voto() que vai receber como parâmetro o ano de nascimento de uma pessoa,
retornando um valor literal indicando se uma pessoa tem voto NEGADO, OPCIONAL e OBRIGATÓRIO nas eleições'''

from datetime import date
def status():
    global AnoNaci
    anoAtual = date.today().year
    idade = anoAtual - AnoNaci
    if idade < 16:
        print(f'\033[0;31mCom {idade} anos de idade, você não pode votar ainda.')
    if 15 < idade < 18 or idade > 69:
        print(f'\033[0;32mCom {idade} anos de idade, seu voto é opcional.')
    if 17 < idade < 70:
        print(f'\033[0;33mCom {idade} anos de idade, seu voto é obrigatorio.')

# Programa principal
print('Saiba aqui seu status eleitoral!')
print('+=' * 20)

AnoNaci = int(input('Qual o ano do seu nacimento? '))
status()


import PyPDF2
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
import re

with open('sample.pdf','rb') as pdf_file, open('sample.txt', 'w') as text_file:
    read_pdf = PyPDF2.PdfFileReader(pdf_file)
    number_of_pages = read_pdf.getNumPages()
    for page_number in range(number_of_pages):   # use xrange in Py2
        page = read_pdf.getPage(page_number)
        page_content = page.extractText()
        text_file.write(page_content)

with open('sample.txt', 'r', encoding="latin-1") as f:
    read_output = f.readlines()
read_output = '\n'.join(read_output).strip().replace('\n','')

REPLACE_BY_SPACE_RE = re.compile('[/(){}\[\]\|@,;.]')
BAD_SYMBOLS_RE = re.compile('[^0-9a-z #+_]')
STOPWORDS = set(stopwords.words('english'))
SHORTWORD = re.compile(r'\W*\b\w{1,3}\b')

stop_words_lst = ['cell','spectral','data','double','bond','barrier','soluble', 'cells', 'performed using']

def clean_text(text):
    """
        text: a string

        return: modified initial string
    """
    text = str(text).lower() # lowercase text
    text = REPLACE_BY_SPACE_RE.sub(' ', text) # replace REPLACE_BY_SPACE_RE symbols by space in text. substitute the matched string in REPLACE_BY_SPACE_RE with space.
    text = BAD_SYMBOLS_RE.sub('', text) # remove symbols which are in BAD_SYMBOLS_RE from text. substitute the matched string in BAD_SYMBOLS_RE with nothing.
    text = re.sub(r'\b[a-zA-Z]\b','',str(text)) # remove single letter words
    text = re.sub('\d+','',text) # remove digits
    text = SHORTWORD.sub('',text)
    text = ' '.join(word for word in text.split() if word not in STOPWORDS) # remove stopwors from text
    for w in stop_words_lst:
        pattern = r'\b'+w+r'\b'
        text = re.sub(pattern, '', str(text))

    return text

pdf_o = clean_text(read_output)
text_tokens = word_tokenize(pdf_o)

pdf_i=[pdf_o]

# Getting bigrams
vectorizer = CountVectorizer(ngram_range =(2, 3))
X1 = vectorizer.fit_transform(pdf_i)
features = (vectorizer.get_feature_names())

X2 = vectorizer.fit_transform(pdf_i)
scores = (X2.toarray())

sums = X2.sum(axis = 0)
data1 = []
for col, term in enumerate(features):
    data1.append( (term, sums[0, col] ))
ranking = pd.DataFrame(data1, columns = ['term', 'rank'])
words = (ranking.sort_values('rank', ascending = False))
print ("\n\nWords : \n", words.head(50))


import os
import openai
import pandas as pd

from secret import API_KEY
from sqlalchemy import create_engine, text
from utils import create_prompt, call_openai

os.environ["OPENAI_API_KEY"] = API_KEY
openai.api_key = os.environ["OPENAI_API_KEY"]

EXIT_KEY = "q"
ERROR_MESSAGE = "Sorry, no results ЪциЪЈ╝РђЇРЎѓ№ИЈ"

df = pd.read_json("instruments.json")
# TEMP DATABASE IN RAM
temp_db = create_engine("sqlite:///:memory:")
# PUSH PANDAS DF ---> TEMP DB
df.to_sql(name="instruments", con=temp_db)

user_input = ""
while user_input != EXIT_KEY:
    print("Enter a prompt. Enter q to quit")
    user_input = input()
    if user_input != EXIT_KEY:
        query_result = create_prompt(df, user_input) # DF + query that does ...
        response = call_openai(query_result)
        print(f"Query: {response}")

        with temp_db.connect() as conn:
            result = conn.execute(text(response))

        print("Results: *")
        print("**********")
        returned_data = result.all()
        for i, instrument in enumerate(returned_data):
            print(f"{i+1}. {instrument.name.lower().capitalize()}")
        print("**********")
print("Bye!")

# HOW TO PICK A LANGUAGE MODEL
# Think about cost of the model and how often you'll use it
# How many tokens you'll pass into the model or get back
# Importance of accuracy in results

# OpenAI Completion Call Params
# model (i.e. text-davinci-003, etc.)
# prompt
# temperature (0.0 to 1.0, the higher, the more likely the model will take risks and be creative)
# max_tokens (most tokens to use in response)
# top_p (similar to temperature)
# n (how many completions to generate)
# frequency_penalty (-2.0 to 2.0, likelihood of model repeating itself, higher means less likely, 0.1 to 1.0 is usually good enough)
# presence_penalty (-2.0 to 2.0, similar to frequency_penalty)


def isSum(n,a,b):
    if a<b:
        b,a=a,b
    while n>=0:
        if n%a==0:
            return True
        n-=b
    return False

n = int(input())
if isSum(n,3,7):
    print("yes")
else:
    print("no")


import random
import pygame
import math
from dataclasses import dataclass

SIZE = (400, 400)
MAX_LINE_LENGTH = 80

SPEED_MU = 20
MAX_SIZE = 3
WHITE = (255, 255, 255, 255)

@dataclass
class Star:
    pos: pygame.Vector2
    speed: pygame.Vector2
    size: int

    def update(self, screen, elapsed):
        pygame.draw.circle(screen, WHITE, self.pos, self.size)
        self.pos += elapsed * self.speed
        return int(self.pos.x) in range(SIZE[0]) and int(self.pos.y) in range(SIZE[1])

    def __sub__(self, other):
        return (self.pos - other.pos).length()

def map_distance_to_color(distance):
    if distance < MAX_LINE_LENGTH:
        g = int(255 * (1 - distance / MAX_LINE_LENGTH))
        return (g, g, g, g)
    return None

class StarField:

    def __init__(self, count=100):
        self._count = count
        self._stars = []
        self._respawn()

    def _respawn(self):
        for _ in range(self._count - len(self._stars)):
            star = Star(
                pos=pygame.Vector2(
                    random.randint(0, SIZE[0] - 1),
                    random.randint(0, SIZE[1] - 1),
                ),
                speed=pygame.Vector2(
                    random.gauss(0, SPEED_MU),
                    random.gauss(0, SPEED_MU),
                ),
                size=random.randint(1, MAX_SIZE),
            )
            self._stars.append(star)

    def update(self, screen, elapsed):
        remove = []
        lines = []
        for a in self._stars:
            for b in self._stars:
                if a is not b:
                    distance = a - b
                    color = map_distance_to_color(distance)
                    if color is not None:
                        lines.append((color, a.pos, b.pos))

        for color, a_pos, b_pos in sorted(lines, key=lambda line: line[0]):
            pygame.draw.line(screen, color, a_pos, b_pos)

        for star in self._stars:
            alive = star.update(screen, elapsed)
            if not alive:
                remove.append(star)
        for star in remove:
            self._stars.remove(star)
        self._respawn()

def main():
    pygame.init()
    pygame.display.set_caption("Star Geometry")

    screen = pygame.display.set_mode(SIZE)
    clock = pygame.time.Clock()
    star_field = StarField()

    running = True
    elapsed = 0

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        screen.fill((0, 0, 0))
        star_field.update(screen, elapsed / 1000)
        pygame.display.flip()
        elapsed = clock.tick(60)

if __name__ == "__main__":
    main()


from Tools.Vector2D import Vector2D
import pygame

class SimpleObject(object):
    def __init__(self, role_image, position):
        self.position = position
        self.speed = 1
        self.role_image = pygame.image.load(role_image)
        self.width = self.role_image.get_width()
        self.height = self.role_image.get_height()

    def move_to(self, destination):
        direction = Vector2D.from_to(self.position, destination).normalize()
        x = self.position[0]
        if 0 < x < self.world.width:
            x = self.position[0] + direction.x * self.speed
        y = self.position[1]
        if 0 < y < self.world.height:
            y = self.position[1] + direction.y * self.speed
        self.position = (x, y)


N = int(input())
A = sorted(list(map(int, input().split())))
X = [[] for _ in range(10)]
for a in A:
  X[len(str(a))].append(a)

B = []
for x in X[::-1]:
  B.extend(sorted(x, reverse=True))

b1, b2, b3 = list(map(str, B[:3]))

C = [
  b1 + b2 + b3,
  b1 + b3 + b2,
  b2 + b1 + b3,
  b2 + b3 + b1,
  b3 + b1 + b2,
  b3 + b2 + b1,
]

ans = max(map(int, C))
print(ans)


import cv2
import numpy as np
from skimage import transform as trans

def face_align(img_rgb, landmarks):
    """
    This function aligns the face based on the 5 facial landmarks.

    :param img_rgb:
    :type img_rgb: np.ndarray
    :param landmarks:
    :type landmarks: list
    :return:
    """

    # These are predefined coordinates for 5 facial landmarks based on the standard 112x112 image.
    src = np.array([
        [30.2946, 51.6963],
        [65.5318, 51.5014],
        [48.0252, 71.7366],
        [33.5493, 92.3655],
        [62.7299, 92.2041]], dtype=np.float32)

    # Convert landmarks to numpy array and reshape it to (5, 2) for further operations.
    dst = np.array(landmarks, dtype=np.float32).reshape(5, 2)

    # Use similarity transform from skimage library to estimate the transformation matrix.
    tform = trans.SimilarityTransform()
    tform.estimate(dst, src)

    # Extract the transformation matrix from the transformation object.
    M = tform.params[0:2, :]

    # Apply the transformation matrix to the image to align the face.
    # Here, borderValue=0 is used to fill pixels outside the input boundaries.
    aligned = cv2.warpAffine(img_rgb, M, (112, 112), borderValue=0)

    return aligned


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

"""
Dado um número inteiro n, escreva “SIM” se ele é ao mesmo
tempo ímpar, múltiplo de 3 e múltiplo de 7. Caso contrário,
escreva “NÃO”.

Obs.:
    * ímpar -> n % 2
    * múltiplo de 3 -> n % 3
    * múltiplo de 7 -> n % 7

link: https://www.pythonprogressivo.net/2018/03/Saber-Numero-Par-Impar-Python.html
"""

n = int(input())
if n % 2 and n % 3 and n % 7:
    print('SIM')
else:
    print('NÃO')

exit(0)


# This file includes two ways of analysising human data.
# precision list & entropy list

# %%
import pandas as pd
import numpy as np
# %%

# This function is for reading the file data and data labels.
def get_human_data(filename):
    data = pd.read_csv(filename, sep=';')
    y_label = data['Story']
    emotions = ['Emo.Happiness','Emo.Joy','Emo.Pride','Emo.Boredom',
        'Emo.Fear','Emo.Sadness','Emo.Shame',]
    full_data = data[emotions].values
    return full_data, y_label

def get_human_limit_data(filename):
    data = pd.read_csv(filename, sep=';')
    y_label = data['Story']
    emotions = ['Em.Happiness','Em.Joy','Em.Pride','Em.Boredom',
        'Em.Fear','Em.Sadness','Em.Shame',]
    full_data = data[emotions].values
    return full_data, y_label

# This function is for extracting the precision list
# The list extract data when its feature and the label are the same

def get_precision_list(data,label):
    precision_list = []
    target_names = ['Happiness','Joy','Pride','Boredom','Fear','Sadness','Shame']
    for i in range(len(data)):
        index = target_names.index(label[i])
        precision_list.append(data[i][index])
    return precision_list

human_data_file = 'data/Exp1_human.csv'
human_data, human_data_label= get_human_data(human_data_file)

precision_list = get_precision_list(human_data, human_data_label)
mean = np.average(precision_list)
variance = np.var(precision_list)

print(mean,variance)
# For human_free:
# 0.4019302024931973 0.027696655833540938

#%%
# To calculate the precision for human limited rating data
human_limit_data_file = 'data/human_limit.csv'
human_limit_data, human_limit_data_label= get_human_limit_data(human_limit_data_file)

precision_list_limit = get_precision_list(human_limit_data, human_limit_data_label)
mean_limit = np.average(precision_list_limit)
variance_limit = np.var(precision_list_limit)

print(mean_limit,variance_limit)
# For human_limit:
# 0.8714285714285714 0.11204081632653061