import torch
import numpy as np
import matplotlib.pyplot as plt
import os
import sklearn as sk
from Code2 import FeatureEngineering as FE
import torchvision
import tqdm
import collections

def to_cuda(elements):
    if torch.cuda.is_available():
        if type(elements) == tuple or type(elements) == list:
            return [x.cuda() for x in elements]
        return elements.cuda()
    return elements

class FullyConnectedModel(torch.nn.Module):

    def __init__(self):
        super().__init__()
        # Number of input nodes (size of images)
        num_input_nodes = 20*20

        hidden_input = 32
        # Number of classes in the chars74k-lite dataset
        num_classes = 26

        # Define our model
        self.classifier = torch.nn.Sequential(
            torch.nn.Linear(num_input_nodes, hidden_input),
            torch.nn.ReLU(),
            torch.nn.Linear(hidden_input, num_classes),
            torch.nn.ReLU()
        )

    def forward(self, x):
        # Runs a forward pass on the images
        x = x.view(-1, 20*20)
        out = self.classifier(x.float())
        return out

class Trainer:

    def __init__(self,
                 model,
                 dataloader_train,
                 dataloader_val,
                 batch_size,
                 loss_function,
                 optimizer):
        self.dataloader_train = dataloader_train
        self.dataloader_val = dataloader_val
        self.batch_size = batch_size

        self.model = model
        self.loss_function = loss_function
        self.optimizer = optimizer

    def train(self, num_epochs):
        tracked_train_loss = collections.OrderedDict()
        tracked_test_loss = collections.OrderedDict()
        global_step = 0

        for epoch in range(num_epochs):
            avg_loss = 0

            for batch_it, (images, target) in enumerate(
                    tqdm.tqdm(self.dataloader_train,
                              desc=f"Training epoch {epoch}")):
                # images has shape: [batch_size, 1, 20, 20]
                # target has shape: [batch_size]

                batch_it, (images, target) = to_cuda([batch_it, (images, target)])

                # Perform forward pass
                logits = self.model(images)

                # Compute loss
                loss = self.loss_function(logits, target)

                avg_loss += loss.detach().item()
                # Perform backpropagation
                loss.backward()

                # Update our parameters with gradient descent
                self.optimizer.step()

                # Reset our model parameter gradients to 0
                self.optimizer.zero_grad()

                # Track the average loss for every 500th image
                if batch_it % (500//self.batch_size) == 0 and batch_it != 0:
                    avg_loss /= (500//self.batch_size)
                    tracked_train_loss[global_step] = avg_loss
                    avg_loss = 0
                global_step += self.batch_size
            # Compute loss and accuracy on the test set
            test_loss, test_acc = compute_loss_and_accuracy(
                self.dataloader_val, self.model, self.loss_function
            )
            tracked_test_loss[global_step] = test_loss
        return tracked_train_loss, tracked_test_loss

def plot_loss(loss_dict, label):
    global_steps = list(loss_dict.keys())
    loss = list(loss_dict.values())
    plt.plot(global_steps, loss, label=label)

def compute_loss_and_accuracy(dataloader, model, loss_function):
    """
    Computes the total loss and accuracy over the whole dataloader
    Args:
        dataloder: Test dataloader
        model: torch.nn.Module
        loss_function: The loss criterion, e.g: nn.CrossEntropyLoss()
    Returns:
        [loss_avg, accuracy]: both scalar.
    """
    model.eval()
    # Tracking variables
    loss_avg = 0
    total_correct = 0
    total_images = 0
    total_steps = 0
    with torch.no_grad():  # No need to compute gradient when testing
        for (X_batch, Y_batch) in dataloader:
            # Forward pass the images through our model
            output_probs = model(X_batch)
            # Compute loss
            loss = loss_function(output_probs, Y_batch)

            # Predicted class is the max index over the column dimension
            predictions = output_probs.argmax(dim=1).squeeze()
            Y_batch = Y_batch.squeeze()

            # Update tracking variables
            loss_avg += loss.item()
            total_steps += 1
            total_correct += (predictions == Y_batch).sum().item()
            #print("Prediction:")
            #print(predictions,Y_batch)
            total_images += predictions.shape[0]
    model.train()
    loss_avg = loss_avg / total_steps
    accuracy = total_correct / total_images
    return loss_avg, accuracy

class MyData(torch.utils.data.Dataset):

    def __init__(self,set):
        self.samples = []
        for i,elements in enumerate(set):
            for element in elements:
                self.samples += [(element,i)]

    def __getitem__(self,idx):
        return self.samples[idx]

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

def load_dataset(batch_size, fe, image_transform):

    dataset_train = MyData(fe.training_set)

    dataset_test = MyData(fe.test_set)

    dataloader_train = torch.utils.data.DataLoader(
        dataset_train,
        batch_size=batch_size,
        shuffle=True,
    )
    dataloader_test = torch.utils.data.DataLoader(
        dataset_test,
        batch_size=batch_size,
        shuffle=False
    )
    return dataloader_train, dataloader_test

if __name__ =="__main__":

    # ### Hyperparameters & Loss function

    # Hyperparameters
    batch_size = 32
    learning_rate = .11
    num_epochs = 5

    fe = FE()
    fe.HOG()
    fe.scaling()
    fe.splitDataset()

    # Use CrossEntropyLoss for multi-class classification
    loss_function = torch.nn.CrossEntropyLoss()

    # Model definition
    model = to_cuda(FullyConnectedModel())

    # Define optimizer (Stochastic Gradient Descent)
    optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)

    image_transform = torchvision.transforms.Compose([
      torchvision.transforms.ToTensor()

    ])
    dataloader_train, dataloader_val = load_dataset(batch_size, fe, image_transform=image_transform)

    trainer = Trainer(
      model=model,
      dataloader_train=dataloader_train,
      dataloader_val=dataloader_val,
      batch_size=batch_size,
      loss_function=loss_function,
      optimizer=optimizer
    )
    train_loss_dict, val_loss_dict = trainer.train(num_epochs)

    final_loss, final_acc = compute_loss_and_accuracy(dataloader_val, model, loss_function)
    print(f"Final Test Cross Entropy Loss: {final_loss}. Final Test accuracy: {final_acc}")


from pathlib import Path

from utils.io_lib import read_file_to_string, puzzle_input_file_name, parse_input_string_to_groups

DAY_NUMBER = 1

def task1():
    """
    Find the Elf carrying the most Calories. How many total Calories is that Elf carrying?
    """
    print(f"Maximum Calories carried by an Elf is {max(calculate_sums_of_lists())}")

def calculate_sums_of_lists() -> list[int]:
    file_input_string = read_file_to_string(puzzle_input_file_name(day_number=DAY_NUMBER))
    list_of_strings = parse_input_string_to_groups(file_input_string)
    sums_of_lists = []
    for index, value in enumerate(list_of_strings):
        value_list = value.splitlines()
        sums_of_lists.append(sum(list(map(int, value_list))))
    return sums_of_lists

def task2():
    """
    Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total?
    """
    print(f"Sum of Calories carried by top three Elves is {sum(sorted(calculate_sums_of_lists(), reverse=True)[:3])}")

if __name__ == "__main__":
    task1()
    task2()


import pandas
import os
import platform
import subprocess

data_dictionary = {
    "state": [],
    "was_correct": [],
    "total_correct": []
}

class States:
    def __init__(self):
        self.compare = False
        self.guess = ""
        self.answers_given = 0
        self.answers_correct = 0

    def check_state(self, guess):
        self.guess = guess.title()
        df = pandas.read_csv("50_states.csv")
        st = df.state
        value = df[st == self.guess]
        self.found_result(value)
        self.append_answers_data()
        try:
            state = value.state.to_string(index=False)
            # state = value.state.item()
            x_state = int(value.x)
            y_state = int(value.y)
            return x_state, y_state, state
        except KeyError as ke:
            print(f"error {ke}")
        except TypeError as te:
            print(f"TYPE: {te}")

    def found_result(self, value):
        self.answers_given += 1
        df = pandas.read_csv("../correct_answers.csv")
        found = df[df['state'].str.contains(self.guess).to_list()]
        if len(value) and not found.empty:
            if not found.count()[0]:
                self.compare = True
                self.answers_correct = self.last_score()
                self.answers_correct += 1
            else:
                self.compare = False
                self.answers_correct = self.last_score()
        elif len(value) and found.empty:
            self.compare = True
            self.answers_correct = self.last_score()
            self.answers_correct += 1

        else:
            self.compare = False

    @staticmethod
    def last_score():
        df = pandas.read_csv("../correct_answers.csv")

        if df.total_correct.notnull().any():
            row_max_score = df.total_correct.max()
        else:
            row_max_score = 0
        return row_max_score

    def append_answers_data(self):
        data_to_save = {
            "state": [self.guess],
            "was_correct": [self.compare],
            "total_correct": [self.answers_correct]
        }
        df = pandas.DataFrame(data_to_save)
        df.to_csv('correct_answers.csv', mode='a', header=False, sep=",")

    @staticmethod
    def new_game_memory():
        new_data = pandas.DataFrame(data_dictionary)
        new_data.to_csv("correct_answers.csv")

    @staticmethod
    def states_to_learn():
        df1 = pandas.read_csv("50_states.csv")
        df2 = pandas.read_csv("../correct_answers.csv")
        col1 = df1.state.to_list()
        col2 = df2.state.to_list()
        set1 = set(col1)
        set2 = set(col2)
        missing = list(sorted(set1 - set2))
        data_to_save = {
            "state": missing
        }
        df = pandas.DataFrame(data_to_save)
        df.to_csv('states_to_learn.csv')

    @staticmethod
    def open_states_to_learn():
        filepath = "../states_to_learn.csv"
        if platform.system() == 'Darwin':
            subprocess.call(('open', filepath))
        elif platform.system() == 'Windows':
            os.startfile(filepath)
        else:
            subprocess.call(('xdg-open', filepath))

if __name__ == "__main__":
    states = States()
    # states.new_game_memory()

    # answer = "tennessee"
    # state_returned = states.check_state(answer)
    # if state_returned:
    #     print(f"RETURNED: {state_returned[0]} {state_returned[1]} {state_returned[2]}")

    # states.create_answers_data()
    # states.append_answers_data()

    # score = states.last_score()
    # print(f"SCORE RESULT {score}")

    states.states_to_learn()


from time import time
import random

def max_sub_sum1(my_vector):
    max_sum = 0
    for i in range((len(my_vector))):

        for j in range(i, len(my_vector)):
            this_sum = 0
            for k in range(i, j):
                this_sum += my_array[k]
            if this_sum > max_sum:
                max_sum = this_sum
    return max_sum

my_array = [int(1000 * random.random()) for i in range(1000)]
t0 = time()
print(max_sub_sum1(my_array))
t1 = time()
print("İşlem %.5f saniyede bitti" % (t1 - t0))


import socket
from threading import Thread

def func(conn):
    conn.send(b'hello')
    ret = conn.recv(1024)
    print(ret.decode('utf-8'))
    conn.close()

sk = socket.socket()
ip_port = ('127.0.0.1', 8080)
sk.bind(ip_port)
sk.listen()

while True:
    conn, addr = sk.accept()
    Thread(target=func, args=(conn, )).start()

sk.close()


class Node:
    """
    Class for the Node instances
    """

    def __init__(self, value):
        self.value = value
        self.next = None

    if __name__ == "__main__":
        pass

class LinkedList:
    """
    Class for the LinkedList instances
    Upon instantiation, an empty Linked List should be created.
    """

    def __init__(self):
        self.head = None

    def insert(self, value):
        """
        method to add a new node with that value to the head of the list with an O(1) Time performance.
        """
        node = Node(value)
        if self.head is None:
            self.head = node
        else:
            node.next = self.head
            self.head = node

    def append(self, node):
        if self.head is None:
            self.head = node

        else:
            current = self.head
            while current.next is not None:
                current = current.next
            current.next = node

    def linked_list_zip(ll1, ll2):
        ll1_current = ll1.head
        ll2_current = ll2.head

        """
        Optimal solution
            - loop thorugh ll2
            - if the ll1 current is empty and the ll2 current is not empty:
                - append ll2 to ll1
            - insert after ll1.head
            1 -> 2 -> 3
            4 ->5 ->6
        """
        while (ll1_current and ll2_current != Null):
            ll1_next = ll1_current.next
            ll2_next = ll2_current.next
            ll1_current.next = ll2_current
            ll1_current = ll1_next
            if ll1_current != Null:
                ll2_current.next = ll1_current

            ll2_current = ll2_next
        return ll1

    # def linked_list_zip(self, linkedlist_1, linkedlist_2):
    #         """
    #         zip list means merge two lists together, So this function will take two linked lists
    #         as parameters
    #         it is like making a braid or when you use the zipper in clothes to
    #         close your jacket or something,You take list1 head and then add the list2  head
    #         and so on..
    #         and it will return one zipped list
    #         """

    #         if linkedlist_1.head == None:
    #             return linkedlist_2
    #         elif linkedlist_2.head == None:
    #             return linkedlist_1

    #         if linkedlist_1.head ==None and linkedlist_2.head==None:
    #                 print("both lists Can't be empty")
    #                 raise Exception("both lists Can't be empty")

    #         new_ll = LinkedList()
    #         curr1 = linkedlist_1.head
    #         curr2 = linkedlist_2.head

    #         while curr1 or curr2:
    #             if curr1:
    #                 """
    #                 if the new list already has nodes in it
    #                 we make an extra check
    #                 """

    #                 if new_ll.head == None:
    #                     new_ll.insert(curr1.value)
    #                 else:
    #                     new_ll.append(curr1.value)

    #             if curr2:
    #                 """
    #                 if the new list already has nodes in it
    #                 we make an extra check
    #                 """
    #                 if new_ll.head == None:
    #                     new_ll.insert(curr2.value)
    #                 else:
    #                     new_ll.append(curr2.value)

    #             if curr1 and curr1.next:
    #                 curr1 = curr1.next
    #             else:
    #                 curr1 = False

    #             if curr2 and curr2.next:
    #                 curr2 = curr2.next
    #             else:
    #                 curr2 = False

    #         return new_ll


# Ask a user for a list of 3 friends
# for each friend, user will be told wether they are nearby
# for each nearby friend, the friend name will be saved to nearby_friends.txt

# hint: readlines()
user_input = input("Please enter names of 3 nearby friends separated by spaces: ").lower().split()
people = open("people.txt", "r")
nearby_people = [line.strip().lower() for line in people.readlines()]
people.close()

print(nearby_people)

for friend in user_input:

    if friend in nearby_people:
        # below 3 lines are to copy the exist content and append it to the file when use write() to avoid override the existing content
        dest_writing_file = open("nearby_friends.txt", "r")
        file_original_content = dest_writing_file.read()
        dest_writing_file.close()
        # append the new content to the old content and write it to the new file
        print(f"{friend}, is in the list of people and been added to the nearby friends list!")
        file_writing = open("nearby_friends.txt", "w")
        file_writing.write(file_original_content + friend.title() + "\n")
        file_writing.close()


import json
from shared.games_manager import GamesManager
from request_response import *

def lambda_handler(event, context):
    req = RequestRespond(event)
    games_manager = GamesManager()
    game_id = req.params['game_id']
    player_id = req.params['player_id']

    if not (
        games_manager.game_exists(game_id)
        and games_manager.player_exists(game_id, player_id)
    ):
        return NOT_ACCEPTABLE

    if req.method == "GET":  # fetch player with <player_id>
        return req.make_response(games_manager.get_game_players(game_id, player_id)[player_id])
    elif (
        req.method == "PUT"
    ):  # update player (change name/api, NOT event management)
        if not (req.is_admin(game_id) or req.is_player(player_id)):
            return UNAUTHORIZED

        if "name" in req.body:
            games_manager.update_player(
                game_id, player_id, name=req.body["name"]
            )

        if "api" in req.body:
            games_manager.update_player(
                game_id, player_id, api=req.body["api"]
            )

        return req.make_response(games_manager.get_game_players(game_id, player_id)[player_id])

    elif req.method == "DELETE":  # delete player with id
        if not (req.is_admin(game_id) or req.is_player(player_id)):
            return UNAUTHORIZED

        games_manager.remove_game_players(game_id, player_id)
        return {"deleted": player_id}

    else:
        return METHOD_NOT_ALLOWED


"Base class"
import __future__

from abc import ABCMeta, abstractmethod
from itertools import product
from typing import Any, Callable, Dict, Optional, Sequence, Tuple, Union

class ListParam(list):
    """
    ListParam Collection of element to be considered as the same parameter
    with different values to test

    Parameters
    ----------
    list : _type_
        List of element corresponding to the same parameter
        with different values.
    """

    def __init__(self, *args) -> None:
        super().__init__(args[0])

class StepInterface(metaclass=ABCMeta):
    """
    StepInterface interface of Step Object

    Will use all the input to call its `run_scenario` function to
    create a output list
    """

    def __init__(self,
                 name: Optional[str] = None,
                 inputs: Optional[Dict] = None,
                 ) -> None:
        if name is None:
            name = type(self).__name__
        self.name = name
        if inputs is None:
            inputs = {}
        self.inputs = inputs

    @property
    def name(self) -> str:
        """
        name step's name

        `name` is used to vizualise the pipeline in a graph
        """
        return self._name

    @name.setter
    def name(self, val: str):
        if val is None:
            val = type(self).__name__
        self._name = val

    @property
    def outputs(self) -> ListParam:
        """
        outputs result of the step given the inputs

        Returns
        -------
        ListParam
            outputs of the step
        """
        if not hasattr(self, "_outputs"):
            self.execute()
        return self._outputs

    @outputs.setter
    def outputs(self, val: ListParam):
        self._outputs = val

    @property
    def inputs(self) -> Dict:
        """
        inputs input necessary for the compute function

        Returns
        -------
        Dict
            Dictionnary of the **kwargs to give to the `compute` function
        """
        return self._inputs

    @inputs.setter
    def inputs(self, val: Dict):
        self._inputs = val

    @property
    def scenarios(self) -> Sequence[Tuple[int]]:
        """
        scenarios

        Scenarios is a list of tuple where each tuple
        correspond to the id of input to use in case there are
        multiple values for one parameter

        Returns
        -------
        Sequence[Tuple[int]]
        """
        if ~hasattr(self, "_scenarios"):
            self.create_step_scenarios()
        return self._scenarios

    @scenarios.setter
    def scenarios(self, val: Sequence[Tuple[int]]):
        self._scenarios = val

    def create_step_scenarios(self):
        """
        create_step_scenario will create the a list of all the possible
        scenarios with their variables values.

        Returns
        -------
        None
        """
        scenarios = (range(len(self.explicit_inputs[key]))
                     for key, _ in self.explicit_inputs.items())
        self.scenarios = list(product(*scenarios))

    @property
    def explicit_inputs(self) -> Dict[str, ListParam]:
        """
        explicit_inputs

        return a dictionnary with key as name of the inputs
        and values a list of the different values they can take.
        The difference with "inputs" is that the other step input object
        are replaced wirth their outputs values.

        Returns
        -------
        Dict[str, ListParam]
        """
        if ~hasattr(self, "_explicit_inputs"):
            self.create_explicit_inputs()
        return self._explicit_inputs

    @explicit_inputs.setter
    def explicit_inputs(self, val: Dict[str, ListParam]):
        self._explicit_inputs = val

    def create_explicit_inputs(self) -> None:
        """
        create_explicit_inputs

        Create output for each inputs that is a Step object
        """
        explicit_inputs: Dict[str, ListParam] = {}
        for key, val in self.inputs.items():
            if isinstance(val, StepInterface):
                explicit_inputs[key] = ListParam(val.outputs)
            elif isinstance(val, ListParam):
                explicit_inputs[key] = val
            else:
                explicit_inputs[key] = ListParam([val])
        self.explicit_inputs = explicit_inputs

    @abstractmethod
    def run_scenario(self, scenario):
        pass

    def execute(self) -> None:
        """
        execute

        Compute all the outputs depending on the scenarios
        """
        outputs = []
        for scenario in range(len(self.scenarios)):
            outputs.append(self.run_scenario(scenario))
        self.outputs = ListParam(outputs)

    def get_explicit_scenario(
            self,
            scenario_nb: Optional[int] = None
        ) -> Union[
                Sequence[Dict[str, Any]],
                Dict[str, Any]]:
        """
        get_explicit_scenario

        return the pipeline step and their params for a given scenario number

        Parameters
        ----------
        scenario_nb : Optional[int], optional
            number of the scenario to get, by default None.
            If None, return a list of all scenario and their parameters id

        Returns
        -------
        Union[ Sequence[Dict[str, Any]], Dict[str, Any]]
        """
        explicit_scenario = []
        for scenario in self.scenarios:
            base = {}
            for i, key in enumerate(self.inputs.keys()):
                val = None
                if isinstance(self.inputs[key], StepInterface):
                    val = self.inputs[key].get_explicit_scenario(scenario[i])
                else:
                    val = scenario[i]
                base[f'{self.name}_{key}'] = val
            explicit_scenario.append(base)
        if scenario_nb is None:
            return explicit_scenario
        return explicit_scenario[scenario_nb]

    def get_pipeline_params(self, base=None) -> Dict[str, Any]:
        """
        get_pipeline_params

        Returns a dictionnary with key the `name` of the
        steps in the pipeline and value its inputs.
        If the input is a step object, its name is given.

        Parameters
        ----------
        base : _type_, optional
            recusrive dictionnary, by default None

        Returns
        -------
        Dict[str, Any]
            Pipeline steps with their inputs
        """
        if base is None:
            base = {}
        params = {}
        for key, val in self.inputs.items():
            if isinstance(val, StepInterface):
                base = val.get_pipeline_params(base)
                params[key] = val.name
            else:
                params[key] = val
        base[self.name] = params
        return base

    def get_scenario_inputs(self, scenario) -> Dict[str, Any]:
        """
        get_scenario_inputs

        _extended_summary_

        Parameters
        ----------
        scenario : _type_
            _description_

        Returns
        -------
        _type_
            _description_
        """
        explicit_inputs = [
            self.explicit_inputs[param][self.scenarios[scenario][i]]
            for i, param in enumerate(self.explicit_inputs)
            ]
        params_dict = dict(zip(self.explicit_inputs.keys(),
                               explicit_inputs))
        return params_dict

class ExampleStep(StepInterface):
    """
    ExampleStep

    example of step that you can implement using the
    StepInterface object
    """
    def run_scenario(self, scenario) -> dict:
        params_dict = self.get_scenario_inputs(scenario)
        return params_dict

class FunctionStep(StepInterface):
    """
    FunctionStep

    Implementation of Stepinterface that use a `self.function`
    in the `run_scenario` function. The inputs has to be a dict
    with the key corresponding to a **kwargs for the `self.function`
    """
    def __init__(self,
                 name: Optional[str] = None,
                 function: Callable = NotImplementedError,
                 inputs: Dict = None,
                 ) -> None:
        super().__init__(name, inputs)
        self.function = function

    @property
    def function(self) -> Callable:
        return self._function

    @function.setter
    def function(self, val: Callable):
        self._function = val

    def run_scenario(self, scenario):
        params_dict = self.get_scenario_inputs(scenario)
        return self.function(**params_dict)


"""
This module defines all methods which deal with the contributing files
"""
import os

from github import Github
from github.GithubException import UnknownObjectException

g = Github(os.environ['GITHUB_GPG_KEY'])

def get_contributing_files(repo_addresses: list[str]) -> dict[str, str]:
    """Method gets multiple contributing files from git and decodes them in utf-8 form.
    Then it adds these files to a dictionairy

    :param repo_addresses: repository addresses in a list formatted as ['author1/name1', 'author2/name2'...]
    :type repo_addresses: list[str]
    :return: A dictionairy from a repository address to its contributing file
    :rtype dict[str, str]
    """
    contributing_files = {}
    for address in repo_addresses:
        repo = g.get_repo(address)
        try:
            contributing_contents = repo.get_contents("CONTRIBUTING.md").decoded_content.decode(
                'utf-8')  # decode to utf-8
        except UnknownObjectException:
            contributing_contents = None
        contributing_files[address] = contributing_contents
    return contributing_files


import requests
import os
from requests.auth import HTTPBasicAuth
import yaml
from dotenv import load_dotenv

load_dotenv()

access_token = os.getenv('access_token')

def read_yaml_from_github(access_token):
    # GitHub API endpoint for raw content
    raw_url = f'https://raw.githubusercontent.com/hmrc/cip-data-domain-mapping/main/data-domain-to-audit-source-mapping.yaml'

    # Make a GET request with the personal access token for authentication
    response = requests.get(raw_url, auth=HTTPBasicAuth('token', access_token))

    # Check if the request was successful (status code 200)
    if response.status_code == 200:
        # Parse the YAML content
        yaml_content = yaml.safe_load(response.text)
        return yaml_content
    else:
        print(f"Failed to fetch YAML file. Status code: {response.status_code}")
        return None

# Replace these values with your repository details and personal access token

# Read YAML content from the private GitHub repository
yaml_data = read_yaml_from_github(access_token)
audit_source = 'income-tax-subscription-eligibility;submit-vat-return-frontend;import-control-entry-declaration-outcome;fake-audit-source'

def find_data_domains(yaml_data, audit_source):

    if yaml_data:
        print({"Response":"Successfully obtained yaml data from repo"})

    audit_source = audit_source.lower()
    audit_source = audit_source.replace('_', '-')

    audit_source_list = audit_source.split(';')
    data_domain_list = []
    found_audit_sources = []

    for key, values in yaml_data.items():
        for audit_sources in audit_source_list:
            if audit_sources in values:

                data_domain_list.append(key)
                found_audit_sources.append(audit_sources)
                print(f'{key}: {audit_sources}')

            # else:
            #     data_domain_list.append(f'{audit_sources} not found')

    missing = list(sorted(set(audit_source_list) - set(found_audit_sources)))
    data_domains = list(set(data_domain_list))

    return data_domains, missing

if __name__=='__main__':
    yaml_data2 = read_yaml_from_github(access_token)
    data_doms = find_data_domains(yaml_data2, audit_source)
    print(data_doms)


__author__ = 'ericmuxagata'
__netid__ = 'eg445'

LINE_ENDING = "\r\n"

SYNACK = 220
OK  = 250

DATA_MODE = 354

ERROR_UNRECOGNIZED_CMD  = 500
ERROR_PROPER_SYNTAX     = 501
ERROR_MISPLACED_CMD     = 503
ERROR_BAD_ADDRESS       = 555
ERRORS = [ERROR_UNRECOGNIZED_CMD, ERROR_PROPER_SYNTAX, ERROR_MISPLACED_CMD, ERROR_BAD_ADDRESS]

TIMEOUT = 421

MSG_SKELETON = "{0} {1}"

def msg_synack():
    msg_body = __netid__ + " SMTP CS4410MP3" + LINE_ENDING
    return MSG_SKELETON.format(str(SYNACK), msg_body)

def msg_helo_ack():
    msg_body = __netid__ + LINE_ENDING
    return MSG_SKELETON.format(str(OK), msg_body)

def msg_for_code(code, feedback):
    msg_body = ""

    if code == OK:
        msg_body = "OK" if not feedback else "OK: " + feedback

    elif code == DATA_MODE:
        msg_body = "End data with <CR><LF>.<CR><LF>"

    elif code in ERRORS:
        if   code == ERROR_UNRECOGNIZED_CMD:
            msg_body = "Error: command not recognized"
        elif code == ERROR_PROPER_SYNTAX:
            msg_body = "Syntax:  proper syntax"
        elif code == ERROR_MISPLACED_CMD:
            msg_body = "Error: " + feedback
        elif code == ERROR_BAD_ADDRESS:
            msg_body = "<bad_email>: " + feedback

    elif code == TIMEOUT:
        msg_body = "4.4.2 %s Error: timeout exceeded" % __netid__

    return MSG_SKELETON.format(str(code), msg_body + LINE_ENDING)


import sys

input = sys.stdin.readline()

def solution(N) :
    n = int(N)
    i = 1
    while True :
        address = 3*(i**2) - 3*i + 1
        if (n <= address) :
            return i
        i += 1

print(solution(input))


import torch
import torch.nn as nn

class BlockedGradients(torch.autograd.Function):
    @staticmethod
    def forward(ctx, x, mask):
        ctx.save_for_backward(x, mask)
        return x

    @staticmethod
    def backward(ctx, grad_output):
        x, mask = ctx.saved_tensors
        return grad_output * mask, mask * 0.0


import numpy as np
import k4a

if __name__ == '__main__':
    # Open Device
    device = k4a.Device.open()

    # Start Cameras
    device_config = k4a.DEVICE_CONFIG_BGRA32_1080P_NFOV_UNBINNED_FPS15
    device.start_cameras(device_config)

    # Get Calibration
    calibration = device.get_calibration(
        depth_mode=device_config.depth_mode,
        color_resolution=device_config.color_resolution)

    # Create Transformation
    transformation = k4a.Transformation(calibration)

    # Capture One Frame
    capture = device.get_capture(-1)

    # Get Point Cloud
    xyz_image = transformation.depth_image_to_point_cloud(capture.depth, k4a.ECalibrationType.DEPTH)

    # Save Point Cloud To Ascii Format File. Interleave the [X, Y, Z] channels into [x0, y0, z0, x1, y1, z1, ...]
    height, width, channels = xyz_image.data.shape
    xyz_data = xyz_image.data.reshape(height * width, channels)

    np.savetxt('data.txt', xyz_data, delimiter=' ', fmt='%u') # save ascii format (x y z\n x y z\n x y z\n ...)

    # Stop Cameras
    device.stop_cameras()


import socket
import threading
import dbwrapper as wrapper

HEADER = 64
PORT = 5050
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = "utf-8"
DISCONNECT_MESSAGE = "!DISCONNECT"

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)

