import numpy as np
from sklearn.decomposition import PCA
from sklearn.decomposition import FastICA
from sklearn.preprocessing import StandardScaler
import pandas as pd
import ta
from tqdm import tqdm
import warnings
import plotly.graph_objects as go
import os

from utils import read_df

warnings.simplefilter("ignore")

DATA_PATH = os.path.join('..', 'data', 'main.csv')
TOL = 1

class DataPreprocessor:
    def __init__(self, input_data= DATA_PATH):
        if isinstance(input_data, str):
            self.data = read_df(input_data)
        elif isinstance(input_data, pd.DataFrame):
            self.data = input_data
        else:
            raise ValueError("Invalid input. Please provide a file path or a DataFrame.")

    def plot_candlestick_with_signals(self, output_file=None):
        fig = go.Figure()

        fig.add_trace(go.Candlestick(x=self.data.index,
                open=self.data['open'],
                high=self.data['high'],
                low=self.data['low'],
                close=self.data['close'],
                name='Candlesticks'))

        buy_signals = self.data[self.data['target'] == 1]
        sell_signals = self.data[self.data['target'] == -1]

        fig.add_trace(go.Scatter(x=buy_signals.index, y=buy_signals['close'],
                                 mode='markers', name='Buy Signals',
                                 marker=dict(color='green', size=10, symbol='triangle-up')))

        fig.add_trace(go.Scatter(x=sell_signals.index, y=sell_signals['close'],
                                 mode='markers', name='Sell Signals',
                                 marker=dict(color='red', size=10, symbol='triangle-down')))

        fig.update_layout(
            title='Candlestick Chart with Buy/Sell Signals',
            xaxis_title='Date',
            yaxis_title='Price',
            template='plotly_dark',
            xaxis_rangeslider_visible=False
        )

        if output_file:
            fig.write_html(output_file)
        else:
            fig.show()

    def add_time_features(self):
        self.data['Year'] = self.data['datetime'].dt.year
        self.data['Month'] = self.data['datetime'].dt.month
        self.data['Day'] = self.data['datetime'].dt.day
        self.data['Hour'] = self.data['datetime'].dt.hour
        self.data['Minute'] = self.data['datetime'].dt.minute
        self.data['Day_of_Week'] = self.data['datetime'].dt.dayofweek
        self.data['Day_Sin'] = np.sin((self.data['Day'] - 1) * (2. * np.pi / 30))
        self.data['Day_Cos'] = np.cos((self.data['Day'] - 1) * (2. * np.pi / 30))
        self.data['Hour_Sin'] = np.sin(self.data['Hour'] * (2. * np.pi / 24))
        self.data['Hour_Cos'] = np.cos(self.data['Hour'] * (2. * np.pi / 24))
        self.data['Minute_Sin'] = np.sin(self.data['Minute'] * (2. * np.pi / 60))
        self.data['Minute_Cos'] = np.cos(self.data['Minute'] * (2. * np.pi / 60))
        self.data.drop(columns=['datetime'], inplace=True)

    def add_summaries(self):
        for col in ['open', 'high', 'low', 'close']:
            rolling_window = self.data[col].rolling(window=20)
            self.data[f'{col}_min_10'] = rolling_window.min()
            self.data[f'{col}_25th_10'] = rolling_window.quantile(0.25)
            self.data[f'{col}_median_10'] = rolling_window.median()
            self.data[f'{col}_75th_10'] = rolling_window.quantile(0.75)
            self.data[f'{col}_max_10'] = rolling_window.max()
            self.data[f'{col}_mean_10'] = rolling_window.mean()
            self.data[f'{col}_std_10'] = rolling_window.std()

    def add_technical_indicators(self):
        self.data['SMA_10'] = ta.trend.sma_indicator(self.data['close'], window=10)
        self.data['EMA_10'] = ta.trend.ema_indicator(self.data['close'], window=10)
        self.data['RSI'] = ta.momentum.RSIIndicator(self.data['close'], window=14).rsi()

        macd = ta.trend.MACD(self.data['close'])
        self.data['MACD'] = macd.macd()
        self.data['MACD_signal'] = macd.macd_signal()
        self.data['MACD_diff'] = macd.macd_diff()

        stoch = ta.momentum.StochasticOscillator(self.data['high'], self.data['low'], self.data['close'])
        self.data['Stoch_%K'] = stoch.stoch()
        self.data['Stoch_%D'] = stoch.stoch_signal()

        self.data['ATR'] = ta.volatility.AverageTrueRange(self.data['high'], self.data['low'], self.data['close']).average_true_range()

        bollinger = ta.volatility.BollingerBands(self.data['close'])
        self.data['Bollinger_hband'] = bollinger.bollinger_hband()
        self.data['Bollinger_lband'] = bollinger.bollinger_lband()
        self.data['Bollinger_mavg'] = bollinger.bollinger_mavg()

        self.data['ROC'] = ta.momentum.ROCIndicator(self.data['close']).roc()
        self.data['PPO'] = ta.momentum.PercentagePriceOscillator(self.data['close']).ppo()

        # Ichimoku Cloud
        self.data['Ichimoku_Conversion'] = (self.data['high'].rolling(window=9).max() + self.data['low'].rolling(window=9).min()) / 2
        self.data['Ichimoku_Base'] = (self.data['high'].rolling(window=26).max() + self.data['low'].rolling(window=26).min()) / 2
        self.data['Ichimoku_Leading_A'] = (self.data['Ichimoku_Conversion'] + self.data['Ichimoku_Base']) / 2
        self.data['Ichimoku_Leading_B'] = (self.data['high'].rolling(window=52).max() + self.data['low'].rolling(window=52).min()) / 2
        self.data['Ichimoku_Lagging'] = self.data['close'].shift(26)

        self.data['Pct_Change_1min'] = self.data['close'].pct_change(1)
        self.data['Pct_Change_5min'] = self.data['close'].pct_change(5)
        self.data['Pct_Change_10min'] = self.data['close'].pct_change(10)
        self.data['Pct_Change_30min'] = self.data['close'].pct_change(30)

        self.data['ATRP'] = ta.volatility.AverageTrueRange(self.data['high'], self.data['low'], self.data['close']).average_true_range()

        self.data['Historical_Volatility'] = self.data['close'].rolling(window=10).std() * (252**0.5)  # Annualized volatility
        self.data['Price_Oscillator'] = self.data['close'].diff(4)  # Difference between the current price and the price 4 periods ago
        self.data['Standard_Deviation'] = self.data['close'].rolling(window=14).std()

        self.data['CCI'] = ta.trend.CCIIndicator(self.data['high'], self.data['low'], self.data['close']).cci()

        donchian = ta.volatility.DonchianChannel(self.data['high'], self.data['low'], self.data['close'])
        self.data['Donchian_Channel_hband'] = donchian.donchian_channel_hband()
        self.data['Donchian_Channel_lband'] = donchian.donchian_channel_lband()
        self.data['Donchian_Channel_mband'] = donchian.donchian_channel_mband()

        self.data['DPO'] = ta.trend.DPOIndicator(self.data['close']).dpo()

        typical_price = (self.data['high'] + self.data['low'] + self.data['close']) / 3
        self.data['MFI'] = ta.volume.MFIIndicator(high=self.data['high'], low=self.data['low'], close=self.data['close'], volume=typical_price).money_flow_index()

        self.data['Trix'] = ta.trend.TRIXIndicator(self.data['close']).trix()

    def handle_missing_values(self):
        self.data.dropna(axis=0, inplace=True)

    def transform_for_pred(self, data):
        self.data = data
        self.data = self.analyze_sharp_changes(self.data, pred=True)
        self.add_time_features()
        self.add_summaries()
        self.add_technical_indicators()
        self.handle_missing_values()
        return self.data

    def analyze_sharp_changes(self, data, window_size=30, price_diff_threshold=20, tolerance=1, pred = False):

        # rolling_min = data['close'].rolling(window_size).min()
        # rolling_max = data['close'].rolling(window_size).max()
        #
        # price_diff = rolling_max - rolling_min
        # sharp_changes_idx = np.where(price_diff >= price_diff_threshold)[0]
        # sharp_changes_idx = sharp_changes_idx[sharp_changes_idx < len(data) - window_size + 1]
        # sharp_changes_info = []
        # for idx in sharp_changes_idx:
        #     min_price = rolling_min.iloc[idx]
        #     max_price = rolling_max.iloc[idx]
        #     actual_price = data['close'].iloc[idx]
        #     if np.abs(actual_price - min_price) > np.abs(max_price - actual_price):
        #         change_start_price = min_price
        #         change_magnitude = actual_price - min_price
        #     else:
        #         change_start_price = max_price
        #         change_magnitude = max_price - actual_price
        #
        #     if not any(np.abs(change_start_price - prev_price) < window_size for prev_price, _ in sharp_changes_info):
        #         sharp_changes_info.append((change_start_price, change_magnitude))
        #
        # # Sort the changes by magnitude in descending order, extract the prices, and then sort by price
        # lines = sorted([price for price, _ in sorted(sharp_changes_info, key=lambda x: x[1], reverse=True)])
        # data = data[data['close'] >= (10000 - 20)]

        rs_lines = pd.read_csv("data/stronglines.csv")
        lines = rs_lines.values.flatten()

        close_prices = data['close'].values[:, np.newaxis]
        lines = np.array(lines)
        lines_reshaped = lines[np.newaxis, :]

        diffs = lines_reshaped - close_prices
        partitioned_indices = np.argpartition(np.abs(diffs), 4, axis=1)[:, :4]
        closest_diffs = np.take_along_axis(diffs, partitioned_indices, axis=1)
        closest_rs_values = np.take_along_axis(lines_reshaped, partitioned_indices, axis=1)

        data['SL_1'] = closest_diffs[:, 0]
        data['SL_2'] = closest_diffs[:, 1]
        data['SL_3'] = closest_diffs[:, 2]
        data['SL_4'] = closest_diffs[:, 3]
        if not pred:
            data['target'] = np.nan
            tolerance = TOL
            close_prices = data['close'].values[:, np.newaxis]
            diffs = np.abs(lines_reshaped - close_prices)
            within_tolerance_indices = np.where(diffs <= tolerance)

            data = data.reset_index(drop=True)

            valid_indices = set(data.index)
            filtered_indices = [idx for idx in within_tolerance_indices[0] if idx in valid_indices]

            data.loc[filtered_indices, 'target'] = lines_reshaped[0, within_tolerance_indices[1]]

            data.loc[within_tolerance_indices[0], 'target'] = lines_reshaped[0, within_tolerance_indices[1]]
            data['target'].fillna(method='bfill', inplace=True)
            data.dropna(subset=['target'], inplace=True)
            diffs = data['target'] - data['close']
            data['target'] = np.where(diffs > 0, 1, np.where(diffs < 0, -1, 0))

        return data

    def transform_for_training(self, n = None):
        self.data = self.analyze_sharp_changes(self.data)
        self.add_time_features()
        self.add_summaries()
        self.add_technical_indicators()
        self.handle_missing_values()
        return self.data

if __name__ == "__main__":
    preprocessor = DataPreprocessor()
    preprocessor.transform_for_training(n=45000)
    preprocessor.plot_candlestick_with_signals()
    print(preprocessor.data.head())


def removeVowels(s: str) -> str:
        """
        1. Goal
            - Remove all vowels from a string
        2. Example
            - Example #1
                a. Input
                    i. s = "leetcodeisacommunityforcoders"
                b. Output
                    i. "ltcdscmmntyfcfgrs"
            - Example #2
                a. Input
                    i. s = "aeiou"
                b. Output
                    i. ""
        3. Implementation
            - Steps
                a. Initialize a list of the characters in the
                s string and a list of the vowels
                b. Iterate through the values in the vowels list,
                c. Write a while loop that will remove the vowels
                while they are still in the vowels list
        """
        s_arr = list(s)
        vowels = list("aAeEiIoOuU")
        for vowel in vowels:
            while vowel in s_arr:
                s_arr.remove(vowel)
        return ''.join(s_arr)

