import pandas as pd
import time

datafile = input("Type your dataset name: (example.csv)\n")
df = pd.read_csv(datafile)
kata = input("Type your 1st word:\n")
start = time.time()
dfsearch = df.loc[df['word1'] == kata] ## mencari data yang mengandung kata yang diinput
newdf = pd.DataFrame(columns=["word1", "word2", "freqs"])
freqstotalkiri = 0 ## frekuensi total dari tabel word1
freqstotalkanan = 0 ## frekuensi total dari tabel word2
maks = 0 ## hasil perbandingan peluang
hasilpredict = '' ## hasil prediction

for index, row in dfsearch.iterrows():
    freqword = 0
    cariword2 = df.loc[df['word2'] == row['word2']]
    for freq in cariword2.freqs:
        freqword += freq
    freqstotalkanan += freqword
    freqstotalkiri += int(row['freqs'])

for index, row in dfsearch.iterrows():

    cari1 = df.loc[(df['word1'] == kata) & (df['word2'] == row['word2'])]
    freq1 = 0
    for freq in cari1.freqs:
        freq1 += int(freq)

    freq2 = 0
    cari2 = df.loc[df['word2'] == row['word2']]
    for freq in cari2.freqs:
        freq2 += int(freq)

    p1 = freq1 / freq2
    p2 = freq2 / freqstotalkanan
    p3 = freqstotalkiri / freqstotalkanan

    rumus = (p1 * p2) / p3
    if rumus > maks:
        maks = rumus
        hasilpredict = row['word2']
print("Result:")
print(kata, hasilpredict)
print()
print("With score:")
print(rumus)
print()
end = time.time()
print("Process duration:")
print(end - start)


from __future__ import absolute_import, division, print_function, unicode_literals

import datetime
from dateutil.parser import parse as date_parse

from .common import BaseTest, Config
from .test_offhours import mock_datetime_now

class ElasticBeanstalkEnvironment(BaseTest):

    def test_resource_manager(self):
        config = Config.empty(account_id='012345678901')
        factory = self.replay_flight_data('test_elasticbeanstalk_describe_envs')
        p = self.load_policy({
            'name': 'eb-env-query',
            'resource': 'elasticbeanstalk-environment',
            }, session_factory=factory)
        resources = p.run()
        self.assertEqual(len(resources), 4)

    def test_eb_env_regex(self):
        config = Config.empty(account_id='012345678901')
        factory = self.replay_flight_data('test_elasticbeanstalk_describe_envs')
        p = self.load_policy({
            'name': 'eb-find-inactive',
            'resource': 'elasticbeanstalk-environment',
            'filters': [
                {
                    'type': 'value',
                    'key': 'CNAME',
                    'op': 'regex',
                    'value': '.*inactive.*',
                    }
                ],
            }, session_factory=factory)
        resources = p.run()
        self.assertEqual(len(resources), 2)

    def test_eb_env_uptime(self):
        config = Config.empty(account_id='012345678901')
        factory = self.replay_flight_data('test_elasticbeanstalk_describe_envs')
        p = self.load_policy({
            'name': 'eb-find-inactive',
            'resource': 'elasticbeanstalk-environment',
            'filters': [
                {
                    'type': 'value',
                    'key': 'DateCreated',
                    'value': 1,
                    'value_type': 'age',
                    'op': 'greater-than',
                    }
                ],
            }, session_factory=factory)
        with mock_datetime_now(date_parse('2017-10-19'), datetime):
            resources = p.run()
        self.assertEqual(len(resources), 2)


"""
Instructor: Charlotte Chaze
Class: Udacity Data Analyst
Semester: Summer 2022
Assignment: Bikeshare Data
Student: Emma Hungrige
"""

#Import Section
import time
import pandas as pd

#CSV Variable
CITY_DATA = { 'chicago': 'chicago.csv',
              'new york city': 'new_york_city.csv',
              'washington': 'washington.csv' }

MONTH_DATA = ["all", "january", "february", "march", "april", "may", "june"]

DAY_DATA = ["all", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]

#Definitions
def get_filters():
    """
    Asks user to specify a city, month, and day to analyze.

    Returns:
        city (str) - name of the city to analyze
        month (str) - name of the month to filter by, or "all" to apply no month filter
        day (str) - name of the day of the week to filter by, or "all" to apply no day filter
    """

    print("Hello! Welcome to the Bikeshare Analysis Program.")
    print()

    #Get user input for the city
    city_name = ""
    while city_name.lower() not in CITY_DATA:
        city_name = input("Which city would you like to filter by? Please enter either New York City, Chicago, or Washington.\n").lower().strip()

        if city_name in CITY_DATA:
            city = CITY_DATA[city_name.lower()]
        else:
            print("ERROR! INVALID ANSWER!")

    #Get user input for month
    month_name = ""
    while month_name.lower() not in MONTH_DATA:
        month_name = input("Which month would you like to filter by? Please enter January, February, March, April, May, June, or 'all' if you do not have any preference.\n").lower().strip()
        if month_name in MONTH_DATA:
            month = month_name.lower()
        else:
            print("ERROR! INVALID ANSWER!")

    #Get user input for day of the week
    day_name = ""
    while day_name.lower() not in DAY_DATA:
        day_name = input("Which day of the week would you like to filter by? Please enter either Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday or 'all'.\n").lower().strip()
        if day_name in DAY_DATA:
            day = day_name.lower()
        else:
            print("ERROR! INVALID ANSWER!")

    print("-"*40)
    return city, month, day

def load_data(city, month, day):
    """
    Loads data for the specified city and filters by month and day if applicable.

    Arguments:
        city (str) - name of the city to analyze
        month (str) - name of the month to filter by, or "all" to apply no month filter
        day (str) - name of the day of the week to filter by, or "all" to apply no day filter

    Returns:
        df - Pandas DataFrame containing city data filtered by month and day
    """

    #Load data file into a dataframe
    df = pd.read_csv(city)

    #Convert start time column to datetime
    df["Start Time"] = pd.to_datetime(df["Start Time"])

    #Extract month and day of week from start time column to create new columns
    df["month"] = df["Start Time"].dt.month
    df["day_of_week"] = df["Start Time"].dt.day_name()
    df["hour"] = df["Start Time"].dt.hour

    #Filter by month if applicable
    if month != "all":
        #Use index of the months list to get corresponding int
        month = MONTH_DATA.index(month)

        #Filter by month to create the new dataframe
        df = df.loc[df["month"] == month]

    #Filter by week if applicable
    if day != "all":
        #Filter by day of the week to create the new dataframe
        df = df.loc[df["day_of_week"] == day.title()]

    return df

def time_stats(df):
    """
    Displays statistics on the most frequent times of travel.
    """

    print("Calculating the most frequent times of travel...\n")
    start_time = time.time()

    #Display the most common month
    pop_month = df["month"].mode()[0]
    print(f"Most Common Month: {MONTH_DATA[pop_month].title()}")

    #Display the most common day of the week
    pop_day = df["day_of_week"].mode()[0]
    print(f"Most Common Day: {pop_day}")

    #Display the most common start hour
    pop_hour = df["hour"].mode()[0]
    print(f"Most Common Hour: {pop_hour}")

    print("This took %s seconds." % (time.time() - start_time))
    print("-"*40)

def station_stats(df):
    """
    Displays statistics on the most popular stations and trips.
    """

    print("Calculating the most popular stations and trips...\n")
    start_time = time.time()

    #Display most commonly used start station
    start_station = df["Start Station"].mode()[0]
    print(f"Most Commonly Used Start Station: {start_station}")

    #Display most commonly used end station
    end_station = df["End Station"].mode()[0]
    print(f"Most Commonly Used End Station: {end_station}")

    #Display most frequent combination of start station and end station trips
    frequent_combination = (df['Start Station'] + "||" + df['End Station']).mode()[0]
    print("The most frequent combination of start station and end station trip is : " + str(frequent_combination.split("||")))

    print("This took %s seconds." % (time.time() - start_time))
    print("-"*40)

def trip_duration_stats(df):
    """
    Displays statistics on the total and average trip durations.
    """
    print("Calculating trip durations...\n")
    start_time = time.time()

    #Display total travel time
    total_travel_time = df["Trip Duration"].sum()
    print(f"Total Travel Time: {total_travel_time} days.")

    #Display mean travel time
    avg_travel_time = df["Trip Duration"].mean()
    print(f"Average Travel Time: {avg_travel_time} minutes.")

    print("This took %s seconds." % (time.time() - start_time))
    print("-"*40)

def user_stats(df):
    """Displays statistics on bikeshare users.
    Args:
        (DataFrame) df - Pandas DataFrame containing city data filtered by month and day
    """

    print('\nCalculating User Stats...\n')
    start_time = time.time()

    # TO DO: Display counts of user types
    user_types = df['User Type'].value_counts()
    print("The count of user types from the given fitered data is: \n" + str(user_types))

    #Display counts of gender
    try:
        gender_types = df["Gender"].value_counts()
        print(f"Gender Types:\n {gender_types}")
    except KeyError:
        print("Gender Types: NO DATA AVAILABLE FOR THIS MONTH.")

    #Display earliest, most recent, and most common birth year
    try:
        earliest = df["Birth Year"].min()
        print(f"Earliest Birth Year: {earliest}")
    except KeyError:
        print("Earliest Birth Year: NO DATA AVAILABLE FOR THIS MONTH.")

    try:
        recent = df["Birth Year"].max()
        print(f"Most Recent Birth Year: {recent}")
    except KeyError:
        print("Most Recent Birth Year: NO DATA AVAILABLE FOR THIS MONTH.")

    try:
        avg_birth_year = df["Birth Year"].value_counts().idxmax()
        print(f"Most Common Birth Year: {avg_birth_year}")
    except KeyError:
        print("Most Common Birth Year: NO DATA AVAILABLE FOR THIS MONTH.")

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)

def raw_data(df):
    """
    Displays raw data on user request.

    Arguments:
        df (DataFrame) - Pandas DataFrame containing city data filtered by month and day
    """

    print(df.head())
    next = 0

    while True:
        see_raw_data = input("Would you like to view the next five rows of raw data? Y or N.\n").lower().strip()
        if see_raw_data != "y":
            return
        next = next + 5
        print(df.iloc[next:next+5])

def main():
    while True:
        city, month, day = get_filters()
        df = load_data(city, month, day)

        time_stats(df)
        station_stats(df)
        trip_duration_stats(df)
        user_stats(df)

        while True:
            see_raw_data = input("Would you like to view the first five rows of data? Y or N.\n ").lower().strip()
            if see_raw_data != "y":
                break
            raw_data(df)
            break

        restart = input("Would you like to start over? Y or N?\n").lower().strip()
        if restart != 'y':
            break

if __name__ == "__main__":
    main()


import numpy as np
import pandas as pd
import indicator_functions
from sklearn import preprocessing
from sklearn.model_selection import train_test_split

indicator_dict = {
    "sma": indicator_functions.get_sma,
    "std": indicator_functions.get_std
}