client_list = []

def handle_client(conn, addr):
    print(f"[NEW CONN] {addr} connected.")

    connected = True
    while connected:
        message_length_decoded = conn.recv(HEADER).decode(FORMAT)
        if message_length_decoded:
            message_length = int(message_length_decoded[1:])
            message = conn.recv(message_length).decode(FORMAT)
            action, info = message.split("|", 1)
            if action == DISCONNECT_MESSAGE:
                connected = False
            else:
                result = wrapper.message_analyzer(action, info)
                if "UPD" in result[0]:
                    msg = result[0]
                    msg_length = get_length(msg)
                    send_to_all(msg_length)
                    send_to_all(msg.encode(FORMAT))
                else:
                    for msg in result:
                        msg_length = get_length(msg)
                        conn.send(msg_length)
                        conn.send(msg.encode(FORMAT))
    remove(conn)
    conn.close()

def get_length(info):
    msg_length = len(info)
    msg_length_coded = ("H" + str(msg_length)).encode(FORMAT)
    msg_length_coded += b' ' * (HEADER - len(msg_length_coded))
    return msg_length_coded

def send_to_all(message):
    for client in client_list:
        try:
            client.send(message)
        except Exception as e:
            print(str(e))
            client.close()
            remove(client)

def remove(conn):
    if conn in client_list:
        client_list.remove(conn)