print(removeVowels("leetcodeisacommunityforcoders"))


import relu_backprop
import data_loader
from parameters import HyperParameters

if __name__ == '__main__':
    # Load training data
    input_x_features = data_loader.load_training_data_from_binary()
    input_labels = data_loader.load_training_labels_from_binary()

    # Load testing data
    testing_features = data_loader.load_testing_data_from_binary()
    testing_labels = data_loader.load_testing_labels_from_binary()

    # Train the neural net
    for par in range(1):
        relu_backprop.do_train(input_x_features,
                          data_loader.transform_output_label_into_vector(input_labels),
                          testing_features,
                          data_loader.transform_output_label_into_vector(testing_labels),
                          parameters=HyperParameters(num_hidden_units=500,
                                                     idx=4,
                                                     low=-0.05,
                                                     high=0.05,
                                                     num_input_units=51,
                                                     num_output_units=10,
                                                     momentum=0.0))


# -*- coding: Latin-1 -*-
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
# trafficLightExperiment.py --- simple Traffic Light example experiment
#                       --------------------------------
#                                November 2013
#                               Hans Vangheluwe
#                              Yentl Van Tendeloo
#                         McGill University (Montréal)
#                       --------------------------------
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##

# Add the directory where pypdevs lives to Python's import path
import sys
sys.path.append('../src/')

# Import code for model simulation:
from simulator import Simulator

# Import the model to be simulated
from trafficLightModel_classic import *

#    ======================================================================

# 1. Instantiate the (Coupled or Atomic) DEVS at the root of the
#  hierarchical model. This effectively instantiates the whole model
#  thanks to the recursion in the DEVS model constructors (__init__).
#
trafficSystem = TrafficSystem(name="trafficSystem")

#    ======================================================================

# 2. Link the model to a DEVS Simulator:
#  i.e., create an instance of the 'Simulator' class,
#  using the model as a parameter.
sim = Simulator(trafficSystem)

#    ======================================================================

# 3. Perform all necessary configurations, the most commonly used are:

# A. Termination time (or termination condition)
#    Using a termination condition will execute a provided function at
#    every simulation step, making it possible to check for certain states
#    being reached.
#    It should return True to stop simulation, or Falso to continue.
def terminate_whenStateIsReached(clock, model):
    return model.trafficLight.state.get() == "manual"
sim.setTerminationCondition(terminate_whenStateIsReached)

#    A termination time is prefered over a termination condition,
#    as it is much simpler to use.
#    e.g. to simulate until simulation time 100.0 is reached
sim.setTerminationTime(300.0)

# B. Set the use of a tracer to show what happened during the simulation run
#    Both writing to stdout or file is possible:
#    pass None for stdout, or a filename for writing to that file
sim.setVerbose(None)

# C. Use Classic DEVS instead of Parallel DEVS
#    If your model uses Classic DEVS, this configuration MUST be set as
#    otherwise errors are guaranteed to happen.
#    Without this option, events will be remapped and the select function
#    will never be called.
sim.setClassicDEVS()

#    ======================================================================

# 4. Simulate the model
sim.simulate()

#    ======================================================================

# 5. (optional) Extract data from the simulated model
print(("Simulation terminated with traffic light in state %s" % (trafficSystem.trafficLight.state.get())))


# Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

# Examples:

# s = "leetcode"
# return 0.

# s = "loveleetcode",
# return 2.
# Note: You may assume the string contain only lowercase letters.

def firstUniqChar(s: str) -> int:
    hm = {}
    smallest = float("inf")
    for i, char in enumerate(s):
        if char not in hm:
            hm[char] = i
        else:
            hm[char] = "dup"

    for key in hm:
        if hm[key] != "dup" and hm[key] < smallest:
            smallest = hm[key]

    return smallest if smallest != float("inf") else -1

print(firstUniqChar("loveleetcode"))


import numpy as np
import numpy.testing as npt
import rasterio
from open_data import open_dataset_readers, stack_bands

def test_open_dataset_readers(tmp_path):
    band_file_info = {}
    for band_name in ["band1", "band2"]:
        tmp_path.mkdir(parents=True, exist_ok=True)
        file_path = tmp_path / f"{band_name}.jp2"
        with rasterio.open(
            file_path, "w", driver="GTiff", height=10, width=10, count=1, dtype="uint8"
        ) as dst:
            dst.write(np.ones((10, 10), dtype="uint8"), 1)
        band_file_info[band_name] = {"resolution": "10m", "file_path": file_path}

    # Call the function under test
    bands = open_dataset_readers(band_file_info)

    # Check the result
    assert set(bands.keys()) == {"band1", "band2"}
    for band_name, dataset_reader in bands.items():
        assert isinstance(dataset_reader, rasterio.DatasetReader)

def test_stack_bands(tmp_path):
    band_file_info = {}
    for band_name in ["band1", "band2"]:
        tmp_path.mkdir(parents=True, exist_ok=True)
        file_path = tmp_path / f"{band_name}.jp2"
        with rasterio.open(
            file_path, "w", driver="GTiff", height=10, width=10, count=1, dtype="uint16"
        ) as dst:
            dst.write(
                np.random.randint(0, 9001, size=(10, 10)), 1
            )  # np.ones((10, 10), dtype="uint16")
        band_file_info[band_name] = {"resolution": "10m", "file_path": file_path}

    # Call the function under test
    bands = open_dataset_readers(band_file_info)
    stacked_bands = stack_bands(bands)

    # Check the result
    assert stacked_bands.shape == (10, 10, 2)
    assert stacked_bands.dtype == np.uint16

def test_open_data_handler(tmp_path):
    band_file_info = {}
    for band_name in ["band1", "band2"]:
        tmp_path.mkdir(parents=True, exist_ok=True)
        file_path = tmp_path / f"{band_name}.jp2"
        with rasterio.open(
            file_path, "w", driver="GTiff", height=10, width=10, count=1, dtype="uint16"
        ) as dst:
            dst.write(np.ones((10, 10), dtype="uint16"), 1)
        band_file_info[band_name] = {"resolution": "10m", "file_path": file_path}

    # Call the function under test
    bands = open_dataset_readers(band_file_info)
    stacked_bands = stack_bands(bands)
    first_band = list(bands.keys())[0]
    original_metadata = bands[first_band].meta

    expected_result = np.ones((10, 10, 2), dtype=int)
    npt.assert_array_equal(stacked_bands, expected_result)

    assert first_band == "band1"
    assert original_metadata["driver"] == "GTiff"
    assert original_metadata["dtype"] == "uint16"
    assert original_metadata["width"] == 10
    assert original_metadata["height"] == 10
    assert original_metadata["count"] == 1


#!/usr/bin/env python
from database import Database as Database
from config import Config as Config
from terraform import Terraform as Terraform
from azure import Azclass as Azclass

credenciais = Config("/home/damato/projetos/dados.json")
#base = Database(credenciais)
az = Azclass(credenciais)
models = Config("terraform_models.json")
tf = Terraform("azure",models)
#base.queryDatabase("select data from projetos2 where id = " + str(2))
#base.printJson(2)
#base.closeDatabase()
#conf.atualizaJson("chave","v2")
az.login()

retorno = az.getVmsList("")
if retorno == False:
    print("False")
else:
    print(dir(retorno))


#! /usr/bin/python3

import logging
import sys
from urllib.parse import urlparse
import socket

from http_browser.Browser import Browser
from http_browser.HttpServerMessage import HTTP_STATUS
from tcp.Exceptions import ClosedSocketException

__author__ = "njhazelh"

logging.basicConfig(
    format='[%(asctime)s] {%(filename)-20s:%(lineno)-3d} %(levelname)s - %(message)s',
    datefmt='%I:%M:%S')
log = logging.getLogger("rawhttpget")

def main(argv):
    """
    Get the resource from the internet.
    :param argv: The commmand line arguments parsed into a handy map.
    """
    dest, path, filename = parse_input(args.url)
    browser = Browser()
    print("Getting %s from %s" % (path, dest))
    try:
        response = browser.get(path, dest=dest)
    except ConnectionRefusedError:
        print("Could not connect to server")
        sys.exit()
    except ClosedSocketException:
        print("Socket was open but closed")
        sys.exit()
    print("Saving response to %s" % (filename))
    saveResponse(response, filename)
    browser.close()

def parse_input(url):
    """
    Convert the user input url into something we can use.

    If the url doesn't have a file name, use index.html

    :param url: The url to convert
    :return: A domain/port pair, the url, and the filename to save under.
    """
    if not url.startswith('http'):
        url = '%s%s' % ('http://', url)
    parsed = urlparse(url)

    # validate url
    if parsed.netloc == '':
        log.critical("domain name must be provided. Received %s", parsed)
        sys.exit(0)
    try:
        socket.gethostbyname(parsed.netloc)
    except OSError:
        print("Could not find IP address for domain name")
        sys.exit(0)

    domain = parsed.netloc
    port = 80

    # calculate filename to save result as
    if parsed.path == '' or parsed.path[-1] == "/":
        filename = "index.html"
    else:
        filename = parsed.path.split("/")[-1]

    return (domain, port), url, filename

def saveResponse(response, filename):
    """
    Save the response to a file.
    :param response: The HTTP Response object.
    :param filename: The name to save the data under
    """
    if response.status_code != HTTP_STATUS.OK:
        print("Failed to load resource. Status Code = %d" % (response.status_code))
    else:
        data = response.body
        file = open(filename, 'wb')
        file.write(data)

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="Basically wget")
    parser.add_argument("url", help="The url to get.  Will use filename from resource or index.html if it's a folder")
    parser.add_argument("--verbosity", "-v", default="CRITICAL",
                        choices=["DEBUG", "INFO", "WARN", "ERROR", "CRITICAL"],
                        help="The verbosity of the output.  Defaults to CRITICAL.")
    args = parser.parse_args()
    log.setLevel(args.verbosity)
    main(args)


#assn3
#ebakan
lst=[raw_input("adjective:"),
     raw_input("noun:"),
     raw_input("verb:"),
     raw_input("plural noun:"),
     raw_input("noun:"),
     raw_input("plural noun:"),
     raw_input("-ing verb:"),
     raw_input("-ing verb:"),
     raw_input("-ing verb:"),
     raw_input("plural noun:")]
ln=['IDLE is Python\'s Tkinter-based Integrated DeveLopment Environment. '
    'IDLE emphasizes a '+lst[0]+', clean design with a simple '+lst[1]+'. ',
    'Although it is suitable for beginners, even advanced users will find that IDLE has everything they really need to '+lst[2]+' pure Python '+lst[3]+'. ',
    'IDLE features a multi-window '+lst[4]+' with multiple '+lst[5]+', Python '+lst[6]+', and many other capabilities. ',
    'The editor has comprehensive '+lst[7]+' functions, including '+lst[8]+' multiple files. ',
    'Class browsers and path browsers provide fast access to '+lst[9]+' from a top level viewpoint without dealing with code folding.']
def out(ln):
    x=''
    for i in range(len(ln)):
        x+=ln[i]
    return x
if __name__=='__main__':
    print(out(ln))
    raw_input()


#!/usr/bin/python3

"""
A function that prints a messages
"""

def say_my_name(first_name, last_name=""):
    """
    Print the name with the format "My name is <first name> <last name>".

    Args:
        first_name (str): The first name.
        last_name (str): The last name (dafualt: "").

    Raises:
        TypeError: If first_name is not a string or last_name is not a string.
    """

    if type(first_name) is not str:
        raise TypeError("first_name must be a string")

    if last_name is None:
        raise TypeError("last_name must be a string")

    if type(last_name) is not str:
        raise TypeError("last_name must be a string")

    print("My name is {} {}".format(first_name, last_name))