class DataSet:
    def __init__(self, df):
        """
        DataSet class contains the current working features for the dataset, as well as
        all the methods used to process the data.

        :param df: Pandas DataFrame with shape (X, 1). The features should contain only
        the closing price, as an absolute price level.
        """
        n_rows = df.shape[0]  # Calculate number of data points for code readability

        assert df.shape[1] == 1, "DataSet initialization failed: Incorrect shape. Expected (X, 1), got {}".format(
            df.shape)

        self.features = df.copy()  # Copy the features to not edit the raw input

        # Create the labels frame
        self.labels = pd.DataFrame(
            np.zeros(shape=(n_rows, 2)),
            columns=["win", "loss"])  # Initialize wins and losses as zeros
        self.labels["nil"] = 1.0  # Initialize nil trades as 1

        # Initialize training and testing tensors for later use
        self.x_train = None
        self.y_train = None
        self.x_test = None
        self.y_test = None

    def get_indicators(self, indicators=None):
        """
        Create the specified indicators and add them to the features. If they already exist within the
        dataset, then copy them instead.
        :param indicators: Indicators to be added to the features. Formatted as a tuple with ("func", period)
        where the func is one of the available functions in the indicator dictionary.
        """
        if indicators is None:
            indicators = [("sma", 10), ("std", 10)]

        max_period = 0

        for item in indicators:
            func, period = item
            if period > max_period:
                max_period = period
            self.features["{}-{}".format(func, period)] = indicator_dict[func](self.features["close"], period)

        self.features = self.features.iloc[max_period:]

    def get_labels(self, profit=0.5/100, reward_risk=2.0, n_future=5):
        """
        calc_trades method will calculate if a trade made at each
        data point would result in a take-profit or a stop-loss.
        For this first implementation, all trades are considered long
        trades, and will execute take-profit if the price goes up
        to the target, or a stop-loss if the price falls below.
        *** MAKE SURE DATA IS NOT RESCALED BEFORE CALLING THIS METHOD ***

        :param profit: The desired profit per trade, in percentage decimal form
        :param reward_risk: The reward-to-risk ratio for the trades
        :param n_future: The amount of time steps into the future to execute on
        :return: None. If return_frame is true, will return DataFrame whose entries
        are either [0,0,0], for stop-loss, indeterminate, or take-profit, respectively.
        """
        features = self.features["close"]  # Make sure we only have the "close" column
        labels = self.labels  # Pull the labels frame for encoding

        for i, val in enumerate(features[:-n_future]):  # Iterate over the close features while avoiding an IndexError
            # take_profit = val * (1 + profit) = val + val*profit The calculation for the take-profit level
            # stop_loss = val * (1 - (profit / reward_risk)) The calculation for the stop-loss level

            for k in range(i, i + n_future):  # Iterate over the next n_future entries in 'close'
                if features.iloc[k] >= val * (1 + profit):  # If the value is above take-profit
                    labels["win"].iloc[i] = 1  # Return 1 for a successful trade
                    labels["nil"].iloc[i] = 0  # Trade was executed, update nil column to 0
                    break  # The take-profit was triggered, so break the current loop
                elif features.iloc[k] <= val * (1 - (profit / reward_risk)):  # If the value is below stop-loss
                    labels["loss"].iloc[i] = 1  # Return -1 for a failed trade
                    labels["nil"].iloc[i] = 0  # Trade was executed, update nil column to 0
                    break  # The stop-loss was triggered, so break the current loop
        return None

    def preprocess(self, feature_window_size=5, test_split=0.5):
        """
        Scales all features data to be equal to the percent difference since the last data point. This allows negative
        values. Next, the data is re-normalized between -1 to 1 for use in the network. Lastly, the features and labels
        are reformatted into tensors of shape (batches, timesteps, features) for use in the LSTM layer. Note that for
        the labels tensor, the timesteps is always set to 1.
        :param test_split: Test-train ratio
        :param feature_window_size: The window size of the timesteps for the features tensor of shape (batches,
            timesteps, features)
        :return: None
        """

        assert isinstance(feature_window_size, int), "feature_window_size must be an integer. Found {}".format(
            str(type(feature_window_size)))

        # Scale the data using percent difference between timesteps, and then re-normalize from -1 to 1
        for item in self.features.columns:  # Iterate over all features
            df = self.features[item]  # Local variable for ease of writing

            for i in range(df.shape[0]-1, 0, -1):  # Iterate backwards over all elements, excluding the 0 position
                df.iloc[i] = 100*(df.iloc[i]-df.iloc[i-1]) / df.iloc[i-1]  # Percent difference from last time step

            df.iloc[0] = 0  # Initialize first value as zero

        # Reshape the features frame into a tensor of shape (batches, window_size, features)
        batches = self.features.shape[0] - feature_window_size
        feature_dim = self.features.shape[1]
        features_tensor = np.empty(shape=(batches, feature_window_size, feature_dim), dtype="float32")

        labels_trimmed = self.labels[feature_window_size:]
        for i in range(batches):
            features_tensor[i] = self.features.iloc[i: i+feature_window_size]

        self.x_train, self.x_test, self.y_train, self.y_test = train_test_split(
            features_tensor, labels_trimmed, test_size=test_split, shuffle=False)

        scaler = preprocessing.StandardScaler(with_mean=False)

        for batch in self.x_train:
            scaler.partial_fit(batch)

        for tensor in [self.x_train, self.x_test]:
            for batch in tensor:
                batch = scaler.transform(batch)  # This only works because np arrays are mutable!

        return None

    def get_splits(self):
        # Function to return test-train split of the data set
        # sklearn.transform.fit(train) scale data according to training set
        #    then, sklearn.transform(test) will use the scaling factors from above
        #    to scale the test data
        pass

    def clear(self):
        # Reset the features to be just the close value
        self.features = self.features["close"]


import tensorflow as tf
import numpy as np
from collections import OrderedDict
import cv2 as cv
import imutils
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import warnings
import pickle
import time
from collections import defaultdict

from src.DepthEstimationModel import DepthEstimationModel

def prepare_image(image=None, feed_width=640, feed_height=192, batch_dim=True, as_tensor=True,
                  channel_first=False, type = 'ImageNet'):
    if image is None:
        image_path = 'assets/test_image.jpg'
        image = cv.imread(image_path)
    image = cv.cvtColor(image, cv.COLOR_BGR2RGB)
    original_height, original_width = image.shape[:2]
    if max(image.shape[:2]) > max(feed_width, feed_height):
        interp_op = cv.INTER_AREA
    else:
        interp_op = cv.INTER_CUBIC
    input_data = cv.resize(image, (feed_width, feed_height), interp_op)
    input_data = input_data.astype(np.float32) / 255.
    if batch_dim is False and (as_tensor or channel_first):
        warnings.warn('Since batch_dim is false, so as_tensor and channel_first do not have effect')
        as_tensor, channel_first = False, False
    if batch_dim:
        input_data = np.expand_dims(input_data, 0)
        if channel_first:
            input_data = np.transpose(input_data, [0, 3, 1, 2])
        if as_tensor:
            input_data = tf.constant(input_data)
    if type == 'ImageNet':
        input_data = (input_data - 0.45) / 0.225
    return input_data, (original_height, original_width)

def visualize(model: DepthEstimationModel = None, channel_first=False):
    outputs = model.disp
    original_height, original_width = model.original_size
    print("H: %d, W: %d"%(original_height, original_width), type(original_height))

    print("-> Visualizing...")
    if channel_first:
        outputs = np.transpose(outputs, [0, 2, 3, 1])
        print("Change to channel-last, now: ", outputs.shape)
    disp_np = np.squeeze(outputs)
    # output_name = os.path.splitext(os.path.basename(image_path))[0]
    vmax = np.percentile(disp_np, 95)
    normalizer = mpl.colors.Normalize(vmin=disp_np.min(), vmax=vmax)
    mapper = cm.ScalarMappable(norm=normalizer, cmap='magma')
    colormapped_im = (mapper.to_rgba(disp_np)[:, :, :3] * 255).astype(np.uint8)

    colormapped_im = imutils.resize(colormapped_im, width=original_width, height=original_height)

    print(type(colormapped_im), colormapped_im.shape)
    # plt.imshow(colormapped_im), plt.show()

    return colormapped_im

def process_enc_outputs(features_raw, enc_model='pb', dec_model='pb'):
    """convert featrues from encoder to proper form for decoder input
    encoder/decoder model type: 'pb' or 'keras'
    Note:
        - For outputs: keras gives LIST; saved_model (.pb) gives DICTIONARY
        - For inputs: for multiple inputs, keras takes TUPLE; saved_model takes DICTIONARY,or keyword-specific arguments
    Examples:
    1) enc_pb -> decoder_pb: 'dict' -> 'dict'
    2) enc_keras -> decoder_keras 'list' -> 'tuple'
    """
    model_types = ['pb', 'keras']
    if enc_model not in model_types and dec_model not in model_types:
        raise NotImplementedError

    if enc_model == model_types[0]:
        if dec_model == model_types[0]:
            features = {}
            for i in range(1, 6):
                features['input_%d' % i] = (features_raw['output_%d' % i])
        elif dec_model == model_types[1]:
            features = []
            for i in range(1, 6):
                features.append(features_raw['output_%d' % i])
                features = tuple(features)

    elif enc_model == model_types[1]:
        if dec_model == model_types[0]:
            features = {}
            for i in range(1, 6):
                features['input_%d' % i] = features_raw[i]
        elif dec_model == model_types[1]:
            features = tuple(features_raw)

    else:
        raise NotImplementedError

    return features

def init_models(model: DepthEstimationModel):
    # encoder = tf.keras.models.load_model("encoder_res18_singlet")
    enc_imported = tf.saved_model.load(model.encoder_path)
    print("encoder loaded")

    # encoder = tf.keras.models.load_model("encoder_res18_singlet")
    dec_imported = tf.saved_model.load(model.decoder_path)
    print("decoder loaded")
    return enc_imported, dec_imported

def run_estimation(image, model: DepthEstimationModel, show_result:bool= True, data_path:str= None, timer_on=True):
    colormapped_img, scaled_disp = None, None
    model.original_size = image.shape[:2]
    if model.encoder_net is None or model.decoder_net is None:
        model.encoder_net, model.decoder_net = init_models(model)

    timers = defaultdict(lambda:1e-4)
    t1 = time.time()
    encoder = model.encoder_net.signatures['serving_default']
    decoder = model.decoder_net.signatures['serving_default']
    model.clear_results()
    input_data, model.size = prepare_image(image, batch_dim=True, as_tensor=True, channel_first=False)
    timers['preprocess'] = time.time() - t1

    t1 = time.time()
    model.features = encoder(input_data)
    dec_input = process_enc_outputs(model.features, enc_model='pb', dec_model='pb')
    timers['encoding'] = time.time() - t1

    t1 = time.time()
    disp_raw = decoder(**dec_input)
    for k, v in disp_raw.items():
        model.disp = v
    timers['decoding'] = time.time() - t1

    if show_result:
        t1 = time.time()
        colormapped_img = visualize(model)
        timers['visualizing'] = time.time() - t1
    if data_path:
        # todo: which one is the depth?
        scaled_disp, depth = postprocess(model.disp, depth_npy_path=data_path)
        print("depth value saving... in %s " % data_path)
    if timer_on:
        print_runtime(timers, image=None)
    return colormapped_img, scaled_disp

def postprocess(disp, depth_npy_path=None):
    import os

    def disp_to_depth(disp, min_depth, max_depth):
        """Convert network's sigmoid output into depth prediction
        The formula for this conversion is given in the 'additional considerations'
        section of the paper.
        """
        min_disp = 1. / max_depth
        max_disp = 1. / min_depth
        scaled_disp = min_disp + (max_disp - min_disp) * disp
        depth = 1. / scaled_disp
        return scaled_disp, depth

    scaled_disp, depth = disp_to_depth(disp, 0.1, 100)

    if depth_npy_path is not None:
        if not os.path.exists(depth_npy_path):
            os.makedirs(depth_npy_path)
        np.save(depth_npy_path, depth.numpy())

    return scaled_disp

