import collections
import re
from typing import Sequence, Tuple, Union

from nltk.translate.bleu_score import sentence_bleu
import numpy as np
from plur.eval import util as eval_util
from plur.eval.plur_eval import PlurEval
from plur.utils import util

class RetrieveAndEditEval(PlurEval):
  """The eval class for the retrieve and edit dataset."""

  def compute_metric_for_one_target(
      self, beam_prediction_lines: Sequence[str],
      target_line: str) -> Tuple[float, int, float]:
    """Return stats computed in the retrieve and edit dataset.

    The target line is a whitespace separated string representing the
    ground truth function tokens. The predicted lines are in the same format.
    We compute the average and maximum number of successive tokens correctly
    predicted, along with the BLEU score for the first prediction.

    Args:
      beam_prediction_lines: A list of prediction strings. Each string is a
        whitespace separated tokens representing the predicted function tokens.
      target_line: The ground truth line.

    Returns:
      Average and maximum number of successive tokens correctly predicted, along
      with the BLEU score for the first prediction.
    """
    assert beam_prediction_lines

    target_tokens = target_line.split(' ')

    beam_expected_tokens_predicted = []
    beam_max_tokens_predicted = []
    for prediction_line in beam_prediction_lines:
      prediction_tokens = prediction_line.split(' ')
      matches = _get_matches(prediction_tokens, target_tokens)
      beam_expected_tokens_predicted.append(
          _expected_correctly_predicted_tokens(matches))
      beam_max_tokens_predicted.append(
          _max_correctly_predicted_tokens(matches))

    # Use the best one from the average tokens predicted.
    best_index = np.argmax(beam_expected_tokens_predicted)

    # BLEU score is only calculated for the first prediction in the beam.
    target_bleu_eval_tokens = _tokenize_for_bleu_eval(target_line)
    prediction_bleu_eval_tokens = _tokenize_for_bleu_eval(
        beam_prediction_lines[0])
    bleu_score = _bleu(target_bleu_eval_tokens, prediction_bleu_eval_tokens)

    return (beam_expected_tokens_predicted[best_index],
            beam_max_tokens_predicted[best_index], bleu_score * 100)

  def evaluate_once(self, grouped_prediction_lines: Sequence[Sequence[str]],
                    target_lines: Sequence[str]) -> eval_util.Results:
    all_expected_successive_tokens = []
    all_max_successive_tokens = []
    all_bleu_scores = []
    for beam_prediction_lines, target_line in zip(grouped_prediction_lines,
                                                  target_lines):
      expected_successive_tokens, max_successive_tokens, bleu_score = (
          self.compute_metric_for_one_target(beam_prediction_lines,
                                             target_line))
      all_expected_successive_tokens.append(expected_successive_tokens)
      all_max_successive_tokens.append(max_successive_tokens)
      all_bleu_scores.append(bleu_score)

    average_expected_successive_tokens = util.safe_division(
        sum(all_expected_successive_tokens),
        len(all_expected_successive_tokens))
    average_max_successive_tokens = util.safe_division(
        sum(all_max_successive_tokens),
        len(all_max_successive_tokens))
    average_bleu_score = util.safe_division(
        sum(all_bleu_scores), len(all_bleu_scores))

    metrics = collections.OrderedDict()
    metrics_format = collections.OrderedDict()

    metrics['average_expected_successive_tokens'] = (
        average_expected_successive_tokens)
    metrics_format['average_expected_successive_tokens'] = '{:.5f}'
    metrics['average_max_successive_tokens'] = average_max_successive_tokens
    metrics_format['average_max_successive_tokens'] = '{:.5f}'
    metrics['bleu'] = average_bleu_score
    metrics_format['bleu'] = '{:.5f}'

    return eval_util.Results(
        total=len(target_lines), metrics=metrics, metrics_format=metrics_format)

  def get_metric_as_string(self) -> str:
    return str(self.evaluate())

def _get_matches(prediction: Sequence[str], reference: Sequence[str]
                 ) -> Sequence[bool]:
  """Get the token matches as a list of boolean.

  Args:
    prediction: The predicted token list.
    reference: The ground truth token list.

  Returns:
    A list of boolean. l[i] == True means that i:th token matched between the
    prediction and reference
  """
  matches = []
  for i in range(max(len(prediction), len(reference))):
    if i < len(prediction) and i < len(reference):
      matches.append(prediction[i] == reference[i])
    else:
      matches.append(False)
  return matches

def _run_length_encoding(
    inarray: Sequence[bool]) -> Tuple[Union[Sequence[int], None],
                                      Union[Sequence[int], None],
                                      Union[Sequence[bool], None]]:
  """The run length encoding algorithm.

  This function is to compute information about sequences in which the same data
  values occurs. It is originally a data compression algorithm. For example
  [True, True, False, False, True] can be compressed to 2-True 2-False 1-True.
  This algorithm keeps the track of:
    1. The length of each sequences with the same value.
    2. The start position of each sequence.
    3. The value in each sequence.

  It is the 'def rle(inarray)' function from 'github_eval.py' in the published
  retrieve and edit source code.

  Args:
    inarray: The input array.

  Returns:
    A tuple of (run lengths, start positions, values). Run lengths is a list
    of integers representing the length  of each sequences with the same value.
    Start positions is a list of integers representing the start position of
    each sequence. Values is the values in each sequences.
  """
  ia = np.asarray(inarray)               # force numpy
  n = len(ia)
  if n == 0:
    return (None, None, None)
  else:
    y = ia[1:] != ia[:-1]                # pairwise unequal (string safe)
    i = np.append(np.where(y), n - 1)    # must include last element posi
    z = np.diff(np.append(-1, i))        # run lengths
    p = np.cumsum(np.append(0, z))[:-1]  # positions
    return (z, p, ia[i])

def _max_correctly_predicted_tokens(matches: Sequence[bool]) -> int:
  """Get the length of the longest consecutive correctly predicted sequence.

  This is the slightly modifed version of 'def correct_runlen(rankin, cut)'
  function from 'github_eval.py' in the published retrieve and edit source code.

  Args:
    matches: A list of boolean, True means that the token matched between the
      prediction and the target, False otherwise.

  Returns:
    The length of the longest consecutive correctly predicted sequence.
  """
  if any(matches):
    # lengths is np.ndarray of the sequence lengths.
    # values is the respective values of each sequence.
    lengths, _, values = _run_length_encoding(matches)
    return np.max(lengths[values])
  else:
    return 0

def _expected_correctly_predicted_tokens(matches: Sequence[bool]) -> float:
  """Get the expected length of the consecutive correctly predicted sequences.

  This is the slightly modifed version of 'def avg_runlen(rankin, cut)'
  function from 'github_eval.py' in the published retrieve and edit source code.

  Args:
    matches: A list of boolean, True means that the token matched between the
      prediction and the target, False otherwise.

  Returns:
    The expected length of consecutive correctly predicted sequences.
  """
  if any(matches):
    # lengths is np.ndarray of the sequence lengths.
    # values is the respective values of each sequence.
    lengths, _, values = _run_length_encoding(matches)
    # The probability of choosing the sequences that matches the ground truth.
    seq_prob = lengths[values] / float(np.sum(lengths))
    # The expected matching sequence length if we sample uniformly.
    # lengths[values] is the length of all matching sequences. For each matching
    # sequence, the expected consecutive correctly predicted tokens is
    # 1 * (1/n) + 2 * (1/n) + 3 * (1/n) + ... = n(n+1)/2n = (n+1)/n
    expected_dist = (lengths[values]+1.0)/2.0
    return np.sum(np.array(expected_dist)*np.array(seq_prob))
  else:
    return 0.0

def _tokenize_for_bleu_eval(code: str) -> Sequence[str]:
  """Tokenize the input for computing the bleu score.

  We perform the same tokenizing step as the retrieve and edit dataset. It is
  the 'def tokenize_for_bleu_eval(code)' function from 'github_eval.py' in the
  published retrieve and edit source code.

  Args:
    code: A string representing the code.

  Returns:
    The tokenized code as a list.
  """
  code = re.sub(r'([^A-Za-z0-9_])', r' \1 ', code)
  code = re.sub(r'([a-z])([A-Z])', r'\1 \2', code)
  code = re.sub(r'\s+', ' ', code)
  code = code.replace('"', '`')
  code = code.replace('\'', '`')
  tokens = [t for t in code.split(' ') if t]
  return tokens

def _bleu(reference: Sequence[str], predict: Sequence[str]) -> float:
  """Compute the bleu score.

  We compute the bleu score in the same way as the retrieve and edit dataset.
  It is the 'def bleu(reference, predict)' function from 'gtd/utils.py' in the
  published retrieve and edit source code.

  Args:
    reference: The reference token list.
    predict: The predicted token list.

  Returns:
    The bleu score.
  """
  if not predict:
    if not reference:
      return 1.0
    else:
      return 0.0

  # use a maximum of 4-grams. If 4-grams aren't present, use only lower n-grams.
  n = max(min(4, len(reference), len(predict)), 1)
  weights = tuple([1. / n] * n)  # uniform weight on n-gram precisions
  return sentence_bleu([reference], predict, weights)


class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        sumNums = 0
        totalSumRequired = 0

        for num in nums:
            sumNums += num

        for i in range(len(nums)+1):
            totalSumRequired += i

        return totalSumRequired - sumNums


from math import ldexp
from threading import Lock

from opentelemetry.sdk.metrics._internal.exponential_histogram.mapping import (
    Mapping,
)
from opentelemetry.sdk.metrics._internal.exponential_histogram.mapping.errors import (
    MappingOverflowError,
    MappingUnderflowError,
)
from opentelemetry.sdk.metrics._internal.exponential_histogram.mapping.ieee_754 import (
    MANTISSA_WIDTH,
    MAX_NORMAL_EXPONENT,
    MIN_NORMAL_EXPONENT,
    MIN_NORMAL_VALUE,
    get_ieee_754_exponent,
    get_ieee_754_mantissa,
)