def start():
    server.listen()
    print(f"[LISTENING] Server is listening on {SERVER}")
    while True:
        conn, addr = server.accept()
        client_list.append(conn)
        thread = threading.Thread(target=handle_client, args=(conn, addr))
        thread.start()
        print(f"[ACTIVE CONNS] {threading.activeCount() - 1}")

print("[START] Server is starting...")
start()


"""
https://algo-method.com/tasks/244

### 問題
$N$ 個の整数 $A_0, A_1, \dots, A_{N-1}$ と整数 $K$ が与えられます。
これらの $N$ 個の整数から、和が $K$ 以下となるように $2$ つの数を選ぶ方法は何通りあるか求めるプログラムを作成してください。
ただし選んだ $2$ つの整数の添字 ($A_i$ の $i$) が等しくなってはいけないものとします。
### 入力
入力は次の形式で与えられます。
```IOExample
$N$ $K$
$A_0 A_1 \dots A_{N-1}$
```
また、入力される値は次の制約を満たします。
- $N$ は $2$ 以上 $100$ 以下の整数
- $K$ は $2$ 以上 $200$ 以下の整数
- $A_0, A_1, \dots, A_{N-1}$ は $1$ 以上 $100$ 以下の整数
### 出力
答えを出力してください。
"""
import itertools

N, K = map(int, input().split())
A = list(map(int, input().split()))
counter = 0

for comb_tuple in itertools.combinations(A, 2):
    equation = comb_tuple[0] + comb_tuple[1]
    if equation <= K:
        counter += 1

print(counter)


"""
    1) Identifique o algoritmo abaixo.
    2) Faça o mapeamento das variáveis (registre em comentário o propósito de cada uma delas).
    3) Há um erro no algoritmo. Identifique-o, descreva-o e corrija-o.
"""
comps = 0 # Número de comparações
def a(b, c):  # b é a lista de base para a busca; c é o valor a ser buscado
    global comps
    comps = 0

    d = 0 # d marca o início da lista
    e = len(b) - 1 # e define o tamanho da lista -1
    while d <= e:
        f = (d + e) // 2 # f recebe a posição do meio da lista

        if c == b[f]:
            comps += 1
            return f
        elif c < b[f]:
            comps += 2
            e = f - 1
        else:
            comps += 2
            d = f + 1

    return -1

"""
1) Busca Binária

2) Variável de estatística comps

3) No primeiro if, assim que entrar no bloco, deveria retornar f, mas estava atribuindo f a variável e. Sendo f a posição do valor buscado.
"""