def print_runtime(timers, image=None):
    """ all timers stored in a dictonary"""
    all_ms, all_fps = '', ''
    for name, val in timers.items():
        all_ms = ''.join([all_ms, name,': ', '%.1f'%(val*1000), 'ms | '])
        all_fps = ''.join([all_fps, name,': ', '%.1f'%(1./(val+1e-5)), 'FPS | '])
    print(all_ms)
    print(all_fps)
    if image is not None:
        fontScale, fontFace = 0.5,  0
        text_size, base_line = cv.getTextSize(all_ms, fontFace, fontScale, 1)
        cv.putText(image, all_ms, (10, 20), fontFace, fontScale, color=(255,255,255), thickness=1)
        cv.putText(image, all_fps, (10, 40),
                   fontFace, fontScale, color=(255, 255, 255), thickness=1)


from nodo import nodo
from pieza import pieza
class lista_piezas:

    def __init__(self):
        self.primero = None
        self.columnas = 0
        self.filas = 0
        self.contador = 0

    def insertar_pieza(self,pieza):
        if self.primero is None:
            self.primero = nodo(pieza = pieza)
            self.contador +=1
        else:
            actual = self.primero
            while actual.siguiente:
                  actual = actual.siguiente
            actual.siguiente = nodo(pieza = pieza)
            self.contador+=1

    def recorrer_e_imprimir_lista(self):
        print("")
        print("")
        actual = self.primero
        print("--------------------------")
        while actual != None:
                print(self.columnas)
                print("Fila: ",actual.pieza.fila,"Columna: ",actual.pieza.columna,"Color: ",actual.pieza.color)
                actual = actual.siguiente
        print("--------------------------")
        print("")
        print("")

    def recorrer_Tablero(self,filas,columnas):
        for i in range(1,filas+1):
         for j in range(1,columnas+1):
            self.insertar_pieza(pieza(i,j,"White"))

    def actualizar_pieza(self,fila,columna,color):
        actual=self.primero
        while actual != None:
            if actual.pieza.fila == fila and actual.pieza.columna == columna:
                actual.pieza.color=color
                print("Se pintó la pieza con éxito!")
                return
            actual = actual.siguiente
        print("La posición ingresada no Existe, pruebe con otra :=)")

    def devolver_color(self,fila,columna):
        actual = self.primero
        while actual != None:
            if actual.pieza.fila == fila and actual.pieza.columna == columna:
                return actual.pieza.color
            actual = actual.siguiente

    def imprimir_tablero(self):
        for i in range(1,self.filas+1):
            for j in range(1,self.columnas+1):
                print(self.devolver_color(i,j), end = " ")

        print("")
        print("")


info = input()

side_by_player = {}
players_by_side = {}

while info != "Lumpawaroo":
    if "|" in info:
        force_side, force_user = info.split(" | ")

        if force_side not in players_by_side:
            players_by_side[force_side] = []

        if force_user not in side_by_player:
            side_by_player[force_user] = force_side
            players_by_side[force_side].append(force_user)
    else:
        force_user, force_side = info.split(" -> ")

        if force_side not in players_by_side:
            players_by_side[force_side] = []

        players_by_side[force_side].append(force_user)

        if force_user in side_by_player:
            old_side = side_by_player[force_user]
            players_by_side[old_side].remove(force_user)
            side_by_player[force_user] = force_side

        else:
            side_by_player[force_user] = force_side
        print(f"{force_user} joins the {force_side} side!")

    info = input()

for side,members in players_by_side.items():
    if len(members) == 0:
        continue
    print(f"Side: {side}, Members: {len(members)}")
    for member in members:
        print(f"! {member}")

PythonFundamentals/Dictionaries - Exercise/11. Force Book.py


# No. 3
# 基于数据构建相关的标签
# 将数据的个个特征打上不同的标记
# 删除缺失值过多的访问（之所以要在这里做而非在之前做，是因为部分访问可能缺失值很多，但是其作为标签时的信息不应被直接浪费）
# 20200715复核
# 20200731复核
from util import *
import os
import numpy as np
import matplotlib.pyplot as plt

def main():
    visit_delete_missing_rate = 0.3
    figure_save_folder = os.path.abspath('../../resource/preprocessed_data/mimic_feature_distribution')
    feature_order_path = os.path.abspath('../../resource/mapping_file/mimic/feature_order.csv')
    data_path = os.path.join(os.path.abspath('../../resource/preprocessed_data/'), 'mimic_after_variable_selection.csv')

    feature_dict_list = read_feature_list(feature_order_path)
    data_dict = general_read_data_to_dict(data_path, skip_extra_line=2)
    print('data, visit: {}, variable num: {}'
          .format(calculate_visit_count(data_dict), calculate_variable_number(data_dict)))
    next_visit_dict = next_visit_index(data_dict)
    reorganized_data_dict = data_reorganization(data_dict, next_visit_dict, feature_dict_list)
    print('reorganized data, visit: {}, variable num: {}'
          .format(calculate_visit_count(reorganized_data_dict), calculate_variable_number(reorganized_data_dict)))
    reorganized_data_dict = delete_visit_missing_too_much(reorganized_data_dict, visit_delete_missing_rate)
    print('discard visit with significant missing, remaining: {}, variable num: {}'
          .format(calculate_visit_count(reorganized_data_dict), calculate_variable_number(reorganized_data_dict)))
    reorganized_data_dict = discard_visit_without_label_or_disease(reorganized_data_dict)
    print('discard visit without label or disease, remaining: {}, variable num: {}'
          .format(calculate_visit_count(reorganized_data_dict), calculate_variable_number(reorganized_data_dict)))

    save_path = os.path.join(os.path.abspath('../../resource/preprocessed_data/'),
                             'mimic_after_label_generate_and_visit_selection.csv')
    write_data_dict_to_csv(reorganized_data_dict, save_path, True, True)
    plot_all_numeric_feature_with_distribution(reorganized_data_dict, figure_save_folder)

def discard_visit_without_label_or_disease(data_dict):
    """20200731复核，删除患者中没有label的或者没有interact的"""
    discard_set = set()
    for patient_id in data_dict:
        for visit_id in data_dict[patient_id]:
            discard_flag_interact = True
            discard_flag_label = True
            for key in data_dict[patient_id][visit_id]:
                if key.__contains__('disease') or key.__contains__('risk') or key.__contains__('category'):
                    value = float(data_dict[patient_id][visit_id][key])
                    if value > 0.5:
                        discard_flag_interact = False
                if key.__contains__('label'):
                    value = float(data_dict[patient_id][visit_id][key])
                    if value > 0.5:
                        discard_flag_label = False
            if discard_flag_interact or discard_flag_label:
                discard_set.add(patient_id+"_"+visit_id)
    for item in discard_set:
        pat_id, visit_id = item.split('_')
        data_dict[pat_id].pop(visit_id)
    print(len(discard_set))
    return data_dict

def read_feature_list(path):
    """
    由于本设计中，数据和知识图谱要搭配使用，因此特征的排列顺序要预先规定，确保idx和KG中的相应节点的idx能够严格对齐
    20200715复核
    20200731复核 确认和知识图谱（无干预版本）排序一致
    """
    feature_dict_list = dict()
    with open(path, 'r', encoding='utf-8-sig', newline='') as file:
        csv_reader = csv.reader(file)
        for line in csv_reader:
            feature_type, name = line
            if not feature_dict_list.__contains__(feature_type):
                feature_dict_list[feature_type] = list()
            feature_dict_list[feature_type].append(name)
    return feature_dict_list

def plot_all_numeric_feature_with_distribution(reorganized_data_dict, save_folder):
    # 绘制数据分布图，为接下来的分布变换做准备
    # 找出数值型变量
    numeric_feature_dict = is_feature_numerical(reorganized_data_dict)
    # 生成序列
    feature_dict = dict()
    for patient_id in reorganized_data_dict:
        for visit_id in reorganized_data_dict[patient_id]:
            for item in reorganized_data_dict[patient_id][visit_id]:
                if numeric_feature_dict[item]:
                    if not feature_dict.__contains__(item):
                        feature_dict[item] = list()
                    value = float(reorganized_data_dict[patient_id][visit_id][item])
                    if value >= 0:
                        feature_dict[item].append(value)
    # 初次值域变换
    num_dict = dict()
    for item in feature_dict:
        feature_dict[item] = np.array(sorted(feature_dict[item]))
        num_dict[item] = {'max': feature_dict[item][-1]+0.001, 'min': feature_dict[item][0]-0.001}
        feature_dict[item] = (feature_dict[item]-num_dict[item]['min'])/(num_dict[item]['max']-num_dict[item]['min'])

    for item in feature_dict:
        skip = feature_dict[item]
        log = np.log(feature_dict[item])
        arcsin = np.arcsin(feature_dict[item])**0.5
        sqrt = feature_dict[item]**0.5
        fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(7, 7))
        axs[0][0].hist(skip, bins=50)
        axs[0][1].hist(log, bins=50)
        axs[1][0].hist(sqrt, bins=50)
        axs[1][1].hist(arcsin, bins=50)
        axs[0][0].set_title('{} skip'.format(item))
        axs[0][1].set_title('{} log'.format(item))
        axs[1][0].set_title('{} sqrt'.format(item))
        axs[1][1].set_title('{} arcsin'.format(item))
        plt.savefig(os.path.join(save_folder, item+'.png'))

def delete_visit_missing_too_much(feature_dict, visit_delete_missing_rate):
    """
    20200715复核
    20200731复核
    如果一个患者的数值型数据的缺失率超过容限，则将该次数据直接删除
    """
    # 构建基本数据，及判定到底哪些特征时数值型
    feature_type_dict = dict()
    for patient_id in feature_dict:
        for visit_id in feature_dict[patient_id]:
            for item in feature_dict[patient_id][visit_id]:
                feature_type_dict[item] = False
    for patient_id in feature_dict:
        for visit_id in feature_dict[patient_id]:
            for item in feature_dict[patient_id][visit_id]:
                value = float(feature_dict[patient_id][visit_id][item])
                if value != 0 and value != 1 and value != -1:
                    feature_type_dict[item] = True
    numerical_feature_num = 0
    for item in feature_type_dict:
        if feature_type_dict[item]:
            numerical_feature_num += 1

    discard_visit_set = set()
    for patient_id in feature_dict:
        for visit_id in feature_dict[patient_id]:
            missing_count = 0
            for item in feature_dict[patient_id][visit_id]:
                if feature_type_dict[item]:
                    value = float(feature_dict[patient_id][visit_id][item])
                    if value < 0:
                        missing_count += 1
            if missing_count / numerical_feature_num > visit_delete_missing_rate:
                discard_visit_set.add(patient_id + '_' + visit_id)

    for item in discard_visit_set:
        patient_id, visit_id = item.split('_')
        feature_dict[patient_id].pop(visit_id)
    return feature_dict