class ExponentMapping(Mapping):
    # Reference implementation here:
    # https://github.com/open-telemetry/opentelemetry-go/blob/0e6f9c29c10d6078e8131418e1d1d166c7195d61/sdk/metric/aggregator/exponential/mapping/exponent/exponent.go

    _mappings = {}
    _mappings_lock = Lock()

    _min_scale = -10
    _max_scale = 0

    def _get_min_scale(self):
        # _min_scale defines the point at which the exponential mapping
        # function becomes useless for 64-bit floats. With scale -10, ignoring
        # subnormal values, bucket indices range from -1 to 1.
        return -10

    def _get_max_scale(self):
        # _max_scale is the largest scale supported by exponential mapping. Use
        # a logarithm mapping for larger scales.
        return 0

    def _init(self, scale: int):
        # pylint: disable=attribute-defined-outside-init

        super()._init(scale)

        # self._min_normal_lower_boundary_index is the largest index such that
        # base ** index < MIN_NORMAL_VALUE and
        # base ** (index + 1) >= MIN_NORMAL_VALUE. An exponential histogram
        # bucket with this index covers the range
        # (base ** index, base (index + 1)], including MIN_NORMAL_VALUE. This
        # is the smallest valid index that contains at least one normal value.
        index = MIN_NORMAL_EXPONENT >> -self._scale

        if -self._scale < 2:
            # For scales -1 and 0, the maximum value 2 ** -1022 is a
            # power-of-two multiple, meaning base ** index == MIN_NORMAL_VALUE.
            # Subtracting 1 so that base ** (index + 1) == MIN_NORMAL_VALUE.
            index -= 1

        self._min_normal_lower_boundary_index = index

        # self._max_normal_lower_boundary_index is the index such that
        # base**index equals the greatest representable lower boundary. An
        # exponential histogram bucket with this index covers the range
        # ((2 ** 1024) / base, 2 ** 1024], which includes opentelemetry.sdk.
        # metrics._internal.exponential_histogram.ieee_754.MAX_NORMAL_VALUE.
        # This bucket is incomplete, since the upper boundary cannot be
        # represented. One greater than this index corresponds with the bucket
        # containing values > 2 ** 1024.
        self._max_normal_lower_boundary_index = (
            MAX_NORMAL_EXPONENT >> -self._scale
        )

    def map_to_index(self, value: float) -> int:
        if value < MIN_NORMAL_VALUE:
            return self._min_normal_lower_boundary_index

        exponent = get_ieee_754_exponent(value)

        # Positive integers are represented in binary as having an infinite
        # amount of leading zeroes, for example 2 is represented as ...00010.

        # A negative integer -x is represented in binary as the complement of
        # (x - 1). For example, -4 is represented as the complement of 4 - 1
        # == 3. 3 is represented as ...00011. Its compliment is ...11100, the
        # binary representation of -4.

        # get_ieee_754_mantissa(value) gets the positive integer made up
        # from the rightmost MANTISSA_WIDTH bits (the mantissa) of the IEEE
        # 754 representation of value. If value is an exact power of 2, all
        # these MANTISSA_WIDTH bits would be all zeroes, and when 1 is
        # subtracted the resulting value is -1. The binary representation of
        # -1 is ...111, so when these bits are right shifted MANTISSA_WIDTH
        # places, the resulting value for correction is -1. If value is not an
        # exact power of 2, at least one of the rightmost MANTISSA_WIDTH
        # bits would be 1 (even for values whose decimal part is 0, like 5.0
        # since the IEEE 754 of such number is too the product of a power of 2
        # (defined in the exponent part of the IEEE 754 representation) and the
        # value defined in the mantissa). Having at least one of the rightmost
        # MANTISSA_WIDTH bit being 1 means that get_ieee_754(value) will
        # always be greater or equal to 1, and when 1 is subtracted, the
        # result will be greater or equal to 0, whose representation in binary
        # will be of at most MANTISSA_WIDTH ones that have an infinite
        # amount of leading zeroes. When those MANTISSA_WIDTH bits are
        # shifted to the right MANTISSA_WIDTH places, the resulting value
        # will be 0.

        # In summary, correction will be -1 if value is a power of 2, 0 if not.

        # FIXME Document why we can assume value will not be 0, inf, or NaN.
        correction = (get_ieee_754_mantissa(value) - 1) >> MANTISSA_WIDTH

        return (exponent + correction) >> -self._scale

    def get_lower_boundary(self, index: int) -> float:
        if index < self._min_normal_lower_boundary_index:
            raise MappingUnderflowError()

        if index > self._max_normal_lower_boundary_index:
            raise MappingOverflowError()

        return ldexp(1, index << -self._scale)

    @property
    def scale(self) -> int:
        return self._scale


class book:
    def __init__(self, title, author, genre, price):
        self.title = title
        self.author = author
        self.genre = genre
        self.price = price

    def display_info(self):
        print("Title:", self.title)
        print("Author:", self.author)
        print("Genre:", self.genre)
        print("Price:", self.price)

class Bookstore:
    def __init__(self):
        self.books = []

    def add_book(self, book):
        self.books.append(book)

    def display_books(self):
        if not self.books:
            print("No books in the bookstore.")
        else:
            print("Bookstore Inventory:")
            for book in self.books:
                print("-" * 30)
                book.display_info()

def main():
    bookstore = Bookstore()

    while True:
        print("\Bookstore Managment System")
        print("1. Add Book")
        print("2. Display Books")
        print("3. Exit")

        choice = input("Enter your Choice: ")

        if choice == "1":
            title = input("Enter the book title: ")
            author = input("Enter the author name: ")
            genre = input("Enter the book genre: ")
            price = float(input("Enter the book price: "))
            book = Book(title, author, genre, price)
            bookstore.add_book(book)
            print("Book added successfully!")
        elif choice == "2":
            bookstore.display_books()
        elif choice == "3":
            print("Exiting Bookstore Management System...")
            break
        else:
            print("Invalid choice. Please try again.")

    if __name__ == "__main__":
        main()


import time

from aiogram.dispatcher.filters import RegexpCommandsFilter
from aiogram.types import Message, ContentTypes, ReplyKeyboardMarkup, KeyboardButton, WebAppInfo, MenuButtonWebApp

from loader import dp, bot
from models import User

@dp.message_handler(RegexpCommandsFilter(regexp_commands=['web_app_test(\shttps:(.*))?']))
async def _web_app_init(message: Message, regexp_command):
    web_app_uri = regexp_command.group(1).strip() if regexp_command.group(1) \
        else 'https://aiogram-peewee-template.vercel.app/web_app_echo.html'
    web_app_uri += '?time=' + str(time.time())

    markup = ReplyKeyboardMarkup(resize_keyboard=True)
    markup.add(
        KeyboardButton('Menu', web_app=WebAppInfo(url=web_app_uri + '&keyboard_button=1'))
    )

    await message.answer('Web app test', reply_markup=markup)
    await bot.set_chat_menu_button(message.chat.id, MenuButtonWebApp(text='Menu', web_app=WebAppInfo(url=web_app_uri)))

@dp.message_handler(content_types=[ContentTypes.WEB_APP_DATA])
async def _web_app(message: Message, user: User):
    text = f'Button text: {message.web_app_data.button_text}\n\n' \
           f'Data:\n<pre>{message.web_app_data.data}</pre>'

    await message.answer(text)


class Employee_Sys:
    def __init__(self):
        self.filename = None
        pass
    def Add_Emp(self,name,age,salary):
        name = name.strip()
        age = int(age)
        salary = int(salary)
        with open(self.filename,"r") as f:
            lines = f.readlines()
            for i in lines:
                line = i.split()
                if line[0] == name:
                    print("\nThis employee already exist!")
                    break
            else:
                with open(self.filename,"a") as f:
                    f.write(f"{name}\t{age}\t{salary}\n")
    def Print_Emp(self):
        with open(self.filename,"r") as f:
            if f.read() == "":
                print("NO employees at the moment!")
            else:
                f.seek(0)
                lines = f.read().splitlines()
                for i in lines:
                    line = i.split()
                    print(f"Employee: {line[0]} has age {line[1]} and salary {line[2]}")
    def Delete_By_Age(self,age_from , age_to):
        age_from = int(age_from)
        age_to = int(age_to)
        flag = True
        with open(self.filename,"r") as f:
            lines = f.readlines()
            for idx,val in enumerate(lines):
                line = val.split()
                if int(line[1]) >= age_from and int(line[1]) <= age_to:
                    print(f"\n\tDeleting {line[0]}")
                    lines.pop(idx)
                    with open(self.filename , "w") as f2:
                        f2.writelines(lines)
                    flag = False
        if flag:
            print("No employee match the age range!")
    def Update_Salary(self,name,new_salary):
        name = name.strip()
        new_salary = int(new_salary)
        with open(self.filename,"r") as f:
            lines = f.readlines()
            for idx,val in enumerate(lines):
                line = val.split()
                if line[0] == name:
                    lines[idx] = f"{line[0]}\t{line[1]}\t{new_salary}\n"
                    with open(self.filename , "w") as f2:
                        f2.writelines(lines)
                    break
            else:
                print("\nThere is no employee with this name!")
    def validate_int(self,inp):
        inp = str(inp)
        inp = inp.strip()
        if inp.isdecimal():
            return True
        return False
    def Export_file(self,filename = "DB.txt"):
        self.filename = filename.strip()
        try:
            open(self.filename , "r")
        except FileNotFoundError:
            open(self.filename, "w")
    def Validate_file_name(self,inp):
        inp = str(inp)
        if inp.endswith(".txt"):
            return True
        return False
if __name__ == "__main__":
    Emp = Employee_Sys()
    while True:
        fname =  input("Enter the file you want to export data from (Default file DB.txt will be created) , Please note that the file extention must be .txt: ")
        if Emp.Validate_file_name(fname):
            break
    Emp.Export_file(fname)
    while True:
        print("\nProgram Options:")
        print("1) Add a new employee")
        print("2) List all employees")
        print("3) Delete by age range")
        print("4) Update salary by name")
        print("5) End the program")
        Option_list = ["1","2","3","4","5"]
        Choice = input("Enter your choice (from 1 to 5): ")
        while Choice not in Option_list:
            print("Invalid input!")
            Choice = input("Enter your choice (from 1 to 5): ")
        if Choice == "1":
            print("\nEnter employee data:")
            name = input("Enter Name: ")
            age = input("Enter Age: ")
            salary = input("Enter Salary: ")
            if Emp.validate_int(age) and Emp.validate_int(salary):
                Emp.Add_Emp(name,age,salary)
            else:
                print("\nThe age and salary must be integers! try again!")
        elif Choice == "2":
            print("\n\tEmployess list\n")
            Emp.Print_Emp()
        elif Choice == "3":
            age_from = input("Enter age from: ")
            age_to = input("Enter age to: ")
            if Emp.validate_int(age_from) and Emp.validate_int(age_to):
                Emp.Delete_By_Age(age_from,age_to)
            else:
                print("\nThe range of age must be integers! try again!")
        elif Choice == "4":
            name = input("Enter the name: ")
            new_salary = input("Enter the new salary: ")
            if Emp.validate_int(new_salary):
                Emp.Update_Salary(name,new_salary)
            else:
                print("\nThe new salary must be integer! try again!")
        else:
            break