from django.urls import path, re_path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('list', views.list_meetings, name='list'),
    re_path(r'^m/(?P<slug>\w+)$', views.unbreakout, name='meeting'),

    path('create', views.create, name='create'),
    path('clear', views.clear, name='clear'),
    re_path(r'^(?P<slug>\w+)/register$', views.register, name='register'),
    re_path(r'^(?P<slug>\w+)/export$', views.export_breakouts, name='export'),
    re_path(r'^(?P<slug>\w+)/freeze$', views.freeze_breakouts, name='freeze_breakouts'),
    re_path(r'^(?P<slug>\w+)/clear$', views.clear_breakouts, name='clear_breakouts'),
    re_path(r'^(?P<slug>\w+)/manual_transfer$', views.manual_transfer, name='manual-transfer'),
    re_path(r'^(?P<slug>\w+)/create_zoom_meeting$', views.create_zoom_meeting, name='create_zoom_meeting'),
    re_path(r'^(?P<slug>\w+)/restore$', views.restore, name='restore'),

    re_path(r'^m/(?P<slug>\w+)/test_users$', views.create_test_users, name='create_test_users'),

    re_path(r'^(?P<slug>\w+)/create_breakout$', views.create_breakout, name='create_breakout'),
    path('<slug:slug>/breakout/<int:breakout_id>/join', views.join_breakout, name='join_breakout'),
    path('<slug:slug>/breakout/unjoin', views.unjoin_breakout, name='unjoin_breakout'),
]


def ColonnaUguale4(m1,j1,m2,j2):
    if len(m1) != len(m2):
        return False
    for i in range(len(m1)):
        if m1[i][j1] != m2[i][j2]:
            return False
    return True

def ColonnaUguale3(m1,m2,j2):
    for j in range(len(m1[0])):
        if ColonnaUguale4(m1,j,m2,j2):
            return True
    return False

def ColonnaUguale2(m1,m2):
    for j in range(len(m2[0])):
        if ColonnaUguale3(m1,m2,j):
            return True
    return False

def TutteColonneUguali(m1,m2):
    if len(m1[0]) != len(m2[0]):
        return False
    for j in range(len(m1[0])):
       if not ColonnaUguale3(m2,m1,j):
           return False
    for j in range(len(m2[0])):
       if not ColonnaUguale3(m1,m2,j):
           return False
    return True

def sudoku(m):
    s = sum(m[0])
    for r in m:
        if sum(r) != s:
            return  False
    for j in range(len(m[0])):
        sj = 0
        for r in m:
            sj += r[j]
        if sj != s:
            return False
    return True

matrici = {}
with open("dati.txt") as f:
    for l in f:
        l =l.strip()
        if len(l)>0:
            s = l.split(",")
            r = [int(s[i]) for i in range(1,len(s))]
            if s[0] in matrici:
                matrici[s[0]].append(r)
            else:
                matrici[s[0]] = [r]

################# punto 1 #######################
# in questo punto chiamo A la prima matrice. Stampare tutte le matrici che abbiano una colonna uguale ad una della matrice A
with open("1.txt","w") as o:
    key = list(matrici.keys())
    for i in range(1,len(key)):
        if ColonnaUguale2(matrici[key[0]],matrici[key[i]]):
            o.write(key[i]+"----->A\n")
################# punto 2 #######################
# per ogni matrice trovare la riga di somma massima
with open("2.txt","w") as o:
    for k,v in matrici.items():
        mo = sorted(v, key=lambda r:sum(r))
        o.write(k+str(mo[-1])+"\n")
################# punto 3 #######################
# in questo punto chiamo A la prima matrice. Stampare tutte le matrici i cui valori siano compresi in quelli della matrice A
with open("3.txt","w") as o:
    valA = []
    for r in matrici["A"]:
        for x in r:
            valA.append(x)
    key = list(matrici.keys())
    for i in range(1,len(key)):
        contenuta = True
        for r in matrici[key[i]]:
            if x not in valA:
                contenuta = False
        if contenuta:
            o.write(key[i]+"\n")
################# punto 4 #######################
# Stampare tutte le coppie di matrici che hanno le stesse colonne (senza duplicati)
with open("4.txt","w") as o:
    key = list(matrici.keys())
    for i in range(len(key)):
        for j in range(i+1,len(key)):
            if TutteColonneUguali(matrici[key[i]],matrici[key[j]]):
                o.write(key[i]+"---->"+key[j])

################# punto 5 #######################
# Stampare le matrici sudoku (anche non quadrate), cioè quelle per cui la somma di tute le righe edi tutte le colonne ha lo stesso valore
with open("5.txt","w") as o:
    for k,v in matrici.items():
        if sudoku(v):
            o.write(k+ " e' sudoku  \n")


'''
Best practice:

def scale_horizontal(strng,k):
    retstrng = strng
    if k > 1:
        s = [s*k for s in strng]
        retstrng = "".join(s)
    return retstrng

def scale(strng, k, n):
    if strng == "": return ""
    lines = strng.split('\n')
    lines = [scale_horizontal(line,k) for line in lines]
    retlines = []
    for i in range(len(lines)):
        for j in range(n):
            retlines.append(lines[i])
    return "\n".join(retlines)
'''

def scale(string, k, n):
    if not string:
        return ''
    result = []
    for row in string.split("\n"):
        newRow = []
        for char in row:
            newRow.append( "".join( [char for i in range(k)] ) )
        result.append( "\n".join(["".join(newRow) for j in range(n)]) )
    return "\n".join(result)


"Ejercicio 1"
def minMaxLengthAverage(lst):
	values = [lst[0],lst[0],len(lst),0]
	for i in lst:
		if(i<=values[0]):
			values[0] = i
		if(i>=values[1]):
			values[1] = i
		values[3]+=i
	values[3] = values[3]/values[2]
	return values

"Ejercicio 2"
def filter_list(lst):
	lst2 = []
	for i in lst:
		typeof = type(i).__name__
		if(typeof!="str"):
			lst2.append(i)
	return lst2

"Ejercicio 3"
def removeDups(lst):
	stack = []
	for i in lst:
		if i not in stack:
			stack.append(i)
	return stack


"""
Asynchronous HTTP client for Aucote. It's using tornado's AsyncHTTPClient.

"""
import logging as log

import functools
from typing import Any

from tornado import gen
from tornado.httpclient import AsyncHTTPClient, HTTPRequest, HTTPError
import ujson

def retry_if_fail(min_retry_time: int, max_retry_time: int, max_retries: int,
                  exceptions: [Exception, tuple]) -> callable:
    """
    Retry function execution in case of connection fail.
    In case of fail double waiting time starting from min_retry_time.
    Waiting time cannot exceed max_retry_time.
    Raise exception after max_retries failed tries. max_retries has to be more than 1
    """
    def decorator(function: callable) -> callable:

        @functools.wraps(function)
        async def function_wrapper(*args, **kwargs) -> Any:
            """
            Try to execute function. In case of fail double waiting time.
            Waiting time cannot exceed max_retry_time.
            Raise ``ToucanConnectionException`` after max_retries failed tries

            """
            wait_time = min_retry_time
            try_counter = 0
            while try_counter < max_retries:
                try:
                    return await function(*args, **kwargs)
                except exceptions as exception:
                    log.warning("Connection error for %s.%s: %s", args[0].__class__.__name__,
                                function.__name__, exception)
                    log.warning("Retry in %s s", wait_time)
                    await gen.sleep(wait_time)
                    wait_time = min(wait_time*2, max_retry_time)
                    try_counter += 1

                    if try_counter >= max_retries:
                        raise exception

        return function_wrapper
    return decorator

class HTTPClient(object):
    """
    Asynchronous HTTP client for Aucote. It's using tornado's AsyncHTTPClient.

    """
    _instance = None

    @classmethod
    def instance(cls, *args, **kwargs) -> 'HTTPClient':
        """
        Return instance of HTTPClient
        """
        if cls._instance is None:
            cls._instance = HTTPClient(*args, **kwargs)
        return cls._instance

    @classmethod
    def _handle_response(cls, response: 'HTTPResponse') -> 'Future':
        """
        Handle response
        """
        if response.error:
            log.info("Error: %s with requesting %s", response.error, response.request.url)
        return response

    def get(self, url: str, **kwargs) -> 'Future':
        """
        Perform GET request
        """
        return self.request(url=url, method="GET", **kwargs)

    def head(self, url: str, **kwargs) -> 'Future':
        """
        Perform HEAD request
        """
        return self.request(url=url, method="HEAD", **kwargs)

    def put(self, url: str, **kwargs) -> 'Future':
        """
        Perform PUT request
        """
        return self.request(url=url, method="PUT", **kwargs)

    def request(self, json: dict = None, **kwargs) -> 'Future':
        """
        Perform request
        """
        if json:
            kwargs['body'] = ujson.dumps(json)
            kwargs.setdefault('headers', {})['Content-Type'] = 'application/json'
        request = HTTPRequest(**kwargs)
        return AsyncHTTPClient().fetch(request, self._handle_response)


#!/usr/bin/env python3

import requests

def upload_data(target, data, timeout=None):
    # first upload the data
    r = requests.put(f"https://{target}/update/stage", data=data, verify=False, timeout=timeout)
    print(r.content)

    # then trigger the install
    r = requests.post(f"https://{target}/update/install", json={"appControlMode":"Auto"}, verify=False, timeout=timeout)
    print(r.content)

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("image", type=argparse.FileType("rb"))
    parser.add_argument("--target", default="192.168.35.2")
    args = parser.parse_args()

    upload_data(args.target, args.image.read())


import numpy as np
import matplotlib.pyplot as plt

n = m = 10
N = 17
gi = []
hi = []
gi_help = []
hi_help = []

for ind in range(1, 11):
    gi_res = 1.5 + (1 / N) * np.sin(ind)
    hi_res = 1.5 + (1 / N) * np.cos(ind)
    gi.append(gi_res)
    hi.append(hi_res)
    gi_help.append([ind, gi_res])
    hi_help.append([ind, hi_res])

print('gi ', gi_help)
print('hi ', hi_help)

gi.sort()
hi.sort(reverse=True)
print('gi ', gi)
print('hi ', hi)

y = [y * 2 for y in range(10)]
plt.step(gi, y)
plt.step(hi, y)
plt.grid()
plt.show()

Maga1Sem/Modeling of information processes/Semestrovaya 2.py


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        # Three Pointer Approach (Iteratively)
        # def reverse(head):
            # if not head or not head.next:
            #     return head
            # p, c, n = head, head.next, head.next.next

            # p.next = None
            # while n:
            #     c.next = p
            #     p , c, n = c , n, n.next
            # c.next = p
            # return c

        # Recursive Approach
        if not head or not head.next:
            return head

        next_node = head.next
        head.next = None
        new_node = self.reverseList(next_node)
        next_node.next = head
        return new_node


# 시간복잡도 최악의 경우 O(n)의 알고리즘
# 2개의 1차원 DP를 n만큼 순회하며 차례로 완성해간다.
# 곱의 경우 양수 음수가 바뀌기 때문에, 최대합구간의 방식 그대로 사용할 수 없다.
# 결국 절댓값이 크고 양수여야 하므로.
# A[i]로 끝나는 구간 최솟값과 최댓값을 이용한다.
# 최솟값은 음의 방향으로 절댓값이 가장 큰 값을 나타내기 때문.

# 결과적으로
# A[i]가 음수일 때, A[i-1] 까지의 구간 최솟값과 곱하여 절댓값이 가장 큰 양수, 즉 최대 구간 곱이 될 경우를 고려해주면
# A[i]로 끝나는 최대, 최소 구간합은 A[i], A[i]*Max[i-1], A[i]*Min[i-1] 세가지 값을 비교하여 얻을 수 있다.
# 이렇게 구한 DP: Max를 순회하며 최대값을 return해주면, 그 값이 최대 구간 곱이다.
# n개의 정수를 한번씩 순회하면 되므로 시간복잡도 O(n)
# T(n) = 3n + 5

def max_mul_interval(A):
	n = len(A)
	Max = [0]*n # A[i]로 끝나는 최대 곱 구간
	Min = [0]*n # A[i]로 끝나는 최소 곱 구간
	Max[0] = Min[0] = A[0] # 초깃값
	for i in range(1,n):
		Min[i] = min(A[i], A[i]*Max[i-1], A[i]*Min[i-1]) # 자기자신, 자기자신*이전 최댓값, 자기자신*이전 최솟값 중 최솟값
		Max[i] = max(A[i], A[i]*Max[i-1], A[i]*Min[i-1]) # 자기자신, 자기자신*이전 최댓값, 자기자신*이전 최솟값 중 최댓값
	return max(Max) % 123464239 # DP에 저장된 값중 최대값