def data_reorganization(data_dict, next_visit_dict, feature_dict_list):
    """
    20200715复核
    20200731复核
    """
    new_data_dict = dict()
    for patient_id in data_dict:
        new_data_dict[patient_id] = dict()
        for visit_id in data_dict[patient_id]:
            # 我们不需要没有标签的数据
            if not (next_visit_dict.__contains__(patient_id) and next_visit_dict[patient_id].__contains__(visit_id)):
                continue
            new_data_dict[patient_id][visit_id] = dict()

            # get label
            next_visit = next_visit_dict[patient_id][visit_id]
            for item in feature_dict_list['disease']:
                if data_dict[patient_id][next_visit].__contains__(item):
                    new_data_dict[patient_id][visit_id][item+'_label'] = data_dict[patient_id][next_visit][item]
            # get risk factor
            for item in feature_dict_list['risk_factor']:
                if data_dict[patient_id][next_visit].__contains__(item):
                    new_data_dict[patient_id][visit_id][item+'_risk_factor'] = data_dict[patient_id][visit_id][item]
            # get treatment
            for item in feature_dict_list['treatment']:
                if data_dict[patient_id][next_visit].__contains__(item):
                    new_data_dict[patient_id][visit_id][item+'_treatment'] = data_dict[patient_id][visit_id][item]
            # get disease
            for item in feature_dict_list['disease']:
                if data_dict[patient_id][next_visit].__contains__(item):
                    new_data_dict[patient_id][visit_id][item+'_disease'] = data_dict[patient_id][visit_id][item]
            # get disease category
            for item in feature_dict_list['category']:
                if data_dict[patient_id][next_visit].__contains__(item):
                    new_data_dict[patient_id][visit_id][item+'_category'] = data_dict[patient_id][visit_id][item]
            # get disease category
            for item in feature_dict_list['feature']:
                if data_dict[patient_id][next_visit].__contains__(item):
                    new_data_dict[patient_id][visit_id][item+'_feature'] = data_dict[patient_id][visit_id][item]
    return new_data_dict

def next_visit_index(data_dict):
    """
    20200715复核
    20200731复核
    """
    index_dict = dict()
    for patient_id in data_dict:
        index_dict[patient_id] = list()
        for visit_id in data_dict[patient_id]:
            index_dict[patient_id].append(int(visit_id))
        index_dict[patient_id] = sorted(index_dict[patient_id])

    next_visit_dict = dict()
    for patient_id in index_dict:
        if len(index_dict[patient_id]) == 1:
            continue
        next_visit_dict[patient_id] = dict()
        for index in range(len(index_dict[patient_id])-1):
            next_visit_dict[patient_id][str(index_dict[patient_id][index])] = str(index_dict[patient_id][index+1])
    return next_visit_dict

if __name__ == '__main__':
    main()


"""Test cases for the __helpers__ module."""

from datetime import datetime

import pytest
from lxml.etree import DocumentInvalid

from pyecospold.core import parse_file_v1
from pyecospold.model_v1 import ProcessInformation

@pytest.fixture(name="process_information")
def _process_information() -> ProcessInformation:
    """Fixture for getting ReferenceFunction element."""
    ecoSpold = parse_file_v1("data/v1/v1_1.xml")
    return ecoSpold.datasets[0].metaInformation.processInformation

def test_set_attribute_validator(process_information: ProcessInformation) -> None:
    "It sets attribute correctly."
    casNumberInput = "    0000110-63-4\n"
    casNumberExpected = "0000110-63-4"
    process_information.referenceFunction.CASNumber = casNumberInput

    assert process_information.referenceFunction.CASNumber == casNumberExpected

def test_set_attribute_fail(process_information: ProcessInformation) -> None:
    "It raises DocumentInvalid error."
    with pytest.raises(DocumentInvalid):
        process_information.referenceFunction.amount = "abc"

def test_set_attribute_success(process_information: ProcessInformation) -> None:
    "It sets attribute correctly."
    amount = 2.0
    process_information.referenceFunction.amount = amount

    assert process_information.referenceFunction.amount == amount

def test_set_attribute_list_success(process_information: ProcessInformation) -> None:
    "It sets attribute list correctly."
    synonyms = ["0", "1", "2"]
    process_information.referenceFunction.synonyms = synonyms

    assert process_information.referenceFunction.synonyms == synonyms

def test_set_element_text_success(process_information: ProcessInformation) -> None:
    "It sets attribute correctly."
    startDate = datetime(2000, 1, 1)
    process_information.timePeriod.startDate = startDate

    assert process_information.timePeriod.startDate == startDate


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

"""
IoT Penetration testing toolset
application EntryPoint testing set

By sarunasil
"""

import pytest
import random
import os

from iotpentool.threatmodel import ThreatModel
from iotpentool.entrypoint import EntryPoint
from iotpentool.asset import Asset
from iotpentool.technology import Technology
from iotpentool.utils import ModellingException

CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
MODEL_DIR = os.path.join(CURRENT_DIR, "stub_model")

@pytest.fixture
def asset():
	return Asset("stub","stub","stub")

@pytest.fixture
def entry_point():
	return EntryPoint("stub","stub","stub_asset","stub_filepath")

@pytest.mark.parametrize(("name","description", "filepath"), [("web page", "web page descr", "stub_filepath")])
def test_init(name, description, asset, filepath):
	'''create new EntryPoint
	'''

	entry_point = EntryPoint(name, description, asset, filepath)

	assert entry_point
	assert entry_point.name == name
	assert entry_point.description == description
	assert entry_point.asset_used == asset
	assert entry_point.entry_points_filepath == filepath

@pytest.mark.parametrize(("content","create"), [
	([], True),
	([], False),
	(["  'entry_pointName1': 'desc_of_entry_point1'\n"], False),
	(["  'entry_pointName1': 'desc_of_entry_point1'\n","  'entry_pointName2': 'desc_of_entry_point2'\n","  'entry_pointName3': 'desc_of_entry_point3'\n"], False)
])
def test_update_known_entry_points(entry_point, content, create):

	#create stub model-entry_points.yml file
	entry_points_filepath = os.path.join(MODEL_DIR, "model-entry_points"+ str(random.randint(1,1001)) +".yml")
	if not create:
		try:
			with open(entry_points_filepath, 'w') as configfile:
				configfile.write("entry_points:\n")
				configfile.writelines(content)
		except IOError as e:
			print("Could not create entry_points file. "+ e.strerror)
			assert False
	entry_point.entry_points_filepath = entry_points_filepath

	#get prev entry_points
	prev_known_entry_points = EntryPoint.fetch_known_entry_points(entry_points_filepath)

	#update entry_points file
	entry_point.update_known_entry_points()

	#get current entry_points
	current_known_entry_points = EntryPoint.fetch_known_entry_points(entry_points_filepath)

	#delete that file
	os.remove(entry_points_filepath)

	#check that prev_entry_points + added entry_point == current_asssets
	assert { **prev_known_entry_points, **{entry_point.name: entry_point.description} } == current_known_entry_points

@pytest.mark.parametrize(("entry_points_file","outcome","delete"), [
	(
		"model-entry_points_fetch.yml",
		{
			"entry_pointName1":"desc_of_entry_point1",
			"entry_pointName2":"desc_of_entry_point2",
			"entry_pointName3":"desc_of_entry_point3"
		},
		False
	),
	(
		"model-entry_points_empty.yml",
		{},
		False
	),
	(
		"model-entry_points_fake.yml",
		{},
		True
	)
])
def test_fetch_known_entry_points(entry_points_file, outcome, delete):

	entry_points_filepath = os.path.join(MODEL_DIR, entry_points_file)
	known_entry_points = EntryPoint.fetch_known_entry_points(entry_points_filepath)

	assert known_entry_points == outcome

	if delete:
		os.remove(entry_points_filepath)

def test_fetch_known_entry_points_exception():

	#create a corrupted file
	entry_points_filepath = os.path.join(MODEL_DIR, "model-entry_points"+ str(random.randint(1,1001)) +".yml")
	try:
		with open(entry_points_filepath, 'w') as entry_points_file:
			entry_points_file.write("\n")
	except IOError as e:
		print("Could not create entry_points file. "+ e.strerror)
		assert False

	with pytest.raises(ModellingException):
		known_entry_points = EntryPoint.fetch_known_entry_points(entry_points_filepath)

	#cleanup
	os.remove(entry_points_filepath)


"""
Module to handle the encryption and decryption of private files
"""

import subprocess

class Encryption:
    """Handles the encryption and decryption of private files"""

    def __init__(self, key_path):
        """constructor: recives a unique parameter, the absolute path to the
                        identity file used for encryption and decryption"""
        self.key_path = key_path

    def encrypt(self, original_filename):
        """Takes a local file name and generates a new one, called the same
           plus the extension '.age', encrypted with the identity file.
           Returns the exit code of the executable."""
        result = subprocess.run(['age',
                                 '--encrypt',
                                 '--identity', self.key_path,
                                 '--output', original_filename + '.age',
                                 original_filename],
                                check=False)
        return result.returncode

    def decrypt(self, target_filename):
        """Takes a local file name ending in .age, and generates a new one,
           called as the given filename, decrypted with the identity file.
           Note the argument is the name of the file to be generated, not the
           imput file.
           Returns the exit code of the executable."""
        result = subprocess.run(['age',
                                 '--decrypt',
                                 '--identity', self.key_path,
                                 '--output', target_filename,
                                 target_filename + '.age'],
                                check=False)
        return result.returncode


p = 13
q = 17
n = p*q
phi_n = (p-1) * (q-1)

e = 2
while phi_n % e == 0:
    e += 1
    if phi_n % e != 0:
        break

d = 0
mod = 0
while True:
    d += 1
    mod = (e * d) % phi_n
    if mod == 1:
        break

# Encryption
# C = P^e mod n

plain = "CAU Industrial Security"
plain_list = [ord(x) for x in plain]

cipher = []
for i in plain_list:
    x = (i ** e) % n
    cipher.append(int(x))

# Decryption
# P = C^d mod n

decrypted = []
for i in cipher:
    x = (i ** d) % n
    decrypted.append(int(x))

print('plain text', plain_list)
print('cipher text', cipher)
print('decrypted text', decrypted)

print([chr(x) for x in decrypted])
decrypted_text = ''.join([chr(x) for x in decrypted])
print(decrypted_text)


"""
calibrate_intrinsics.py and run_repeated_calibrations.sh produce a series of
pickle files in directories where images are found (a.k.a. very scattered).
The filenames will have the pattern
    f"randomrun_{len(sampled_paths)}samples_{timestamp()}.pickle"
"""
import argparse
import pickle
from collections import defaultdict
from glob import glob
from pathlib import Path

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