def run_part_1():
    f = open("day12.txt", "r")
    instruction_set = [(line.strip()) for line in f.readlines() if line.strip()]
    vertical, horizontal, direction = 0, 0, 0
    for instruction in instruction_set:
        inst, value = instruction[0], int(instruction[1:len(instruction)])
        if inst == 'N': vertical += value
        elif inst == 'S': vertical -= value
        elif inst == 'E': horizontal += value
        elif inst == 'W': horizontal -= value
        elif inst == 'F':
            if direction == 0: horizontal += value
            elif direction == 90: vertical += value
            elif direction == 180: horizontal -= value
            elif direction == 270: vertical -= value
        elif inst == 'L': direction = (direction + value) % 360
        elif inst == 'R': direction = (direction - value + 360) % 360
    print(abs(vertical) + abs(horizontal))

def run_part_2(starting):
    f = open("day12.txt", "r")
    instruction_set = [(line.strip()) for line in f.readlines() if line.strip()]
    vertical, horizontal, waypoint = 0, 0, starting.copy()
    for instruction in instruction_set:
        inst, value = instruction[0], int(instruction[1:len(instruction)])
        if inst == 'N': waypoint[1] += value
        elif inst == 'S': waypoint[1] -= value
        elif inst == 'E': waypoint[0] += value
        elif inst == 'W': waypoint[0] -= value
        elif inst == 'F':
            vertical += waypoint[1] * value
            horizontal += waypoint[0] * value
        elif inst == 'R':
            if value == 90: waypoint = [waypoint[1], waypoint[0] * -1]
            elif value == 180: waypoint = [waypoint[0] * -1, waypoint[1] * -1]
            else: waypoint = [waypoint[1] * -1, waypoint[0]]
        elif inst == 'L':
            if value == 90: waypoint = [waypoint[1] * -1, waypoint[0]]
            elif value == 180: waypoint = [waypoint[0] * -1, waypoint[1] * -1]
            else: waypoint = [waypoint[1], waypoint[0] * -1]
    print(abs(vertical) + abs(horizontal))

def main():
    # run_part_1()
    # E/W, N/S
    waypoint = [10, 1]
    run_part_2(waypoint)

if __name__ == "__main__":
    main()


import boa
from boa.test import strategy
from hypothesis.stateful import (
    initialize,
    invariant,
    rule,
    run_state_machine_as_test,
)

from tests.unitary.tricrypto.stateful.test_stateful import ProfitableState

MAX_SAMPLES = 100
MAX_COUNT = 100
MAX_D = 10**12 * 10**18  # $1T is hopefully a reasonable cap for tests
ALLOWED_DIFFERENCE = 0.02

class RampTest(ProfitableState):
    future_gamma = strategy(
        "uint256",
        min_value=int(7e-5 * 1e18 / 9),
        max_value=int(7e-5 * 1e18 * 9),
    )
    future_A = strategy(
        "uint256",
        min_value=135 * 3**3 * 10000 // 9,
        max_value=3**3 * 10000 * 1000,
    )

    exchange_amount_in = strategy(
        "uint256", min_value=10**18, max_value=50000 * 10**18
    )
    token_amount = strategy(
        "uint256", min_value=10**18, max_value=10**12 * 10**18
    )
    exchange_i = strategy("uint8", max_value=2)
    exchange_j = strategy("uint8", max_value=2)
    user = strategy("address")

    @initialize(future_A=future_A, future_gamma=future_gamma)
    def initialize(self, future_A, future_gamma):
        with boa.env.prank(self.swap.owner()):
            self.swap.ramp_A_gamma(
                future_A,
                future_gamma,
                boa.env.vm.state.timestamp + 14 * 86400,
            )

    @rule(
        exchange_amount_in=exchange_amount_in,
        exchange_i=exchange_i,
        exchange_j=exchange_j,
        user=user,
    )
    def exchange(self, exchange_amount_in, exchange_i, exchange_j, user):
        super()._exchange(
            exchange_amount_in, exchange_i, exchange_j, user, False
        )

    @rule(token_amount=token_amount, exchange_i=exchange_i, user=user)
    def remove_liquidity_one_coin(self, token_amount, exchange_i, user):
        super().remove_liquidity_one_coin(
            token_amount, exchange_i, user, False
        )

    @invariant()
    def virtual_price(self):
        # Invariant is not conserved here
        # so we need to override super().virtual_price()
        pass

def test_ramp(tricrypto_swap, tricrypto_lp_token, users, pool_coins):
    from hypothesis import settings
    from hypothesis._settings import HealthCheck

    RampTest.TestCase.settings = settings(
        max_examples=MAX_SAMPLES,
        stateful_step_count=MAX_COUNT,
        suppress_health_check=HealthCheck.all(),
        deadline=None,
    )

    for k, v in locals().items():
        setattr(RampTest, k, v)

    run_state_machine_as_test(RampTest)


#! /usr/bin/env python3

from lxml import html, etree
from lxml.html import builder as E
import re, os, sys, subprocess

def parse_html(fname):
    return html.parse(fname)
    # none of these works:
    #from bs4 import BeautifulSoup
    #return BeautifulSoup(open('naslov.html', 'rb'), "lxml")
    #import html5lib
    #parser = html5lib.HTMLParser(tree=html5lib.treebuilders.getTreeBuilder("lxml"), namespaceHTMLElements=False, strict=False)
    #return parser.parse(open(fname, 'rb'))

def reformat_chapter(chapter):
    # this is where the content is, ignore all else of the file
    content = chapter.xpath('.//center/table//tr/td/*')
    header = content[0]
    header.text = header.text.strip()
    yield header

    paragraphs = content[1:]
    # remove leading space from the first line in a paragraph, the proper place for indent is css
    # also replace \r\n with \n on every text node
    for para in paragraphs:
        p = html.Element('p')
        p.text = para.text.lstrip().replace('\r\n', '\n')
        yield p
        for el in para:
            if el.tag == 'br':
                # create new paragraph for each <br> tag
                p = html.Element('p')
                if el.tail:
                    p.text = el.tail.lstrip().replace('\r\n', '\n')
                p.tail = '\n'
                yield p
            else:
                # if this is not a br element, just add it to the last <P> element
                if el.text:
                    el.text = el.text.replace('\r\n', '\n')
                if el.tail:
                    el.tail = el.tail.replace('\r\n', '\n')
                p.append(el)
        if para.tail:
            p = html.Element('p')
            p.text = para.tail.replace('\r\n', '\n')
            yield p

def get_content_from_files(index='menu.html'):
    index_doc = parse_html(index)
    index_body = index_doc.getroot().find('body')
    for fname in index_body.xpath('.//table//tr/td/p/a/@href'):
        chapter = parse_html(fname)
        yield from reformat_chapter(chapter)

def extract_metadata(fname='naslov.html'):
    meta = {}

    doc = parse_html(fname)
    head = doc.getroot().find('head')

    def reverse_last_first_name(author):
        return ' '.join(reversed(author.split(' ', 1))).strip()

    authors, _, title = head.find('title').text.rpartition(',')
    meta['authors'] = ' & '.join([ reverse_last_first_name(author) for author in authors.split('/')])
    meta['title'] = title.strip().title()

    content = doc.xpath('.//table//tr/td[1]/font[1]')[0]

    try:
        # a book that has author(s)
        meta['coverpage-author(s)'] = content[0].text.strip()
        meta['coverpage-title'] = content[1][0][0].text.strip()
        meta['coverpage-translator'] = content[1][0][2].text.strip()
        meta['coverpage-orig-title'] = content[1][0][2][0].text.strip()
    except:
        meta['coverpage-title'] = content[0][0][0].text.strip()

    try:
        el = content.xpath('.//font/p[2]/font')[0]
        series = el.text.strip()
        meta['series'] = re.match(r'Serija "(.*)"', series).group(1)
        series_index = el[0].tail.strip()
        meta['series_index'] = re.match(r'\((\d*)\)', series_index).group(1)
    except:
        pass

    try:
        meta['publisher'] = content.xpath('.//font[last()]')[0].text.strip()
        meta['pubdate'] = content.xpath('.//br[last()]')[0].tail.strip()
    except:
        pass

    # take the last image of the second table cell
    img = doc.xpath('.//img[last()]')[0]
    meta['cover-image'] = img.attrib['src']
    return meta

def create_cover_page(meta):
    if meta['level1-toc'] == 'h1':
        HEADER = E.H1
    elif meta['level1-toc'] == 'h2':
        HEADER = E.H2
    else:
        HEADER = E.H3

    cover = E.DIV(E.CLASS('my-cover-page'),
        HEADER(E.CLASS('title'), meta['coverpage-title']),
        E.DIV(E.CLASS('authors'), meta.get('coverpage-author(s)', '')),
        E.DIV(E.CLASS('translator'), meta.get('coverpage-translator', '')),
        E.DIV(E.CLASS('orig-title'), meta.get('coverpage-orig-title', ''))
    )
    if 'series' in meta:
        series_index = meta.get('series_index', '')
        cover.append(E.DIV(E.CLASS('series'),
            meta['series'], ' - (%s)' % series_index if series_index else ''
        ))
    cover.append(E.HR())
    if 'publisher' in meta:
        pubdate = meta.get('pubdate', '')
        cover.append(E.DIV(E.CLASS('publisher'),
            meta['publisher'], ' - %s' % pubdate if pubdate else ''
        ))
    return cover

_css = '''\
p { text-indent: 1.2em; margin: 0.2em; }
.my-cover-page .authors {
   font-size: 150%;
   font-weight: bold;
   margin-bottom: 0.6em;
}'''
def create_head(meta):
    head = E.HEAD(
        E.STYLE(_css),
        E.META(charset='utf8'),
        E.TITLE(meta['title']),
        E.META(name='dc.language', content='sr')
    )
    if meta['authors']:
        head.append(E.META(name='Author', content=meta['authors']))
    if 'publisher' in meta:
        head.append(E.META(name='dc.publisher', content=meta['publisher']))
    if 'pubdate' in meta:
        head.append(E.META(name='dc.date.published', content=meta['pubdate']))
    if 'series' in meta:
        head.append(E.META(name='series', content=meta['series']))
    if 'series_index' in meta:
        head.append(E.META(name='series_index', content=meta['series_index']))
    return head

def create_document():
    meta = extract_metadata()
    head = create_head(meta)

    body = html.Element('body')
    # first get all the (sanitized) content from all the separate html files
    body.extend(get_content_from_files())

    # find the highest header element (alternativelly I could normalize them)
    if len(body.xpath('.//h1')) > 0:
        meta['level1-toc'] = 'h1'
        meta['level2-toc'] = 'h2'
        meta['level3-toc'] = 'h3'
    elif len(body.xpath('.//h2')) > 0:
        meta['level1-toc'] = 'h2'
        meta['level2-toc'] = 'h3'
        meta['level3-toc'] = 'h4'
    else:
        meta['level1-toc'] = 'h3'
        meta['level2-toc'] = 'h4'
        meta['level3-toc'] = 'h5'

    # now insert the cover page before everything
    body.insert(0, create_cover_page(meta))

    doc = html.Element('html')
    doc.append(head)
    doc.append(body)
    return doc, meta