A = list(map(int, input().split()))
print(max_mul_interval(A))


def biggest_power_of2(n):
	res = 0
	for i in range(n, 0, -1):

		# If i is a power of 2
		if ((i & (i - 1)) == 0):

			res = i
			break

	return res


# -*- coding: utf-8 -*-
import logging
import phonenumbers
from datetime import datetime, timedelta
from dateutil import tz
from djmoney.money import Money
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.auth import authenticate
from django.db.models import Q, Prefetch
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.utils.http import urlquote
from rest_framework import exceptions, serializers
from rest_framework.response import Response

from shared_foundation.custom.drf.fields import PhoneNumberField
from shared_foundation import constants
from tenant_api.serializers.skill_set import SkillSetListCreateSerializer
from tenant_api.serializers.tag import TagListCreateSerializer
from tenant_foundation.constants import *
from tenant_foundation.models import (
    Comment,
    WorkOrderComment,
    WORK_ORDER_STATE,
    WorkOrderInvoice,
    ONGOING_WORK_ORDER_STATE,
    OngoingWorkOrder,
    SkillSet,
    Tag,
    TaskItem
)

logger = logging.getLogger(__name__)

class WorkOrderInvoiceSecondSectionUpdateSerializer(serializers.Serializer):

    line01_qty = serializers.IntegerField(required=True, write_only=True,)
    line01_desc = serializers.CharField(required=True, write_only=True, allow_null=True, allow_blank=True,)
    line01_price = serializers.FloatField(required=True, write_only=True, allow_null=True,)
    line01_amount = serializers.FloatField(required=True, write_only=True, allow_null=True,)
    line02_qty = serializers.IntegerField(required=False, write_only=True, allow_null=True,)
    line02_desc = serializers.CharField(required=False, write_only=True, allow_null=True, allow_blank=True,)
    line02_price = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line02_amount = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line03_qty = serializers.IntegerField(required=False, write_only=True, allow_null=True,)
    line03_desc = serializers.CharField(required=False, write_only=True, allow_null=True, allow_blank=True,)
    line03_price = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line03_amount = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line04_qty = serializers.IntegerField(required=False, write_only=True, allow_null=True,)
    line04_desc = serializers.CharField(required=False, write_only=True, allow_null=True, allow_blank=True,)
    line04_price = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line04_amount = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line05_qty = serializers.IntegerField(required=False, write_only=True, allow_null=True,)
    line05_desc = serializers.CharField(required=False, write_only=True, allow_null=True, allow_blank=True,)
    line05_price = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line05_amount = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line06_qty = serializers.IntegerField(required=False, write_only=True, allow_null=True,)
    line06_desc = serializers.CharField(required=False, write_only=True, allow_null=True, allow_blank=True,)
    line06_price = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line06_amount = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line07_qty = serializers.IntegerField(required=False, write_only=True, allow_null=True,)
    line07_desc = serializers.CharField(required=False, write_only=True, allow_null=True, allow_blank=True,)
    line07_price = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line07_amount = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line08_qty = serializers.IntegerField(required=False, write_only=True, allow_null=True,)
    line08_desc = serializers.CharField(required=False, write_only=True, allow_null=True, allow_blank=True,)
    line08_price = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line08_amount = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line09_qty = serializers.IntegerField(required=False, write_only=True, allow_null=True,)
    line09_desc = serializers.CharField(required=False, write_only=True, allow_null=True, allow_blank=True,)
    line09_price = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line09_amount = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line10_qty = serializers.IntegerField(required=False, write_only=True, allow_null=True,)
    line10_desc = serializers.CharField(required=False, write_only=True, allow_null=True, allow_blank=True,)
    line10_price = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line10_amount = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line11_qty = serializers.IntegerField(required=False, write_only=True, allow_null=True,)
    line11_desc = serializers.CharField(required=False, write_only=True, allow_null=True, allow_blank=True,)
    line11_price = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line11_amount = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line12_qty = serializers.IntegerField(required=False, write_only=True, allow_null=True,)
    line12_desc = serializers.CharField(required=False, write_only=True, allow_null=True, allow_blank=True,)
    line12_price = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line12_amount = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line13_qty = serializers.IntegerField(required=False, write_only=True, allow_null=True,)
    line13_desc = serializers.CharField(required=False, write_only=True, allow_null=True, allow_blank=True,)
    line13_price = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line13_amount = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line14_qty = serializers.IntegerField(required=False, write_only=True, allow_null=True,)
    line14_desc = serializers.CharField(required=False, write_only=True, allow_null=True, allow_blank=True,)
    line14_price = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line14_amount = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line15_qty = serializers.IntegerField(required=False, write_only=True, allow_null=True,)
    line15_desc = serializers.CharField(required=False, write_only=True, allow_null=True, allow_blank=True,)
    line15_price = serializers.FloatField(required=False, write_only=True, allow_null=True,)
    line15_amount = serializers.FloatField(required=False, write_only=True, allow_null=True,)

    class Meta:
        model = WorkOrderInvoice
        fields = (
            'line01_qty', 'line01_desc', 'line01_price', 'line01_amount',
            'line02_qty', 'line02_desc', 'line02_price', 'line02_amount',
            'line03_qty', 'line03_desc', 'line03_price', 'line03_amount',
            'line04_qty', 'line04_desc', 'line04_price', 'line04_amount',
            'line05_qty', 'line05_desc', 'line05_price', 'line05_amount',
            'line06_qty', 'line06_desc', 'line06_price', 'line06_amount',
            'line07_qty', 'line07_desc', 'line07_price', 'line07_amount',
            'line08_qty', 'line08_desc', 'line08_price', 'line08_amount',
            'line09_qty', 'line09_desc', 'line09_price', 'line09_amount',
            'line10_qty', 'line10_desc', 'line10_price', 'line10_amount',
            'line11_qty', 'line11_desc', 'line11_price', 'line11_amount',
            'line12_qty', 'line12_desc', 'line12_price', 'line12_amount',
            'line13_qty', 'line13_desc', 'line13_price', 'line13_amount',
            'line14_qty', 'line14_desc', 'line14_price', 'line14_amount',
            'line15_qty', 'line15_desc', 'line15_price', 'line15_amount',
        )

    def update(self, instance, validated_data):
        """
        Override this function to include extra functionality.
        """
        instance.line_01_qty = validated_data.get('line01_qty', instance.line_01_qty)
        instance.line_01_desc = validated_data.get('line01_desc', instance.line_01_desc)
        instance.line_01_price = validated_data.get('line01_price', instance.line_01_price)
        instance.line_01_amount = validated_data.get('line01_amount', instance.line_01_amount)

        instance.line_02_qty = validated_data.get('line02_qty', instance.line_02_qty)
        instance.line_02_desc = validated_data.get('line02_desc', instance.line_02_desc)
        instance.line_02_price = validated_data.get('line02_price', instance.line_02_price)
        instance.line_02_amount = validated_data.get('line02_amount', instance.line_02_amount)

        instance.line_03_qty = validated_data.get('line03_qty', instance.line_03_qty)
        instance.line_03_desc = validated_data.get('line03_desc', instance.line_03_desc)
        instance.line_03_price = validated_data.get('line03_price', instance.line_03_price)
        instance.line_03_amount = validated_data.get('line03_amount', instance.line_03_amount)

        instance.line_04_qty = validated_data.get('line04_qty', instance.line_04_qty)
        instance.line_04_desc = validated_data.get('line04_desc', instance.line_04_desc)
        instance.line_04_price = validated_data.get('line04_price', instance.line_04_price)
        instance.line_04_amount = validated_data.get('line04_amount', instance.line_04_amount)

        instance.line_05_qty = validated_data.get('line05_qty', instance.line_05_qty)
        instance.line_05_desc = validated_data.get('line05_desc', instance.line_05_desc)
        instance.line_05_price = validated_data.get('line05_price', instance.line_05_price)
        instance.line_05_amount = validated_data.get('line05_amount', instance.line_05_amount)

        instance.line_06_qty = validated_data.get('line06_qty', instance.line_06_qty)
        instance.line_06_desc = validated_data.get('line06_desc', instance.line_06_desc)
        instance.line_06_price = validated_data.get('line06_price', instance.line_06_price)
        instance.line_06_amount = validated_data.get('line06_amount', instance.line_06_amount)

        instance.line_07_qty = validated_data.get('line07_qty', instance.line_07_qty)
        instance.line_07_desc = validated_data.get('line07_desc', instance.line_07_desc)
        instance.line_07_price = validated_data.get('line07_price', instance.line_07_price)
        instance.line_07_amount = validated_data.get('line07_amount', instance.line_07_amount)

        instance.line_08_qty = validated_data.get('line08_qty', instance.line_08_qty)
        instance.line_08_desc = validated_data.get('line08_desc', instance.line_08_desc)
        instance.line_08_price = validated_data.get('line08_price', instance.line_08_price)
        instance.line_08_amount = validated_data.get('line08_amount', instance.line_08_amount)

        instance.line_09_qty = validated_data.get('line09_qty', instance.line_09_qty)
        instance.line_09_desc = validated_data.get('line09_desc', instance.line_09_desc)
        instance.line_09_price = validated_data.get('line09_price', instance.line_09_price)
        instance.line_09_amount = validated_data.get('line09_amount', instance.line_09_amount)

        instance.line_11_qty = validated_data.get('line11_qty', instance.line_11_qty)
        instance.line_11_desc = validated_data.get('line11_desc', instance.line_11_desc)
        instance.line_11_price = validated_data.get('line11_price', instance.line_11_price)
        instance.line_11_amount = validated_data.get('line11_amount', instance.line_11_amount)

        instance.line_12_qty = validated_data.get('line12_qty', instance.line_12_qty)
        instance.line_12_desc = validated_data.get('line12_desc', instance.line_12_desc)
        instance.line_12_price = validated_data.get('line12_price', instance.line_12_price)
        instance.line_12_amount = validated_data.get('line12_amount', instance.line_12_amount)

        instance.line_13_qty = validated_data.get('line13_qty', instance.line_13_qty)
        instance.line_13_desc = validated_data.get('line13_desc', instance.line_13_desc)
        instance.line_13_price = validated_data.get('line13_price', instance.line_13_price)
        instance.line_13_amount = validated_data.get('line13_amount', instance.line_13_amount)

        instance.line_14_qty = validated_data.get('line14_qty', instance.line_14_qty)
        instance.line_14_desc = validated_data.get('line14_desc', instance.line_14_desc)
        instance.line_14_price = validated_data.get('line14_price', instance.line_14_price)
        instance.line_14_amount = validated_data.get('line14_amount', instance.line_14_amount)

        instance.line_15_qty = validated_data.get('line15_qty', instance.line_15_qty)
        instance.line_15_desc = validated_data.get('line15_desc', instance.line_15_desc)
        instance.line_15_price = validated_data.get('line15_price', instance.line_15_price)
        instance.line_15_amount = validated_data.get('line15_amount', instance.line_15_amount)

        instance.revision_version += 1;
        instance.save()
        logger.info("Updated invoice second section.")

        return instance


#!/usr/bin/env python

"""
deepthought@42 ~ $ pdlisten

[{constants.success}]: Server is listening on 192.168.1.58:8080
[{constants.success}]: Connection Key: 192@168@1@58+8080
[{constants.success}]: Waiting for a connection for files...

This program is used to listen for incoming connections from the
pdsnd.py program. If it recieves a connection, it will write the
file in the directory.

The pdsnd command is used for sending a file to the server
created by the server "pdlisten" program.

### PDLISTEN ###

The pdlisten command when run gives a connection key which
is needed to send a file while using pdsnd.

The -port argument may be used to change the port of the server.

Thanks for having interest in this library.
This file is the script for the pdlisten program.
"""