2_Semestre/Estrutura de Dados - Fausto/Tarefas/Avaliação 1º Bimestre/Turma A - João Pedro/algoritmo2.py


#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 24 11:09:19 2022

@author: user
"""

# importing required libraries
import sys
import cv2
import time
import random
import configparser
import matplotlib.pyplot as plt
from threading import Thread # library for implementing multi-threaded processing

import TIS

# deskewing
import numpy as np
import math
# from deskew import determine_skew # for detect angle
from typing import Tuple, Union

# OCR
import pytesseract
from libc import azure_ocr
# import pytessy

# modbus
import modbus_tk.defines as cst
import modbus_tk.modbus_tcp as modbus_tcp

# debug
image_debug = False
# image_file = "./MKS.png"
image_file = "./img/2022_09_01_Catupre_8.png"

# parameters
config = configparser.ConfigParser()
config.read('/home/smg/smg/ocr/v5/config.ini')

windows_base    = config['general'].getboolean('windows_base')
debug           = config['general'].getboolean('debug')

# ocr
azure_ocr_en    = config['ocr'].getboolean('azure_ocr_en')
win_psm         = config['ocr'].getint('win_psm')

# camera
cameraID = config['camera'].getint('cameraID')
wind_show = config['camera'].getboolean('windows_show')

# image pre-processing
angle           = config['img_preprocessing'].getfloat('angle')
region_topx     = config['img_preprocessing'].getint('region_topx')
region_topy     = config['img_preprocessing'].getint('region_topy')
region_bottomx  = config['img_preprocessing'].getint('region_bottomx')
region_bottomy  = config['img_preprocessing'].getint('region_bottomy')

# modbus
mod_client  = config['modbus']['mod_client']
mod_port    = config['modbus'].getint('mod_port')
slaveID     = config['modbus'].getint('slaveID')
size        = config['modbus'].getint('size')
scale       = config['modbus'].getint('scale')

list_KEY = ['GNITE','GHITE','ON','hour']

err_char = False
result = 0
key_type = 0
lastVal_ON = 0
lastVal_hour = 0
lastVal_IGNITE = 0
list_last = []

# list_READY = ['READY', 'EADY']
# list_IGNITE = ['IGNITE', 'GNITE']
# list_PLASMA = ['PLASMA', 'PLASHA']

# if(windows_base):
#     print("windows_base: {}".format(windows_base))
#     pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

def rotate(
        image: np.ndarray, angle: float, background: Union[int, Tuple[int, int, int]]
) -> np.ndarray:
    old_width, old_height = image.shape[:2]
    angle_radian = math.radians(angle)
    width = abs(np.sin(angle_radian) * old_height) + abs(np.cos(angle_radian) * old_width)
    height = abs(np.sin(angle_radian) * old_width) + abs(np.cos(angle_radian) * old_height)

    image_center = tuple(np.array(image.shape[1::-1]) / 2)
    rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)
    rot_mat[1, 2] += (width - old_width) / 2
    rot_mat[0, 2] += (height - old_height) / 2
    return cv2.warpAffine(image, rot_mat, (int(round(height)), int(round(width))), borderValue=background)

def merge_rgb(R,G,B):
    img = cv2.merge([B,G,R])
    return img

def img_preprocessing(image, angle):
    global region_topx
    global region_topy
    global region_bottomx
    global region_bottomy

    #print("region_topx:{}".format(region_topx))
    grayscale = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    if(image_debug):
        # print("test")

        skewed = rotate(grayscale, 3.5, (0, 0, 0))

        # region
        region_topx = 200
        region_topy = 0
        region_bottomx = 320
        region_bottomy = 650
        Cropped = skewed[region_topx:region_bottomx+1, region_topy:region_bottomy+1]

        # print("grayscale shape:{}".format(grayscale.shape))

        # blur = Cropped
        blur = cv2.fastNlMeansDenoising(Cropped, h=7,templateWindowSize=7,searchWindowSize=21);

        result = blur

    else:

        # Cropped
        region_topx = 170
        region_topy = 70
        region_bottomx = 300
        region_bottomy = 550
        Cropped = frame[region_topx:region_bottomx, region_topy:region_bottomy]
        # show_img(Cropped)

        # skew
        skewed = rotate(Cropped, 3.3, (0, 0, 0))
        # show_img(skewed)

        # Cropped
        region_topx = 45
        region_topy = 30
        region_bottomx = 115
        region_bottomy = 445
        Cropped = skewed[region_topx:region_bottomx, region_topy:region_bottomy]
        # show_img(Cropped)

        # G channel
        (B, G, R) = cv2.split(Cropped)
        zeros = np.ones(Cropped.shape[:2],dtype=np.uint8)
        G_ch_img = merge_rgb(R=zeros, G=G, B=zeros)
        # show_img(G_ch_img)

        # gray
        grayscale = cv2.cvtColor(G_ch_img, cv2.COLOR_BGR2GRAY)

        # blur-median
        blur_median = cv2.medianBlur(grayscale,3)
        # show_img(blur_median)

        # enhance black
        enhanced = np.where((blur_median>50) & (blur_median<135), blur_median-40, blur_median)
        # show_img(enhanced)

        result = enhanced

    return result

def isfloat(num):
    try:
        float(num)
        return True
    except ValueError:
        return False

def modbus_preprocessing(ocr_text):
    global scale
    global lastVal_ON
    global lastVal_hour
    global lastVal_IGNITE
    global list_last
    global key_type
    global err_char

    global result
    scale = 1
    st_idx = 0

    # case sensitive
    for key in list_KEY: #choosen key
        if(key in ocr_text): #check key
            if(key=="ON"):
                st_idx = ocr_text.find(" ")+1
                scale = 100
                key_type = 1
                if(len(ocr_text.strip())>st_idx): # "PLASMA ON 3. 7kw"
                    tmp_val = ""
                    for i in range(len(ocr_text)-st_idx):
                        tmp_char = ocr_text[st_idx+i]
                        if(tmp_char==" " and i>3):
                            break
                        elif(tmp_char.isnumeric() or tmp_char=="."): #fetch if char is valid
                            tmp_val = tmp_val+tmp_char
                    if(tmp_val[-1:]=="."): #remove last char if non-numeric
                        tmp_val = tmp_val[:-1]
                    if(isfloat(tmp_val)): #chech float or not
                        list_last.append(float(tmp_val)*scale)
                        print(list_last)

            elif(key=="hour"):
                st_idx = ocr_text.find(" ")+1
                scale = 1
                key_type = 2
                if(len(ocr_text.strip())>st_idx): # "READY 14996. hour"
                    tmp_val = ""
                    for i in range(len(ocr_text)-st_idx):
                        tmp_char = ocr_text[st_idx+i]
                        if(tmp_char==" " and i>3):
                            break
                        elif(tmp_char.isnumeric() or tmp_char=="."): #fetch if char is valid
                            tmp_val = tmp_val+tmp_char

                    if(tmp_val[-1:]=="."): #remove last char if non-numeric
                        tmp_val = tmp_val[:-1]
                    if(isfloat(tmp_val)): #chech float or not
                        list_last.append(float(tmp_val)*scale)
                        print(list_last)

            elif(key=="GNITE" or key=='GHITE'):
                st_idx = ocr_text.find(" ")+1
                scale = 1
                key_type = 3
                if(len(ocr_text.strip())>st_idx): # "READY 14996. hour"
                    tmp_val = ""
                    for i in range(len(ocr_text)-st_idx):
                        tmp_char = ocr_text[st_idx+i]
                        if(tmp_char==" " and i>3):
                            break
                        elif(tmp_char.isnumeric() or tmp_char=="."): #fetch if char is valid
                            tmp_val = tmp_val+tmp_char
                        else:
                            if(err_char):
                                break
                            err_char = True

                    if(tmp_val[-1:]=="."): #remove last char if non-numeric
                        tmp_val = tmp_val[:-1]
                    if(isfloat(tmp_val)): #chech float or not
                        list_last.append(float(tmp_val)*scale)
                        print(list_last)

        elif(key==list_KEY[-1]): #end
            #print("result")
            lastVal = 0
            if(key_type==1):
                lastVal = lastVal_ON

            elif(key_type==2):
                lastVal = lastVal_hour

            elif(key_type==3):
                lastVal = lastVal_IGNITE

            if((lastVal*scale) in list_last): # choose lastVal as output
                result = lastVal
            else: # update lastVal and choose mode value
                for i in list_last:
                    counts = np.bincount(list_last)
                    result = (np.argmax(counts)/scale)
                    lastVal = (result/scale)

            # reset
            #key_type = 0
            list_last = []

    return result

# define ModbusTCP with multi-threaded processing
class ModbusTCP:
    def __init__(self, client='127.0.0.1', port=502, slaveID=1, size=8):
        self.client = client
        self.slaveID = slaveID
        self.port = port
        self.size = size
        self.val = 0

        # create modbus server
        self.SERVER = modbus_tcp.TcpServer(address = '127.0.0.1', port = int(self.port))

        # server start
        self.SERVER.start()

        # print("slaveID: {}, size: {}".format(self.slaveID, self.size))
        # build slave
        self.slave = self.SERVER.add_slave(int(self.slaveID))
        self.slave.add_block('A', cst.HOLDING_REGISTERS, 0, self.size) # adres:0, len:8

        self.stopped = True

        # reference to the thread for reading next available frame from input stream
        self.t = Thread(target=self.holdingRegister, args=())
        self.t.daemon = True # daemon threads keep running in the background while the program is executing

    # start
    def start(self):
        self.stopped = False
        self.t.start()

    # update
    def holdingRegister(self):
        while True:
            if(self.stopped):
                break
            else:
                self.slave.set_values('A', 0, int(self.val))
            time.sleep(0.5)

        self.SERVER.stop()

    def update(self, value):
        self.val = value

    def stop(self):
        self.stopped = True

# initializing and starting multi-threaded webcam capture input stream
# webcam_stream = WebcamStream(stream_id=0) #  stream_id = 0 is for primary camera
# webcam_stream.start()

class CustomData:
    ''' Example class for user data passed to the on new image callback function
    '''
    def __init__(self, newImageReceived, image):
        self.newImageReceived = newImageReceived
        self.image = image
        self.busy = False

CD = CustomData(False, None)

def on_new_image(tis, userdata):
    '''
    Callback function, which will be called by the TIS class
    :param tis: the camera TIS class, that calls this callback
    :param userdata: This is a class with user data, filled by this call.
    :return:
    '''
    # Avoid being called, while the callback is busy
    if userdata.busy is True:
        return

    userdata.busy = True
    userdata.newImageReceived = True
    userdata.image = tis.Get_image()
    userdata.busy = False

Tis = TIS.TIS()

# The following line opens and configures the video capture device.
Tis.openDevice("16024087", 640, 480, "30/1",TIS.SinkFormats.BGRA, False)

# The next line is for selecting a device, video format and frame rate.
# if not Tis.selectDevice():
#     quit(0)

#Tis.List_Properties()
Tis.Set_Image_Callback(on_new_image, CD)

Tis.Set_Property("TriggerMode", "On")

Tis.Start_pipeline()

# Remove comment below in oder to get a propety list.
# Tis.List_Properties()

# In case a color camera is used, the white balance automatic must be
# disabled, because this does not work good in trigger mode
try:
    Tis.Set_Property("BalanceWhiteAuto", "Continuous")
    # Tis.Set_Property("BalanceWhiteAuto", "Off")
    # Tis.Set_Property("BalanceWhiteRed", 1.2)
    # Tis.Set_Property("BalanceWhiteGreen", 1.0)
    # Tis.Set_Property("BalanceWhiteBlue", 1.4)

except Exception as error:
    print(error)

try:
    # Query the gain auto and current value :
    print("GainAuto : %s " % Tis.Get_Property("GainAuto"))
    print("Gain : %d" % Tis.Get_Property("Gain"))

    # Check, whether gain auto is enabled. If so, disable it.
    if Tis.Get_Property("GainAuto"):
        Tis.Set_Property("GainAuto", "Off")
        print("Gain Auto now : %s " % Tis.Get_Property("GainAuto"))

    Tis.Set_Property("Gain", 0)

    # Now do the same with exposure. Disable automatic if it was enabled
    # then set an exposure time.
    if Tis.Get_Property("ExposureAuto") :
        Tis.Set_Property("ExposureAuto", "Off")
        print("Exposure Auto now : %s " % Tis.Get_Property("ExposureAuto"))

    Tis.Set_Property("ExposureTime", 24000)

except Exception as error:
    print(error)
    quit()

error = 0
print('Press Esc to stop')
lastkey = 0
# cv2.namedWindow('Window',cv2.WINDOW_NORMAL)

modbus = ModbusTCP(client=mod_client, port=mod_port, slaveID=slaveID, size=size)
modbus.start()

if(debug):
    # processing frames in input stream
    num_frames_processed = 0
    start = time.time()

try:
    while lastkey != 27 and error < 5:
        # time.sleep(1)
        Tis.execute_command("TriggerSoftware") # Send a software trigger

        # Wait for a new image. Use 10 tries.
        tries = 10
        while CD.newImageReceived is False and tries > 0:
            time.sleep(0.1)
            tries -= 1

        # Check, whether there is a new image and handle it.
        if CD.newImageReceived is True:
            CD.newImageReceived = False
            frame = CD.image

    # while True :
    #     if webcam_stream.stopped is True :
    #         break
    #     else :
    #         frame = webcam_stream.read()

            if(image_debug):
                frame = cv2.imread(image_file)
                # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
                # gray = cv2.bilateralFilter(gray, 13, 15, 15)

            # image pre-processing
            proced_img = img_preprocessing(frame, angle)

            # plt.imshow(proced_img)

            # OCR
            if(azure_ocr_en):
                ocr_text = azure_ocr.azure_ocr(proced_img)
            else: # local ocr
                ocr_type = "--psm {}".format(win_psm)
                ocr_text = pytesseract.image_to_string(proced_img, config=ocr_type)

            print(ocr_text.strip())

            # modbus pre-processing
            tmpVal = modbus_preprocessing(ocr_text)
            print("ocr_value: {}".format(tmpVal))

            # modbus
            if(debug):
                ocr_val = random.uniform(3.5,4.5)*100
            # print(ocr_text)

            #modbus.update(ocr_val)

            if(debug):
            # adding a delay for simulating time taken for processing a frame
            # delay = 0.03 # delay value in seconds. so, delay=1 is equivalent to 1 second
            # time.sleep(delay)
                num_frames_processed += 1

                if(wind_show):
                    cv2.imshow('frame' , proced_img)
                    key = cv2.waitKey(1)
                    if key == ord('q'):
                        break

except KeyboardInterrupt:
    print("User Terminated..!")
    # webcam_stream.stop()
    # modbus.stop()

finally:
    if(debug):
        end = time.time()

    # terminate process
    print("Stop the threading..!")
    # webcam_stream.stop()
    Tis.Stop_pipeline()
    modbus.stop()

    if(debug):
        # printing time elapsed and fps
        elapsed = end-start
        fps = num_frames_processed/elapsed
        print("FPS: {} , Elapsed Time: {} , Frames Processed: {}".format(fps, elapsed, num_frames_processed))

        if(wind_show):
            # closing all windows
            cv2.destroyAllWindows()
        #cv2.destroyAllWindows()


import ctypes
from pyWinAPI import *
from pyWinAPI.shared.wtypes_h import *

class _RX_WORK_ITEM_(ctypes.Structure):
    pass

RX_WORK_ITEM = _RX_WORK_ITEM_
PRX_WORK_ITEM = POINTER(_RX_WORK_ITEM_)

# /* + + Copyright (c) 1994 Microsoft Corporation Module Name: RxTimer.h
# Abstract: This module defines the prototypes and structures for the timer on
# the rdbss architecture. What is provided is a 55ms timer...that is, if you
# register a routine then you get a call every 55ms. On NT, you're at DPC
# level. Also contained here are the routines for posting to a thread from DPC
# level. Author: - -

_RXTIMER_H_ = None
if not defined(_RXTIMER_H_):
    _RXTIMER_H_ = 1

    from pyWinAPI.km.rxworkq_h import * # NOQA

    # The RX_WORK_ITEM encapsulates the context for posting to a worker thread
    # as well as
    # a timer routine to be triggered after a specific interval.
    _RX_WORK_ITEM_._fields_ = [
        ('WorkQueueItem', RX_WORK_QUEUE_ITEM),
        ('LastTick', ULONG),
        ('Options', ULONG),
    ]
    rdbss = ctypes.windll.RDBSS

    # extern NTSTATUS
    # NTAPI
    # RxPostOneShotTimerRequest(
    # IN PRDBSS_DEVICE_OBJECT     pDeviceObject,
    # IN PRX_WORK_ITEM            pWorkItem,
    # IN PRX_WORKERTHREAD_ROUTINE Routine,
    # IN PVOID                    pContext,
    # IN LARGE_INTEGER            TimeInterval);
    RxPostOneShotTimerRequest = rdbss.RxPostOneShotTimerRequest
    RxPostOneShotTimerRequest.restype = NTSTATUS

    # extern NTSTATUS
    # NTAPI
    # RxPostRecurrentTimerRequest(
    # IN PRDBSS_DEVICE_OBJECT     pDeviceObject,
    # IN PRX_WORKERTHREAD_ROUTINE Routine,
    # IN PVOID                    pContext,
    # IN LARGE_INTEGER            TimeInterval);
    RxPostRecurrentTimerRequest = rdbss.RxPostRecurrentTimerRequest
    RxPostRecurrentTimerRequest.restype = NTSTATUS

    # extern NTSTATUS
    # NTAPI
    # RxCancelTimerRequest(
    # IN PRDBSS_DEVICE_OBJECT     pDeviceObject,
    # IN PRX_WORKERTHREAD_ROUTINE Routine,
    # IN PVOID                    pContext
    # );
    RxCancelTimerRequest = rdbss.RxCancelTimerRequest
    RxCancelTimerRequest.restype = NTSTATUS

    # Routines for initializing and tearing down the timer service in RDBSS

    # extern NTSTATUS
    # NTAPI
    # RxInitializeRxTimer();
    RxInitializeRxTimer = rdbss.RxInitializeRxTimer
    RxInitializeRxTimer.restype = NTSTATUS

    # extern VOID
    # NTAPI
    # RxTearDownRxTimer(void);
    RxTearDownRxTimer = rdbss.RxTearDownRxTimer
    RxTearDownRxTimer.restype = VOID
# END IF   _RXTIMER_STUFF_DEFINED_


z = int(input())
x = input().split()
lst = list()
for i in x:
    lst.append(int(i)>0)
lis = list()
if all(lst):
    for i in x:
        lis.append(i == i[::-1])
print(any(lis))


"""