def ebook_convert(format, meta):
    ebook_fname = '%s.%s' % (meta['title'], format)
    cmd = ['ebook-convert', 'single-page-book.html', ebook_fname,
         '--cover', meta['cover-image'],
         '--level1-toc', '//h:%s' % meta['level1-toc'],
         '--level2-toc', '//h:%s' % meta['level2-toc'],
         '--level3-toc', '//h:%s' % meta['level3-toc'],
         "--page-breaks-before=//*[name()='h1' or name()='h2' or name()='h3']"
    ]
    if 'series' in meta:
        cmd.append('--series=%s' % meta['series'])
    if 'series_index' in meta:
        cmd.append('--series-index=%s' % meta['series_index'])
    subprocess.call(cmd)

if __name__ == '__main__':
    doc, meta = create_document()
    tree = etree.ElementTree(doc)

    with open('single-page-book.html', 'wb') as out:
        out.write(html.tostring(tree, method='html', encoding='utf-8',
                                pretty_print=True,
                                doctype='<!DOCTYPE html>'))
    if '--azw3' in sys.argv:
        ebook_convert('azw3', meta)
    if '--epub' in sys.argv:
        ebook_convert('epub', meta)


with open('input.txt', 'r', encoding='utf8') as f:
    n = int(f.readline())
    blocks = []
    for i in range(n):
        blocks.append([-x for x in list(map(int, f.readline().split()))])
    blocks.sort()
    cur = None
    h = 0
    for x in blocks:
        if cur is None or x[0]>cur:
            cur = x[0]
            h+=x[1]
    print(-h)


import json
import yaml
import os
import sys

dname = sys.argv[1]
datasets = f'configs/{dname}'
dpath = 'configs/data/'
os.makedirs(dpath, exist_ok=True)

# open file with dataset names
with open(datasets) as f:
    dsets = yaml.load(f, yaml.Loader)

lib = "root://xrootd-cms.infn.it//"

for year in dsets:
    for dtmc in dsets[year]:
        fdict = {}
        for era in dsets[year][dtmc]:
            fdict[era] = []
            for sample in dsets[year][dtmc][era]["samples"]:
                stream = os.popen(f'dasgoclient -query="file dataset={sample}"')
                fdict[era] += [
                    lib+s.replace('\n', '') for s in stream.readlines()[:10]
                ]
        with open(dpath+year+dtmc+'.yaml', "w") as f:
            yaml.dump(fdict, f)


from __future__ import print_function
import platform
PY3 = False
if platform.python_version().startswith('3'):
    PY3 = True
import sys
import textwrap
import re
import math
from time import sleep
from io import StringIO
from subprocess import (
    check_output,
    CalledProcessError)
if PY3:
    get_input = input
else:
    get_input = raw_input

from . import COMPACT_TITLES
from .color import colors, THEME
from .banner import bannerize
from .album import gen_art
from .api import Client

# TODO
#   windows detect terminal size
#   leverage Radio/Station class to simplify menu "other stations"
#       aka station switch selections
#

def stream_list(streams):
    exploded = []
    name_re = re.compile("name=(.*),url")
    desc_re = re.compile("desc=\"(.*)\",art")
    for s in streams:
        name_m = name_re.search(s)
        desc_m = desc_re.search(s)
        s_exp = {
            'name': name_m.group(1),
            'desc': desc_m.group(1),
            'repr': s
        }
        exploded.append(s_exp)
    return exploded

def print_streams(station, streams, stations):
    (term_w, term_h) = term_wh()
    line_cnt = 0
    if len(streams) == 0:
        print("Exiting, empty station file, delete it and rerun")
        sys.exit(1)
    # set up to pretty print station data
    # get left column width
    name_len = max([len(s['name']) for s in streams]) + 1
    # the first line has the name
    # each subsequent line has whitespace up to column begin mark
    # print the stations
    i = 0
    for s in streams:
        prefix = (" %2d" % i + " ) " + s['name'] +
                  ' ' * (name_len - len(s['name'])))
        (w, h) = print_blockify(
            prefix, THEME['ui_names'],
            s['desc'], THEME['ui_desc'])
        line_cnt += h
        i += 1
    # TODO get rid of hard coded access to the other stations
    prefix = (" %2d" % len(streams) + " ) SomaFM" +
              ' ' * (name_len - len("SomaFM")))
    desc = ("Enter " + str(len(streams)) +
            " or 's' to show SomaFM streams")
    if station == "soma":
        prefix = (" %2d" % len(streams) + " ) Favorites" +
                  ' ' * (name_len - len("Favorites")))
        desc = ("Enter " + str(len(streams)) +
                " or 'f' to show favorite streams")
    (w, h) = print_blockify(
        prefix, THEME['ui_names'],
        desc, THEME['ui_desc'])
    line_cnt += h
    return line_cnt - 1

# \033[A moves cursor up 1 line
# ' ' overwrites text
# '\b' resets cursor to start of line
# if the term is narrow enough, you need to go up multiple lines
def del_prompt(num_chars):
    # determine lines to move up, there is at least 1
    # bc user pressed enter to give input
    # when they pressed Enter, the cursor went to beginning of the line
    (term_w, term_h) = term_wh()
    move_up = int(math.ceil(float(num_chars) / float(term_w)))
    print("\033[A" * move_up + ' ' * num_chars + '\b' * (num_chars), end='')

def term_wh():
    (w, h) = (80, 40)
    try:
        # TODO os agnostic tty size
        # *nix get terminal/console width
        outp = check_output('stty size', shell=True)
    except CalledProcessError:
        return False
    outp.decode('ascii').strip()
    try:
        rows, columns = outp.split()
    except ValueError:
        return (w, h)
    try:
        w = int(columns)
        h = int(rows)
    except ValueError:
        pass
    # print("term width: %d"% width)
    return (w, h)

def read_input():
    try:
        stream_num = get_input("\nPlease select a stream [q to quit]: ")
    except SyntaxError:
        return
    if not stream_num:
        return
    stream_num = str(stream_num).strip().lower()
    if len(stream_num) == 0:
        return
    return stream_num

def try_as_int(stream_num, station, max_val):
    try:
        stream_num = int(stream_num)
    except ValueError:
        return None
    # keys[len] is the other station
    if stream_num < 0 or stream_num > max_val:
        return None
    # the final row is not a stream, but a station change
    if stream_num == max_val:
        if station == 'favs':
            return (None, 'soma')
        # else station == 'soma'
        return (None, 'favs')
    return (stream_num, station)

def get_choice(station, streams):
    """Get user choice of stream to play, or station to change"""
    while True:
        stream_num = read_input()
        if stream_num is None:
            continue
        ctrl_char = stream_num[0]
        if ctrl_char not in ['q', 'e', 's', 'f']:
            retval = try_as_int(stream_num, station, len(streams))
            if retval is None:
                continue
            else:
                return retval
        if (ctrl_char == 'q' or ctrl_char == 'e'):
            return (None, 'q')
        if ctrl_char == 'f':
            return (None, 'favs')
        if ctrl_char == 's':
            return (None, 'soma')
    # should never be here

def ui():
    # set term title
    sys.stdout.write("\x1b]0;" + "~=radio tuner=~" + "\x07")
    c = Client()
    do_another = True
    next_st = 'favs'
    while do_another:
        try:
            next_st = ui_loop(c, next_st)
        except KeyboardInterrupt:
            do_another = False
        if next_st == 'q':
            do_another = False
    # clear term title
    sys.stdout.write("\x1b]0;" + "\x07")

def ui_loop(client, station='favs'):
    """list possible stations, read user input, and call player"""
    # when the player is exited, this loop happens again
    c = client
    if station is None:
        station = c.stations()[0]
    deets = c.station(station)
    streams = stream_list(c.streams(station))
    stations = c.stations()
    # streams.sort()  # put in alpha order
    # ######
    # print stations
    (term_w, term_h) = term_wh()
    banner_txt = deets['ui_name'] + ' Tuner'
    with colors(THEME['ui_banner']):
        (banner, font) = bannerize(banner_txt, term_w)
        b_IO = StringIO(banner)
        b_h = len(b_IO.readlines())
        print(banner)
        b_h += 1
    line_cnt = print_streams(station, streams, stations)
    loop_line_cnt = line_cnt + b_h + 2
    loop_line_cnt += 1
    if term_h > loop_line_cnt:
        print('\n' * (term_h - loop_line_cnt - 1))
    (stream_num, station) = get_choice(station, streams)
    if station == 'q':
        return 'q'
    # no stream given, must have been a station change, refresh list
    if stream_num is None:
        return station
    # ######
    # otherwise stream num specified, so call player
    ##
    # get the stream name only
    to_stream = streams[stream_num]
    # convert the name only into more details
    stream = c.stream(station, to_stream['name'])
    if stream is None:
        print('Error, could not get stream details')
        return station
    display_album(stream['art'])
    display_banner(stream['name'])
    # this play->pause->play loop should never accumulate lines
    # in the output (except for the first Enter they press
    # at a prompt and even then, it's just an empty line)
    i = 0
    do_another = True
    while do_another:
        display_info()
        try:
            if display_metadata(c, stream):
                c.stop()
                do_another = False
        # TODO poll user input for q to stop
        except KeyboardInterrupt:
            c.pause()
            # clear ctrl+c
            print('\b' * 5 + ' ' * 5 + '\b' * 5, end='')
            if COMPACT_TITLES:
                # clear info, name, song
                to_del = term_wh()[0]
                for i in range(3):
                    print("\033[A" + ' ' * to_del + '\b' * to_del, end='')
                sys.stdout.flush()
            prompt = "Paused. Press enter to Resume; m for menu. "
            with colors(THEME['stream_exit_confirm']):
                reloop = get_input(prompt)
            del_prompt(len(prompt) + len(reloop))
            # any key, not just m, takes you to the menu
            if len(reloop) != 0:
                c.stop()
                do_another = False
        i += 1
    # you can't use mpg123's 'pause' cmd (spacebar) bc it'll
    # fail a minute or two after resuming (buffer errors)
    # it literally pauses the music,
    # buffering the stream until unpaused, but the
    # behavior we want is to stop recving the stream
    # (like turning off a radio)
    return station

def display_info():
    msg1 = "Playing stream, enjoy..."
    msg2 = "[ctrl-c for pause/options]"
    with colors(THEME['stream_name_confirm']):
        if term_wh()[0] <= (len(msg1) + len(msg2)):
            print(msg1)
        else:
            print(msg1 + ' ' + msg2)