# Import libraries

import sys
import socket
import readline
import os
import constants
from rich import print

# Decodes the key

def keymaker(key: str) -> str:
    return key.replace(".", "@").replace(":", "+")

# HEADER Variable
HEADER = 64

# CLIENT
# A class which makes life easier.
class Client:
    def __init__(self, server, port):

        # CHANGE STUFF HERE
        self.SERVER_HOST = server
        self.SERVER_PORT = port
        # CHANGE STUFF HERE

        self.BUFFER_SIZE = 4096
        self.SEPARATOR = "<pyserved21>"
        self.s = socket.socket()
        self.s.bind((self.SERVER_HOST, self.SERVER_PORT))

    def listen(self):
        # Listen for incoming connections
        self.s.listen(10)

    def accept(self):
        # Accept incoming connections from client
        # and return client socket and address.
        self.client_socket, self.address = self.s.accept()
        return (self.client_socket, self.address)

    def receive(self):
        # Receive message from client_socket
        # and return filename and filesize
        received = self.client_socket.recv(self.BUFFER_SIZE).decode()
        filename, filesize = received.split(self.SEPARATOR)
        self.filename = os.path.basename(filename)
        self.filesize = int(filesize)
        return self.filename, self.filesize

    def write(self):
        # Write file which is received from client_socket
        # in the same directory.
        with open(self.filename, "wb") as f:
            while True:
                # read 1024 bytes from the socket (receive)
                bytes_read = self.client_socket.recv(self.BUFFER_SIZE)
                if not bytes_read:
                    # nothing is received
                    # file transmitting is done
                    break
                # write to the file the bytes we just received
                f.write(bytes_read)

    def close(self):
        # close the client socket
        self.client_socket.close()
        # close the server socket
        self.s.close()

# Function to get Internal IP of device

def get_internal_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    ip = s.getsockname()[0]
    s.close()
    return ip

# CHANGE SERVER HERE
SERVER = get_internal_ip()
# CHANGE SERVER HERE

# CHANGE PORT HERE
PORT = 8080
# CHANGE PORT HERE

ADDR = (SERVER, PORT)

# Check if port is not in use
# If port is in use, return True
# Else False
def is_port_in_use() -> bool:
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        return s.connect_ex((get_internal_ip(), PORT)) == 0

# Checks if -port argument is passed
try:
    if sys.argv[1] is None:
        pass
    else:
        if "-port" in sys.argv[1]:
            PORT = int(sys.argv[2])
            # print(PORT)
            ADDR = (SERVER, PORT)
except IndexError:
    pass

# If port 8080 is in use,
# End program with message informing that port is in use
if is_port_in_use() is True:
    print(
        f"[bold red][{constants.error}]: Port 8080 is already in use in your network. Choose another port instead using the '-port' parameter.[/]"
    )
    exit()

# Start server

try:
    client = Client(SERVER, PORT)

    print(
        f"[bold green][{constants.success}]:[/] Server is listening on {SERVER}:{PORT}"
    )
    print(
        f"[bold green][{constants.success}]:[/] Connection Key: {keymaker(str(SERVER + ':' + str(PORT)))}"
    )
    print(
        f"[bold green][{constants.success}]:[/] Waiting for a connection for files..."
    )

    client.listen()
    _, address = client.accept()

    print(
        f"[bold green][{constants.success}]:[/] Connection from {address[0]}:{address[1]} accepted."
    )
    print(f"[bold green][{constants.success}]:[/] Reading file data.....")

    try:
        client.receive()
    except ValueError as e:
        print(
            f"{repr(e)} \n\n [bold red][{constants.error}]: An error occured. Please try again in few seconds....[/]"
        )
        exit()

    print(
        f"[bold green][{constants.success}]:[/] Received file '[bold yellow]{client.filename}[/]', saving to current directory."
    )
    client.write()

    print(
        "[bold green][{constants.success}]:[/] File transferred successfully. Closing connection..."
    )
    client.close()

except KeyboardInterrupt:
    print(f"\n\n[bold red][{constants.error}]: KeyboardInterrupt[/]")
    exit()

except Exception as e:
    print(
        f"\n\n[bold red][{constants.error}]: {repr(e)} \n\n If the problem persists, contact the owner of the package at https://github.com/SblipDev/pyserved[/] \n"
    )
    exit()


# -*- coding: utf-8 -*-
"""
@author: Yifan Cheng, Skylar Du, Yashash Gaurav, Mark He
"""

import pandas as pd

merged_data_path = "merged_data.xlsx"

merged_data = pd.read_excel(merged_data_path, index_col=0)

def view_recommendations(preferred_state, sat_score, total_4_year_cost):
    in_range_college = merged_data[
        (merged_data["State"] == preferred_state)
        & (merged_data["SAT Min"] < sat_score)
        # & (merged_data['SAT Max'] > sat_score) - the more the
        # score the better?
        & (
            merged_data["Total 4 Year Cost (Integer)"]
            < (float(total_4_year_cost) * 1.1)
        )
    ]

    if len(in_range_college) > 0:
        print("Here are the schools that we recommend!:")

        result_count = 0
        for index, college in in_range_college.iterrows():
            result_count += 1
            if result_count > 10:
                print("\n^   Showing top 10 results!   ^\n")
                break
            print("- - - - - - - - - - - - - - - - - - - - - - - - - -")
            print(f"20 Year Net ROI:   {str(college[2]):>30}")
            print(f"College Name:      {str(college[1]):>30}")
            print(f"Total 4 Year Cost: {str(college[3]):>30}")
            print(f"Graduation Rate:   {str(college[4]):>30}")
            print(f"City:              {str(college[7]):>30}")
            print(f"State:             {str(college[8]):>30}")
            print(f"Acceptance Rate:   {str(college[9]):>30}")
    else:
        print("\nConsider updating preferences to find better results!")


import telebot
import json

from telebot.types import ReplyKeyboardMarkup, InlineKeyboardMarkup, InlineKeyboardButton

from bot_key import bot_key
from send import send

bot = telebot.TeleBot(bot_key)

with open('../db/settings.json') as file:
    settings = json.load(file)
id = settings["telegram"]["id"]

@bot.message_handler(commands=['start', 'help'])
def start_help_message(message):
    if str(message.chat.id) == id:
        text = "Этот бот предназдначен для получения напоминаний о ваших задачах.\nТак же через него можно работать " \
               "с задачами.\n\nДоступные команды:\n\n/help - выводит подсказку о возможностях бота\n\n/tasks - выводит все" \
               " задачи которые у вас есть"
        bot.send_message(message.chat.id, text, parse_mode="html")
    else:
        bot.send_message(message.chat.id, "Под не подключен", parse_mode="html")

@bot.message_handler(commands=['tasks'])
def send_tasks(message):
    with open('../db/tasks.json') as file:
        tasks = json.load(file)["tasks"]
    keys_list = list(tasks.keys())

    if str(message.chat.id) == id:
        count = len(keys_list)
        page = 1
        markup = InlineKeyboardMarkup()
        markup.add(InlineKeyboardButton(text=f'{page}/{count}', callback_data=f' '),
                   InlineKeyboardButton(text=f'Вперёд --->',
                                        callback_data="{\"method\":\"pagination\",\"NumberPage\":" + str(
                                            page + 1) + ",\"CountPage\":" + str(count) + "}"))

        key = keys_list[0]
        task = tasks[key]

        time_1, time_2 = tuple(key.split(";"))
        time_2 = time_2.replace(":", ".")
        time_1 = ":".join(time_1.split(":")[:0:-1])
        time = " / ".join([time_1, time_2])

        text = f"{task[0]}\n\n{task[1]}\n\n{time}\n{'Завершено' if task[2] else 'Не завершено'}"

        bot.send_message(message.chat.id, text, parse_mode="html", reply_markup=markup)

    else:
        bot.send_message(message.chat.id, "Под не подключен", parse_mode="html")

@bot.callback_query_handler(func=lambda call: True)
def callback_query(call):
    req = call.data.split('_')

    if 'pagination' in req[0]:
        json_string = json.loads(req[0])
        count = json_string['CountPage']
        page = json_string['NumberPage']

        with open('../db/tasks.json') as file:
            tasks = json.load(file)["tasks"]
        keys_list = list(tasks.keys())

        key = keys_list[page - 1]
        task = tasks[key]

        markup = InlineKeyboardMarkup()
        if page == 1:
            markup.add(InlineKeyboardButton(text=f'{page}/{count}', callback_data=f' '),
                       InlineKeyboardButton(text=f'Вперёд --->',
                                            callback_data="{\"method\":\"pagination\",\"NumberPage\":" + str(
                                                page + 1) + ",\"CountPage\":" + str(count) + "}"))

        elif page == count:
            markup.add(InlineKeyboardButton(text=f'<--- Назад',
                                            callback_data="{\"method\":\"pagination\",\"NumberPage\":" + str(
                                                page - 1) + ",\"CountPage\":" + str(count) + "}"),
                       InlineKeyboardButton(text=f'{page}/{count}', callback_data=f' '))

        else:
            markup.add(InlineKeyboardButton(text=f'<--- Назад',
                                            callback_data="{\"method\":\"pagination\",\"NumberPage\":" + str(
                                                page - 1) + ",\"CountPage\":" + str(count) + "}"),
                       InlineKeyboardButton(text=f'{page}/{count}', callback_data=f' '),
                       InlineKeyboardButton(text=f'Вперёд --->',
                                            callback_data="{\"method\":\"pagination\",\"NumberPage\":" + str(
                                                page + 1) + ",\"CountPage\":" + str(count) + "}"))

        time_1, time_2 = tuple(key.split(";"))
        time_2 = time_2.replace(":", ".")
        time_1 = ":".join(time_1.split(":")[:0:-1])
        time = " / ".join([time_1, time_2])

        text = f"{task[0]}\n\n{task[1]}\n\n{time}\n{'Завершено' if task[2] else 'Не завершено'}"

        bot.edit_message_text(text, reply_markup=markup, chat_id=call.message.chat.id,
                              message_id=call.message.message_id, parse_mode="html")

while True:
    try:
        bot.polling()
    except Exception:
        pass


#!/usr/bin/env python3

from hanzi_util import is_zhs, is_terminator
import jieba
from copy import deepcopy
import os
import pickle

STOP_FILE = 'stopwords.txt'
TYCC_FILE = 'TYCCL.txt'
TRAIN_COPS = 'train.txt'
#TRAIN_COPS = 'C08-财经.txt'
#TRAIN_COPS = 'all.txt'

#
# {   '单词': [{'意项1': W1, W2, ...}, {'意项2': W1, W2, ...}, ]   }
#

STOP_WORDS = []
SCAN_WORDS = []
TYCC_ITEMS = {}
TYCC_DAT = {}

PAD = 'P'

def split_to_sentnces(lst):
    ret = []
    len_t = len(lst)
    fro = 0
    for i in range(len_t):
        if is_terminator(lst[i]):
            ret.append(lst[fro:i])
            fro = i + 1
    return ret