def parse_args():
    parser = argparse.ArgumentParser(
        prog="visualize_repeated_calibrations",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    parser.add_argument(
        "datadir",
        type=Path,
        help="Root directory where all images are stored downstream of",
    )
    args = parser.parse_args()
    return args

def project_pts(extrinsics, square_size, num_sqares_x, num_squares_y):
    """
    extrinsics : np.ndarray
        The (3,4) matrix for one set of points
    square_size : float
        The size of the square in meters
    num_squares_x :
        The number of checkerboard squares in x
    num_squares_x :
        The number of checkerboard squares in y
    """
    # Create a bunch of points in the z=0 plane
    # Project them based on extrinsics
    width = board_width * square_size
    height = board_height * square_size

    # draw calibration board
    X_board = np.ones((4, 5))
    # X_board_cam = np.ones((extrinsics.shape[0],4,5))
    X_board[0:3, 0] = [0, 0, 0]
    X_board[0:3, 1] = [width, 0, 0]
    X_board[0:3, 2] = [width, height, 0]
    X_board[0:3, 3] = [0, height, 0]
    X_board[0:3, 4] = [0, 0, 0]

if __name__ == "__main__":
    args = parse_args()
    all_pickles = glob(
        str(args.datadir.joinpath("**/randomrun*pickle")), recursive=True
    )
    for p in all_pickles:
        with open(p, "rb") as infile:
            data = pickle.load(infile)
            objpoints = data["objpoints"]
            rvecs = data["rvecs"]
            tvecs = data["tvecs"]
            fig = plt.figure()
            ax = fig.add_subplot(projection="3d")
            for i in range(len(rvecs)):
                R, _ = cv2.Rodrigues(rvecs[i])
                M = np.eye(4)
                M[:3, :3] = R
                t = tvecs[i]
                M[:3, 3:4] = t
                M = M[:3]
                objpoints = data["objpoints"][0]
                objpoints_homog = np.concatenate(
                    (objpoints, np.ones((objpoints.shape[0], 1))), axis=1
                )
                projected = M @ objpoints_homog.T

                ax.scatter(projected[0], projected[1], projected[2])

                ax.set_xlabel("X Label")
                ax.set_ylabel("Y Label")
                ax.set_zlabel("Z Label")

            plt.show()


import time
import pyautogui

def post_or_destroy(action, freq):
    counter = 0
    time.sleep(5)
    while counter < 10:
        x, y = pyautogui.position()
        button = pyautogui.locateOnScreen("img/" + action + ".png", confidence=0.8)
        if button is not None:
            pyautogui.click(button)
            pyautogui.moveTo(x, y)
            time.sleep(freq)
            button = None
            counter = 0
        else:
            counter += 1
            time.sleep(1)


"""empty message

Revision ID: c1a1267e92f7
Revises:
Create Date: 2022-07-07 00:07:40.357098

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql

# revision identifiers, used by Alembic.
revision = 'c1a1267e92f7'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('test')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('test',
    sa.Column('test', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True),
    comment='test',
    mysql_comment='test',
    mysql_default_charset='utf8mb4',
    mysql_engine='InnoDB'
    )
    # ### end Alembic commands ###


#Q2.Design python application which creates two threads as evenfactor and oddfactor.
# Both the thread accept one parameter as integer. Evenfactor thread will display
# addition of even factors of given number and oddfactor will display addition of odd
# factors of given number. After execution of both the thread gets completed main
# thread should display message as “exit from main”.
import threading

def Factor(fun,no,lock):
    fun(no,lock)

def Evenfactor(no,lock):
    lock.acquire()
    print("Even factors are")
    for i in range(1,(no//2)+1):
        if ((no%i) == 0):
            if ((i%2) == 0):
                print(i,end = " ")
    print()
    lock.release()
def Oddfactor(no,lock):
    lock.acquire()
    print("Odd factors are")
    for i in range(1,(no//2)+1):
        if ((no%i) == 0):
            if ((i%2) != 0):
                print(i,end = " ")
    print()
    lock.release()
def main():
    print("Inside main")
    value = int(input("Enter the number:"))
    lock = threading.Lock()

    t1 = threading.Thread(target = Factor,args = (Evenfactor,value,lock,))
    t2 = threading.Thread(target = Factor,args = (Oddfactor,value,lock,))

    t1.start()
    t2.start()
    t1.join()
    t2.join()

    print("Exit from main")

if __name__ =="__main__":
    main()


import numpy as np
import pickle
import pandas as pd
import tensorflow as tf
from typing import Union
from sklearn import preprocessing
from charts import WindowsChartBuilder
from features import FeaturesBuilder
from markups import MarkupBuilder

class DataBuilder:
    """
    Класс для подготовки данных для модели

    @ patch_size - Размер выборки по которым модель будет делать прогноз из прошлого (патча)
    @ features - Список используемых фич для обучения модели
    @ save_serializer - Сохранять полученный датасет без/с фич(ами) в конце
    @ show_features - Показывать текущие фичи в датасете
    @ show_forward - Показывать полученные окна на графике
    @ embed_train - Сделать вложенное проверочное окно
    @ step_window - Отступ окон с начала датасета
    @ from_end - Перенести окна в конец датасета
    @ train_window - Размер тренировочного окна
    @ val_window - Размер валидационного окна
    @ test_window - Размер тестового окна
    @ train_index - Индекс начала тренировочного окна
    @ val_index - Индекс начала валидационного окна
    @ test_index - Индекс начала тестового окна

    """

    def __init__(self, token: str, train_window=None, val_window=0.4, test_window=None,
                 features=None, save_serializer=False, serializer="csv",
                 patch_size=30, markup_frequency=10.0, show_features=None, show_windows=False, show_markup=False,
                 embed_train=False, from_end=True, step_window=500) -> None:
        self.token = token
        self.patch_size = patch_size
        self.features = features
        self.serializer = serializer
        self.save_serializer = save_serializer
        self.markup_frequency = markup_frequency
        self.show_markup = show_markup
        self.show_features = show_features
        self.show_windows = show_windows
        self.embed_train = embed_train
        self.step_window = step_window
        self.from_end = from_end

        self.train_window = train_window
        self.val_window = val_window
        self.test_window = test_window
        self.train_index = 0
        self.val_index = 0
        self.test_index = 0

        self.windows = {}
        self.data = self._try_load_or_make_dataset()
        self.targets = self._try_load_or_make_markup(self.data)
        self.scaler = self._try_load_or_make_scaler()
        # self.train_generator = self._train_window()
        # self.val_generator = self._val_window()
        # self.test_generator = self._test_window()

    def _try_load_or_make_dataset(self) -> ():
        """Метод для формирования первоначального датасета"""
        try:
            # Попробуем загрузить файл из директории
            data = pd.read_csv(f"datasets/{self.token}_.csv")
        except FileNotFoundError:
            # Файл не найден, необходимо сгенерировать датасет с нуля
            # для этого выгрузим не отформатированные данные из каталога _no_format
            data = self._read_dataset_from_file()[:5000, :-1]
            # Переводим numpy массив в DataFrame, чтобы в дальнейшем было удобно работать с данными
            data = pd.DataFrame(data, columns=["Datetime", "Open", "High", "Low", "Close", "Volume"])
            data['Datetime'] = pd.to_datetime(data['Datetime'].astype('int64'), unit='s')
            data = data.set_index("Datetime")

            if self.save_serializer:
                # Сохраним результаты в файл, что в дальнейшем выгружать все из кеша
                data.to_csv(f"datasets/{self.token}_.csv")

        # # Сформировать окна для модели
        # self._form_index_windows(data)
        # # Если включено отображение форвардного анализа - выводим график
        # if self.show_forward:
        #     WindowsChartBuilder(self.token, data,
        #                  self.train_index, self.val_index, self.test_index,
        #                  self.train_window, int(self.train_window * self.val_window), self.test_window).draw()
        return data

    def _try_load_or_make_markup(self, data) -> ():
        """Метод для формирования разметки датасета"""
        try:
            # Попробуем загрузить файл из директории
            targets = pd.read_csv(f"datasets/{self.token}_targets_.csv")
        except FileNotFoundError:
            # Делаем разметку по всему датасету
            targets = MarkupBuilder(data, self.markup_frequency, self.show_markup).make_markup()

            if self.save_serializer:
                # Сохраним результаты в файл, что в дальнейшем выгружать все из кеша
                targets.to_csv(f"datasets/{self.token}_targets_.csv")

        return targets

    def _try_load_or_make_scaler(self) -> ():
        """Метод для формирования скейлера датасета"""
        # TODO: Сделать загрузку скейлера
        scaler = preprocessing.MinMaxScaler()
        return scaler

    def add_window(self, name: str, size: Union[int, tuple], features_by_patch: bool = False):
        """Метод для инициализации нового окна"""
        # Если в качестве размера передан кортеж
        if isinstance(size, tuple):
            assert size[0] in self.windows, \
                f"{size[0]} not found in dataset dictionary! There is/are {self.windows.keys()}"
            # Извлекаем окно, которое было указано в размере
            # и получаем новый размер умножая на коэффициент
            size = int(self.windows[size[0]]["Size"] * size[1])
        # Конвертнем словарь в список
        windows = list(self.windows.keys()) # [-1]
        if len(windows) > 0:
            # Получаем последнее добавленное окно
            last_window = self.windows[windows[-1]]
            # Получаем позицию последнего окна и устанавливаем старт от него
            start_index = last_window["Start"] + last_window["Size"]
        else:
            # Это первое окно, устанавливаем позицию как нулевую
            start_index = 0
        # Если необходимо брать окно с конца, переносим все
        self.windows[name] = {"Start": start_index, "Size": size, "Features": features_by_patch}

    def compile_windows(self):
        """Метод для компиляции всех окон"""
        # Проверяем включено ли использование окон с конца
        if self.from_end:
            # Проходимся по всем окнам с конца и переносит их в конец датасета
            keys = list(self.windows.keys())
            preview_index = self.data.shape[0]
            for key in reversed(keys):
                self.windows[key]["Start"] = preview_index - self.windows[key]["Size"]
                preview_index = self.windows[key]["Start"]
        # Проходимся по всем окнам для масштабирования
        for key, item in self.windows.items():
            start_index = self.windows[key]["Start"]
            end_index = self.windows[key]["Start"] + self.windows[key]["Size"]
            features_by_patch = self.windows[key]["Features"]
            # Формируем данные окна вместе с фичами
            data, targets = self.__form_window(start_index, end_index, features_by_patch)
            print(data, targets)
            # Формируем данные патчей внутри окна
            patches = self.__form_patches(data, targets)
            # Создаем новый ключ и записываем данные патча
            self.windows[key]["Patches"] = patches
        # Если включено отображение окон
        if self.show_windows:
            self._show_windows()

    def _show_windows(self):
        """Метод для отображения окон"""
        WindowsChartBuilder(self.token, self.data, self.windows).draw()

    def __form_window(self, start_index: int, end_index: int, features_by_patch: bool) -> tuple:
        """Метод для обрезания общих данных до нужных окон"""
        data = self.data[start_index:end_index]
        targets = self.targets[start_index:end_index]
        # Формируем новый датасет, расставляем фичи
        featurized_data = FeaturesBuilder(data, self.features, by_patch=features_by_patch).make_features()
        return featurized_data, targets

    def __form_patches(self, data, targets) -> tf.keras.preprocessing.sequence.TimeseriesGenerator:
        """Метод для формирования патчей из датасета"""
        # Формируем патчи из полученного финального датасета
        patches = tf.keras.preprocessing.sequence.TimeseriesGenerator(
            data=data.to_numpy(), targets=targets.to_numpy(), length=self.patch_size,
            sampling_rate=1, batch_size=64
        )
        return patches

    def _read_dataset_from_file(self) -> np.array:
        """Метод для чтения данных с биржи из файла"""
        with open(f'tokens/{self.token}.pickle', 'rb') as handle:
            klines_per_day = pickle.load(handle)
        return np.array(klines_per_day).astype(float)

    def build(self) -> ():
        """Метод для чтения данных с биржи из файла"""

        # Загрузим данные
        # Определим сигналы
        # Определим фичи
        # Нормализуем данные
        # Сплит данных

        self.get_signals(percent=0.8, candles=self.data)
        # Получаем данные по открытиям свечи
        # prices = [float(candle[1]) for candle in self.data[:]]

        # # Получаем все сигналы по функции
        # self.signals = self.get_signals(percent=1.8, price_history=prices)
        #
        # self.x = []
        # self.y = []
        #
        # old_train_x = 10
        #
        # self.data = np.array(self.data)
        #
        # open = self.data[:, 1].astype(float)
        # open = self.scaler.fit_transform(open.reshape(-1, 1)).flatten()
        #
        # self.signals = self._signals_normalization(self.signals)
        #
        # new_signals = [{'Type': 'HOLD', 'Start': index, 'Price': price} for index, price in enumerate(prices)]
        #
        # for index_main, signal in enumerate(self.signals):
        #     new_signals[signal['Start']]['Type'] = signal['Type']
        #
        # self.signals = new_signals
        #
        # # Построим график по входным данным обучения
        # self.trade_builder = SignalsChartBuilder(self.token, self.data, self.signals)
        # self.trade_builder.build()
        #
        # # Делаем up sampling, расширение данных
        # # Иначе сеть проглотит слишком неравномерное количество равных данных
        # len_max = len([item for item in self.signals if item['Type'] == 'HOLD'])
        #
        # new_arr_sell = [item for item in self.signals if item['Type'] == 'SELL']
        # new_arr_sell *= len_max // len(new_arr_sell)
        #
        # new_arr_buy = [item for item in self.signals if item['Type'] == 'BUY']
        # new_arr_buy *= len_max // len(new_arr_buy)
        #
        # self.signals.extend(new_arr_buy)
        # self.signals.extend(new_arr_sell)
        #
        # indexes = []
        #
        # for signal in self.signals:
        #     if signal['Start'] <= old_train_x:
        #         continue
        #
        #     if signal['Type'] == 'BUY':
        #         y_binary = [0, 0, 1]
        #     elif signal['Type'] == 'SELL':
        #         y_binary = [0, 1, 0]
        #     else:
        #         y_binary = [1, 0, 0]
        #
        #     # Входными данными для X являются данные по свечам
        #     # с момента сигнала и все 5 предыдущих свечей
        #     self.x.append(open[signal['Start'] - old_train_x:signal['Start']])
        #     self.y.append(y_binary)
        #     indexes.append(signal['Start'])
        #
        # self.x = np.array(self.x)
        # self.y = np.array(self.y)
        #
        # # TODO: Тестовые данные просачиваются в тренировочные
        # indexes_train, \
        # indexes_test, \
        # x_train, \
        # x_test, \
        # y_train, \
        # y_test = train_test_split(
        #     indexes,
        #     self.x,
        #     self.y,
        #     test_size=0.20,
        #     shuffle=True
        # )
        # print('indexes_test', indexes_test)
        # return x_train, x_test[old_train_x + 2:], y_train, y_test[old_train_x + 2:], prices, indexes_test[old_train_x + 2:]


from flask import Flask, render_template, request, redirect, url_for
from tinydb import TinyDB, Query

app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True

golinks_json = 'golinks.json'
golinks_db = TinyDB(golinks_json)

########
# Routes
##########

@app.route('/')
@app.route('/index')
def index():
    return _index()

@app.route('/create')
def create():
    return render_template('create.html',
                           title='Create a new link',
                           shortcut=None,
                           redirect_url=None)

@app.route('/add', methods=['POST'])
def add():
    add_link(request.form['shortcut'], request.form['redirect'])
    return redirect(url_for('index'))

@app.route('/delete/<shortcut>/')
def delete(shortcut):
    delete_link(shortcut)
    return redirect(url_for('index'))

@app.route('/edit/<shortcut>/')
def edit(shortcut):
    link_query = Query()
    link = golinks_db.search(link_query.shortcut == shortcut)[0]
    return render_template('create.html',
                           title='Edit Link',
                           shortcut=link['shortcut'],
                           redirect_url=link['redirect'])

@app.route('/<path:path>')
def catch_all(path):
    link_query = Query()
    redirect_url = golinks_db.search(link_query.shortcut == path)

    if redirect_url:
        return redirect(redirect_url[0]['redirect'])

    return render_template('create.html',
                           title='Create a new link',
                           shortcut=path,
                           redirect_url=None)

###########
# Helpers
###########

def _index():
    links = golinks_db.all()
    return render_template('index.html',
                           title='Home',
                           links=links)

#########
# Storage
#########

def add_link(shortcut, redirect_url):
    link_query = Query()
    link = golinks_db.search(link_query.shortcut == shortcut)

    if link:
        golinks_db.update({'shortcut': shortcut, 'redirect': redirect_url},
                          link_query.shortcut == shortcut)
    else:
        golinks_db.insert({'shortcut': shortcut, 'redirect': redirect_url})

def delete_link(shortcut):
    link_query = Query()
    golinks_db.remove(link_query.shortcut == shortcut)


import datetime
from biblioteca import Biblioteca
from libro import Libro

biblioteca = Biblioteca()
while True:
    print("Bienvenido a la biblioteca. ¿Qué acción desea realizar?")
    print("1. Alta de socio")
    print("2. Baja de socio")
    print("3. Alta de libro")
    print("4. Baja de libro")
    print("5. Prestar libro")
    print("6. Devolver libro")
    print("7. Consultar libros")
    print("8. Consultar usuarios")
    print("9. Consultar prestamos")
    print("0. Salir")
    opcion = input("Opción: ")

    if opcion == "1":
        dni = input("Introduzca el DNI del usuario: ")
        nombre = input("Introduzca el nombre del usuario: ")
        correo = input("Introduzca el correo electrónico del usuario: ")
        telefono = input("Introduzca el teléfono del usuario: ")
        domicilio = input("Introduzca el domicilio del usuario: ")
        biblioteca.alta_usuario(dni, nombre, correo, telefono, domicilio)
        print("Usuario dado de alta.")

    elif opcion == "2":
        dni = input("Introduzca el DNI del usuario que desea dar de baja: ")
        for usuario in biblioteca.usuarios:
            if usuario.dni == dni:
                biblioteca.usuarios.remove(usuario)
                print("Usuario dado de baja.")
                break
        else:
            print("Usuario no encontrado.")

    elif opcion == "3":
        isbn = input("Introduzca el ISBN del libro: ")
        titulo = input("Introduzca el título del libro: ")
        autor = input("Introduzca el autor del libro: ")
        genero = input("Introduzca el género del libro: ")
        portada = input("Introduzca la portada del libro: ")
        sinopsis = input("Introduzca la sinopsis del libro: ")
        ejemplares = int(input("Introduzca el número de ejemplares del libro: "))
        libro = Libro(isbn, titulo, autor, genero, portada, sinopsis, ejemplares)
        biblioteca.libros.append(libro)
        print("Libro dado de alta.")

    elif opcion == "4":
        isbn = input("Introduzca el ISBN del libro que desea dar de baja: ")
        for libro in biblioteca.libros:
            if libro.isbn == isbn:
                biblioteca.libros.remove(libro)
                print("Libro dado de baja.")
                break
        else:
            print("Libro no encontrado.")

    elif opcion == "5":
        dni = input("Introduzca el DNI del usuario que desea prestar el libro: ")
        isbn = input("Introduzca el ISBN del libro que desea prestar: ")
        fecha_prestamo = datetime.date.today()
        usuario_encontrado = False
        libro_encontrado = False
        for usuario in biblioteca.usuarios:
            if usuario.dni == dni:
                usuario_encontrado = True
                break
        else:
            print("Usuario no encontrado.")
        for libro in biblioteca.libros:
            if libro.isbn == isbn:
                libro_encontrado = True
                libro.prestar(usuario, fecha_prestamo)
                biblioteca.prestamos.append(libro)
                break
        else:
            print("Libro no encontrado.")
            if usuario_encontrado and libro_encontrado:
                print("Libro prestado correctamente.")
            else:
                print("No se ha podido prestar el libro.")
    elif opcion == "6":
        dni = input("Introduzca el DNI del usuario que desea devolver el libro: ")
        isbn = input("Introduzca el ISBN del libro que desea devolver: ")
        fecha_devolucion = datetime.date.today()
        usuario_encontrado = False
        libro_encontrado = False
        for usuario in biblioteca.usuarios:
            if usuario.dni == dni:
                usuario_encontrado = True
                break
        else:
            print("Usuario no encontrado.")
        for libro in biblioteca.libros:
            if libro.isbn == isbn:
                libro_encontrado = True
                libro.devolver(usuario, fecha_devolucion)
                break
        else:
            print("Libro no encontrado.")
        if usuario_encontrado and libro_encontrado:
            print("Libro devuelto correctamente.")
        else:
            print("No se ha podido devolver el libro.")

    elif opcion == "7":
        for libro in biblioteca.libros:
            print(f"ISBN: {libro.isbn}")
            print(f"Título: {libro.titulo}")
            print(f"Autor: {libro.autor}")
            print(f"Género: {libro.genero}")
            print(f"Portada: {libro.portada}")
            print(f"Sinopsis: {libro.sinopsis}")
            print(f"Ejemplares: {libro.ejemplares}")
            if libro.ejemplares > 0:
                print("Disponible")
            else:
                print("No disponible")

    elif opcion == "8":
        for usuario in biblioteca.usuarios:
            print(f"DNI: {usuario.dni}")
            print(f"Nombre: {usuario.nombre}")
            print(f"Correo electrónico: {usuario.correo}")
            print(f"Teléfono: {usuario.telefono}")
            print(f"Domicilio: {usuario.domicilio}")
            print("Libros en préstamo:")
            for libro in usuario.libros_en_prestamo:
                print(libro.__str__())

    elif opcion == "9":
        for libro in biblioteca.prestamos:
            print(libro.__str__())

    elif opcion == "0":
        print("Hasta pronto.")
        break

    else:
        print("Opción no válida. Introduce una opcion valida.")


DOLLAR = 100

def main():
	pennies = int(input('Enter pennies: '))
	nickels = int(input('Enter nickels: '))
	dimes = int(input('Enter dimes: '))
	quarters = int(input('Enter quarters: '))
	calc(pennies, nickels, dimes, quarters)

def calc(p, n, d, q):
	total = p + n * 5 + d * 10 + q * 25

	if total == DOLLAR:
		print('Congrates!!!! You WIN!')
	elif total > DOLLAR:
		print('You are over the Dollar Mark')
	elif total < DOLLAR:
		print('Bellow Dollar')

main()


import pybedtools as bt
from os import listdir
from os import remove
import pandas as pd
import atexit

# Read data:
x=pd.read_table('../processed_data/hcasmc_specific_open_chromatin/intersect/intersect.bed')

# Creating id column:
x['id']=x[['chrom','start','end','num']].apply(lambda x: '_'.join([str(y) for y in x]),axis=1)

# Rearrange columns:
cols=x.columns.tolist()
cols=cols[0:5]+[cols[len(cols)-1]]+cols[6:(len(cols)-2)]
x=x[cols]

# Rename columns:
x.rename(columns={'start':'chromStart','end':'chromEnd'},inplace=True)

# Output to temporary file:
tmp_file='../processed_data/hcasmc_specific_open_chromatin/intersect/tmp_file.bed'
x.iloc[:,0:6].to_csv(tmp_file,sep='\t',header=False,index=False)
atexit.register(remove,tmp_file)

# Create bedtool object:
intersect=bt.BedTool(tmp_file)

# Get signal at shared peaks:
IN_DIR='../processed_data/hcasmc_specific_open_chromatin/encode_plus_hcasmc_filt/'
in_files=listdir(IN_DIR)
op=bt.BedTool()

for i in in_files:
	print(i)
	a=bt.BedTool(IN_DIR+'/'+i)
	res=op.intersect(a=a,b=intersect,wa=True,wb=True)

	id=list()
	signalValue=list()
	for interval in res:
		id.append(interval[9])
		signalValue.append(interval[3])

	sample=i.replace('.bed','')
	df=pd.DataFrame({'id':id,sample:signalValue})

	df=df[['id',sample]]
	df.to_csv('../processed_data/hcasmc_specific_open_chromatin/intersect/samplewise_count/intersect.%s.count'%sample,sep='\t',header=True,index=False)


import numpy as np
import pandas as pd
from neo4j import Query

from nepal.datasets import CountyDistance, Dataset, Vaccinations

from .base import Connection, Mergeable

class County(Mergeable):
    def __init__(self, dataset: Vaccinations):
        self._dataset: Dataset = dataset

    def merge(self, connection: Connection) -> None:
        self.create_constraint(connection)
        self.insert_and_connect_nodes(connection)

    @classmethod
    def create_constraint(cls, connection: Connection) -> None:
        connection.query(
            """CREATE CONSTRAINT counties IF NOT EXISTS ON (c:County) ASSERT c.fips IS UNIQUE"""
        )

    def prepare_data(self) -> pd.DataFrame:
        data: pd.DataFrame = self._dataset.load()
        result: pd.DataFrame = (
            data.pipe(self._keep_relevant_columns)
            .pipe(self._add_derived_columns)
            .pipe(self._select_output_columns)
        )

        return result

    @classmethod
    def _keep_relevant_columns(cls, data: pd.DataFrame) -> pd.DataFrame:
        return (
            data[
                [
                    "FIPS",
                    "Recip_State",
                    "Metro_status",
                    "SVI_CTGY",
                    "Census2019",
                    "Census2019_5PlusPop",
                    "Census2019_5to17Pop",
                    "Census2019_18PlusPop",
                    "Census2019_65PlusPop",
                ]
            ]
            .drop_duplicates()
            .dropna(subset=["FIPS"])
        )

    @classmethod
    def _add_derived_columns(cls, data: pd.DataFrame) -> pd.DataFrame:
        data["RegionCode"] = "US_" + data["Recip_State"].astype(str)
        data["Under5_Pop_Pct"] = (data["Census2019"] - data["Census2019_5PlusPop"]) / data[
            "Census2019"
        ]
        data["Between5to17_Pop_Pct"] = data["Census2019_5to17Pop"] / data["Census2019"]
        data["Between18to65_Pop_Pct"] = (
            data["Census2019_18PlusPop"] - data["Census2019_65PlusPop"]
        ) / data["Census2019"]
        data["Plus65_Pop_Pct"] = data["Census2019_65PlusPop"] / data["Census2019"]
        data["Is_Metro"] = np.where(data["Metro_status"] == "Metro", 1, 0)
        data["SVI_A"] = np.where(data["SVI_CTGY"] == "A", 1, 0)
        data["SVI_B"] = np.where(data["SVI_CTGY"] == "B", 1, 0)
        data["SVI_C"] = np.where(data["SVI_CTGY"] == "C", 1, 0)
        data["SVI_D"] = np.where(data["SVI_CTGY"] == "D", 1, 0)
        return data

    @classmethod
    def _select_output_columns(cls, data: pd.DataFrame) -> pd.DataFrame:
        return data[
            [
                "FIPS",
                "RegionCode",
                "Census2019",
                "Under5_Pop_Pct",
                "Between5to17_Pop_Pct",
                "Between18to65_Pop_Pct",
                "Plus65_Pop_Pct",
                "Is_Metro",
                "SVI_A",
                "SVI_B",
                "SVI_C",
                "SVI_D",
            ]
        ]

    def insert_and_connect_nodes(self, connection: Connection) -> None:
        query: Query = Query(
            """
            UNWIND $rows AS row
            MERGE (c:County {fips: row.FIPS})
            ON CREATE SET
                c.census = row.Census2019,
                c.pop_under_5 = row.Under5_Pop_Pct,
                c.pop_5_to_17 = row.Between5to17_Pop_Pct,
                c.pop_18_to_65 = row.Between18to65_Pop_Pct,
                c.pop_plus_65 = row.Plus65_Pop_Pct,
                c.is_metro = row.Is_Metro,
                c.svi_a = row.SVI_A,
                c.svi_b = row.SVI_B,
                c.svi_c = row.SVI_C,
                c.svi_d = row.SVI_D

            WITH c, row
            MATCH (s:State {code: row.RegionCode})
            MERGE (c)-[:IN_STATE]->(s)
            """
        )

        rows: pd.DataFrame = self.prepare_data()
        connection.insert_data(query, description="County nodes", rows=rows, batch_size=5000)

class CountyDistances(Mergeable):
    def __init__(self, dataset: CountyDistance):
        self._dataset: CountyDistance = dataset

    def merge(self, connection: Connection) -> None:
        query: Query = Query(
            """
            UNWIND $rows as row
            MATCH (a:County {fips: row.county1})
            MATCH (b:County {fips: row.county2})
            MERGE (a)-[:IS_NEAR {weight: row.weight}]-(b)
            """
        )

        rows: pd.DataFrame = self.prepare_data()
        connection.insert_data(query, description="County distances", rows=rows)

    def prepare_data(self) -> pd.DataFrame:
        radius: int = int(self._dataset.radius)

        data: pd.DataFrame = self._dataset.load()
        data["weight"] = (radius - data["mi_to_county"]) / radius
        return data[["county1", "county2", "weight"]]

class CountyVaccinations(Mergeable):
    def __init__(self, dataset: Vaccinations):
        self._dataset: Dataset = dataset

    def merge(self, connection: Connection) -> None:
        self.create_constraint(connection)
        self.insert_nodes(connection)

    @classmethod
    def create_constraint(cls, connection: Connection) -> None:
        connection.query(
            """CREATE CONSTRAINT vaccinations IF NOT EXISTS ON (v:Vaccinations) ASSERT v.id IS UNIQUE"""
        )

    def prepare_data(self) -> pd.DataFrame:
        data: pd.DataFrame = self._dataset.load()
        data = data[data["FIPS"] != "UNK"]
        return data[
            [
                "Date",
                "FIPS",
                "Completeness_pct",
                "Administered_Dose1_Pop_Pct",
                "Administered_Dose1_Recip_18PlusPop_Pct",
                "Administered_Dose1_Recip_65PlusPop_Pct",
                "Series_Complete_Pop_Pct",
                "Series_Complete_18PlusPop_Pct",
                "Series_Complete_65PlusPop_Pct",
                "Booster_Doses_Vax_Pct",
                "Booster_Doses_18Plus_Vax_Pct",
                "Booster_Doses_50Plus_Vax_Pct",
                "Booster_Doses_65Plus_Vax_Pct",
            ]
        ]

    def insert_nodes(self, connection: Connection) -> None:
        query: Query = Query(
            """
            UNWIND $rows AS row
            MERGE (v:Vaccinations {id: coalesce(row.FIPS, "") + ',' + coalesce(row.Date, "")})
            ON CREATE SET
                v.completeness = row.Completeness_pct,
                v.dose1_pop = row.Administered_Dose1_Pop_Pct,
                v.dose1_18plus = row.Administered_Dose1_Recip_18PlusPop_Pct,
                v.dose1_65plus = row.Administered_Dose1_Recip_65PlusPop_Pct,
                v.series_complete = row.Series_Complete_Pop_Pct,
                v.series_complete_18plus = row.Series_Complete_18PlusPop_Pct,
                v.series_complete_65plus = row.Series_Complete_65PlusPop_Pct,
                v.booster_pop = row.Booster_Doses_Vax_Pct,
                v.booster_18plus = row.Booster_Doses_18Plus_Vax_Pct,
                v.booster_50plus = row.Booster_Doses_50Plus_Vax_Pct,
                v.booster_65plus = row.Booster_Doses_65Plus_Vax_Pct

            WITH v, row
            MATCH (d:Date {id: date(row.Date)})
            MATCH (c:County {fips: row.FIPS})
            MERGE (c)<-[:IN_COUNTY]-(v)-[:REPORTED_ON]->(d)
            """
        )

        rows: pd.DataFrame = self.prepare_data()
        connection.insert_data(
            query, description="Vaccination nodes", rows=rows, batch_size=5000
        )


from fastapi import FastAPI
from enum import Enum

app = FastAPI()

class Available_Cuisines(str,Enum):
    indian = "indian"
    american = "american"
    italian = "italian"

food_items = {
    'indian' : [ "Samosa", "Dosa" ],
    'american' : [ "Hot Dog", "Apple Pie"],
    'italian' : [ "Ravioli", "Pizza"]
}

valid_cuisine = food_items.keys()
content = "-".join(list(valid_cuisine))
@app.get("/get_items/{cuisine}")
async def get_items(cuisine:Available_Cuisines):
    # return food_items.get(cuisine)
    # if cuisine not in valid_cuisine:
    #     return f"supported food items are {content}"
    return food_items.get(cuisine)

coupon_code = {
    1: '10%',
    2: '20%',
    3: '30%'
}

@app.get("/get_coupon/{code}")
async def get_coupon(code: int):
    return { 'discount_amount': coupon_code.get(code) }


def kaprekar_iteration(n):
    if not (1000 <= n) and not (n <= 9998):
        return 0
    elif n < 1000:
        asstr = str(n)
        while len(asstr) < 4:
            asstr += '0'

    if(len(set(asstr))==1):
        return 0
    lower = "".join(sorted(asstr))

    upper = int(lower[::-1])
    return upper - int(lower)

if __name__ == '__main__':
    for k in range(1,100):
        print(kaprekar_iteration(k))


from flask import Flask, render_template,redirect, url_for, flash, request
import pickle
app = Flask(__name__)
app.config['SECRET_KEY'] = 'debudaisasecretkey'
fileobj = open("model/bnb.pkl","rb")
BNB = pickle.load(fileobj)
fileobj.close()
fileobj  = open("model/cv.pkl","rb")
CV = pickle.load(fileobj)
fileobj.close()
@app.route("/", methods = ['GET', 'POST'])
def home():
    if request.method == 'POST':
        data = request.form.get('data')
        bow = CV.transform([data])
        predict = BNB.predict(bow)
        if predict == 1:
            x = 'This is Spam.'
            return render_template('home page.html', x=x)

        else:
            x = 'This is Ham.'
            return render_template('home page.html', x=x)

    return render_template('home page.html')

if __name__ == '__main__':
    app.run()


import pandas as pd
import numpy as np
import pickle
import glob
from IPython.display import display, HTML

'''
    Code Smells: Vocabulary
    X: Android Versions (to which files are associated)

    Data: (per file)
                AntiSingleton, ....... (codesmells)...
    Android1.0      1       2           3
    Android2.0      0       2           2
    .....
    (android versions)
'''
codeSmells = ["AntiSingleton", "BaseClassKnowsDerivedClass", "BaseClassShouldBeAbstract", "Blob", "ClassDataShouldBePrivate",
               "ComplexClass", "FunctionalDecomposition", "LargeClass", "LazyClass", "LongMethod", "LongParameterList",
               "ManyFieldAttributesButNotComplex", "MessageChains", "RefusedParentBequest", "SpaghettiCode", "SpeculativeGenerality",
               "SwissArmyKnife", "TraditionBreaker"];

theta_threshold = 2

# Testing Data
fileBasedDF = pd.DataFrame({'TFD' : ['AA', 'SL', 'BB', 'D0', 'Dk', 'FF'],
                    'Snack' : ['1', '0', '1', '1', '0', '0'],
                    'Trans' : ['1', '1', '1', '0', '0', '1'],
                    'Dop' : ['1', '0', '1', '0', '1', '1']}).set_index('TFD')

#============================================================== Counts

#===================== Co-occurrence Counts
co_occurrence_counts = pd.DataFrame(columns = fileBasedDF.columns, index = fileBasedDF.columns)         # Unnecessary Declaration

# Creating Co-occurrence
fileBasedDF_asint = fileBasedDF.astype(int)
co_occurrence_counts = fileBasedDF_asint.T.dot(fileBasedDF_asint)

# Filtering Data below Threshold
co_occurrence_counts.mask(co_occurrence_counts < theta_threshold, other=0, inplace = True)
display ("Co-occurrence Counts: ", co_occurrence_counts)

#===================== Creating Marginal Counts
marginal_counts = pd.DataFrame(columns = ["Count"], index = fileBasedDF.columns)
marginal_counts = pd.DataFrame(co_occurrence_counts.sum(axis=1))
marginal_counts.rename(columns={0: 'counts'}, inplace=True)
display ("Marginal Counts: ", marginal_counts)

#===================== Creating Total Counts
total_counts = float(marginal_counts.sum(axis=0))/2
print ("Total Count :", total_counts)

# NOT SURE IF DIAGONAL ELEMENTS ARE EXCLUDED
# NOT SURE IF SAME ELEMENT COUNT IS EXCLUDED

#============================================================== Probabilities

#===================== Co-occurrence Probabilities
co_occurrence_prob = co_occurrence_counts/total_counts
display ("Co-occurrence Probabilities: ", co_occurrence_prob)

#===================== Marginal Probabilities
marginal_prob = marginal_counts/total_counts
display ("Marginal Probabilities: ", marginal_prob)

#


import os
import traceback

from config.main import TMP_DIR
from lib.FileManager.workers.baseWorkerCustomer import BaseWorkerCustomer

class ReadImages(BaseWorkerCustomer):
    def __init__(self, paths, session, *args, **kwargs):
        super(ReadImages, self).__init__(*args, **kwargs)

        self.paths = paths
        self.session = session

    def run(self):
        try:
            self.preload()
            self.logger.info("FTP ReadImages process run")

            hash_str = self.random_hash()
            download_dir = TMP_DIR + '/images/' + self.login + '/' + hash_str + '/'
            success_paths, error_paths = self.copy_files_to_tmp(download_dir)

            if len(success_paths) == 1:
                one_file = True
            else:
                one_file = False

            if len(error_paths) == 0:  # Значит все хорошо, можно дальше обрабатывать

                file_list = {
                    "succeed": list(os.path.basename(filename) for filename in success_paths),
                    "failed": list(os.path.basename(filename) for filename in error_paths)
                }

                answer = {
                    "success": True,
                    "file_list": file_list,
                    "hash": hash_str,
                    "one_file": one_file,
                    "sid": self.login
                }

                result = {
                    "data": answer
                }

                self.on_success(result)
            else:
                raise Exception("read error")

        except Exception as e:
            result = {
                "error": True,
                "message": str(e),
                "traceback": traceback.format_exc()
            }

            self.on_error(result)

    def copy_files_to_tmp(self, target_path):
        if not os.path.exists(target_path):
            os.makedirs(target_path)

        ftp = self.get_ftp_connection(self.session)

        success_paths = []
        error_paths = []

        for path in self.paths:
            try:
                abs_path = ftp.path.abspath(path)
                source_path = ftp.path.dirname(path)
                file_basename = ftp.path.basename(abs_path)

                if ftp.isdir(abs_path):
                    destination = os.path.join(target_path, file_basename)

                    if not os.path.exists(destination):
                        os.makedirs(destination)
                    else:
                        raise Exception("destination already exist")

                    for current, dirs, files in ftp.ftp.walk(ftp.to_string(abs_path)):
                        current = current.encode("ISO-8859-1").decode("UTF-8")
                        relative_root = os.path.relpath(current, source_path)

                        for d in dirs:
                            d = d.encode("ISO-8859-1").decode("UTF-8")
                            target_dir = os.path.join(target_path, relative_root, d)
                            if not os.path.exists(target_dir):
                                os.makedirs(target_dir)
                            else:
                                raise Exception("destination dir already exists")

                        for f in files:
                            f = f.encode("ISO-8859-1").decode("UTF-8")
                            source_file = os.path.join(current, f)
                            target_file_path = os.path.join(target_path, relative_root)
                            target_file = os.path.join(target_path, relative_root, f)
                            if not os.path.exists(target_file):
                                download_result = ftp.download(source_file, target_file_path)
                                if not download_result['success'] or len(
                                        download_result['file_list']['failed']) > 0:
                                    raise download_result['error'] if download_result[
                                                                          'error'] is not None else Exception(
                                            "Download error")
                            else:
                                raise Exception("destination file already exists")

                elif ftp.isfile(abs_path):
                    try:
                        target_file = os.path.join(target_path, file_basename)
                        if not os.path.exists(target_file):
                            download_result = ftp.download(abs_path, target_path)
                            if not download_result['success'] or len(download_result['file_list']['failed']) > 0:
                                raise download_result['error'] if download_result[
                                                                      'error'] is not None else Exception(
                                        "Download error")
                        else:
                            raise Exception("destination file already exists")

                    except Exception as e:
                        self.logger.info("Cannot copy file %s , %s" % (abs_path, str(e)))
                        raise e

                success_paths.append(path)

            except Exception as e:
                self.logger.error(
                        "Error copy %s , error %s , %s" % (str(path), str(e), traceback.format_exc()))
                error_paths.append(path)

        return success_paths, error_paths


from tkinter import *

#
def clear():
    e_city.delete(0, "end")
    e_phone.delete(0, "end")
    e_age.delete(0, "end")
    e_name.delete(0, "end")
    e_name.focus()

def write():
    with open("Entry widget exercise.txt", "a") as f:
         f.write(f"{e_name.get()},{e_age.get()},{e_phone.get()},{e_city.get()}\n")
    clear()

#def write():
    # v = e_age.get()
 #   w.set(e_age.get())

window = Tk()
window.title("Dance Class")
window.geometry("700x700")

# f1 = Frame(window, width=300, height=300)
f1 = Frame(window, bg="purple", highlightbackground="purple")
f1.pack(anchor="nw")

name = Label(f1, text="Enter Name", bg="purple")
name.grid(row=0, column=0, sticky="w")
# name.place(x=0, y=0)
e_name = Entry(f1)
# e_name.place(x=150, y=0)
e_name.grid(row=0, column=1)

age = Label(f1, text="Enter Age", bg="purple")
# age.place(x=0, y=25)
age.grid(row=1, column=0, sticky="w")
e_age = Entry(f1)
# e_age.place(x=150, y=25)
e_age.grid(row=1, column=1)

phone = Label(f1, text="Enter  Phone", bg="purple")
# phone.place(x=0, y=50)
phone.grid(row=2, column=0, sticky="w")
e_phone = Entry(f1, show="*")
# e_phone.place(x=150, y=50)
e_phone.grid(row=2, column=1)

city = Label(f1, text="Enter  City", bg="purple")
# city.place(x=0, y=75)
city.grid(row=3, column=0, sticky="w")
e_city = Entry(f1)
# e_city.place(x=150, y=75)
e_city.grid(row=3, column=1)

confirm = Label(f1, text="Do you want to Submit :", bg="purple")
# confirm.place(x=70, y=100)
confirm.grid(row=4, column=0)

yes = Button(f1, text="YES", command=write)
# yes.place(x=70, y=125)
yes.grid(row=5, column=0, sticky="w")

no = Button(f1, text="NO")
# # no.place(x=170, y=125)
no.grid(row=5, column=0, sticky="e")

# w = StringVar()
# c = Entry(f1, textvariable=w, justify="right")
# # confirm.place(x=70, y=100)
# c.grid(row=7, column=1)

#
#var = IntVar()
# check = Checkbutton(f1, text="Do you satisfy?", variable=var)
# check.grid(row=8, column=0, sticky="w")
#
# var1 = IntVar()
# check = Checkbutton(f1, text="Do you not satisfy?", variable=var1, relief="raised", bd=6, fg="red", bg="powder blue")
# check.grid(row=9, column=0)
window.mainloop()

Taimoor Python/Code with harry/python GUI/entry widget and grid.py


string = []
while True:
  sentence = str(input())
  if sentence == '.':
    break
  string.append(sentence)

for sentence in string:
  stack = []
  isTrue = 1
  for i in range(len(sentence)):
    if sentence[i] == '(' or sentence[i] == '[':
      stack.append(sentence[i])
    if sentence[i] == ')':
      if len(stack) == 0:
        print('no')
        isTrue = 0
        break
      else:
        a = stack.pop()
        if a == '[':
          print('no')
          isTrue = 0
          break
    if sentence[i] == ']':
      if len(stack) == 0:
        print('no')
        isTrue = 0
        break
      else:
        a = stack.pop()
        if a == '(':
          print('no')
          isTrue = 0
          break

  if len(stack) == 0 and isTrue == 1:
    print('yes')
  elif len(stack) !=0 and isTrue == 1:
    print('no')

백준/Silver/4949. 균형잡힌 세상/균형잡힌 세상.py


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

'''Mask R-CNN coco inference

Using the trained model to detect and segment objects.'''

import os
import sys
import random
import colorsys
import skimage.io

import numpy as np
from skimage.measure import find_contours
import matplotlib.pyplot as plt
from matplotlib import patches
from matplotlib.patches import Polygon
import time

# Root directory of the project
ROOT_DIR = os.path.abspath("../../")

# Import Mask RCNN
sys.path.append(ROOT_DIR)  # To find local version of the library
import mrcnn.model as modellib
from mrcnn.config import Config
from mrcnn import visualize
# Import COCO config
# sys.path.append(os.path.join(ROOT_DIR, "samples/coco/"))  # To find local version
import coco

class InferenceConfig(coco.CocoConfig):
    # Set batch size to 1 since we'll be running inference on
    # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
    GPU_COUNT = 1
    IMAGES_PER_GPU = 1
    # save or not
    SAVE = True

if __name__ == '__main__':

    # set the config and show
    config = InferenceConfig()
    config.display()

    # Local path to trained weights file
    MODEL_DIR = os.path.join(ROOT_DIR, "logs")
    COCO_MODEL_PATH = os.path.join(MODEL_DIR, 'mask_rcnn_coco.h5')

    # Directory of images to run detection on
    IMAGE_DIR = '/home/ason/datasets/images'

    '''Create Model and Load Trained Weights'''

    # Create model object in inference mode.
    model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)

    # Load weights trained on cityscapes
    model.load_weights(COCO_MODEL_PATH, by_name=True)

    # COCO Class names
    # Index of the class in the list is its ID. For example, to get ID of
    # the teddy bear class, use: class_names.index('teddy bear')
    class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
                   'bus', 'train', 'truck', 'boat', 'traffic light',
                   'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
                   'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',
                   'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',
                   'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
                   'kite', 'baseball bat', 'baseball glove', 'skateboard',
                   'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',
                   'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
                   'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
                   'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',
                   'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
                   'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',
                   'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
                   'teddy bear', 'hair drier', 'toothbrush']

    '''Run Object Detection'''

    # get the path of images folder
    file_names = next(os.walk(IMAGE_DIR))[2]
    id = 0 # image id

    # # Run detection
    all_start = time.time()

    for f in file_names:

        # Load images from the images folder
        input_path = os.path.abspath(os.path.join(IMAGE_DIR, f))
        image = skimage.io.imread(input_path)
        print("input_path:", input_path)

        detect = model.detect
        results = detect([image], verbose=1)

        r = results[0]

        # Save and show results
        if config.SAVE == True:
            # output file path
            output_path = input_path.replace("images", "images_results")
            print("output_path:", output_path)
            print('\n')
            visualize.save_instances(output_path = output_path, image=image,
                           boxes=r['rois'], masks=r['masks'], class_ids=r['class_ids'],
                           class_names=class_names, scores=r['scores'], title = "")
        # Show results only
        else:
            visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'],
                                       class_names, r['scores'])

        id += 1

    all_end = time.time()
    average_time = (all_end - all_start) / id
    print("inference runtime per image : {:.3f} s".format(average_time))


# Ask the user for a positive price
while True:
    price = input("Change owed: ")
    try:
        price = float(price)
        if price >= 0:
            break
    except:
        continue

# Converting dollars into cents
cents = int(price * 100)

# Coins used
qCoins = 0
while cents > 0:
    if cents >= 25:
        cents = cents - 25
    elif cents >= 10:
        cents = cents - 10
    elif cents >= 5:
        cents = cents - 5
    else:
        cents -= 1

    qCoins += 1

print(str(qCoins))