Revision ID: 7cb3da03c2a2
Revises: 45f89f245e3d
Create Date: 2023-03-28 09:50:24.225706

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

# revision identifiers, used by Alembic.
revision = '7cb3da03c2a2'
down_revision = '45f89f245e3d'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('widget_map', sa.Column('file_name', sa.Text(), nullable=True))
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('widget_map', 'file_name')
    # ### end Alembic commands ###


import tushare as ts
import pandas as pd

loc = 'C:\\Users\\Caesar\\Desktop\\Data\\share.xlsx'
df = pd.read_excel(loc, 0)

df_out = pd.DataFrame(columns=['code', 'value'])

for codes in df[['code']].values:
    #print(codes[0])
    #20日历史数据
    code = str(codes[0]).zfill(6)
    df = ts.get_hist_data(code)
    #print(type(df))
    if df is not None :
        turnover_df = df[['turnover']]
        if turnover_df.empty != True :
            turnover = turnover_df.values[0][0]
            if turnover>=15:
                row = {'code': code, 'value': turnover}
                df_out = df_out.append(row, ignore_index=True)
                print(code)
                print(str(turnover))

path = 'C:\\Users\\Caesar\\Desktop\\test.xlsx'
df_out.to_excel(path)


from ament_index_python import get_package_share_directory
from launch.actions import Shutdown
from launch import LaunchDescription
from launch_ros.actions import Node
from launch_ros.actions import ComposableNodeContainer
from launch_ros.descriptions import ComposableNode
from launch.substitutions import EnvironmentVariable
from carma_ros2_utils.launch.get_log_level import GetLogLevel
from carma_ros2_utils.launch.get_current_namespace import GetCurrentNamespace
from launch.substitutions import LaunchConfiguration
from launch.actions import DeclareLaunchArgument
import os