def build_train_dat():
    global TYCC_DAT
    TYCC_DAT = {}

    line_num = 0
    with open(TRAIN_COPS) as fin:
        while True:
            try:
                each_line = fin.readline()
                if not each_line:
                    break_flag = True
                    print("处理完毕！")
                    break
                line_num += 1
                if not (line_num % 2000): print("C:%d" %(line_num))
                each_line = each_line.strip()

                seg_list = jieba.cut(each_line, cut_all=False)
                seg_list = split_to_sentnces(list(seg_list))
                for seg_ls in seg_list:
                    if not seg_ls: continue

                    words = []
                    for item in seg_ls:
                        if not is_zhs(item): continue
                        if item in STOP_WORDS: continue
                        words.append(item)

                    len_t = len(words)
                    if not len_t or len_t < 3: continue
                    for i in range(len_t):
                        if words[i] in SCAN_WORDS:
                            if words[i] not in TYCC_DAT:
                                TYCC_DAT[words[i]] = {}
                                if (i-2) >= 0:
                                    TYCC_DAT[words[i]][words[i-2]] = 1
                                    TYCC_DAT[words[i]][words[i-1]] = 2
                                elif (i-1) >= 0:
                                    TYCC_DAT[words[i]][words[i-1]] = 2
                                if (i+2) < len_t:
                                    TYCC_DAT[words[i]][words[i+2]] = 1
                                    TYCC_DAT[words[i]][words[i+1]] = 2
                                elif (i+1) < len_t:
                                    TYCC_DAT[words[i]][words[i+1]] = 2
                            else:
                                if (i-2) >= 0:
                                    if words[i-2] in TYCC_DAT[words[i]]:
                                        TYCC_DAT[words[i]][words[i-2]] += 1
                                    else:
                                        TYCC_DAT[words[i]][words[i-2]] = 1
                                    # for i - 1
                                    if words[i-1] in TYCC_DAT[words[i]]:
                                        TYCC_DAT[words[i]][words[i-1]] += 2
                                    else:
                                        TYCC_DAT[words[i]][words[i-1]] = 2
                                elif (i-1) >= 0:
                                    if words[i-1] in TYCC_DAT[words[i]]:
                                        TYCC_DAT[words[i]][words[i-1]] += 2
                                    else:
                                        TYCC_DAT[words[i]][words[i-1]] = 2

                                if (i+2) < len_t:
                                    if words[i+2] in TYCC_DAT[words[i]]:
                                        TYCC_DAT[words[i]][words[i+2]] += 1
                                    else:
                                        TYCC_DAT[words[i]][words[i+2]] = 1
                                    # for i + 1
                                    if words[i+1] in TYCC_DAT[words[i]]:
                                        TYCC_DAT[words[i]][words[i+1]] += 2
                                    else:
                                        TYCC_DAT[words[i]][words[i+1]] = 2
                                elif (i+1) < len_t:
                                    if words[i+1] in TYCC_DAT[words[i]]:
                                        TYCC_DAT[words[i]][words[i+1]] += 2
                                    else:
                                        TYCC_DAT[words[i]][words[i+1]] = 2

            except UnicodeDecodeError as e:
                print('Unicode Error! filename=%s, line_num=%d'%(TRAIN_COPS, line_num))
                pass

def build_model():
    global STOP_WORDS
    global SCAN_WORDS
    global TYCC_ITEMS

    STOP_WORDS = []
    with open(STOP_FILE, 'r') as fin:
        for line in fin:
            item = line.strip()
            if len(item.split()) > 1:
                print(item)
            if is_zhs(item):
                STOP_WORDS.append(item)

    STOP_WORDS = set(STOP_WORDS)
    print("STOP_WORDS:%d" %(len(STOP_WORDS)))

    STOP_WORDS = []

    SCAN_WORDS = []
    TYCC_ITEMS_PREP = {}
    with open(TYCC_FILE, 'r') as fin:
        for line in fin:
            items = line.strip().split()
            if len(items) < 3: continue
            if items[1][0] != '【' and items[1][-1] != '】': continue

            # 只注重同义词部分
            if items[1][-3:] != '.=】': continue

            # 目前只考虑动词
            if items[0] != 'v': continue

            words = []
            for item in items[2:]:
                if item not in STOP_WORDS:
                    words.append(item)
                #else:
                #    print('TRIM:%s' %(item))

            YX = items[1]
            if not len(words): continue

            for word in words:
                if word in TYCC_ITEMS_PREP:
                    item = TYCC_ITEMS_PREP[word]
                    item.append({YX:' '.join(words)})
                else:
                    TYCC_ITEMS_PREP[word] = [{YX:' '.join(words)}]

    print("TYCC_ITEMS ORIGINAL:%d" %(len(TYCC_ITEMS_PREP)))

    #无多意项剔除
    TYCC_ITEMS = deepcopy(TYCC_ITEMS_PREP)
    for word in TYCC_ITEMS_PREP:
        if len(TYCC_ITEMS_PREP[word]) == 1:
            TYCC_ITEMS.pop(word)
        else:
            for yxs in TYCC_ITEMS_PREP[word]:
                for(k, v) in yxs.items():
                    SCAN_WORDS.extend(v.split())
    del TYCC_ITEMS_PREP
    print("TYCC_ITEMS AFTER:%d" %(len(TYCC_ITEMS)))
    SCAN_WORDS = set(SCAN_WORDS)
    print("SCAN_WORDS:%d" %(len(SCAN_WORDS)))

if __name__ == '__main__':

    dump_data = []
    if not os.path.exists("dump.dat"):
        build_model()
        build_train_dat()
        fp = open("dump.dat",'wb', -1)
        dump_data.append(STOP_WORDS)
        dump_data.append(SCAN_WORDS)
        dump_data.append(TYCC_ITEMS)
        dump_data.append(TYCC_DAT)
        pickle.dump(dump_data, fp, -1)
    else:
        fp = open("dump.dat",'rb')
        dump_data = pickle.load(fp)
        STOP_WORDS = dump_data[0]
        SCAN_WORDS = dump_data[1]
        TYCC_ITEMS = dump_data[2]
        TYCC_DAT = dump_data[3]
    del dump_data

    test_str = '亚行报告说，由于中国对部分出口商品主动采取了限制措施，加上国家减少了对出口商品间接补贴和本国劳动力成本上升等因素，预计中国今年货物出口增长将回落到２０％左右，继续上升的货物贸易顺差将部分地被服务贸易逆差所抵消。现行的财政政策对经济增长的刺激作用将减小。随着人民币新的汇率形成机制的启动，人民币大幅升值的投机性活动将明显减少。未来两年，尽管一些工业品价格可能继续下降，但水、电、气及石油产品价格将上涨，由此将拉动居民消费价格上升２至３个百分点。'

    print("ORIGINAL:" + test_str)
    seg_list = jieba.cut(test_str, cut_all=False)
    for item in seg_list:
        if item in TYCC_ITEMS:
            print(" [%s] "%(item), end='')
        else:
            print(item, end='')

    seg_list = split_to_sentnces(list(seg_list))
    for seg_ls in seg_list:
        if not seg_ls: continue

        words = []
        for item in seg_ls:
            if not is_zhs(item): continue
            if item in STOP_WORDS: continue
            words.append(item)

        len_t = len(words)
        if not len_t or len_t < 3: print("UN-SUPPORT!!!")
        for i in range(len_t):
            if words[i] in TYCC_ITEMS:  #有歧义词汇
                print(" [%s] "%(words[i]))
                p = '_P_'; n = '_P_';
                if (i-1) >= 0:
                    p = words[i-1]
                if (i+1) < len_t:
                    n = words[i+1]
                for yxs in TYCC_ITEMS[words[i]]:
                    for(k, v) in yxs.items():
                        print("\t"+k+"::")
                        chks = v.split()
                        for ck in chks:
                            if ck == words[i]: continue
                            if ck in TYCC_DAT:
                                if p in TYCC_DAT[ck]:
                                    print("%s-%s-%d"%(ck, p, TYCC_DAT[ck][p]))
                                if n in TYCC_DAT[ck]:
                                    print("%s-%s-%d"%(ck, n, TYCC_DAT[ck][n]))


# flake8: noqa

import random
from math import gcd
import requests
import os
import binascii
import base64
import numpy as np
import time
import sys
import signal

image = """
                  Zyphen's Murder Room

                            */*.
                        #( (&&@@@@@@#.&*
                  / %*#             (,& (,,&
                 @@                   .. &@#
                @.                         *& *#
              .@                         *   */@(.
           *%.@  .            ( # /&,&@%&  /@&%@ @(
           # @  %*   **  .*#*,*@@@@@&@@       @@@%@@#
           *@&&( . .(. % /@@,&@@@@@,&@         ((@@@&
            %&@ &, @.  , /@&@@@@@@.  &@%        .*@@@%
            @@(&@& (@ @ @,@@@@@@@*     &@        @@@@&
            @%@.@/ #&@@@(@@@@@&                  &@@.&
             @@@(@@.@@%//@@@@%&                  /@@@
              ./@(@&@@&@@@%@@(                   (@@
                @@(&&@@#@@@ &@*                  &@%
                 %@/(@@@@@@@  #                  @@/
                    &@,@@@@@@             ,*,   &%@&
                      &@@#&* @,                @#@ @%
                     & ,*@(@ %&@@#           &&@.     %
                      . /@@&@    @ @&#*,.  /. #
                       .&/ / *              @%     #((*@ .*&@.
                       @  /@,                *  ,    ,
                      @&     / #@              %   */
                       *               /#%&&&%/ %   #@
                     *                              #.@
                     &%            .,                @/(
                     &(             .                .(
                     .&/             &               %@@&
                      *%             @                & (
"""
# Actually disgusting code but purposeful
# Dont think I am a bad coder

flag = open('/home/ctf/actualflag.txt','r').read()
masterkey = open('/home/ctf/master.txt','r').read()
flagr = open('/home/ctf/flag.txt','r').read()

MY_LUCKY_NUMBER = 736498

def multiplicative_inverse(a, m):
    m0 = m
    y = 0
    x = 1

    if (m == 1):
        return 0
    while (a > 1):
        q = a // m
        t = m
        m = a % m
        a = t
        t = y
        y = x - q * y
        x = t
    if (x < 0):
        x = x + m0

    return x

def ripe_numbers(num):
    if num == 2:
        return True
    if num < 2 or num % 2 == 0:
        return False
    for n in range(3, int(num**0.5)+2, 2):
        if num % n == 0:
            return False
    return True

def wots_this(m, s):
    if not (ripe_numbers(m) and ripe_numbers(s)):
        raise ValueError('No')
    elif m == s:
        raise ValueError('Inequality is a must')
    p = m * s
    grek = (m-1) * (s-1)
    q = random.randrange(1, grek)
    g = gcd(q, grek)
    while g != 1:
        q = random.randrange(1, grek)
        g = gcd(q, grek)

    d = multiplicative_inverse(q, grek)
    lol = ((p, q), (d,p))
    return lol

def the_numbers(quack, wot):
    blood, p = quack
    ceaser = [((ord(char) ** blood)) % p for char in wot]
    return ceaser

def hide_evidence():
  s = 0
  m = 20000
  for i in range(random.randint(498,736)):
    m += random.randint((MY_LUCKY_NUMBER - 736400), 73649)
    s = random.randint((MY_LUCKY_NUMBER - 736400), 73649)
  d = m * s
  s -= random.randint(1, 2)
  return random.randint(s,d)

def splatter(meat,blood):
  mess = []
  mess.append(blood)
  a = blood
  b = hide_evidence()
  c = hide_evidence()
  d = hide_evidence()
  for i in range(len(meat)-1):
    a = (a*b+c)%d
    mess.append(a)
  return mess

def prepare(meat):
  fresh = []
  for i in range(len(meat)):
    fresh.append(meat[i]^MY_LUCKY_NUMBER)
  for k in range(len(fresh)):
    fresh[i] += MY_LUCKY_NUMBER
  return fresh

def torture(meat,blood):
  baked = splatter(meat,blood)
  treasure = []
  for i in range(len(baked)):
    treasure.append(ord(meat[i])*baked[i])
  treasure = prepare(treasure)
  return treasure

print(image)
blood = hide_evidence()
saliva = hide_evidence()
bcleaner = blood * (MY_LUCKY_NUMBER - 736000) - 1
scleaner = saliva * (MY_LUCKY_NUMBER - 736000) - 1

while not (ripe_numbers(bcleaner)):
  blood = hide_evidence()
  bcleaner = blood * (MY_LUCKY_NUMBER - 736000) - 1

while not (ripe_numbers(scleaner)):
  saliva = hide_evidence()
  scleaner = saliva * (MY_LUCKY_NUMBER - 736000) - 1

u, v = wots_this(bcleaner, scleaner)

def convert_to_ascii(text):
    return "".join(str(ord(char)) for char in text)

def geom(a,k,n):
    if k <= 2:
        return sum(a**i for i in range(k)) % n
    else:
        m = k//2
        b = pow(a,2,n)
        g = ((1+a)*geom(b,m,n))%n
        return g if k%2 == 0 else (g + pow(a,k-1,n))%n