def display_metadata(client, stream):
    # to test these updates against another stream
    #   without conflicting audio:
    #   mpg123 -f 0 -C -@ <url>
    c = client
    station_name = stream['station']
    stream_name = stream['name']
    if COMPACT_TITLES:
        print()
        print()
    # don't assume that it's not playing from another client
    if not c.play(station_name, stream_name):
        print('Error, already playing %s' % c.status())
        # TODO ignore if playing what was requested
        return False
    showed_name = False
    i = 0
    disp_name = stream['meta_name']
    # disp names of '', like DEF CON Radio will escape loop
    while i < 10 and disp_name is None:
        stream = c.stream(station_name, stream_name)
        disp_name = stream['meta_name']
        sleep(0.5)
        i += 1
    if disp_name is None:
        disp_name = stream_name
    if disp_name is not None and disp_name.strip() != '':
        showed_name = True
        if COMPACT_TITLES:
            print("\033[A" * 2, end='')
        print_blockify(
            THEME['meta_prefix_str'], THEME['meta_prefix'],
            disp_name, THEME['meta_stream_name'],
            wrap=False)
        if COMPACT_TITLES:
            print()
    # wait for initial song
    i = 0
    song_len = 0
    song_name = stream['meta_song']
    # song names of '', like WCPE will escape loop
    while i < 10 and song_name is None:
        stream = c.stream(station_name, stream_name)
        song_name = stream['meta_song']
        sleep(0.5)
        i += 1
    showed_song = False
    if song_name is not None and song_name.strip() != '':
        showed_song = True
        if COMPACT_TITLES:
            print("\033[A", end='')
            if not showed_name:
                print("\033[A", end='')
        song_len = print_blockify(
            THEME['meta_prefix_str'], THEME['meta_prefix'],
            song_name, THEME['meta_song_name'],
            wrap=False)[0]
        if COMPACT_TITLES and not showed_name:
            print()
    # keep polling for song title changes
    do_another = True
    while do_another:
        status = c.status()
        song_now = status['song']
        if (song_now != song_name and
                song_now is not None and song_now.strip() != ''):
            if COMPACT_TITLES:
                if not showed_name:
                    print("\033[A", end='')
                if not showed_song:
                    print("\033[A", end='')
                showed_song = True
                if song_len > 0:
                    del_prompt(song_len)
            song_len = print_blockify(
                THEME['meta_prefix_str'], THEME['meta_prefix'],
                song_now, THEME['meta_song_name'],
                wrap=False)[0]
            song_name = song_now
        is_playing = status['currently_streaming']
        if not is_playing:
            return True
        sleep(1)
    return True

def print_blockify(prefix='', prefix_color='endc',
                   blk='', blk_color='endc',
                   wrap=True):
    # NOTE won't print only prefix without blk
    if len(blk) == 0:
        return (0, 0)
    p_len = len(prefix)
    with colors(prefix_color):
        # sys.stdout.write && flush
        print(prefix, end='')
    (term_w, term_h) = term_wh()
    lines = textwrap.wrap(blk, term_w - p_len)
    max_blk_len = len(lines[0])
    with colors(blk_color):
        print(lines[0])
    if not wrap:
        return (len(prefix) + max_blk_len, 1)
    # prefix only appears on 1st line, justifying remainder
    prefix = ' ' * p_len
    for line in lines[1:]:
        if len(line) > max_blk_len:
            max_blk_len = len(line)
        with colors(blk_color):
            print(prefix + line)
    return (max_blk_len, len(lines))

def display_album(art_url):
    if art_url is None or art_url == '':
        return
    (term_w, term_h) = term_wh()
    art = gen_art(art_url, term_w, term_h)
    if art is None:
        return
    print("ASCII Printout of Station's Logo:")
    print(art)

def display_banner(stream_name):
    unhappy = True
    while unhappy:
        (term_w, term_h) = term_wh()
        font = "unknown"
        with colors(THEME['stream_name_banner']):
            (banner, font) = bannerize(stream_name, term_w)
            b_IO = StringIO(banner)
            b_height = len(b_IO.readlines())
            if term_h > (b_height + 3):  # Playing, Station Name, Song Title
                print('\n' * (term_h - b_height - 2))
            print(banner, end='')
        with colors(THEME['stream_name_confirm']):
            prompt = "Press enter if you like banner"
            prompt += " (font: " + font + "), else any char then enter "
            try:
                happiness = get_input(prompt)
            except SyntaxError:
                happiness = ''
            del_prompt(len(prompt) + len(happiness))
            if len(happiness) == 0:
                unhappy = False
            else:
                print("")  # empty line for pretty factor


class Customer:

    def __init__(self, customer_id=0, name="", phone_num="", email="", birthday="", address=""):
        self.customer_id = customer_id
        self.phone_num = phone_num
        self.email = email
        self.birthday = birthday
        self.name = name
        self.address = address

    def json(self):
        return {
            'id': self.customer_id,
            'name': self.name,
            'phone_num': self.phone_num,
            'email': self.email,
            'date_of_birth': self.birthday,
            'address': self.address
        }

    @staticmethod
    def json_parse(json):
        customer = Customer()
        customer.customer_id = json["id"] if "id" in json else 0
        customer.name = json["name"]
        customer.phone_num = json["phone_num"]
        customer.email = json["email"]
        customer.birthday = json["date_of_birth"]
        customer.address = json["address"]
        return customer

    def __repr__(self):
        return str(self.json())


from django.shortcuts import render
from .forms import regform,emergencyform
from .models import registersos
from police.sms import SMS
from django.http import HttpResponseRedirect
import geocoder
# Create your views here.
def registers(request):
    form = regform(request.POST or None)
    all_forms = registersos.objects.all()
    if form.is_valid():
        cleanphone=form.cleaned_data['phone']
        for i in all_forms:
            if(cleanphone==i.phone):
                return render(request, 'emergency/register.html',{"form": form})
        instance = form.save(commit=False)
        instance.save()
        return HttpResponseRedirect('/')
    return render(request,'emergency/register.html', {"form": form})

def alert(request):
    form = emergencyform()
    if request.method == 'POST':
        form = emergencyform(request.POST)
        if form.is_valid():
            cleanphone = form.cleaned_data['phone']
            reg = registersos.objects.get(phone=cleanphone)
            lat = str(geocoder.ip('me').latlng[0])
            lng = str(geocoder.ip('me').latlng[1])
            SMS("Your friend +91"+ cleanphone+ " is in distress at lat:"+lat+" long:"+ lng, reg.phone1)
            SMS("Your friend +91"+ cleanphone+ " is in distress at lat:"+lat+" long:"+ lng, reg.phone2)
            SMS("Your friend +91"+ cleanphone+ " is in distress at lat:"+lat+" long:"+ lng, reg.phone3)
            return HttpResponseRedirect('/')
    return render(request,'emergency/alert.html', {'form': form})


# Tai Sakuma <tai.sakuma@gmail.com>
import sys
import time, random
import itertools
import threading
import multiprocessing

import pytest

from atpbar import atpbar

try:
    from mantichora import mantichora
except ImportError:
    pytestmark = pytest.mark.skip(reason="mantichora not instaled")

##__________________________________________________________________||
def task(n, name):
    for i in atpbar(range(n), name=name):
        time.sleep(0.0001)

def run_with_mantichora(nprocesses, ntasks, niterations):
    # print(nprocesses, ntasks, niterations)
    with mantichora(nworkers=nprocesses) as mcore:
        for i in range(ntasks):
            name = 'task {}'.format(i)
            n = niterations[i]
            mcore.run(task, n, name)
        returns = mcore.returns()