def generate_launch_description():
    """
    Launch perception nodes.
    """

    vehicle_config_param_file = LaunchConfiguration('vehicle_config_param_file')
    declare_vehicle_config_param_file_arg = DeclareLaunchArgument(
        name = 'vehicle_config_param_file',
        default_value = "/opt/carma/vehicle/config/VehicleConfigParams.yaml",
        description = "Path to file contain vehicle configuration parameters"
    )

    vehicle_characteristics_param_file = LaunchConfiguration('vehicle_characteristics_param_file')
    declare_vehicle_characteristics_param_file_arg = DeclareLaunchArgument(
        name = 'vehicle_characteristics_param_file',
        default_value = "/opt/carma/vehicle/calibration/identifiers/UniqueVehicleParams.yaml",
        description = "Path to file containing unique vehicle calibrations"
    )

    vector_map_file = LaunchConfiguration('vector_map_file')
    declare_vector_map_file = DeclareLaunchArgument(name='vector_map_file', default_value = 'vector_map.osm', description = "Path to the map osm file if using the noupdate load type")

    autoware_auto_launch_pkg_prefix = get_package_share_directory(
        'autoware_auto_launch')

    euclidean_cluster_param_file = os.path.join(
        autoware_auto_launch_pkg_prefix, 'param/component_style/euclidean_cluster.param.yaml')

    ray_ground_classifier_param_file = os.path.join(
        autoware_auto_launch_pkg_prefix, 'param/component_style/ray_ground_classifier.param.yaml')

    tracking_nodes_param_file = os.path.join(
        autoware_auto_launch_pkg_prefix, 'param/component_style/tracking_nodes.param.yaml')

    object_detection_tracking_param_file = os.path.join(
        get_package_share_directory('object_detection_tracking'), 'config/parameters.yaml')

    subsystem_controller_default_param_file = os.path.join(
        get_package_share_directory('subsystem_controllers'), 'config/environment_perception_controller_config.yaml')

    subsystem_controller_param_file = LaunchConfiguration('subsystem_controller_param_file')
    declare_subsystem_controller_param_file_arg = DeclareLaunchArgument(
        name = 'subsystem_controller_param_file',
        default_value = subsystem_controller_default_param_file,
        description = "Path to file containing override parameters for the subsystem controller"
    )

    frame_transformer_param_file = os.path.join(
        get_package_share_directory('frame_transformer'), 'config/parameters.yaml')

    object_visualizer_param_file = os.path.join(
        get_package_share_directory('object_visualizer'), 'config/parameters.yaml')

    points_map_filter_param_file = os.path.join(
        get_package_share_directory('points_map_filter'), 'config/parameters.yaml')

    motion_computation_param_file = os.path.join(
        get_package_share_directory('motion_computation'), 'config/parameters.yaml')

    env_log_levels = EnvironmentVariable('CARMA_ROS_LOGGING_CONFIG', default_value='{ "default_level" : "WARN" }')

    carma_wm_ctrl_param_file = os.path.join(
        get_package_share_directory('carma_wm_ctrl'), 'config/parameters.yaml')

    # lidar_perception_container contains all nodes for lidar based object perception
    # a failure in any one node in the chain would invalidate the rest of it, so they can all be
    # placed in the same container without reducing fault tolerance
    # a lifecycle wrapper container is used to ensure autoware.auto nodes adhere to the subsystem_controller's signals
    lidar_perception_container = ComposableNodeContainer(
        package='carma_ros2_utils', # rclcpp_components
        name='perception_points_filter_container',
        executable='lifecycle_component_wrapper_mt',
        namespace=GetCurrentNamespace(),
        composable_node_descriptions=[
            ComposableNode(
                package='frame_transformer',
                plugin='frame_transformer::Node',
                name='lidar_to_map_frame_transformer',
                extra_arguments=[
                    {'use_intra_process_comms': True},
                    {'--log-level' : GetLogLevel('frame_transformer', env_log_levels) },
                    {'is_lifecycle_node': True} # Flag to allow lifecycle node loading in lifecycle wrapper
                ],
                remappings=[
                    ("input", [ EnvironmentVariable('CARMA_INTR_NS', default_value=''), "/lidar/points_raw" ] ),
                    ("output", "points_in_map"),
                    ("change_state", "disabled_change_state"), # Disable lifecycle topics since this is a lifecycle wrapper container
                    ("get_state", "disabled_get_state")        # Disable lifecycle topics since this is a lifecycle wrapper container
                ],
                parameters=[
                    { "target_frame" : "map"},
                    { "message_type" : "sensor_msgs/PointCloud2"},
                    { "queue_size" : 1},
                    { "timeout" : 50 },
                ]
            ),
            ComposableNode(
                package='points_map_filter',
                plugin='points_map_filter::Node',
                name='points_map_filter',
                extra_arguments=[
                    {'use_intra_process_comms': True},
                    {'--log-level' : GetLogLevel('points_map_filter', env_log_levels) },
                    {'is_lifecycle_node': True} # Flag to allow lifecycle node loading in lifecycle wrapper
                ],
                remappings=[
                    ("points_raw", "points_in_map" ),
                    ("filtered_points", "map_filtered_points"),
                    ("lanelet2_map", "semantic_map"),
                    ("change_state", "disabled_change_state"), # Disable lifecycle topics since this is a lifecycle wrapper container
                    ("get_state", "disabled_get_state")        # Disable lifecycle topics since this is a lifecycle wrapper container
                ],
                parameters=[ points_map_filter_param_file ]
            ),
            ComposableNode(
                package='frame_transformer',
                plugin='frame_transformer::Node',
                name='lidar_frame_transformer',
                extra_arguments=[
                    {'use_intra_process_comms': True},
                    {'--log-level' : GetLogLevel('frame_transformer', env_log_levels) },
                    {'is_lifecycle_node': True} # Flag to allow lifecycle node loading in lifecycle wrapper
                ],
                remappings=[
                    ("input", "map_filtered_points" ),
                    ("output", "points_in_base_link"),
                    ("change_state", "disabled_change_state"), # Disable lifecycle topics since this is a lifecycle wrapper container
                    ("get_state", "disabled_get_state")        # Disable lifecycle topics since this is a lifecycle wrapper container
                ],
                parameters=[ frame_transformer_param_file ]
            ),
            ComposableNode(
                package='ray_ground_classifier_nodes',
                name='ray_ground_filter',
                plugin='autoware::perception::filters::ray_ground_classifier_nodes::RayGroundClassifierCloudNode',
                extra_arguments=[
                    {'use_intra_process_comms': True},
                    {'--log-level' : GetLogLevel('ray_ground_classifier_nodes', env_log_levels) }
                ],
                remappings=[
                    ("points_in", "points_in_base_link"),
                    ("points_nonground", "points_no_ground")
                ],
                parameters=[ ray_ground_classifier_param_file]
            ),
            ComposableNode(
                package='euclidean_cluster_nodes',
                name='euclidean_cluster',
                plugin='autoware::perception::segmentation::euclidean_cluster_nodes::EuclideanClusterNode',
                extra_arguments=[
                    {'use_intra_process_comms': True},
                    {'--log-level' : GetLogLevel('euclidean_cluster_nodes', env_log_levels) }
                ],
                remappings=[
                    ("points_in", "points_no_ground")
                ],
                parameters=[ euclidean_cluster_param_file ]
            ),
            ComposableNode(
                package='object_detection_tracking',
                plugin='bounding_box_to_detected_object::Node',
                name='bounding_box_converter',
                extra_arguments=[
                    {'use_intra_process_comms': True},
                    {'--log-level' : GetLogLevel('object_detection_tracking', env_log_levels) },
                    {'is_lifecycle_node': True} # Flag to allow lifecycle node loading in lifecycle wrapper
                ],
                remappings=[
                    ("bounding_boxes", "lidar_bounding_boxes"),
                    ("lidar_detected_objects", "detected_objects"),
                ]
            ),
            ComposableNode(
                    package='tracking_nodes',
                    plugin='autoware::tracking_nodes::MultiObjectTrackerNode',
                    name='tracking_nodes_node',
                    extra_arguments=[
                        {'use_intra_process_comms': True},
                        {'--log-level' : GetLogLevel('tracking_nodes', env_log_levels) }
                    ],
                    remappings=[
                        ("ego_state", [ EnvironmentVariable('CARMA_LOCZ_NS', default_value=''), "/current_pose_with_covariance" ] ),
                        # TODO note classified_rois1 is the default single camera input topic
                        # TODO when camera detection is added, we will wan to separate this node into a different component to preserve fault tolerance
                    ],
                    parameters=[ tracking_nodes_param_file ]
            )
        ]
    )

    # carma_external_objects_container contains nodes for object detection and tracking
    # since these nodes can use different object inputs they are a separate container from the lidar_perception_container
    # to preserve fault tolerance
    carma_external_objects_container = ComposableNodeContainer(
        package='carma_ros2_utils',
        name='external_objects_container',
        executable='carma_component_container_mt',
        namespace=GetCurrentNamespace(),
        composable_node_descriptions=[
            ComposableNode(
                package='carma_wm_ctrl',
                plugin='carma_wm_ctrl::WMBroadcasterNode',
                name='carma_wm_broadcaster',
                extra_arguments=[
                    {'use_intra_process_comms': True},
                    {'--log-level' : GetLogLevel('carma_wm_ctrl', env_log_levels) }
                ],
                remappings=[
                    ("georeference", [ EnvironmentVariable('CARMA_LOCZ_NS', default_value=''), "/map_param_loader/georeference" ] ),
                    ("geofence", [ EnvironmentVariable('CARMA_MSG_NS', default_value=''), "/incoming_geofence_control" ] ),
                    ("incoming_map", [ EnvironmentVariable('CARMA_MSG_NS', default_value=''), "/incoming_map" ] ),
                    ("current_pose", [ EnvironmentVariable('CARMA_LOCZ_NS', default_value=''), "/current_pose" ] ),
                    ("route", [ EnvironmentVariable('CARMA_GUIDE_NS', default_value=''), "/route" ] ),
                    ("outgoing_geofence_ack", [ EnvironmentVariable('CARMA_MSG_NS', default_value=''), "/outgoing_mobility_operation" ] ),
                    ("outgoing_geofence_request", [ EnvironmentVariable('CARMA_MSG_NS', default_value=''), "/outgoing_geofence_request" ] )
                ],
                parameters=[ carma_wm_ctrl_param_file, vehicle_config_param_file, vehicle_characteristics_param_file ]
            ),
            ComposableNode(
                    package='object_detection_tracking',
                    plugin='object::ObjectDetectionTrackingNode',
                    name='external_object',
                    extra_arguments=[
                        {'use_intra_process_comms': True},
                        {'--log-level' : GetLogLevel('object_detection_tracking', env_log_levels) }
                    ],
                    remappings=[
                        ("detected_objects", "tracked_objects"),
                    ],
                    parameters=[ object_detection_tracking_param_file ]
            ),
            ComposableNode(
                    package='object_visualizer',
                    plugin='object_visualizer::Node',
                    name='object_visualizer_node',
                    extra_arguments=[
                        {'use_intra_process_comms': True},
                        {'--log-level' : GetLogLevel('object_visualizer', env_log_levels) }
                    ],
                    remappings=[
                        ("external_objects", "external_object_predictions"),
                    ],
                    parameters=[ object_visualizer_param_file ]
            ),
            ComposableNode(
                package='motion_computation',
                plugin='motion_computation::MotionComputationNode',
                name='motion_computation_node',
                extra_arguments=[
                    {'use_intra_process_comms': True},
                    {'--log-level' : GetLogLevel('motion_computation', env_log_levels) }
                ],
                remappings=[
                    ("incoming_mobility_path", [ EnvironmentVariable('CARMA_MSG_NS', default_value=''), "/incoming_mobility_path" ] ),
                    ("incoming_psm", [ EnvironmentVariable('CARMA_MSG_NS', default_value=''), "/incoming_psm" ] ),
                    ("incoming_bsm", [ EnvironmentVariable('CARMA_MSG_NS', default_value=''), "/incoming_bsm" ] ),
                    ("georeference", [ EnvironmentVariable('CARMA_LOCZ_NS', default_value=''), "/map_param_loader/georeference" ] )
                ],
                parameters=[
                    motion_computation_param_file,
                ]
            ),
            ComposableNode( #CARMA Motion Prediction Visualizer Node
                    package='motion_prediction_visualizer',
                    plugin='motion_prediction_visualizer::Node',
                    name='motion_prediction_visualizer',
                    extra_arguments=[
                        {'use_intra_process_comms': True},
                        {'--log-level' : GetLogLevel('motion_prediction_visualizer', env_log_levels) }
                    ],
                    remappings=[
                        ("external_objects", "external_object_predictions" ),
                    ]
            ),
            ComposableNode(
                    package='roadway_objects',
                    plugin='roadway_objects::RoadwayObjectsNode',
                    name='roadway_objects_node',
                    extra_arguments=[
                        {'use_intra_process_comms': True},
                        {'--log-level' : GetLogLevel('roadway_objects', env_log_levels) }
                    ],
                    remappings=[
                        ("external_objects", "external_object_predictions"),
                        ("incoming_spat", [ EnvironmentVariable('CARMA_MSG_NS', default_value=''), "/incoming_spat" ] ),
                        ("route", [ EnvironmentVariable('CARMA_GUIDE_NS', default_value=''), "/route" ] )
                    ],
                    parameters = [
                        vehicle_config_param_file
                    ]

            ),
            ComposableNode(
                    package='traffic_incident_parser',
                    plugin='traffic_incident_parser::TrafficIncidentParserNode',
                    name='traffic_incident_parser_node',
                    extra_arguments=[
                        {'use_intra_process_comms': True},
                        {'--log-level' : GetLogLevel('traffic_incident_parser', env_log_levels) }
                    ],
                    remappings=[
                        ("georeference", [ EnvironmentVariable('CARMA_LOCZ_NS', default_value=''), "/map_param_loader/georeference" ] ),
                        ("geofence", [ EnvironmentVariable('CARMA_MSG_NS', default_value=''), "/incoming_geofence_control" ] ),
                        ("incoming_mobility_operation", [ EnvironmentVariable('CARMA_MSG_NS', default_value=''), "/incoming_mobility_operation" ] ),
                        ("incoming_spat", [ EnvironmentVariable('CARMA_MSG_NS', default_value=''), "/incoming_spat" ] ),
                        ("route", [ EnvironmentVariable('CARMA_GUIDE_NS', default_value=''), "/route" ] )
                    ],
                    parameters = [
                        vehicle_config_param_file
                    ]

            ),
        ]
    )

    # Vector map loader
    lanelet2_map_loader_container = ComposableNodeContainer(
        package='carma_ros2_utils', # rclcpp_components
        name='lanelet2_map_loader_container',
        executable='lifecycle_component_wrapper_mt',
        namespace=GetCurrentNamespace(),
        composable_node_descriptions=[
            ComposableNode(
                package='map_file_ros2',
                plugin='lanelet2_map_loader::Lanelet2MapLoader',
                name='lanelet2_map_loader',
                extra_arguments=[
                    {'use_intra_process_comms': True},
                    {'--log-level' : GetLogLevel('lanelet2_map_loader', env_log_levels) },
                    {'is_lifecycle_node': True} # Flag to allow lifecycle node loading in lifecycle wrapper
                ],
                remappings=[
                    ("lanelet_map_bin", "base_map"),
                    ("change_state", "disabled_change_state"), # Disable lifecycle topics since this is a lifecycle wrapper container
                    ("get_state", "disabled_get_state")        # Disable lifecycle topics since this is a lifecycle wrapper container
                ],
                parameters=[
                    { "lanelet2_filename" : vector_map_file}
                ]
            )
        ]
    )

    # Vector map visualization
    lanelet2_map_visualization_container = ComposableNodeContainer(
        package='carma_ros2_utils', # rclcpp_components
        name='lanelet2_map_visualization_container',
        executable='lifecycle_component_wrapper_mt',
        namespace= GetCurrentNamespace(),
        composable_node_descriptions=[
            ComposableNode(
                package='map_file_ros2',
                plugin='lanelet2_map_visualization::Lanelet2MapVisualization',
                name='lanelet2_map_visualization',
                extra_arguments=[
                    {'use_intra_process_comms': True},
                    {'--log-level' : GetLogLevel('lanelet2_map_visualization', env_log_levels) },
                    {'is_lifecycle_node': True} # Flag to allow lifecycle node loading in lifecycle wrapper
                ],
                remappings=[
                    ("lanelet_map_bin", "semantic_map"),
                    ("change_state", "disabled_change_state"), # Disable lifecycle topics since this is a lifecycle wrapper container
                    ("get_state", "disabled_get_state")        # Disable lifecycle topics since this is a lifecycle wrapper container
                ],
                parameters=[

                ]
            )
        ]
    )
    # subsystem_controller which orchestrates the lifecycle of this subsystem's components
    subsystem_controller = Node(
        package='subsystem_controllers',
        name='environment_perception_controller',
        executable='environment_perception_controller',
        parameters=[ subsystem_controller_default_param_file, subsystem_controller_param_file ],
        on_exit= Shutdown(), # Mark the subsystem controller as required
        arguments=['--ros-args', '--log-level', GetLogLevel('subsystem_controllers', env_log_levels)]
    )

    return LaunchDescription([
        declare_vehicle_characteristics_param_file_arg,
        declare_vehicle_config_param_file_arg,
        declare_subsystem_controller_param_file_arg,
        declare_vector_map_file,
        lidar_perception_container,
        carma_external_objects_container,
        lanelet2_map_loader_container,
        lanelet2_map_visualization_container,
        subsystem_controller
    ])