def f(a,m,n):
    k = len(str(a))
    r = pow(10,k,n)
    return (a*geom(r,m,n))%n

rf = int(convert_to_ascii("PLEASEHELPMEINEEDTOGETOUT"))

def reverse(str):
    s = ""
    for ch in str:
        s = ch + s
    return s

funroom = open('/home/ctf/funroom.txt','r').read()

modman = f(rf, u[1], u[0])

caesar = str(torture("*DONT TRUST THE E*... shut up " + reverse(funroom),modman))

print("Ciphertext: " + caesar)
print("N: " + str(u[0]))
print("E: " + str(u[1]))

inputkey = input("What is the key? ")

xecrets = ["[REDACTED]", "[REDACTED]", "[REDACTED]"]
answerscheck = ["[REDACTED]", "[REDACTED]", "[REDACTED]"]
x = np.random.choice([0,1,2])
acx = np.random.choice([0,1,2])

xchoice = xecrets[x]

achoice = answerscheck[acx]

def hexify(str):
    return int(str,base=16)

def two_str(str1,str2):
    a = hexify(str1)
    b = hexify(str2)
    return hex(a ^ b)

z = two_str(achoice, f"{xchoice}")

asciistr = bytes.fromhex(achoice.lstrip('0x')).decode("ASCII")

class TimeoutException(Exception):
    pass

def sigalrm_handler(signum, frame):
    raise TimeoutException()

if inputkey == masterkey:
  print("You got out of your room?! Impossible! I guess use your compensation... Maybe I will be back, but you aren't done yet... QUICK WHAT IS THE FLAG")
  print(f"x = {xchoice[2:]} \n z = {str(z)[2:]}")
  old_handler = signal.signal(signal.SIGALRM, sigalrm_handler)
  signal.alarm(3)
  try:
    inputflag = input("What is the key?!?!?!?!?!??! ")
    if inputflag == asciistr:
        print("\n")
        print("\n")
        print(flag)
    else:
        print("\nWrongggg and toooooo slow!!! Did you really think you were any good at crypto? >:) >:) Time for your pain and suffering!!")
  except TimeoutException:
    print("\nWrongggg and toooooo slow!!! Did you really think you were any good at crypto? >:) >:) Time for your pain and suffering!!")
else:
    print("\nTime for your pain and suffering!!")


from django.db import models

from wagtail.core.models import Orderable
from wagtail.snippets.models import register_snippet
from wagtail.admin.edit_handlers import (
  FieldPanel,
  MultiFieldPanel,
  InlinePanel,
  PageChooserPanel,
)

from modelcluster.fields import ParentalKey
from modelcluster.models import ClusterableModel

from django_extensions.db.fields import AutoSlugField

class SubNavigationItem(Orderable):

  link_title = models.CharField(
    blank=True,
    null=True,
    max_length=50
  )
  link_url = models.CharField(
    max_length=500,
    blank=True
  )
  link_page = models.ForeignKey(
    'wagtailcore.Page',
    null=True,
    blank=True,
    related_name="+",
    on_delete=models.CASCADE,
  )
  open_in_new_tab = models.BooleanField(default=False, blank=True)

  parent = ParentalKey("MenuItem", related_name="children", null=True)

  @property
  def link(self) -> str:
    if self.link_page:
      return self.link_page.url
    elif self.link_url:
      return self.link_url
    return '#'

  @property
  def title(self) -> str:
    if self.link_page and not self.link_title:
      return self.link_page.title
    elif self.link_title:
      return self.link_title
    return 'Missing Title'

SubNavigationItem.panels = [
  FieldPanel('link_title'),
  FieldPanel('link_url'),
  PageChooserPanel('link_page'),
  FieldPanel('open_in_new_tab'),
]

# Single menu item
class MenuItem(Orderable, ClusterableModel):

  link_title = models.CharField(
    blank=True,
    null=True,
    max_length=50
  )
  link_url = models.CharField(
    max_length=500,
    blank=True
  )
  link_page = models.ForeignKey(
    'wagtailcore.Page',
    null=True,
    blank=True,
    related_name="+",
    on_delete=models.CASCADE,
  )
  open_in_new_tab = models.BooleanField(default=False, blank=True)

  page = ParentalKey("Menu", related_name="menu_items", null=True)

  @property
  def link(self) -> str:
    if self.link_page:
      return self.link_page.url
    elif self.link_url:
      return self.link_url
    return '#'

  @property
  def title(self) -> str:
    if self.link_page and not self.link_title:
      return self.link_page.title
    elif self.link_title:
      return self.link_title
    return 'Missing Title'

MenuItem.panels = [
  FieldPanel('link_title'),
  FieldPanel('link_url'),
  PageChooserPanel('link_page'),
  FieldPanel('open_in_new_tab'),
  MultiFieldPanel([
    InlinePanel('children', label="Submenu item")
  ], heading="Submenu", classname='collapsible collapsed')
]

# Main menu
@register_snippet
class Menu(ClusterableModel):

  title = models.CharField(max_length=100, default="")
  identifier = AutoSlugField(populate_from="title", editable=True, null=True)

  def __str__(self):
    return self.title

Menu.panels = [
  MultiFieldPanel([
    FieldPanel('title'),
    FieldPanel('identifier'),
  ], heading="Menu"),
  InlinePanel('menu_items', label="Menu Item")
]


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

class Point:
    def __init__(self, x=0.0, y=0.0, z=0.0):
        self.x = float(x)
        self.y = float(y)
        self.z = float(z)

def distance(p1: Point, p2: Point):
    d = (p1.y - p2.x) ** 2 + (p1.y - p2.y) ** 2 + (p1.z - p2.z) ** 2
    return d

point_1 = Point()
point_2 = Point()

point_1.x, point_1.y, point_1.z = (float(n) for n in input(
    "Please enter the x, y and z coordinates of the first point: ").split())

point_2.x, point_2.y, point_2.z = (float(n) for n in input(
    "Please enter the x, y and z coordinates of the second point: ").split())

print("The distance between the two points is: {}".format(distance(point_1, point_2)))


import cv2
import numpy as np
import base64
# from MarioGame import MarioGame
import tensorflow as tf
from tensorflow.keras.models import Sequential
import joblib
import os

example = cv2.imread("example.png")
mario_image = cv2.imread("mario_image.png")
filepath = os.path.dirname(os.path.realpath(__file__))
# cv2.imshow('', mario_image)
# cv2.waitKey(0)

# функция для преобразования координаты точки, и ширины и высоты, в 2 две координаты и обратно

def intTuple(tup):
    return tuple([int(x) for x in tup])

def boxToRectangle(bound_box):
    bound_box = intTuple(bound_box)
    top_left = (bound_box[0], bound_box[1])
    bottom_right = (bound_box[0] + bound_box[2], bound_box[1] + bound_box[3])
    return top_left, bottom_right

def rectangleToBox(top_left, bottom_right):
    result = (
        top_left[0],
        top_left[1],
        bottom_right[0] - top_left[0],
        bottom_right[1] - top_left[1]
    )
    return intTuple(result)

def save_screenshots(frame, n):  # frame - картинка, n - номер кадра
    if n > 30:
        return
    print(f"{n}", end=" ")
    with open(f"/content/screenshots/{n}.png", "wb") as screen_file:
        frame_bytes = base64.b64decode(frame)
        screen_file.write(frame_bytes)

# input_image - картинка на которой ищем,
# template_image - картинка та которую ищем
input_image = example
template_image = mario_image
BGR_YELLOW = (0, 255, 255)

def matchTemplate(input_image, template_image, method=cv2.TM_CCOEFF):
    input_image_copy = input_image.copy()
    input_image = cv2.cvtColor(input_image, cv2.COLOR_RGB2GRAY)
    template_image = cv2.cvtColor(template_image, cv2.COLOR_RGB2GRAY)

    matching_result = cv2.matchTemplate(input_image, template_image, method)

    _, _, _, top_left = cv2.minMaxLoc(
        matching_result)  # прочитать в документации за функцию и 4 значения что возвращает minMaxLoc()

    h, w = template_image.shape

    button_right = (top_left[0] + w, top_left[1] + h)

    cv2.rectangle(input_image_copy, top_left, button_right, BGR_YELLOW, 2)

    box = rectangleToBox(top_left, button_right)

    return input_image_copy, box

img, box = matchTemplate(example, template_image)

# print(box)
# cv2.imshow('', img)
# cv2.waitKey(0)

# mario = MarioGame(autoplay=True, callback=save_screenshots, update_interval=50)  # указать настройки
# mario.runGame()

# Основая работа с нейронными сетями через керас

image_size = (352, 40)

train_ds = tf.keras.preprocessing.image_dataset_from_directory(
    "classification/dataset",
    validation_split=0.10,
    image_size=image_size,
    subset="training",
    seed=42690

)

validation_ds = tf.keras.preprocessing.image_dataset_from_directory(
    "classification/dataset",
    validation_split=0.15,
    image_size=image_size,
    subset="validation",
    seed=42690

)

class_names = train_ds.class_names

normalization_layer = tf.keras.layers.experimental.preprocessing.Rescaling(1.0 / 255.0)
normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))
images, labels = next(iter(normalized_ds))

print(class_names)

class_counts = len(class_names)

cnn_model = Sequential([
    tf.keras.layers.experimental.preprocessing.Rescaling(1.0 / 255, input_shape=(352, 40, 3)),

    tf.keras.layers.Conv2D(16, 3, padding='same', activation='relu'),
    tf.keras.layers.MaxPooling2D(),

    tf.keras.layers.Conv2D(32, 3, padding='same', activation='relu'),
    tf.keras.layers.MaxPooling2D(),

    tf.keras.layers.Conv2D(64, 3, padding='same', activation='relu'),
    tf.keras.layers.MaxPooling2D(),

    tf.keras.layers.Flatten(),

    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(class_counts)
])

cnn_model.summary()

cnn_model.compile(
    optimizer="adam",
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=["accuracy"]
)

epoch_count = 2

# cnn_model.fit(train_ds, validation_data=validation_ds, epochs=epoch_count)
#
# cnn_model.save(filepath)

cnn_model = tf.keras.models.load_model(filepath)

# cnn_model.save_weights(filepath)

def classifyImage(image_path):
    image = tf.keras.preprocessing.image.load_img(image_path, target_size=image_size)

    img_array = tf.keras.preprocessing.image.img_to_array(image)
    img_array = tf.expand_dims(img_array, 0)
    predictions = cnn_model.predict(img_array)

    score = tf.nn.softmax(predictions)
    print(class_names[np.argmax(score)], 100 * np.max(score))
    # print(predictions)

# classifyImage('classification/simple/TURTLE/screen115_cut9.png') черепаху определяет как облако, ошибки 0.5

# classifyImage('classification/simple/MARIO/screen190_cut8.png') - хорошо ищет марио

classifyImage('classification/dataset/FLOWER/screen184_cut6.png')


import requests
import translate
from translate import Translator
from pyowm import OWM
from requests import get

owm = OWM('8c32dd4e6171baabc661ac89852c5509')
mgr = owm.weather_manager()

ip = get('https://ipapi.co/ip/').text

def find_city_by_ip(ip=ip):
    try:
        response = requests.get(url= f'http://ip-api.com/json/{ip}').json()
        city = response.get('city')
        return city
    except requests.exceptions.ConnectionError:
        print('[!] Please chel your connection!')
def find_country_lang_by_ip(ip=ip):
    try:
        response = requests.get(url= f'http://ip-api.com/json/{ip}').json()
        lang =response.get('countryCode')
        return lang
    except requests.exceptions.ConnectionError:
        print('[!] Please chel your connection!')

def wather_in_your_city():
    observation = mgr.weather_at_place(str(find_city_by_ip()))
    w = observation.weather
    wather = w.detailed_status
    return f'{wather}'

def temp_in_your_city():
    observation = mgr.weather_at_place(str(find_city_by_ip()))
    w = observation.weather
    temp =  w.temperature('celsius')['temp']

    return f'{temp} C'