# @pytest.mark.xfail()
@pytest.mark.parametrize('niterations', [[5, 4, 3], [5, 0, 1], [0], [1]])
@pytest.mark.parametrize('ntasks', [6, 3, 1, 0])
@pytest.mark.parametrize('nprocesses', [10, 6, 2, 1])
def test_mantichora(mock_create_presentation, nprocesses, ntasks, niterations):

    # make niterations as long as ntasks. repeat if necessary
    niterations = list(itertools.chain(*itertools.repeat(niterations, ntasks//len(niterations)+1)))[:ntasks]

    run_with_mantichora(nprocesses, ntasks, niterations)

    print()
    print(mock_create_presentation)

    nreports_expected = sum(niterations) + ntasks
    presentations = mock_create_presentation.presentations

    assert 3 == len(presentations)

    progressbar0 = presentations[0]
    assert nreports_expected == len(progressbar0.reports)
    assert ntasks == len(progressbar0.taskids)
    assert ntasks == progressbar0.nfirsts
    assert ntasks == progressbar0.nlasts

    progressbar1 = presentations[1]
    assert 0 == len(progressbar1.reports)

    progressbar2 = presentations[2]
    assert 0 == len(progressbar2.reports)

##__________________________________________________________________||


#!/usr/bin/env python

import os
import sys
import math

if __name__ == "__main__":
    filepath = 'input.txt'
    result = 0
    with open(filepath) as file:
        content = file.read()
        groups = content.split('\n\n')
        for g in groups:
            answers = g.split('\n')
            for c in set(g.replace('\n','')):
                if all(c in a for a in answers):
                    result += 1

    print(result)


import io

from fastapi import APIRouter, HTTPException
from fastapi.responses import JSONResponse, StreamingResponse

from models.calcul.Moyennes import Moyenne
from models.imports.Results import Result
from models.static_tables.Student import Student
from utils.calcul.calculMethod import calculMoyenne, getDataForExcelMoyenne
from utils.calcul.pdf import merge_pdfs

router = APIRouter()

@router.get("/makeCalcul/{period:str}")
async def madeCalcul(period: str):
    try:
        calculMoyenne(period)
        return JSONResponse("Calcul réalisés")
    except Exception as e:
        raise HTTPException(
            status_code=500, detail=f"Erreur Calcul : {e}")

@router.get("/getPeriodWithData")
async def getPeriod():
    try:
        lst = Result.getDate()
        return lst
    except Exception as e:
        raise HTTPException(
            status_code=500, detail=f"Erreur recup period : {e}")

@router.get("/lastCalculForPeriod/{period:str}")
async def getDateUpdate(period: str):
    try:
        return Moyenne.lastDateCalculPeriod(period)
    except Exception as e:
        raise HTTPException(
            status_code=500, detail=f"Erreur recup period : {e}")

@router.get("/uploadExcelMoyennes/{period:str}")
async def uploadMoyennes(period: str):
    try:
        df = getDataForExcelMoyenne(period)
        excel_content = io.BytesIO()
        df.to_excel(excel_content, index=False)
        excel_content.seek(0)
        return StreamingResponse(content=excel_content,
                                 media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                                 headers={"Content-Disposition": "attachment;filename=resultats.xlsx"})

    except Exception as e:
        raise HTTPException(
            status_code=500, detail=f"Erreur extraction excel : {e}")

@router.get("/uploadPDFMoyennes/{period:str}")
async def uploadMoyennes(period: str):
    df_results, reults = Result.get(period)
    df_students, students = Student.get()
    merged_pdf_content = merge_pdfs(students, df_results, df_students)
    return StreamingResponse(merged_pdf_content, media_type="application/pdf")


from bauhaus import Encoding, proposition, constraint, Or, And

from bauhaus.utils import count_solutions, likelihood
import string
import random
# import pprint
# pp = pprint.PrettyPrinter(indent=4)

# import numpy as np
# import seaborn as sn
# import matplotlib.pyplot as plt

# These two lines make sure a faster SAT solver is used.
from nnf import config

config.sat_backend = "kissat"

# Encoding that will store all of your constraints
E = Encoding()

# To create propositions, create classes for them first, annotated with "@proposition" and the Encoding
@proposition(E)
class BasicPropositions:

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

    def __repr__(self):
        return f"A.{self.data}"

class Hashable:
    def __hash__(self):
        return hash(str(self))

    def __eq__(self, __value: object) -> bool:
        return hash(self) == hash(__value)

    def __repr__(self):
        return str(self)

BOARD_SIZE = 6
# ----------------------------------------- Propositions -----------------------------------------
@proposition(E)
class Boat(Hashable):
    def __init__(self, coords: tuple, length: int, orientation: str):
        self.coords = coords
        self.length = length
        self.orientation = orientation
        self.hits = 0  # New attribute to track hits

    def hit(self, coord):
        if coord in self.coords:
            self.hits += 1
            return True
        return False

    def is_sunk(self):
        return self.hits == self.length

    def __str__(self):
        boat_coords = ""
        for coord in self.coords:
            boat_coords += (f"({coord[0]},{coord[1]}),")
        boat_coords.rstrip(",")
        return f"{boat_coords} + {self.length} + {self.orientation}"

@proposition(E)
class Game(Hashable):
    def __init__(self, boats:tuple):
        self.boats = boats

    def __str__(self):
        game = ""
        for boat in self.boats:
            game+=(f"({boat}, ")
        game.rstrip(", ")
        game+=")"
        return f"{game}"

@proposition(E)
class Guess(Hashable):
    def __init__(self, coords: tuple):
        self.coords = coords

    def __str__(self):
        return f"Guess({self.coords})"

# ----------------------------------------- Variables -----------------------------------------
board_status = [[' ' for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
guesses = []
# Mini-Game will have one boat of lengths 5, 4, and 3
all_games = []
# ----------------------------------------- Create all variations -----------------------------------------

def create_coords(length, orientation, board_size):
    boats = []

    if orientation == "vertical":
        for start in range((board_size + 1) - length):
            for r in range(board_size):
                temp_coords = []
                for c in range(length):
                    temp_coords.append((r, c + start))
                coords = tuple(temp_coords)
                boats.append(Boat(coords, length, orientation))

    elif orientation == "horizontal":
        for start in range((board_size + 1) - length):
            for r in range(board_size):
                temp_coords = []
                for c in range(length):
                    temp_coords.append((r, c + start))
                coords = tuple(temp_coords)
                boats.append(Boat(coords, length, orientation))

    return boats

# Boats by size and orientation
all_boats_5_horizontal = create_coords(5, "horizontal", BOARD_SIZE)
all_boats_5_vertical = create_coords(5, "vertical", BOARD_SIZE)
all_boats_4_horizontal = create_coords(4, "horizontal", BOARD_SIZE)
all_boats_4_vertical = create_coords(4, "vertical", BOARD_SIZE)
all_boats_3_horizontal = create_coords(3, "horizontal", BOARD_SIZE)
all_boats_3_vertical = create_coords(3, "vertical", BOARD_SIZE)

# Boats by size
all_boats_5 = all_boats_5_horizontal + all_boats_5_vertical
all_boats_4 = all_boats_4_horizontal + all_boats_4_vertical
all_boats_3 = all_boats_3_horizontal + all_boats_3_vertical

# All the boats
all_boats = all_boats_5 + all_boats_4 + all_boats_3

# generate all possible variations
for boat1 in all_boats_5:
    for boat2 in all_boats_4:
        for boat3 in all_boats_3:
            all_games.append(Game(tuple([boat1, boat2, boat3])))

# ----------------------------------------- Guessing Stuff -----------------------------------------

def get_user_guess(board_status):
    while True:
        try:
            col_input = input("Enter column (A, B, C, etc.): ").upper()
            row_input = input("Enter row (1, 2, 3, etc.): ")

            col = string.ascii_uppercase.index(col_input)
            row = int(row_input) - 1

            if 0 <= row < BOARD_SIZE and 0 <= col < BOARD_SIZE:
                if board_status[row][col] in ['H', 'M']:
                    print("Spot already guessed. Please choose another spot.")
                else:
                    return (row, col)  # Return row and column as zero-indexed values
            else:
                print("Invalid input. Please enter a valid coordinate.")
        except (ValueError, IndexError):
            print("Invalid input. Please enter a valid coordinate.")

def process_guess(game_board, player_board, x, y):
    """
    Check if the guess is a hit or a miss and update the player's board accordingly.
    """
    if game_board[x][y] == 1:
        player_board[x][y] = 'H'  # Mark as hit on the player's board
        return True
    else:
        player_board[x][y] = 'M'  # Mark as miss on the player's board
        return False

# ----------------------------------------- Generate Random Game -----------------------------------------

BOAT_LENGTHS = [5, 4, 3]  # Lengths of boats to be placed

def is_valid_placement(board, boat_coords):
    for x, y in boat_coords:
        if x < 0 or x >= BOARD_SIZE or y < 0 or y >= BOARD_SIZE or board[x][y] == 1:
            return False
        # Check surrounding cells
        for dx in [-1, 0, 1]:
            for dy in [-1, 0, 1]:
                adj_x, adj_y = x + dx, y + dy
                if 0 <= adj_x < BOARD_SIZE and 0 <= adj_y < BOARD_SIZE and board[adj_x][adj_y] == 1:
                    return False
    return True

def place_boat(board, length, max_attempts=1000):
    attempts = 0
    while attempts < max_attempts:
        orientation = random.choice(['horizontal', 'vertical'])
        if orientation == 'horizontal':
            x = random.randint(0, BOARD_SIZE - 1)
            y = random.randint(0, BOARD_SIZE - length)
            boat_coords = [(x, y + i) for i in range(length)]
        else:
            x = random.randint(0, BOARD_SIZE - length)
            y = random.randint(0, BOARD_SIZE - 1)
            boat_coords = [(x + i, y) for i in range(length)]

        if is_valid_placement(board, boat_coords):
            for coord in boat_coords:
                board[coord[0]][coord[1]] = 1  # Mark the boat position
            return True
        attempts += 1

    return False  # Failed to place the boat

def generate_game():
    board = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
    for length in BOAT_LENGTHS:
        if not place_boat(board, length):
            # Could not place a boat, so start over or handle it differently
            return generate_game()  # This is a simple recursive approach to start over
    return board
# ----------------------------------------- Frequency Map Stuff -----------------------------------------

def is_valid_game(game):
    # Check each pair of boats for separation
    for i in range(len(game.boats)):
        for j in range(i + 1, len(game.boats)):
            if not boats_are_separated(game.boats[i], game.boats[j]):
                return False
    return True

def boats_are_separated(boat1, boat2):
    # check if boats are separated
    for x1, y1 in boat1.coords:
        for x2, y2 in boat2.coords:
            if abs(x1 - x2) <= 1 and abs(y1 - y2) <= 1:
                return False
    return True

def count_boat_occupancy(solutions):
    occupancy_count = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]

    if solutions is None:
        return occupancy_count  # Return empty or default occupancy count

    # for each solution, get each boat coord and add them to frequency map
    for sol in solutions:
        if hasattr(sol, 'boats') and sol:
            for boat in sol.boats:
                for coord in boat.coords:
                    x, y = coord
                    occupancy_count[x][y] += 1

    return occupancy_count

# ----------------------------------------- Display -----------------------------------------

def print_board(board_status):
    # Print column headers
    print(" ", end=" ")
    for col in range(BOARD_SIZE):
        print(chr(ord('A') + col), end=" ")
    print()

    # Print each row
    for row in range(BOARD_SIZE):
        # Print row number
        print(f"{row + 1}", end=" ")

        # Print each cell in the row
        for col in range(BOARD_SIZE):
            print(board_status[row][col], end=" ")
        print()
# ----------------------------------------- Main -----------------------------------------

def build_theory():
    # clear all previous constraints for a new turn
    E.clear_constraints()
    E._custom_constraints.clear()

    valid_games = []
    # First, find all valid games (with separated boats)
    for game in all_games:
        if is_valid_game(game):
            valid_games.append(game)

    # then remove all invalid games(ones that do not align with the guesses)
    for x, y, is_hit in guesses:
        invalid_games = 0
        for game in valid_games:
            # get true or false based on whether there is a boat at guessed location or not
            boat_at_guess = any(coord == (x, y) for boat in game.boats for coord in boat.coords)
            # if there is a hit but not a boat at the guessed hit or...
            # if there is not a hit at a location but there is a boat:
            # remove that corresponding game from the list
            if (is_hit and not boat_at_guess) or (not is_hit and boat_at_guess):
                invalid_games += 1
                valid_games.remove(game)
        # FOR DEBUGGING
        print(f"Guess at ({x},{y}), Hit: {is_hit}, Invalidated Games: {invalid_games}")

    # all remaining games in valid_games should theoretically align with the separation rules and guesses
    for game in valid_games:
        E.add_constraint(Game(game.boats))

    return E

if __name__ == "__main__":
    # generate a random game
    board_status = generate_game()
    print_board(board_status)

    # set up player board
    player_board = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]

    game_over = False
    while not game_over:
        # Recompile the theory with the updated constraints
        A = build_theory()
        A_new = A.compile()
        new_solution = A_new.solve()

        print("\nSatisfiable: %s" % A_new.satisfiable())

        # Count boat occupancy based on the solutions
        print("Frequency Map:")
        occupancy_count = count_boat_occupancy(new_solution)
        for row in occupancy_count:
            print(row)

        print("Your Board:")
        print_board(player_board)  # Print the current board status

        guess_coord = get_user_guess(player_board)  # Get user guessA
        print(guess_coord)
        x, y = guess_coord

        # determine if the guess is a hit or miss
        # and hold those results inside guesses
        result = process_guess(board_status, player_board, x, y)
        guesses.append((x, y, result))

        # need a game stopper
        if result:  # If the guess is a hit
            for boat in all_boats:  # Assuming all_boats is a list of Boat objects
                if boat.hit((x, y)):
                    print(f"Hit at {x}, {y}!")
                    break

            # Check if all boats are sunk
        all_sunk = all(boat.is_sunk() for boat in all_boats)
        if all_sunk:
            print("All boats have been sunk! Game Over.")
            game_over = True


from django.urls import re_path

from products.views import (
    ProductListView,
    ProductDetailSlugView
)

urlpatterns = [
    re_path(r'^$', ProductListView.as_view(), name='products_page_url'),
    re_path(r'^(?P<slug>[\w-]+)/$', ProductDetailSlugView.as_view(), name='product_detail_page_url'),
]


import os,sys
from os.path import isdir,isfile
from os import system
from argparse import ArgumentParser
import glob2
import logging
import subprocess
import pandas as pd
from rdflib import Graph,util,Namespace, Literal,RDFS,RDF, URIRef
from pyld import jsonld
from os.path import join
import json
from urllib.parse import urlparse
import tempfile
import urllib.request as ur
from urllib.parse import urldefrag

import datalad.api as dl
from shutil import copyfile, rmtree

def main(argv):
    parser = ArgumentParser(description='This program will copy augmented BIDS sidecar files back'
                                        'to the original BIDS data and run bidsmri2nidm on it')

    parser.add_argument('-datalad_dir', dest='datalad_dir', required=True, help="Path to directory containing "
                            "datalad datasets to copy BIDS sidecar files to (e.g. /datasets.datalad.org/openfmri)")
    parser.add_argument('-new_sidecar_dir', dest='sidecar_dir', required=True, help="Path to directory containing "
                            "sub-directories for each BIDS dataset with augmented BIDS sidecar files")
    parser.add_argument('-nidm_dir', dest='nidm_dir', required=False, help="If path is included then "
                            "NIDM files will be put in this location under dataset name otherwise they will be"
                            "added to the datalad dataset directly.")
    parser.add_argument('-logfile', dest='logfile', required=True, help="Logfile to track progress and errors")

    args = parser.parse_args()

    # open log file
    logger = logging.getLogger('bidsidecar_to_datset')
    hdlr = logging.FileHandler(args.logfile)
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(logging.INFO)

    # step 1 check directories exist
    if not isdir(args.datalad_dir):
        logger.error("Datalad directory not found: %s" %args.datalad_dir)
        exit(1)
    if not isdir(args.sidecar_dir):
        logger.error("BIDS augmented sidecar directory not found: %s" % args.sidecar_dir)
        exit(1)

    # set working directory to args.datalad_dir
    #os.chdir(args.datalad_dir)

    # step 2 loop through all datasets in args.sidecar_dir
    bids_datasets = [ x for x in os.listdir(args.sidecar_dir) if isdir(join(args.sidecar_dir,x)) ]
    # for each dataset
    for ds in bids_datasets:
        # check if we already have a nidm file created.  If so, skip this dataset
        if isfile(join(args.nidm_dir,ds,"nidm.ttl")):
            logger.info("NIDM file already exists for dataset: %s" %ds)
            continue
        # search recursively in ds looking for json files.  Path should be same as found within the dataset in
        # datalad so it'll be a simple copy.
        json_files = glob2.glob(join(args.sidecar_dir,ds,'**',"*.json"))

        # check of we have json files before we download dataset from datalad
        if len(json_files) == 0:
            continue

        # download datalad dataset and install
        #cmd = ["datalad","get", "-r", join(args.datalad_dir,ds)]
        # replacing with datalad api
        #cmd = ["datalad", "get", "-r", ds]
        try:
        	dl.Dataset(join(args.datalad_dir,ds)).get(recursive=True,jobs=1)
        	logger.info("Running datalad get command on dataset: %s" %join(args.datalad_dir,ds))
        	#ret = subprocess.run(cmd, stdout=subprocess.PIPE, text=True)
        except:
                logger.error("Datalad returned error: %s for dataset %s." %(sys.exc_info()[0], ds))
                logger.info("Trying AWS S3 for dataset: %s" %ds)
                # set up aws command
                cmd = "aws s3 sync --no-sign-request s3://openneuro.org/" + ds + " " + join(args.datalad_dir,ds)
                # execute command
                logger.info(cmd)
                system(cmd)
                # check if aws command downloaded something
                if not isdir(join(args.datalad_dir,ds)):
                    logger.error("Couldn't get dataset from AWS either...")
                    continue

        # now copy each of the json_files into the datalad dataset
        for file in json_files:
            # changing copy to use copyfile from shutil
            #cmd = ["cp",join(args.sidecar_dir,ds,file),join(args.datalad_dir,ds)]
            #if not isdir(join(args.datalad_dir,file[file.find('ds'):])):
            #     os.mkdir(join(args.datalad_dir,ds))
            logger.info("Copying file: source=%s, dest=%s" %(file,join(args.datalad_dir,file[file.find('ds'):])))
            copyfile(file,join(args.datalad_dir,file[file.find('ds'):]))
            #ret = subprocess.run(cmd, stdout=subprocess.PIPE, text=True)

        # make sure it's there
        if not isfile(join(args.datalad_dir,ds,file)):
            logger.error("ERROR: copy of file %s to %s didn't complete successfully!" %(file,join(args.datalad_dir,file[file.find('ds'):])))

        # now run bidsmri2nidm
        # check if output directory exists, if not create it
        if not isdir(join(args.nidm_dir,ds)):
            os.mkdir(join(args.nidm_dir,ds))
        if args.nidm_dir is not None:
            try:
                #cmd = ["bidsmri2nidm","-d",join(args.datalad_dir,ds),"-o",join(args.nidm_dir,ds,"nidm.ttl"),"-bidsignore","-no_concepts"]
                cmd = "bidsmri2nidm -d "+ join(args.datalad_dir,ds) + " -o " + join(args.nidm_dir,ds,"nidm.ttl") + " -bidsignore -no_concepts"
            except:
                logger.error("bidsmri2nidm generated error %s with command: %s" %(sys.exc_info()[0], cmd))
                continue
        else:
            #cmd = ["bidsmri2nidm", "-d", join(args.datalad_dir, ds), "-o", join(args.datalad_dir, ds, "nidm.ttl"),
            #       "-bidsignore","-no_concepts"]
            try:
                cmd = "bidsmri2nidm -d "+ join(args.datalad_dir,ds) + " -o " + join(args.datalad_dir,ds,"nidm.ttl") + " -bidsignore -no_concepts"
            except:
                logger.error("bidsmri2nidm generated error %s with command: %s" %(sys.exc_info()[0], cmd))
                continue
        logger.info("Running command: %s" % cmd)
        #ret = subprocess.run(cmd, stdout=subprocess.PIPE, text=True)
        system(cmd)

        # now remove the datalad dataset to save space
        # replacing with datalad api call
        #cmd = ["datalad", "uninstall", "-r", join(args.datalad_dir, ds)]
        try:
            dl.Dataset(join(args.datalad_dir,ds)).uninstall(recursive=True)
            logger.info("Running datalad uninstall command on dataset: %s" %join(args.datalad_dir,ds))
        except:
                logger.error("Datalad returned error: %s for uninstalling dataset %s." %(sys.exc_info()[0], ds))
                logger.info("Checking if dataset was downloaded from AWS...")
                if isdir(join(args.datalad_dir,ds)):
                    rmtree(join(args.datalad_dir,ds))
                else:
                    continue
        #ret = subprocess.run(cmd, stdout=subprocess.PIPE, text=True)

if __name__ == "__main__":
   main(sys.argv[1:])


#Ejercicio 7, juego
import random
aleatorio=random.randint(0,100)
aux=False
contador=0
while True:
    numero=int(input("Ingrese el número: "))
    contador+=1
    if numero>aleatorio:
        print("No es el número. Digita un numero menor")
    elif numero<aleatorio:
        print("No es el número. Digita un numero mayor")
    else:
        print("Número adivinado. Ha acertado.¡Felicidades!")
        break
print(f"Cantidad de intentos: {contador}")


"""https://www.hackerrank.com/contests/projecteuler/challenges/euler004/problem

This problem is a programming version of Problem 4 from projecteuler.net

A palindromic number reads the same both ways. The smallest 6 digit palindrome made from the product of two 3-digit
numbers is 101101 = 143 * 707.

Find the largest palindrome made from the product of two 3-digit numbers which is less than N.

(101101 < N < 1000000)

"""
import sys
from typing import Optional

sys.stdin = open(__file__.replace('.py', ' - Inputs.txt'))  # Simulate inputs from stdin - remove this on Hackerrank

all_products = []
for x in range(100, 1000):
    for y in range(x, 1000):
        if x * y >= 100000:
            all_products.append(x * y)
all_products.sort(key=lambda product: -product)

def is_pallindrome_int(num: int) -> bool:
    return str(num) == str(num)[::-1]

def find_largest_pallindrome(limit: int) -> Optional[int]:
    try:
        return next(filter(lambda num: num < limit and is_pallindrome_int(num), all_products))
    except StopIteration:
        return None

if __name__ == '__main__':
    #  below from the HackerRank problem:
    t = int(input().strip())
    for a0 in range(t):
        n = int(input().strip())
        #  below is my own.
        print(find_largest_pallindrome(n))


def solution():
    stack=[]
    results=[]
    for index,height in enumerate(towers):
        while stack:
            if stack[-1][0] < height:
                stack.pop()
            else:
                results.append(stack[-1][1])
                break
        if len(stack)==0:
            results.append(0)

        stack.append((height,index+1))

    print(*results)

if __name__ == "__main__":
    with open("input2493.txt","r") as file:
        n=int(file.readline())
        towers=list(map(int,file.readline().split()))

    solution()


import pyblish.api
from openpype.pipeline import (
    PublishValidationError,
    OptionalPyblishPluginMixin
)
from maya import cmds
from openpype.pipeline.publish import RepairAction
from openpype.hosts.maya.api import lib
from openpype.hosts.maya.api.lib import reset_scene_resolution

class ValidateResolution(pyblish.api.InstancePlugin,
                         OptionalPyblishPluginMixin):
    """Validate the render resolution setting aligned with DB"""

    order = pyblish.api.ValidatorOrder
    families = ["renderlayer"]
    hosts = ["maya"]
    label = "Validate Resolution"
    actions = [RepairAction]
    optional = True

    def process(self, instance):
        if not self.is_active(instance.data):
            return
        invalid = self.get_invalid_resolution(instance)
        if invalid:
            raise PublishValidationError(
                "Render resolution is invalid. See log for details.",
                description=(
                    "Wrong render resolution setting. "
                    "Please use repair button to fix it.\n\n"
                    "If current renderer is V-Ray, "
                    "make sure vraySettings node has been created."
                )
            )

    @classmethod
    def get_invalid_resolution(cls, instance):
        width, height, pixelAspect = cls.get_db_resolution(instance)
        current_renderer = instance.data["renderer"]
        layer = instance.data["renderlayer"]
        invalid = False
        if current_renderer == "vray":
            vray_node = "vraySettings"
            if cmds.objExists(vray_node):
                current_width = lib.get_attr_in_layer(
                    "{}.width".format(vray_node), layer=layer)
                current_height = lib.get_attr_in_layer(
                    "{}.height".format(vray_node), layer=layer)
                current_pixelAspect = lib.get_attr_in_layer(
                    "{}.pixelAspect".format(vray_node), layer=layer
                )
            else:
                cls.log.error(
                    "Can't detect VRay resolution because there is no node "
                    "named: `{}`".format(vray_node)
                )
                return True
        else:
            current_width = lib.get_attr_in_layer(
                "defaultResolution.width", layer=layer)
            current_height = lib.get_attr_in_layer(
                "defaultResolution.height", layer=layer)
            current_pixelAspect = lib.get_attr_in_layer(
                "defaultResolution.pixelAspect", layer=layer
            )
        if current_width != width or current_height != height:
            cls.log.error(
                "Render resolution {}x{} does not match "
                "asset resolution {}x{}".format(
                    current_width, current_height,
                    width, height
                ))
            invalid = True
        if current_pixelAspect != pixelAspect:
            cls.log.error(
                "Render pixel aspect {} does not match "
                "asset pixel aspect {}".format(
                    current_pixelAspect, pixelAspect
                ))
            invalid = True
        return invalid

    @classmethod
    def get_db_resolution(cls, instance):
        asset_doc = instance.data["assetEntity"]
        project_doc = instance.context.data["projectEntity"]
        for data in [asset_doc["data"], project_doc["data"]]:
            if (
                "resolutionWidth" in data and
                "resolutionHeight" in data and
                "pixelAspect" in data
            ):
                width = data["resolutionWidth"]
                height = data["resolutionHeight"]
                pixelAspect = data["pixelAspect"]
                return int(width), int(height), float(pixelAspect)

        # Defaults if not found in asset document or project document
        return 1920, 1080, 1.0

    @classmethod
    def repair(cls, instance):
        # Usually without renderlayer overrides the renderlayers
        # all share the same resolution value - so fixing the first
        # will have fixed all the others too. It's much faster to
        # check whether it's invalid first instead of switching
        # into all layers individually
        if not cls.get_invalid_resolution(instance):
            cls.log.debug(
                "Nothing to repair on instance: {}".format(instance)
            )
            return
        layer_node = instance.data['setMembers']
        with lib.renderlayer(layer_node):
            reset_scene_resolution()


import string

def anagrams(s):
    if s == "":
        return [s]
    else:
        ans = []
        for an in anagrams(s[1:]):
            for pos in range(len(an)+1):
                ans.append(an[:pos]+s[0]+an[pos:])
        return ans

def unscrambleWord(anagram):
    anaLst = anagrams(anagram)
    diction = dictionary("words2.txt")
    solutions = []
    for ana in anaLst:
        if diction.has_key(ana):
            solutions.append(ana)

    return list(set(solutions))

def dictionary(wordlist):
    dict = {}
    infile = open(wordlist, "r")
    for line in infile:
        word = line.split("\n")[0]
        dict[word] = 1
    infile.close()
    return dict

wordlist = open("words2.txt","r").read().split("\n")

def getRhymes(word,wordlist):
    word = word.lower()
    results = []
    for i in wordlist:
        if i.lower().endswith(word[-3:]):
            results.append(i)
    return results

def sendmsg(chan, msg,ircsock):
    ircsock.send("PRIVMSG {0} :{1}\n".format(chan, msg))#

def runCommands(channel,nick,commandChar,ircmsg,hostmask,ircsock):
    if ircmsg.find(commandChar+"unscramble ") != -1:
        if len(ircmsg.split(commandChar+"unscramble ")[1].replace(" ","")) > 9:
            sendmsg(channel,"Word too long :C",ircsock)
        else:
            result = unscrambleWord(ircmsg.split(commandChar+"unscramble ")[1].replace(" ",""))
            if len(result) == 0:
                sendmsg(channel,"There were no anagrams of the given text.",ircsock)
            else:
                returned = "Results: "
                index = 0
                for i in result:
                    returned = returned + i + ", "
                    index += 1
                    if index > 10:
                        break
                sendmsg(channel,returned[0:420]+"...",ircsock)

    elif ircmsg.find(commandChar+"anagram ") != -1:
        if len(ircmsg.split(commandChar+"anagram ")[1].replace(" ","")) > 9:
            sendmsg(channel,"Word too long :C",ircsock)
        else:
            result = unscrambleWord(ircmsg.split(commandChar+"anagram ")[1].replace(" ",""))
            if len(result) == 0:
                sendmsg(channel,"There were no anagrams of the given text.",ircsock)
            else:
                returned = "Results: "
                index = 0
                for i in result:
                    returned = returned + i + ", "
                    index += 1
                    if index > 10:
                        break
                sendmsg(channel,returned[0:420]+"...",ircsock)

    elif ircmsg.find(commandChar+"rhyme ") != -1:
        results = getRhymes(ircmsg.split(commandChar+"rhyme ",1)[1] , wordlist)
        if len(results) == 0:
            sendmsg(channel,"There were no rhymes of the given text.",ircsock)
        else:
            returned = "Results: "
            for i in results:
                returned = returned + i + ", "
            sendmsg(channel,returned[0:310]+"...",ircsock)


from swimfunction.global_config.config import config
from swimfunction.data_models import DataSet
from swimfunction.pose_processing.pose_conversion import ANGLE_POSE_SIZE
import numpy

BEHAVIORS = config.getnamedtuple('BEHAVIORS', 'names', 'BEHAVIORS', 'symbols')
PPW = config.getint('BEHAVIOR_ANNOTATION', 'poses_per_window')

class WindowsDataSet(DataSet.DataSet):
    ''' Transforms a series of 1d poses into temporal windows of poses.
    WindowsDataSet only works with 1d (angle or complete-angle) poses,
    not with 2d (coordinate) poses.
    '''
    __slots__ = ['margin']
    WINDOW_SIZE = int(PPW * ANGLE_POSE_SIZE)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.margin = PPW // 2

    ''' Concatenates poses into windows of length POSES_PER_WINDOW
    Example if POSES_PER_WINDOW is 3:
        Input
            poses = [p1, p2, ... , pN]
            behaviors = [b1, b2, ... , bN]
            meta_labels = [m1, m2, ... , mN]
        Becomes
            windows = [p1p2p3, p2p3p4, ... , pN-2pN-1pN]
            labels = [b2, b3, ... , bN-1]
            meta_labels = [m2, m3, ... , mN-1]
    '''
    def from_poses(self, poses, behaviors=None, meta_labels=None):
        if poses is None:
            return self
        n_windows = poses.shape[0] - PPW + 1
        windows = []
        for i in range(n_windows):
            window = poses[i:i+PPW].reshape(PPW * poses.shape[1])
            windows.append(window)
        self.data = numpy.asarray(windows)
        if behaviors is None:
            self.labels = numpy.full(len(self.data), BEHAVIORS.unknown)
        else:
            self.labels = behaviors[self.margin:self.margin+len(self.data)]
        if meta_labels is not None:
            self.meta_labels = self.meta_labels[self.margin:self.margin+len(self.data)]
        return self

    def from_concatenated_poses(self, concatenated_poses, labels=None, meta_labels=None):
        self.data = numpy.asarray(concatenated_poses)
        if labels is None:
            self.labels = numpy.full(len(self.data), BEHAVIORS.unknown)
        else:
            self.labels = labels
        self.meta_labels = meta_labels
        return self

    def get_middle_poses(self):
        ''' Returns the middle pose of the window.
        '''
        pose_length = self.data.shape[-1] // PPW
        middle_poses = self.data[
            :, # all windows
            pose_length*((PPW + 1)//2):pose_length*((PPW + 1)//2)+pose_length
        ]
        return middle_poses

    def to_pose_dataset(self):
        d = self.as_dict()
        d['data'] = self.get_middle_poses()
        return DataSet.DataSet.from_dict(d)

    def reshape_to_WNA(self):
        ''' Reshapes data from (W, N*A) to (W, N, A)
        Where W is number of windows, N is number of poses in a window, A is number of angles in a pose.

        Returns
        -------
        self
            For convenience.
        '''
        if len(self.data.shape) == 3:
            return self
        self.data = self.data.reshape((self.data.shape[0], PPW, self.data.shape[1] // PPW))
        return self

    @staticmethod
    def from_dict(ds_dict):
        ''' Creates a WindowsDataSet from a dict.
        '''
        return WindowsDataSet(
            data=ds_dict['data'] if 'data' in ds_dict else None,
            labels=ds_dict['labels'] if 'labels' in ds_dict else None,
            meta_labels=ds_dict['meta_labels'] if 'meta_labels' in ds_dict else None
        )

    @staticmethod
    def cast(ds):
        return WindowsDataSet(ds.data, ds.labels, ds.meta_labels)

    @staticmethod
    def to_poses(window):
        return window.reshape((PPW, -1))


#!/usr/bin/python3

"""  Python script that takes in a URL, sends a request to the URL and displays
     the body of the response. """

import requests

def recurse(subreddit, hot_list=[], nexT=""):
    headers = {'User-agent': 'Alb4tr02'}
    url = "https://www.reddit.com/r/"+subreddit+"/hot/.json"+nexT
    req = requests.get(url, headers=headers)
    json = req.json()
    if ('error' in json.keys()):
        return None
    for post in json['data']['children']:
        hot_list.append(post['data']['title'])
    if (json['data']['after'] is not None):
        return recurse(subreddit, hot_list, "?after="+json['data']['after'])
    else:
        return hot_list


from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from finalboss.models import User, Reksadana
from finalboss.forms import userForm, reksaDanaForm
from django import forms

def users(request):
    users = User.objects.all()
    usersDict = {'users': users}
    return render(request, 'users.html', context=usersDict)

def userDetail(request, username):
    userDetail = User.objects.get(userName__exact=username)
    return render(request, 'userDetail.html', context={'user': userDetail})

def editProfile(request, username):
    profileDetail = User.objects.get(userName__exact=username)
    form = userForm(instance=profileDetail)
    if request.method == 'POST':
        form = userForm(request.POST, instance=profileDetail)
        if form.is_valid():
            form.save(commit=True)
            return HttpResponseRedirect('../')
        else:
            print('Validation error!')
    return render(request, 'editProfile.html', context={'form': form})

def buyReksaDana(request, username):
    form = reksaDanaForm(initial={'userName': username})
    if request.method == 'POST':
        form = reksaDanaForm(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return HttpResponseRedirect('details')
        else:
            print('Validation Error')
    return render(request, 'buyReksadana.html', context={'form': form, 'username': username})

def detailReksaDana(request, username):
    reksaDanaData = Reksadana.objects.all().filter(userName=username)
    return render(request, 'detailReksaDana.html', context={'reksaDana': reksaDanaData, 'username': username})

def sellReksaDana(request, username, id):
    reksaDanaDetail = Reksadana.objects.get(id__exact=id)
    if request.method == 'POST':
        reksaDanaDetail.delete()
        return HttpResponseRedirect('../details')
    return render(request, 'sellReksaDana.html', context={'reksaDana': reksaDanaDetail, 'username': username})