#Marshal Zhange from S3C3
# This is my code for "Monopoly"

import random
class ListNode :
   def __init__(self) :
      self.who= 0
      self.pointer=0
      self.whose =0
      self.cost = 0

List = [ListNode() for i in range(10)]
for i in range(10) :
    List[i].pointer = i + 1
    List[i].cost =random.randint(30,200)

List[9].pointer=0

a=random.randint(1,9) # The position of player1
b=random.randint(1,9) # The position of player2

List[a].who=1
List[b].who=2

print("Welcome to the game created by Marshal, a simple rule:1 for yes 0 for no")
print("1 for 1000, 2 for 3000, 3 for 10000, 4 for DIY")
option= int(input("choose the amount of money you want to have at first:"))
if option ==1:
    ma= 1000          #Money of Player1
    mb= 1000          #Money of Player2
if option ==2:
    ma= 3000
    mb= 3000
if option ==3:
    ma= 10000
    mb= 10000
if option ==4:
    ma = mb= int(input("please enter the init money you wish to have:"))

def playergo(p):
    global a
    global b
    global ma
    global mb
    r=random.randint(1,6)
    rr=random.randint(1,6)
    print("It's player",p,"'s turn")
    ndice=int(input("please choose the number of dice you want to throw 1 or 2:"))
    if ndice==1:
        n=r
    if ndice==2:
        n=r+rr
    print("The number of steps that you go is:",n)
    x=0
    if p==1:
        while List[a].who==p and x!=n:
            List[a].who=0
            if List[List[a].pointer].who==3-p:
                a=List[List[a].pointer].pointer
                List[a].who=p

            else:
                a=List[a].pointer
                List[a].who=p
            x+=1
        if List[a].whose==0:
            buy(p)
        elif List[a].whose==p:
            upgrade(p)
        elif List[a].whose==3-p:
            pay(p)
    if p==2:
        while List[b].who==p and x!=n:
            List[b].who=0
            if List[List[b].pointer].who==3-p:
                b=List[List[b].pointer].pointer
                List[b].who=p

            else:
                b=List[b].pointer
                List[b].who=p
            x+=1
        if List[b].whose==0:
            buy(p)
        elif List[b].whose==p:
            upgrade(p)
        elif List[b].whose==3-p:
            pay(p)

def buy(p):
    global a
    global b
    global ma
    global mb
    if p==1:
        cost=List[a].cost
        print("this house is empty, do you want to buy it for:",cost,"dollars?")
        option=int(input("yes or no?"))
        if option==1:
            ma-= cost
            List[a].whose=p
    if p==2:
        cost=List[b].cost
        print("this house is empty, do you want to buy it for:",cost,"dollars?")
        option=int(input("yes or no?"))
        if option==1:
            mb-= cost
            List[b].whose=p

def Output():
    for i in range(10):
        print(i, List[i].who, List[i].whose, List[i].cost)
    print("player1 has", ma, "dollars")
    print("player2 has", mb, "dollars")
    if ma<0:
        print("player2 is the winner, with", mb, "dollars")
    if mb<0:
        print("player1 is the winner, with", ma, "dollars")

def upgrade(p):
    global a
    global b
    global ma
    global mb
    print("You have already bought it, Do you want to ungrade it for 77 dollars?")
    print("After unpgrading, the rent will double")
    Option=int(input("please enter your choice:"))
    if Option==1:
        if p==1:
            ma-=77
            List[a].cost*=2
        if p==2:
            mb-=77
            List[b].cost*=2
def pay(p):
    global a
    global b
    global ma
    global mb
    if p==1:
        c=List[a].cost
        ma-=c
        mb+=c
        print("You have stepped onto the other player's area, you have to pay",c,"dollars")
    if p==2:
        c=List[b].cost
        mb-=c
        ma+=c
        print("You have stepped onto the other player's area, you have to pay",c,"dollars")

Output()
p=1
while ma>0 and mb>0:
    playergo(p)
    p=3-p
    Output()


import os
import unittest
import json
from flask_sqlalchemy import SQLAlchemy
from flaskr import create_app
from models import setup_db, Question, Category

class TriviaTestCase(unittest.TestCase):
    """This class represents the trivia test case"""

    def setUp(self):
        """Define test variables and initialize app."""
        self.app = create_app()
        self.client = self.app.test_client
        self.database_host = '127.0.0.1:5432'
        self.database_username = 'postgres'
        self.database_name = 'trivia_test'
        self.database_path = 'postgresql+psycopg2://{}@{}/{}'.format(
            self.database_username,
            self.database_host,
            self.database_name)
        setup_db(self.app, self.database_path)

        self.new_question = {
            "question": "Which two are names of Santa's reindeer?",
            "answer": "Comet and Cupid",
            "category": "3",
            "difficulty": 1
        }

        # binds the app to the current context
        with self.app.app_context():
            self.db = SQLAlchemy()
            self.db.init_app(self.app)
            # create all tables
            self.db.create_all()

    def tearDown(self):
        pass

    def test_get_paginated_questions(self):
        res = self.client().get('/questions')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertTrue(data['total_questions'])
        self.assertTrue(len(data['questions']))

    def test_get_paginated_categories(self):
        res = self.client().get('/categories')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertTrue(data['total_categories'])
        self.assertTrue(len(data['categories']))

# test with wrong values
    def test_404_sent_requesting_beyond_valid_page(self):
        res = self.client().get('/questions?page=1000')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 404)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'resource not found')
# test search with and without results

    def test_get_question_search_with_results(self):
        res = self.client().post('/questions', json={'searchTerm': 'largest'})
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertTrue(data['total_questions'])
        self.assertEqual(len(data['questions']), 1)

    def test_get_question_search_withoutresults(self):
        res = self.client().post('/questions', json={'searchTerm': 'jdhfkf'})
        data = json.loads(res.data)
        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['total_questions'], 0)
        self.assertEqual(data['success'], True)
# test to new question and error

    def test_create_new_question(self):
        res = self.client().post('/questions', json=self.new_question)
        data = json.loads(res.data)
        pass

    def test_422_if_question_creation_fails(self):
        res = self.client().post('/questions', json=self.new_question)
        data = json.loads(res.data)
        pass

# test with questions by category and error
    def test_questions_by_category(self):
        res = self.client().get('/categories/4/questions')
        data = json.loads(res.data)

        self.assertEqual(data['success'], True)
        self.assertEqual(data['total_questions'], 4)
        self.assertEqual(data['current_category'], 4)

    def test_404_questions_by_category(self):
        res = self.client().get('/categories/1000/questions')
        data = json.loads(res.data)

        self.assertEqual(data['error'], 404)
        self.assertEqual(data['message'], 'resource not found')
        self.assertEqual(data['success'], False)