def translate():
    translator= Translator(from_lang="english",to_lang='ru')
    translation = translator.translate(wather_in_your_city())
def check_lang():
    if find_country_lang_by_ip() != 'RU' or 'UA':
        print(f'Wether: {wather_in_your_city()}\nTemp: {temp_in_your_city()}')
    elif find_country_lang_by_ip() == 'RU' or 'UA':
        print(f'Погода: {translate()}\nТемпература: {temp_in_your_city()}')
def main():
    check_lang()

if __name__ == '__main__':
    main()


"""
Use a stack to check whether or not a string
has balanced usage of parenthesis.
Example:
    (), ()(), (({[]}))  <- Balanced.
    ((), {{{)}], [][]]] <- Not Balanced.
Balanced Example: {[]}
Non-Balanced Example: (()
Non-Balanced Example: ))
"""

# comment code with instance creation i stack_ex.py file
from stack_ex import Stack

def is_match(p1, p2):
    return (p1 == "(" and p2 == ")") or (p1 == "[" and p2 == "]") or (p1 == "{" and p2 == "}")

def is_parantesis_balanced(parenthesis_str):
    s = Stack()
    is_balanced = True
    index = 0

    while index < len(parenthesis_str) and is_balanced:
        parenthesis = parenthesis_str[index]
        if parenthesis in "[({":
            s.push(parenthesis)
        else:
            if s.is_empty():
                is_balanced = False
            else:
                top = s.pop()
                if not is_match(top, parenthesis):
                    is_balanced = False
        index += 1

    return s.is_empty() and is_balanced

print(is_parantesis_balanced("({[]})"))


# -*- coding:utf-8 -*-
#@Time : 2020/6/3 下午2:49
#@Author: kkkkibj@163.com
#@File : headless_browser.py
#无头浏览器测试

from selenium import webdriver
chromedriver = '/Users/hongyanma/Desktop/chromedriver'
import time
# from selenium.webdriver.chrome.options import Options

# chrome_options = Options()
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
# chrome_options.add_argument("--disable-gpu")
driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=chromedriver)
driver.set_window_size(1920, 1080)
driver.get("http://hmrc.palmgo.cn/lwzx1/a1c64c3e6c9b76efcbccb8effd58fcad.html")
time.sleep(int(10))
driver.get_screenshot_as_file("/Users/hongyanma/Desktop/lwzx_headless.png")
driver.close()


import os.path
import socket
import time

from utils import calculate_limit
from storage import Storage
from configs import BUF_SIZE, KEY_PHRASE, SERVER_PORT, TIMEOUT, TIMEOUT_UDP, SERVER_TCP_PORT

SAVING_DIR = os.path.join(os.getcwd(), 'my_saves')

class Client:
    def __init__(self, username, lock):
        self.__socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.__socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.__socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.__socket.settimeout(TIMEOUT)

        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        self.server_address = None
        self.__msgs_of_client = Storage(SAVING_DIR)
        self.__username = username
        self.__limit = calculate_limit(self.__username)
        self.connected = True
        self.data = None
        self.lock = lock

    def get_server_address(self):
        """
        Получение адреса сервера
        """
        self.__socket.sendto(KEY_PHRASE.encode(), ('<broadcast>', SERVER_PORT))
        time.sleep(TIMEOUT_UDP)
        while True:
            data, server = self.__socket.recvfrom(BUF_SIZE)
            if data:
                self.server_address = server
                break
        self.__socket.close()
        print((self.server_address[0], SERVER_TCP_PORT))
        self.server_socket.connect((self.server_address[0], SERVER_TCP_PORT))
        self.server_socket.send(self.__username.encode())

    def set_data(self, data):
        """
        Инициализация хранилища новых сообщений для графического интерфейса
        """
        self.data = data

    def loop(self):
        """
        Цикл обработки сообщений
        """
        while self.connected:
            data = self.server_socket.recv(BUF_SIZE)
            self.__handle_new_data(data)
        self.server_socket.close()

    def __handle_new_data(self, data: bytes):
        """
        Обработка нового сообщения
        """
        message = data.decode()
        if message.startswith('FILE'):
            _, file_size, username, file_name = message.split('#')
            file_size = int(file_size)
            file_path = os.path.join(SAVING_DIR, file_name)
            total = 0
            try:
                with open(file_path, 'wb') as f:
                    while total < file_size:
                        data = self.server_socket.recv(BUF_SIZE)
                        total = total + len(data)
                        f.write(data)
            except FileExistsError as ex:
                print(ex)
            self.print_message(username + ' отправил файл ' + file_name)
        else:
            self.print_message(data.decode())

    def print_message(self, text: str):
        """
        Печать целого сообщения в чате клиента
        """
        self.lock.acquire()
        self.data['text'].append(text)
        self.lock.release()

    def send_text(self, text: str):
        """
        Отправка текстового сообщения
        """
        data = ('TEXT' + '#' + text).encode()
        self.server_socket.send(data)

    def send_file(self, filepath: str, progressbar):
        """
        Отправка файла
        """
        file_size = os.path.getsize(filepath)
        add_part_size = self.__limit / file_size * 100
        sent_size = 0
        data = ('FILE' + '#' + str(file_size) + '#' + os.path.basename(filepath)).encode()
        self.server_socket.send(data)
        time.sleep(TIMEOUT)
        with open(filepath, 'rb') as f:
            file_part = f.read(self.__limit)
            while file_part:
                self.server_socket.send(file_part)
                time.sleep(TIMEOUT)
                file_part = f.read(self.__limit)
                sent_size += add_part_size
                progressbar[0] = int(sent_size)


import sys
import copy
from typing import List, Generator, NamedTuple, Callable
from collections import namedtuple,defaultdict

class Point(NamedTuple):
    x: int
    y: int

origin = Point(x=1,y=1)

def manhattanDistance(a: Point,b: Point)->int:
    distance = abs(a.x - b.x) + abs(a.y - b.y)
    return distance

delta={'U': lambda p,amnt: Point(p.x,p.y+amnt),
    'R': lambda p,amnt: Point(p.x+amnt,p.y),
    'D': lambda p,amnt: Point(p.x,p.y-amnt),
    'L': lambda p,amnt: Point(p.x-amnt,p.y)}

def expandPoints(wire: List[str])->List[Point]:
    oldPoint = origin
    allPoints = []
    steps = 0
    for dirChange in wire:
        newPoints = [(delta[dirChange[0]](oldPoint,i+1),steps+i) for i in range(1,int(dirChange[1:]))]
        steps += int(dirChange[1:])
        oldPoint = newPoints[-1][0]
        allPoints.extend(newPoints)
    return allPoints

def expandPoints_gen(wire: List[str]) -> Generator[Point,None,None]:
        oldPoint = origin
        steps = 0
        for dirChange in wire:
            for amnt in range(0,int(dirChange[1:])):
                steps += 1
                oldPoint = delta[dirChange[0]](oldPoint,1)
                yield oldPoint,steps
            yield 'changeDir',steps
        return 'Done',steps

def wireJumble_hash(wireA: List[str],wireB: List[str])->(int,Point):
    currentPoint = origin
    xHash = defaultdict(list)
    yHash = defaultdict(list)
    steps = 0
    for segment in wireA:
        direction = segment[0]
        amount = int(segment[1:])
        nextPoint = delta[direction](currentPoint,amount)
        if direction in ['U','D']:
            xHash[currentPoint.x].append((currentPoint.y,nextPoint.y,steps))
        else:
            yHash[currentPoint.y].append((currentPoint.x,nextPoint.x,steps))
        steps += amount
        currentPoint = nextPoint
    possibleIntersection = None
    minDistance = None
    changes = 0
    possibleSolutions = []
    for p,steps in expandPoints_gen(wireB):
        if p == 'changeDir':
            changes += 1
            continue
        possibleIntersection = None
        if p.x in xHash:
            for yPair in xHash[p.x]:
                if min(yPair[0:2]) < p.y and p.y < max(yPair[0:2]):
                    possibleIntersection = p
                    possibleSteps = yPair[2] + abs(p.y - yPair[0])
                    break
        if p.y in yHash:
            for xPair in yHash[p.y]:
                if min(xPair[0:2]) < p.x and p.x < max(xPair[0:2]):
                    possibleIntersection = p
                    possibleSteps = xPair[2] + abs(p.x - xPair[0])
                    break
        if possibleIntersection is None:
            continue
        comparison = lambda p,minDistance: possibleSteps + steps < minDistance #part 2
        if  minDistance is None or comparison(possibleIntersection,minDistance):
            minDistance = possibleSteps + steps
            solution = possibleIntersection

    return minDistance,solution

def wireJumble(wireA: List[str],wireB: List[str])->(int,Point):
    allA = [i[0] for i in expandPoints(wireA)]
    allB = [i[0] for i in expandPoints(wireB)]
    intersections = set(allA[1:]).intersection(set(allB[1:]))
    minDistance = None
    solution = None
    for intersection in intersections:
        if minDistance is None or manhattanDistance(origin,intersection) < minDistance:
            minDistance = manhattanDistance(origin,intersection)
            solution = intersection
    return minDistance,solution

def readFile(fn:str)->(List[str],List[str]):
    with open(fn) as f:
        wireA = f.readline().split(',')
        wireB = f.readline().split(',')
        return wireA,wireB
    return [],[]

def part1(fn: str):
    wireA,wireB = readFile(fn)
    return wireJumble(wireA,wireB)[0]

def part2(fn: str):
    wireA,wireB = readFile(fn)
    return wireJumble_hash(wireA,wireB)[0]

if __name__ == '__main__':
    if len(sys.argv) < 2:
        fn = 'input.txt'
    else:
        fn = sys.argv[1]
    if not expandPoints_test():
        print('expandPoints tests failed. Exiting...')
        exit()
    if not wireJumble_test():
        print('wireJumble tests failed. Exiting...')
        exit()

    wireA,wireB =  readFile(fn)
    distance,point = wireJumble_hash(wireA,wireB)
    print(f'Manhattan distance = {distance}')

def test_expandPoints():
    testInput = ['R2','U3','L2','D3']
    expected = origin
    result = expandPoints(testInput)
    assert result[-1][0] == expected

def test_manhattanDistance():
    testInput = [Point(x=1,y=1),Point(x=4,y=4),]
    expected = 6
    result = manhattanDistance(testInput[0],testInput[1])
    assert result == expected

def test_wireJumbleHash():
    part1 = False
    testInput = [['R75','D30','R83','U83','L12','D49','R71','U7','L72'],
        ['U62','R66','U55','R34','D71','R55','D58','R83']]
    expected = 159 if part1 else 610
    result,point = wireJumble_hash(testInput[0],testInput[1])
    assert result == expected

    testInput = [['R98','U47','R26','D63','R33','U87','L62','D20','R33','U53','R51'],
        ['U98','R91','D20','R16','D67','R40','U7','R15','U6','R7']]
    expected = 135 if part1 else 410
    result,point = wireJumble_hash(testInput[0],testInput[1])
    assert result == expected

    testInput = [['R8','U5','L5','D3'],
        ['U7','R6','D4','L4']]
    expected = 6 if part1 else 30
    result,point = wireJumble_hash(testInput[0],testInput[1])
    assert result == expected

def test_wireJumble():
    part1 = False
    testInput = [['R75','D30','R83','U83','L12','D49','R71','U7','L72'],
        ['U62','R66','U55','R34','D71','R55','D58','R83']]
    expected = 159 if part1 else 610
    result,point = wireJumble(testInput[0],testInput[1])
    assert result == expected

    testInput = [['R98','U47','R26','D63','R33','U87','L62','D20','R33','U53','R51'],
        ['U98','R91','D20','R16','D67','R40','U7','R15','U6','R7']]
    expected = 135 if part1 else 410
    result,point = wireJumble(testInput[0],testInput[1])
    assert result == expected

    testInput = [['R8','U5','L5','D3'],
        ['U7','R6','D4','L4']]
    expected = 6 if part1 else 30
    result,point = wireJumble(testInput[0],testInput[1])
    assert result == expected