# test for quizz and error

    def test_quiz_questions(self):
        play_quiz = {
            'previous_questions': [],
            'quiz_category': {
                'type': 'sports',
                'id': '6'}}
        res = self.client().post('/play', json=play_quiz)
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)

    def test_422_quiz_questions(self):
        res = self.client().post('/play', json={})
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 422)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'unprocessable')

# test to delete with correct value and does not exist value
    def test_delete_question(self):
        question = Question(question='test_question', answer='test_answer',
                            difficulty=2, category=3)
        question.insert()
        question_id = question.id

        res = self.client().delete(f'/questions/{question_id}')
        data = json.loads(res.data)

        question = Question.query.filter(
            Question.id == question.id).one_or_none()

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertEqual(data['deleted'], question_id)
        self.assertEqual(question, None)

    def test_404_if_question_does_not_exist(self):
        res = self.client().delete('/questions/5000')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 404)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'resource not found')

# Make the tests conveniently executable
if __name__ == "__main__":
    unittest.main()


from package import hex
import time
#import os
#import sys
import socket
from threading import Thread

class Hex_Server:
    serverSocket = None
    hex_program = None
    stopSock = False

    def __init__(self, hex_program):
        self.hex_program = hex_program
        self.serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def listen(self, host, port):
        self.serverSocket.bind((host, port))
        self.serverSocket.settimeout(1)
        self.serverSocket.listen(5)
        stopSock = False
        try:
            while not stopSock:
                try:
                    (clientSocket, address) = self.serverSocket.accept()
                    t = Thread(target=self.hex_program, args=(clientSocket, address))
                    t.start()

                except socket.timeout as e1:
                    pass

        except KeyboardInterrupt as e2:
            stopSock = True

        self.serverSocket.close()

def evaluateClient(cSocket, address):
    print("Client {0} trying to connect".format(address))
    bufferSize = 2048

    returnData = "Welcome to GrayCTF."
    returnData += "\r\nThe theme is hexadecimal."
    returnData += "\r\nYou will be solving a series of problems to get the cookie! (flag)"
    returnData += "\r\n\r\n"
    cSocket.send(bytearray(returnData, "UTF-8"))

    hexClass = hex.Hex_Challenge()
    #hexClass.print_hextable()
    error_code = hexClass.print_rows(cSocket, bufferSize)
    if error_code == -1:
        cSocket.close()
        print("User closed the connection.")
    elif error_code == 1:
        cSocket.shutdown(socket.SHUT_RDWR)
        cSocket.close()

grayServer = Hex_Server(evaluateClient)
port = 2210
print("My port is: " + str(port))
grayServer.listen("169.254.155.222", port); #"107.170.192.50", port)


import sys
import tornado
import asyncio
import logging
from tornado.ioloop import PeriodicCallback
from tornado.options import define, options
import tornado.platform.asyncio

from .application import BrokerApplication
from .coap import coap_server_init, _check_dead_nodes
from .logger import logger

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s - %(name)14s - '
                           '%(levelname)5s - %(message)s')

def parse_command_line():
    """Parse command line arguments for IoT broker application."""
    define("port", default=8000,
           help="Broker port")
    define("max_time", default=120,
           help="Retention time for lost nodes (s).")
    define("debug", default=False,
           help="Enable debug mode.")
    options.parse_command_line()

    if options.debug:
        logger.setLevel(logging.DEBUG)

def run():
    """Start a broker instance."""
    parse_command_line()
    try:
        # Tornado ioloop initialization
        ioloop = asyncio.get_event_loop()
        tornado.platform.asyncio.AsyncIOMainLoop().install()
        PeriodicCallback(_check_dead_nodes, 1000).start()

        # Initialize Coap server
        coap_server_init(options.max_time)

        # Start tornado application
        app = BrokerApplication(options=options)
        app.listen(options.port)
        ioloop.run_forever()
    except KeyboardInterrupt:
        print("Exiting")
        ioloop.stop()
        sys.exit()

if __name__ == '__main__':
    run()


import numpy as np
import nltk
from itertools import chain
from nltk.corpus import wordnet

class Wordnet:
    """
    A set of functions used to augment data.

    Typical usage: ::
        >>> import nltk
        >>> nltk.download('punkt')
        >>> nltk.download('wordnet')
        >>> nltk.download('averaged_perceptron_tagger')
        >>> from textaugment import Wordnet
        >>> t = Wordnet(v=True,n=True,p=0.5)
        >>> t.augment('I love school')
        i adore school
    """

    def __init__(self, **kwargs):
        """
        A method to initialize parameters

        :type random_state: int
        :param random_state: seed
        :type v: bool
        :param v: Verb, default is True
        :type n: bool
        :param n: Noun
        :type runs: int
        :param runs: Number of repetition on single text
        :type p: float, optional
        :param p: The probability of success of an individual trial. (0.1<p<1.0), default is 0.5
        :rtype:   None
        :return:  Constructer do not return.
        """

        # Set random state
        if 'random_state' in kwargs:
            self.random_state = kwargs['random_state']
            if isinstance(self.random_state, int):
                np.random.seed(self.random_state)
            else:
                raise TypeError("random_state must have type int, float, str, bytes, or bytearray")

        # Set verb to be default if no values given
        try:
            if "v" not in kwargs and "n" not in kwargs:
                kwargs['v'] = True
                kwargs['n'] = False
            elif "v" in kwargs and "n" not in kwargs:
                kwargs['v'] = True
                kwargs['n'] = False
            elif "v" not in kwargs and "n" in kwargs:
                kwargs['n'] = True
                kwargs['v'] = False
            if "runs" not in kwargs:
                kwargs['runs']=1

        except KeyError:
            raise

        try:
            if "p" in kwargs:
                if type(kwargs['p']) is not float:
                    raise TypeError("p represent probability of success and must be a float from 0.1 to 0.9. E.g p=0.5")
                elif type(kwargs['p']) is float:
                    self.p = kwargs['p']
            else:
                kwargs['p'] = 0.5  # Set default value
        except KeyError:
            raise

        self.p = kwargs['p']
        self.v = kwargs['v']
        self.n = kwargs['n']
        self.runs = kwargs['runs']

    def geometric(self, data):
        """
        Used to generate Geometric distribution.

        :type data: list
        :param data: Input data
        :rtype:   ndarray or scalar
        :return:  Drawn samples from the parameterized Geometric distribution.
        """

        data = np.array(data)
        first_trial = np.random.geometric(p=self.p, size=data.shape[0]) == 1  # Capture success after first trial
        return data[first_trial]

    def replace(self, data, lang):
        """
        The method to replace words with synonyms

        :type data: str
        :param data: sentence used for data augmentation
        :rtype:   str
        :return:  The augmented data
        :type lang: str
        :param lang: choose lang
        """
        data = data.lower().split()
        data_tokens = [[i, x, y] for i, (x, y) in enumerate(nltk.pos_tag(data))]  # Convert tuple to list
        if self.v:
            for loop in range(self.runs):
                words = [[i, x] for i, x, y in data_tokens if y[0] == 'V']
                words = [i for i in self.geometric(data=words)]  # List of selected words
                if len(words) >= 1:  # There are synonyms
                    for word in words:
                        synonyms1 = wordnet.synsets(word[1], wordnet.VERB, lang=lang)  # Return verbs only
                        synonyms = list(set(chain.from_iterable([syn.lemma_names(lang=lang) for syn in synonyms1])))
                        synonyms_ = []  # Synonyms with no underscores goes here
                        for w in synonyms:
                            if '_' not in w:
                                synonyms_.append(w)  # Remove words with underscores
                        if len(synonyms_) >= 1:
                            synonym = self.geometric(data=synonyms_).tolist()
                            if synonym:  # There is a synonym
                                data[int(word[0])] = synonym[0].lower()  # Take the first success

        if self.n:
            for loop in range(self.runs):
                words = [[i, x] for i, x, y in data_tokens if y[0] == 'N']
                words = [i for i in self.geometric(data=words)]  # List of selected words
                if len(words) >= 1:  # There are synonyms
                    for word in words:
                        synonyms1 = wordnet.synsets(word[1], wordnet.NOUN, lang=lang)  # Return nouns only
                        synonyms = list(set(chain.from_iterable([syn.lemma_names(lang=lang) for syn in synonyms1])))
                        synonyms_ = []  # Synonyms with no underscores goes here
                        for w in synonyms:
                            if '_' not in w:
                                synonyms_.append(w)  # Remove words with underscores
                        if len(synonyms_) >= 1:
                            synonym = self.geometric(data=synonyms_).tolist()
                            if synonym:  # There is a synonym
                                data[int(word[0])] = synonym[0].lower()  # Take the first success

        return " ".join(data)

    def augment(self, data, lang="eng"):
        """
        Data augmentation for text. Generate new dataset based on verb/nouns synonyms.

        :type data: str
        :param data: sentence used for data augmentation
        :rtype:   str
        :return:  The augmented data
        :type lang: str
        :param lang: choose lang
        """
        # Error handling
        if type(data) is not str:
            raise TypeError("Only strings are supported")
        data = self.replace(data, lang)
        return data


# -*- coding: utf-8 -*-

import sys
import time

from PySide           import QtGui,QtCore
from PySide.QtUiTools import QUiLoader

def getWidget(path,load):

    qLoader = QUiLoader()
    qFile   = QtCore.QFile(path)
    qFile.open(QtCore.QFile.ReadOnly)
    ui = qLoader.load(qFile,load)
    qFile.close()
    return ui

class TextEdit(QtGui.QWidget):

    uiFile  = "textUI.ui"
    count   = 0
    maxLine = 10

    def __init__(self, parent=None):
        super(TextEdit, self).__init__(parent)
        self.ui = getWidget(self.uiFile,self)

        layout  = QtGui.QVBoxLayout()
        layout.addWidget(self.ui)

        self.setLayout(layout)

        #Signal
        self.ui.pushButton.clicked.connect(self.pushBtn)

        self.p = TestProcess()
        self.p.printThread.connect(self.push)

        self.logModel = QtGui.QStringListModel()
        self.ui.logView.setModel(self.logModel)

    def pushBtn(self):

        self.p.start()

    def push(self,line):

        logs = self.logModel.stringList()
        logs.append(line)
        if len(logs) > self.maxLine:
            logs.pop(0)
        self.logModel.setStringList(logs)
        self.ui.logView.scrollToBottom()

class TestProcess(QtCore.QThread):

    printThread = QtCore.Signal( str )

    def __init__(self,parent=None):
        QtCore.QThread.__init__(self,parent)

    def run(self):

        for i in range(100):
            self.printLog(str(i))
            time.sleep(1)

        self.finished.emit()

    def printLog(self,line):

        self.printThread.emit(line)

app = QtGui.QApplication(sys.argv)
dlg = TextEdit()
dlg.show()
sys.exit(app.exec_())


def minmaxsum(a,b):
    s = 0
    l = len(a)
    i = 0
    while i < int(b):
        s+=int(a[i])
        i+=1
    return s

if __name__ == '__main__':
    inpt = input('Please enter 5 positive integers separated by comma : ')
    inpt2 = input('Please enter the number of element for min max sum : ')
    lst = inpt.split(',')
    lst.sort()
    print(lst)
    mini = minmaxsum(lst,inpt2)
    lst.sort(reverse = True)
    print(lst)
    maxm = minmaxsum(lst,inpt2)
    print(mini,maxm)