"""Main classes used at the top level of the wilson package:

`Wilson`: main interface to the wilson package, providing automatic running
and matching in SMEFT and WET

`RGsolution`: Class representing a continuous solution to the
SMEFT and WET RGEs to be used for plotting.
"""

from wilson.run.smeft import SMEFT
from wilson.run.wet import WETrunner
from wilson import parameters
import numpy as np
from math import log, e
from wilson import wcxf
import voluptuous as vol

class ConfigurableClass:
    """Class that provides the functionality to set and get configuration
    options.

    Methods:

    - `set_option`: Set configuration option
    - `get_option`: Show configuration option
    - `set_default_option`: Class method! Set deault configuration option
      affecting only future instances of the class.
    """

    # default config options:
    # dictionary with option name as 'key' and default option value as 'value'
    _default_options = {}

    # option schema:
    # Voluptuous schema defining allowed option values/types
    _option_schema = vol.Schema({})

    def __init__(self):
        self._options = self._default_options.copy()

    @classmethod
    def set_default_option(cls, key, value):
        """Class method. Set the default value of the option `key` (string)
        to `value` for all future instances of the class.

        Note that this does not affect existing instances or the instance
        called from."""
        cls._default_options.update(cls._option_schema({key: value}))

    def set_option(self, key, value):
        """Set the option `key` (string) to `value`.

        Instance method, affects only current instance.
        This will clear the cache."""
        self._options.update(self._option_schema({key: value}))
        self.clear_cache()

    def get_option(self, key):
        """Return the current value of the option `key` (string).

        Instance method, only refers to current instance."""
        return self._options.get(key, self._default_options[key])

class Wilson(ConfigurableClass):
    """Main interface to the wilson package, providing automatic running
    and matching in SMEFT and WET.

    Caching is used for intermediate results.

    Methods:

    - `from_wc`: Return a `Wilson` instance initialized by a `wcxf.WC` instance
    - `load_wc`: Return a `Wilson` instance initialized by a WCxf file-like object
    - `match_run`: Run the Wilson coefficients to a different scale (and possibly different EFT) and return them as `wcxf.WC` instance
    - `set_option`: Set configuration option
    - `get_option`: Show configuration option
    - `set_default_option`: Class method! Set deault configuration option
      affecting only future instances of the class.
    """

    # default config options:
    # dictionary with option name as 'key' and default option value as 'value'
    _default_options = {'smeft_accuracy': 'integrate',
                        'qed_order': 1,
                        'qcd_order': 1,
                        'smeft_matching_order': 0,
                        'smeft_matchingscale': 91.1876,
                        'mb_matchingscale': 4.2,
                        'mc_matchingscale': 1.3,
                        'parameters': {},
                        }

    # option schema:
    # Voluptuous schema defining allowed option values/types
    _option_schema = vol.Schema({
        'smeft_accuracy': vol.In(['integrate','leadinglog']),
        'qed_order': vol.In([0,1]),
        'qcd_order': vol.In([0,1]),
        'smeft_matching_order':  vol.In([0,1]),
        'smeft_matchingscale': vol.Coerce(float),
        'mb_matchingscale': vol.Coerce(float),
        'mc_matchingscale': vol.Coerce(float),
        'parameters': vol.Schema({vol.Extra: vol.Coerce(float)}),
    })

    def __init__(self, wcdict, scale, eft, basis):
        """Initialize the `Wilson` class.

        Parameters:

        - `wcdict`: dictionary of Wilson coefficient values at the input scale.
          The keys must exist as Wilson coefficients in the WCxf basis file.
          The values must be real or complex numbers (not dictionaries with key
          'Re'/'Im'!)
        - `scale`: input scale in GeV
        - `eft`: input EFT
        - `basis`: input basis
        """
        super().__init__()
        self.wc = wcxf.WC(eft=eft, basis=basis, scale=scale,
                          values=wcxf.WC.dict2values(wcdict))
        self.wc.validate()
        self._cache = {}

    def __hash__(self):
        """Return a hash of the `Wilson` instance.
        The hash changes when Wilson coefficient values or options are modified.
        It assumes that `wcxf.WC` instances are not modified after instantiation."""
        return hash((self.wc, frozenset(self._options)))

    @classmethod
    def from_wc(cls, wc):
        """Return a `Wilson` instance initialized by a `wcxf.WC` instance"""
        return cls(wcdict=wc.dict, scale=wc.scale, eft=wc.eft, basis=wc.basis)

    @classmethod
    def load_wc(cls, stream):
        """Return a `Wilson` instance initialized by a WCxf file-like object"""
        wc = wcxf.WC.load(stream)
        return cls.from_wc(wc)

    def _repr_html_(self):
        r_wcxf = self.wc._repr_html_()
        r_wcxf = '\n'.join(r_wcxf.splitlines()[2:])  # remove WCxf heading
        html = "
Wilson coefficients
\n\n"
        html += r_wcxf
        return html

    @property
    def parameters(self):
        """Parameters to be used for running and translation."""
        # start with a copy of the default parameters
        p = parameters.p.copy()
        # overwrite by the user defined parameters, if any
        p.update(self.get_option('parameters'))
        return p

    @property
    def matching_parameters(self):
        """Parameters to be used for the SMEFT->WET matching."""
        # start with a copy of the numerical parameters
        p = self.parameters.copy()
        # properly set 'loop_order' for `match.smeft.match_all`
        p['loop_order'] = self.get_option('smeft_matching_order')
        return p

    def _wetrun_opt(self):
        """Return a dictionary of options to pass to a `run.wet.WETrunner`
        instance."""
        return {'qed_order': self.get_option('qed_order'),
                'qcd_order': self.get_option('qcd_order')}

    def match_run(self, scale, eft, basis, sectors='all'):
        """Run the Wilson coefficients to a different scale
        (and possibly different EFT)
        and return them as `wcxf.WC` instance.

        Parameters:

        - `scale`: output scale in GeV
        - `eft`: output EFT
        - `basis`: output basis
        - `sectors`: in the case of WET (or WET-4 or WET-3), a tuple of sector
          names can be optionally provided. In this case, only the Wilson coefficients
          from this sector(s) will be returned and all others discareded. This
          can speed up the computation significantly if only a small number of sectors
          is of interest. The sector names are defined in the WCxf basis file.
        """
        cached = self._get_from_cache(sector=sectors, scale=scale, eft=eft, basis=basis)
        if cached is not None:
            return cached
        if sectors  == 'all':
            # the default value for sectors is "None" for translators
            translate_sectors = None
        else:
            translate_sectors = sectors
        scale_ew = self.get_option('smeft_matchingscale')
        mb = self.get_option('mb_matchingscale')
        mc = self.get_option('mc_matchingscale')
        if self.wc.basis == basis and self.wc.eft == eft and scale == self.wc.scale:
            return self.wc  # nothing to do
        if self.wc.eft == eft and scale == self.wc.scale:
            wc_out = self.wc.translate(basis, sectors=translate_sectors, parameters=self.parameters)  # only translation necessary
            self._set_cache(sectors, scale, eft, basis, wc_out)
            return wc_out
        if self.wc.eft == 'SMEFT':
            smeft_accuracy = self.get_option('smeft_accuracy')
            if eft == 'SMEFT':
                smeft = SMEFT(self.wc.translate('Warsaw', sectors=translate_sectors, parameters=self.parameters))
                # if input and output EFT ist SMEFT, just run.
                wc_out = smeft.run(scale, accuracy=smeft_accuracy).translate(basis)
                self._set_cache('all', scale, 'SMEFT', wc_out.basis, wc_out)
                return wc_out
            else:
                # if SMEFT -> WET-x: match to WET at the EW scale
                wc_ew = self._get_from_cache(sector='all', scale=scale_ew, eft='WET', basis='JMS')
                if wc_ew is None:
                    if self.wc.scale == scale_ew:
                        wc_ew = self.wc.match('WET', 'JMS', parameters=self.matching_parameters)  # no need to run
                    else:
                        smeft = SMEFT(self.wc.translate('Warsaw', parameters=self.parameters))
                        wc_ew = smeft.run(scale_ew, accuracy=smeft_accuracy).match('WET', 'JMS', parameters=self.matching_parameters)
                self._set_cache('all', scale_ew, wc_ew.eft, wc_ew.basis, wc_ew)
                wet = WETrunner(wc_ew, **self._wetrun_opt())
        elif self.wc.eft in ['WET', 'WET-4', 'WET-3']:
            wet = WETrunner(self.wc.translate('JMS', parameters=self.parameters, sectors=translate_sectors), **self._wetrun_opt())
        else:
            raise ValueError(f"Input EFT {self.wc.eft} unknown or not supported")
        if eft == wet.eft:  # just run
            wc_out = wet.run(scale, sectors=sectors).translate(basis, sectors=translate_sectors, parameters=self.parameters)
            self._set_cache(sectors, scale, eft, basis, wc_out)
            return wc_out
        elif eft == 'WET-4' and wet.eft == 'WET':  # match at mb
            wc_mb = wet.run(mb, sectors=sectors).match('WET-4', 'JMS', parameters=self.matching_parameters)
            wet4 = WETrunner(wc_mb, **self._wetrun_opt())
            wc_out = wet4.run(scale, sectors=sectors).translate(basis, sectors=translate_sectors, parameters=self.parameters)
            self._set_cache(sectors, scale, 'WET-4', basis, wc_out)
            return wc_out
        elif eft == 'WET-3' and wet.eft == 'WET-4':  # match at mc
            wc_mc = wet.run(mc, sectors=sectors).match('WET-3', 'JMS', parameters=self.matching_parameters)
            wet3 = WETrunner(wc_mc, **self._wetrun_opt())
            wc_out = wet3.run(scale, sectors=sectors).translate(basis, sectors=translate_sectors, parameters=self.parameters)
            return wc_out
            self._set_cache(sectors, scale, 'WET-3', basis, wc_out)
        elif eft == 'WET-3' and wet.eft == 'WET':  # match at mb and mc
            wc_mb = wet.run(mb, sectors=sectors).match('WET-4', 'JMS', parameters=self.matching_parameters)
            wet4 = WETrunner(wc_mb, **self._wetrun_opt())
            wc_mc = wet4.run(mc, sectors=sectors).match('WET-3', 'JMS', parameters=self.matching_parameters)
            wet3 = WETrunner(wc_mc, **self._wetrun_opt())
            wc_out = wet3.run(scale, sectors=sectors).translate(basis, sectors=translate_sectors, parameters=self.parameters)
            self._set_cache(sectors, scale, 'WET-3', basis, wc_out)
            return wc_out
        else:
            raise ValueError(f"Running from {wet.eft} to {eft} not implemented")

    def clear_cache(self):
        self._cache = {}

    def _get_from_cache(self, sector, scale, eft, basis):
        """Try to load a set of Wilson coefficients from the cache, else return
        None."""
        try:
            return self._cache[eft][scale][basis][sector]
        except KeyError:
            return None

    def _set_cache(self, sector, scale, eft, basis, wc_out):
        if eft not in self._cache:
            self._cache[eft] = {scale: {basis: {sector: wc_out}}}
        elif scale not in self._cache[eft]:
            self._cache[eft][scale] = {basis: {sector: wc_out}}
        elif basis not in self._cache[eft][scale]:
            self._cache[eft][scale][basis] = {sector: wc_out}
        else:
            self._cache[eft][scale][basis][sector] = wc_out

class RGsolution:
    """Class representing a continuous (interpolated) solution to the
    SMEFT RGEs to be used for plotting."""

    def __init__(self, fun, scale_min, scale_max):
        """Initialize.

        Parameters:

        - fun: function of the scale that is expected to return a
        dictionary with the RGE solution and to accept vectorized input.
        - scale_min, scale_max: lower and upper boundaries of the scale
        """
        self.fun = fun
        self.scale_min = scale_min
        self.scale_max = scale_max

    def plotdata(self, key, part='re', scale='log', steps=50):
        """Return a tuple of arrays x, y that can be fed to plt.plot,
        where x is the scale in GeV and y is the parameter of interest.

        Parameters:

        - key: dicionary key of the parameter to be plotted (e.g. a WCxf
          coefficient name or a SM parameter like 'g')
        - part: plot the real part 're' (default) or the imaginary part 'im'
        - scale: 'log'; make the x steps logarithmically distributed; for
          'linear', linearly distributed
        - steps: steps in x to take (default: 50)
        """
        if scale == 'log':
            x = np.logspace(log(self.scale_min),
                            log(self.scale_max),
                            steps,
                            base=e)
        elif scale == 'linear':
            x = np.linspace(self.scale_min,
                            self.scale_max,
                            steps)
        y = self.fun(x)
        y = np.array([d[key] for d in y])
        if part == 're':
            return x, y.real
        elif part == 'im':
            return x, y.imag

    def plot(self, key, part='re', scale='log', steps=50, legend=True, plotargs={}):
        """Plot the RG evolution of parameter `key`.

        Parameters:

        - part, scale, steps: see `plotdata`
        - legend: boolean, show the legend (default: True)
        - plotargs: dictionary of arguments to be passed to plt.plot
        """
        try:
            import matplotlib.pyplot as plt
        except ImportError:
            raise ImportError("Please install matplotlib if you want to use the plot method")
        pdat = self.plotdata(key, part=part, scale=scale, steps=steps)
        plt.plot(*pdat, label=key, **plotargs)
        if scale == 'log':
            plt.xscale('log')
        if legend:
            plt.legend()


# 3. zadanie: hashmap
# autor: Jana Oravcova
# datum: 1.11.2018
class ChainHashMap:
    class _Item:
        def __init__(self, key, value, next=None):
            self._key, self._value, self._next = key, value, next

        def __repr__(self):
            return repr(self._key) + ':' + repr(self._value)

    #------------------
    def __iter__(self):

        def iterate(current):
            while current.next is not None:
                next = current.next
                yield current
                current = next

        return iterate(self)

    def __init__(self, capacity=11):
        # kazdy prvok je bud None (volne),
        #   alebo je typu _Item (obsahuje key, value a nasledovnika)
        self._table = [None]*capacity
        self.keys=[]
        self.num=[]

    def _hash(self, key):
        return key % len(self._table)

    def valueof(self, key):
        # pre dany key vrati value alebo vyvola KeyError
        for bucket in self._table:
            while bucket:
                if bucket._key == key:
                    return bucket._value
                bucket = bucket._next
        raise KeyError

    def add(self, key, value=None):
        # ak existuje dany key, zmeni value
        # ak neexistuje, do tabulky prida dvojicu key, value
        # ak je tabulka viac ako na 90% obsadena, tabulka sa resize na dvojnasobok + 1
        k = self._hash(key)
        if k not in self.num:
            self.num.append(k)
        else:
            pass

        if key not in self.keys:
            self.keys.append(key)
            new = self._Item(key,value)
            temp = self._table[self._hash(key)]
            if temp is not None:
                new._next = temp
            self._table[self._hash(key)]=new
            item = self._table[self._hash(key)]
            while item:
                item = item._next

        else:
            for bucket in self._table:
                while bucket:
                    if bucket._key==key:
                        bucket._value = value
                    bucket = bucket._next

        if len(self.keys)>0.9*len(self._table):
            self.resize(len(self._table)*2+1)

    def copy(self, table):
        for bucket in self._table:
            if bucket is not None:
                while bucket:
                    table.append(bucket)
                    bucket = bucket._next

        return table

    def resize(self, n):
        old_table = self.copy([])
        self._table = [None]*n
        self.num=[]
        self.keys=[]
        for bucket in old_table:
            while bucket:
                self.add(bucket._key, bucket._value)
                bucket = bucket._next

    def _remove(self, item):
        ...

    def delete(self, key):
        # pre dany kluc vyhodi dvojicu key, value alebo vyvola KeyError
        for bucket in self._table:
            if bucket is not None:

                if bucket._key == key:
                    self._table[self._hash(key)] = bucket._next
                    self.keys.remove(bucket._key)
                    return
                while bucket._next:
                    if bucket._next._key == key:
                        #self._remove(bucket)
                        self.keys.remove(bucket._next._key)
                        temp = bucket._next._next
                        bucket._next = temp
                        return
                    bucket = bucket._next
        raise KeyError

    def __len__(self):
        # vrati pocet klucov
        return len(self.keys)

    def __iter__(self):
        for bucket in self._table:
            while bucket:
                yield bucket._key
                bucket = bucket._next

    def print(self):
        for index, bucket in enumerate(self._table):
            print(index, end=' ')
            while bucket:
                print(bucket, end=' -> ')
                bucket = bucket._next
            print(None)

if __name__ == '__main__':
    a = ChainHashMap(10)
    pole = [(55,'a'),(42,'b'),(15,'c'),(60,'d'),(78,'e'),
            (35,'f'),(22,'g'),(10,'h'),(11,'i'),(15,'j')]
    for key, value in pole:
        a.add(key, value)
    a.print()
    a.delete(78)
    a.print()
##    a = ChainHashMap(5)
##    d = {}
##    for i in 3, 16, 5, 11, 23, 25, 15, 18, 15, 14, 25:
##        try:
##            a.add(i, a.valueof(i) + 1)
##        except KeyError:
##            a.add(i, 1)
##        d[i] = d.get(i, 0) + 1
##    set1 = {(it, a.valueof(it)) for it in a}
##    set2 = set(d.items())
##    print('=== druhy test', set1 == set2)
##    a.print()


import sys
import math
input = sys.stdin.readline

N = int(input())
nums = list(map(int, input().split()))
oprs = list(map(int, input().split()))

data = []

def f(lst, lst2):
  if sum(lst) == 0:
    # print("완성")
    ans = nums[0]
    for i in range(N-1):
        if lst2[i] == 0:
            ans += nums[i+1]
        elif lst2[i] == 1:
            ans -= nums[i+1]
        elif lst2[i] == 2:
            ans *= nums[i+1]
        else:
            ans /= nums[i+1]
            if ans < 0:
                ans = math.ceil(ans)
            else:
                ans = math.floor(ans)
    data.append(ans)
    return

  for i in range(4):
    if lst[i] == 0:
      continue
    idx = lst.copy()
    idx[i] -= 1
    # print(f"{i} 번째 실행 / lst : {lst}, lst2 : {lst2 + [i]}")
    f(idx, lst2 + [i])

f(oprs, [])
# print(f"data : {data}")
print(max(data))
print(min(data))

추문비/단계별/15_백트래킹/7.1S_연산자 끼워넣기.py


from maze import Maze
from window import Window

def main():
    num_rows = 12
    num_cols = 16
    margin = 10
    screen_x = 800
    screen_y = 600
    cell_size_x = (screen_x - 2 * margin) / num_cols
    cell_size_y = (screen_y - 2 * margin) / num_rows
    window = Window(screen_x, screen_y)

    maze = Maze(margin, margin, num_rows, num_cols,
                cell_size_x, cell_size_y, window)

    print("Maze Created")
    solvable = maze.solve()
    print(solvable)
    if not solvable:
        print("Maze cannot be solved")
    else:
        print("Maze solved!")

    window.wait_for_close()

main()


import os, torch, pickle, torch, config, argparse, stats
from torch.utils.data import DataLoader, Dataset
from LangIdentDataset import RTDataset
from tqdm import tqdm
from GRUNetwork import RNN_GRU

def get_args():
    parser = argparse.ArgumentParser(
        description="")
    parser.add_argument("-M", "--trained_model", dest='model_name', type=str,
                        help="select trained model")
    args = parser.parse_args()
    return args

def langencoder(language_codes):
    one_hot_lang = {}
    lang2int = {lang : (num) for num, lang in dict(enumerate(language_codes)).items()}

    return lang2int

def load_model(path, config):
    model = path
    if config['device'] == 'gpu':
        device = torch.device('cuda:01')
    else:
        device = torch.device('cpu')
    with open(path, 'rb') as input_model:
        data = torch.load(input_model)
    trained_model = RNN_GRU(vocab_size=config['vocab_size'], seq_len=100, input_size=100,
               hidden_size=256, num_layers=2, output_size=10, device=device, dropout=0.0)
    trained_model.load_state_dict(data)
    return trained_model

def get_vocab(path):
    with open(path+'vocab.pkl', 'rb')as file:
        vocab = pickle.load(file)
    return vocab

def get_test_loader(path):

    with open(path, 'rb') as file:
        testing_loader = pickle.load(file)

    return testing_loader

def test_model(trained_model, test_data, language_stats, device, language_names_dict, int2lang):
    correct_per_example = 0
    total_predictions = 5000
    incorrect_guesses_per_instance = 0
    percent = 0
    example = 0
    batch_nr = 1
    tenp = 500
    num_characters = []
    count = 0
    for x, y in tqdm(test_data):
        batch_nr +=1
        example +=1
        hidden_layer = trained_model.init_hidden(1).to(device)
        for examples in zip(x,y):
            #total_predictions += 1
            count += 1
            prediction = trained_model(examples[0].unsqueeze(0).to(device), hidden_layer)
            _, indeces = torch.max(prediction[0].data, dim=1)
            characters = len(torch.nonzero(examples[0]))

            if indeces[0].item() == examples[1].item():
                num_characters.append(characters)
                correct_per_example += 1
                stats.update_stats(language_stats, indeces[0].item(), examples[1].item(), int2lang, characters, language_names_dict)
                break
            else:
                #characters = 0
                stats.update_stats(language_stats, indeces[0].item(), examples[1].item(), int2lang, characters, language_names_dict)
                incorrect_guesses_per_instance += 1
                continue

    print(example)
    print(correct_per_example)
    print(incorrect_guesses_per_instance)
    print(count)

    return language_stats

def main():
    print('Testing Model')
    CONFIG = config.get_config('config/config.json')
    if CONFIG['device'] == 'cpu':
        device = torch.device('cpu')
    else:
        device = 'cuda:01'
    language_codes = [i[1] for i in CONFIG['languages']]
    language_names = CONFIG['languages']
    lang2int = langencoder(language_codes)
    int2lang = {num : lang for lang, num in lang2int.items()}
    vocab = get_vocab('vocab/{}_'.format(args.model_name))
    trained_model = load_model('trained_models/{}.pt'.format(args.model_name), CONFIG).to(device)
    test_data = get_test_loader('dataloaders/{}_test_dataset.pkl'.format(args.model_name))
    language_names_dict = {i[1] : i[0] for i in language_names}
    language_stats = stats.gen_empty_stats(int2lang, language_names_dict)
    language_stats = test_model(trained_model, test_data, language_stats, device, language_names_dict, int2lang)
    evaluation = stats.further_analysis(language_stats, language_names,int2lang, language_names_dict)

if __name__ == '__main__':
    args = get_args()
    main()


# Extra3: Create another table to write your users data and save the date as DATETIME (and not varchar).
# I fix only insert, get, isexist functions to accommodate with this new table, didn't have time to make it more generic.
from datetime import datetime, time

from project_first_part.db_connector import open_connection, querydb

# create another users table with datetime
def create_tbl():
    connection = open_connection()
    sql_tbl = "create table IF NOT EXISTS users2 (user_id int not null primary key,user_name varchar(50) not null,creation_date datetime null)"
    try:
        cursor = connection.cursor()
        cursor.execute(sql_tbl)
    finally:
        # Close connection.
        connection.close()

# function will create a new user and return TRUE if success
def create_user(user_id, name):
    is_success = False
    try:
        now = datetime.now()
        sql = "INSERT into QzeMAiiWP6.users2 (user_id, user_name, creation_date) VALUES (%s, '%s', '%s');" % (user_id, name, now)
        cursor = querydb(sql)
        if cursor.rowcount > 0:
            is_success = True
    except Exception as e:
        print("general error when trying to create new user in DB ", e)
    finally:
        cursor.close()
        return is_success

# internal function for debug, will return all users from db
def print_all_users():
    try:
        sql = "SELECT * FROM QzeMAiiWP6.users2;"
        cursor = querydb(sql)
        for row in cursor:
            print(row)
    finally:
        cursor.close()

# function will return TRUE if user exist in the table
def is_id_exist(user_id):
    isexist = False
    try:
        sql = "SELECT * FROM QzeMAiiWP6.users2 where user_id = %s;" % user_id
        cursor = querydb(sql)
        if cursor.rowcount > 0:
            isexist = True
    except Exception as e:
        print("general error when trying to get user from DB ", e)
    finally:
        cursor.close()
        return isexist

def main():
    id = 1
    name = 'p'

    # test the new table
    create_tbl()
    # check if id already exist in db
    if not is_id_exist(id):
        # create a new user in the new table
        is_success = create_user(id, name)
        if is_success:
            print_all_users()
    else:
        print("user already exist")

if __name__ == '__main__':
    main()


def child_begin_handler(self,scache,*args):
        '''
            _creat_child_desc
            update depth,parent_breadth_path,parent_path,sib_seq,path,lsib_path,rsib_path,lcin_path,rcin_path
        '''
        pdesc = self.pdesc
        depth = scache.depth
        sib_seq = self.sib_seq
        sibs_len = self.sibs_len
        pdesc_level = scache.pdesc_level
        desc = copy.deepcopy(pdesc)
        desc = reset_parent_desc_template(desc)
        desc['depth'] = depth
        desc['parent_breadth_path'] = copy.deepcopy(desc['breadth_path'])
        desc['sib_seq'] = sib_seq
        desc['parent_path'] = copy.deepcopy(desc['path'])
        desc['path'].append(sib_seq)
        update_desc_lsib_path(desc)
        update_desc_rsib_path(desc,sibs_len)
        if(depth == 1):
            pass
        else:
            update_desc_lcin_path(desc,pdesc_level)
            update_desc_rcin_path(desc,sibs_len,pdesc_level)
        return(desc)


import numpy as np
import pandas as pd

rho = 1.22
g = 9.81
Area = 2.3
Mass = 1000
trails = 6

# Enter your own Spreadsheet name
velocity = pd.read_csv("Untitled 1.csv")
velocity_matrix = velocity.iloc[:,1:]
time_matrix = velocity.iloc[:,0]

#Finding average
velocity_avg = np.nanmean(velocity_matrix, axis=1)

#converting km/h to m/s
velocity_act = velocity_avg/3.6

time_diff = np.empty((np.size(time_matrix),))
for i in range(len(time_matrix)):
    if i == 0:
        time_diff[i] = 0
    else:
        time_diff[i] = time_matrix[i] - time_matrix[i-1]

def predict_velocity(vel_start, size, weights, t_diff):
    temp_ = np.empty((size*2,))
    velocity_ = np.empty((size,))
    for i in range(size*2):
        if i==0:
            temp_[0] = vel_start
        else:
            acc = -(Area*0.5*rho*weights[0]/Mass)*(temp_[i-1]**2) - weights[1]*g
            fin_vel = temp_[i-1] + acc*t_diff
            temp_[i] = fin_vel

    key=0
    for j in range(0,size*2,2):
        velocity_[key] = temp_[j]
        key = key + 1
    return(velocity_)

def gradient_descent(vel_cal, initial_weights, lrn_rate, conv_fac):
    converged = False
    weights = np.array(initial_weights)
    Epoch = 0
    while(not converged):
        grad_sum_squares = 0
        Epoch = Epoch + 1
        for i in range(len(weights)):

            v_pred = predict_velocity(vel_cal[0],np.size(vel_cal),weights,time_diff[1]/2)

            errors = v_pred - vel_cal
            if i ==0:
                temp = -(Area*0.5*rho/Mass)*(time_diff[1]/2)
                print(temp)
                print(v_pred)
                print(errors)
                derivative = np.dot(2*errors, temp*(v_pred**2))
                print(derivative)
            elif i == 1:
                derivative = np.sum(2*errors*(-g*time_diff[1]/2))
                print(derivative)
            weights[i] = weights[i] - (lrn_rate * derivative)
            grad_sum_squares = grad_sum_squares + derivative**2

        grad_mag = np.sqrt(grad_sum_squares)
        print("---------------------------------------------------------------")
        print("Epoch = " + str(Epoch))
        print("Weights = "+ str(weights))
        print("Error = " + str(grad_mag))
        if(grad_mag < conv_fac):
            converged = True
    return weights, grad_mag


# import necessary packages
import cv2
import numpy as np
import mediapipe as mp
import tensorflow as tf
from tensorflow.keras.models import load_model

from djitellopy import Tello

# initialize mediapipe
mpHands = mp.solutions.hands
hands = mpHands.Hands(max_num_hands=1, min_detection_confidence=0.7)
mpDraw = mp.solutions.drawing_utils

# Load the gesture recognizer model
model = load_model('mp_hand_gesture')

# Load class names
f = open('gesture.names', 'r')
classNames = f.read().split('\n')
f.close()
print(classNames)

w, h = 360, 240
startCounter = 0  # for no Flight 1   - for flight 0

def move(className: str, myDrone):
    udv = 0  # up down velocity
    fbv = 0  # for back velocity
    speed = 20
    if className == "okay":
        myDrone.land()
        return
    elif className == "thumbs up" or className == "call me":
        udv = speed
    elif className == "thumbs down":
        udv = -speed
    elif className == "fist":
        fbv = speed
    elif className == "stop" or className == "live long":
        fbv = -speed
    elif className == "peace":
        myDrone.flip('r')
        return

    myDrone.up_down_velocity = udv
    myDrone.for_back_velocity = fbv
    if myDrone.send_rc_control:
        myDrone.send_rc_control(myDrone.left_right_velocity,
                                myDrone.for_back_velocity,
                                myDrone.up_down_velocity,
                                myDrone.yaw_velocity)
    return

def initializeTello():
    myDrone = Tello()
    myDrone.connect()
    myDrone.for_back_velocity = 0
    myDrone.left_right_velocity = 0
    myDrone.up_down_velocity = 0
    myDrone.yaw_velocity = 0
    myDrone.speed = 0
    myDrone.streamoff()
    myDrone.streamon()
    print(myDrone.get_battery())
    return myDrone

def telloGetFrame(myDrone, w=360, h=240):
    myFrame = myDrone.get_frame_read()
    myFrame = myFrame.frame
    img = cv2.resize(myFrame, (w, h))
    return img

myDrone = initializeTello()

while True:
    # Flight
    if startCounter == 0:
        myDrone.takeoff()
        myDrone.move_up(20)
        startCounter = 1
    # Step 1
    frame = telloGetFrame(myDrone, w, h)
    # if myDrone.get_height() < 15:
    #     myDrone.land()
    #     break

    x, y, c = frame.shape

    # Flip the frame vertically
    frame = cv2.flip(frame, 1)
    framergb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    # Get hand landmark prediction
    result = hands.process(framergb)

    # print(result)

    className = ''

    # post process the result
    if result.multi_hand_landmarks:
        landmarks = []
        for handslms in result.multi_hand_landmarks:
            for lm in handslms.landmark:
                # print(id, lm)
                lmx = int(lm.x * x)
                lmy = int(lm.y * y)

                landmarks.append([lmx, lmy])

            # Drawing landmarks on frames
            mpDraw.draw_landmarks(frame, handslms, mpHands.HAND_CONNECTIONS)

        # Predict gesture
        prediction = model.predict([landmarks])
        # print(prediction)
        classID = np.argmax(prediction)
        className = classNames[classID]
    move(className, myDrone)

    # show the prediction on the frame
    cv2.putText(frame, className, (10, 50), cv2.FONT_HERSHEY_SIMPLEX,
                   1, (0, 0, 255), 2, cv2.LINE_AA)
    cv2.putText(frame, "Battery: " + str(myDrone.get_battery()), (10, 200), cv2.FONT_HERSHEY_SIMPLEX,
                0.33, (255, 0, 0), 1, cv2.LINE_AA)

    # Show the final output
    cv2.imshow("Output", frame)

    if cv2.waitKey(1) == ord('q'):
        myDrone.land()
        print("battery: " + str(myDrone.get_battery()))
        break

# release the webcam and destroy all active windows
cap.release()

cv2.destroyAllWindows()


#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

from heatclient import exc
import keystoneclient

from heat_integrationtests.functional import functional_base

class ServiceBasedExposureTest(functional_base.FunctionalTestsBase):
    # NOTE(pas-ha) if we ever decide to install Sahara on Heat
    # functional gate, this must be changed to other not-installed
    # but in principle supported service
    unavailable_service = 'Sahara'
    unavailable_template = """
heat_template_version: 2015-10-15
resources:
  not_available:
    type: OS::Sahara::NodeGroupTemplate
    properties:
      plugin_name: fake
      hadoop_version: 0.1
      flavor: m1.large
      node_processes: []
"""

    def setUp(self):
        super(ServiceBasedExposureTest, self).setUp()
        # check that Sahara endpoint is available
        if self._is_sahara_deployed():
            self.skipTest("Sahara is actually deployed, "
                          "can not run negative tests on "
                          "Sahara resources availability.")

    def _is_sahara_deployed(self):
        keystone = self.identity_client
        try:
            keystone.service_catalog.url_for(
                attr='region',
                filter_value=self.conf.region,
                service_type='data-processing',
                endpoint_type='publicURL')
        except keystoneclient.exceptions.EndpointNotFound:
            return False
        return True

    def test_unavailable_resources_not_listed(self):
        resources = self.client.resource_types.list()
        self.assertFalse(any(self.unavailable_service in r.resource_type
                             for r in resources))

    def test_unavailable_resources_not_created(self):
        stack_name = self._stack_rand_name()
        ex = self.assertRaises(exc.HTTPBadRequest,
                               self.client.stacks.create,
                               stack_name=stack_name,
                               template=self.unavailable_template)
        self.assertIn('ResourceTypeUnavailable', ex.message)
        self.assertIn('OS::Sahara::NodeGroupTemplate', ex.message)


import time
import tasks

COMMANDS = {
    '/new': 'COMMAND_NEW',
    '/tasks': 'COMMAND_TASKS',
    '/closed_tasks': 'COMMAND_CLOSED_TASKS',
    '/close': 'COMMAND_CLOSE'
}

class UserState:

    def __init__(self, user_id, state):
        self._user_id = user_id
        if state in COMMANDS:
            self._state = COMMANDS[state]
            self.is_terminated = False
        else:
            self.is_terminated = True
        self.reply_text = ''

    def process_state(self, msg):

        if self.is_terminated:
            return

        if self._state == 'COMMAND_NEW':
            self._state = 'WAIT_FOR_TITLE'
            self.reply_text = 'Пришли текст задачи'
            return

        if self._state == 'WAIT_FOR_TITLE':
            self._state = 'CONFIRM_EDITING'
            self._task = tasks.create_task(self._user_id, msg)
            self.reply_text = 'Задача создана. Добавить описание и напоминание?'
            return

        if self._state == 'CONFIRM_EDITING':
            if msg.lower() in ('нет', 'no', '-'):
                self.is_terminated = True
                self.reply_text = ''
            if msg.lower() in ('да', 'yes', '+'):
                self._state = 'SET_DESCRIPTION'
                self.reply_text = 'Добавь описание или пришли "-"'
            return

        if self._state == 'SET_DESCRIPTION':
            if msg != '-':
                tasks.update_field(self._user_id, self._task, 'DESCRIPTION', msg)
            self._state = 'SET_REMINDER'
            self.reply_text = 'Напиши дату и время напоминания (по Москве) в формате ДД.ММ.ГГГГ ЧЧ:ММ или пришли "-"'
            return

        if self._state == 'SET_REMINDER':
            if msg != '-':
                try:
                    reminder_timestamp = str(int(time.mktime(time.strptime(msg + ' +0300', '%d.%m.%Y %H:%M %z'))))
                except ValueError:
                    self.reply_text = 'Дата и время не распознаны. Напиши дату и время напоминания в формате ДД.ММ.ГГГГ ЧЧ:ММ или пришли "-"'
                    return
                tasks.update_field(self._user_id, self._task, 'REMIND_TS', reminder_timestamp)
            self.is_terminated = True
            self.reply_text = 'Задача создана'
            return

        if self._state == 'COMMAND_TASKS':
            self.is_terminated = True
            task_list = tasks.get_task_list(self._user_id)
            self.reply_text = task_list
            return

        if self._state == 'COMMAND_CLOSED_TASKS':
            self.is_terminated = True
            task_list = tasks.get_task_list(self._user_id, mode='closed')
            self.reply_text = task_list
            return

        if self._state == 'COMMAND_CLOSE':
            self._state = 'CHOOSE_TASK'
            head = 'Введи номер выполненной задачи или "-". Актуальные задачи:\n\n'
            task_list = tasks.get_task_list(self._user_id)
            self.reply_text = head + task_list
            return

        if self._state == 'CHOOSE_TASK':
            if msg != '-':
                try:
                    task_id = int(msg)
                except ValueError:
                    self.reply_text = 'Нет адачи с таким номером. Введи номер выполненной задачи или "-"'
                    return
                close_result = tasks.update_field(self._user_id, task_id, 'STATUS', 'CLOSED')
                if close_result == 0:
                    self.reply_text = 'Нет адачи с таким номером. Введи номер выполненной задачи или "-"'
                    return
                self.reply_text = 'Задача выполнена. Ура!'
            self.is_terminated = True


from data_process import cleanData
import numpy as np
import tensorflow as tf

cleanData = np.array(cleanData)

# spliting data
X_train = cleanData[:int(0.9 * len(cleanData)), :-1]
Y_train = cleanData[:int(0.9 * len(cleanData)), -1]

temp = []
for i in Y_train:
    temp.append([1,0]) if i == 2 else temp.append([0,1])

Y_train = np.array(temp)

X_test = cleanData[int(0.9 * len(cleanData)):, :-1]
Y_test = cleanData[int(0.9 * len(cleanData)):, -1]

temp = []
for i in Y_test:
    temp.append([1,0]) if i == 2 else temp.append([0,1])

Y_test = np.array(temp)

X = tf.placeholder(tf.float32, [None, 4], name="Input")

W1 = tf.Variable(tf.truncated_normal([4, 50], stddev=0.1), name="W1")
b1 = tf.Variable(tf.zeros([50]), name="B1")

W2 = tf.Variable(tf.truncated_normal([50, 2], stddev=0.1), name="W2")
b2 = tf.Variable(tf.zeros([2]), name="B2")

with tf.name_scope("First_Layer") as scope:
    l1 = tf.nn.leaky_relu(tf.matmul(X, W1) + b1)

tf.summary.histogram("weights1", W1)
tf.summary.histogram("biases1", b1)

with tf.name_scope("Second_Layer") as scope:
    l2 = tf.matmul(l1, W2) + b2

tf.summary.histogram("weights2", W2)
tf.summary.histogram("biases2", b2)

with tf.name_scope("Output") as scope:
    Y = tf.nn.softmax(l2)

Y_ = tf.placeholder(tf.float32, [None, 2], name="labels")

# cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=l2,
#                                                         labels=Y_)
# cross_entropy = tf.reduce_mean(cross_entropy)*613

cross_entropy = -tf.reduce_sum(Y_*tf.log(Y))

is_correct = tf.equal(tf.argmax(Y, 1), tf.argmax(Y_, 1))
accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))

tf.summary.scalar("cost_train", cross_entropy)
tf.summary.scalar("acc_train", accuracy)

learning_rate = 0.00003
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)

merged_summary_op = tf.summary.merge_all()

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    writer = tf.summary.FileWriter('./log', graph=sess.graph)

    #500 epochs
    for i in range(500):
        acc, ce = sess.run([accuracy, cross_entropy], feed_dict={X: X_train,
                                                                 Y_: Y_train})
        if i%10 == 0:
            print("Accuracy train:", acc, "Train loss", ce)

        acc, ce = sess.run([accuracy, cross_entropy], feed_dict={X: X_test,
                                                                 Y_: Y_test})
        if i%10 == 0:
            print("Accuracy test:", acc, "Test loss", ce)

        _, summary = sess.run([optimizer, merged_summary_op], feed_dict={X: X_train, Y_: Y_train})
        writer.add_summary(summary, i * 613 + i)


from django.core.mail import send_mail

def send(user_email, user_name):
    send_mail(
        'Добро пожаловать на Lemon',
        f'Ваша учетная запись {user_name} была успешно зарегистрирована',
        'LemonSendMes@gmail.com',
        [user_email],
        fail_silently=False,
    )


# -*- coding: utf-8 -*-
import numpy as np

import geatpy as ea

class ZDT5(ea.Problem):  # 继承Problem父类

    def __init__(self, M=None, Dim=None):  # M : 目标维数；Dim : 决策变量维数
        name = 'ZDT5'  # 初始化name（函数名称，可以随意设置）
        M = 2  # 初始化M（目标维数）
        maxormins = [1] * M  # 初始化maxormins（目标最小最大化标记列表，1：最小化该目标；-1：最大化该目标）
        Dim = 11  # 初始化Dim（决策变量维数）
        varTypes = [1] * Dim  # 初始化varTypes（决策变量的类型，0：实数；1：整数）
        lb = [0] * Dim  # 决策变量下界
        ub = [30] + [5] * (Dim - 1)  # 决策变量上界
        lbin = [1] * Dim  # 决策变量下边界（0表示不包含该变量的下边界，1表示包含）
        ubin = [1] * Dim  # 决策变量上边界（0表示不包含该变量的上边界，1表示包含）
        # 调用父类构造方法完成实例化
        ea.Problem.__init__(self,
                            name,
                            M,
                            maxormins,
                            Dim,
                            varTypes,
                            lb,
                            ub,
                            lbin,
                            ubin)

    def evalVars(self, Vars):  # 目标函数
        v = np.zeros(Vars.shape)
        v[np.where(Vars < 5)] += 2
        v[np.where(Vars == 5)] = 1
        ObjV1 = 1 + Vars[:, 0]
        g = np.sum(v[:, 1:], 1)
        h = 1 / ObjV1
        ObjV2 = g * h
        f = np.array([ObjV1, ObjV2]).T
        return f

    def calReferObjV(self):  # 设定目标数参考值（本问题目标函数参考值设定为理论最优值，即“真实帕累托前沿点”）
        ObjV1 = np.arange(1, 32)
        ObjV2 = (self.Dim + 39) / 5 / ObjV1
        referenceObjV = np.array([ObjV1, ObjV2]).T
        return referenceObjV


from numpy import *
import analysis
from pylab import *

def labelings_from_partitions():
    txt = open("set_partitions.txt",'r').read()
    sets = eval(txt.replace("\r\n"," "))
    labelings = -1*ones((115975,10),dtype=uint8)
    for k in range(len(sets)):
        l = sets[k]
        for i in range(len(l)):
            s = l[i]
            if type(s) != tuple:
                s = tuple([s])
            for j in range(len(s)):
                labelings[k,s[j]-1] = i
    savetxt('labelings.txt',labelings,fmt="%i")

def compute_entropy(labelings,lnp):
    N,T = labelings.shape
    ent = zeros(T)
    for t in range(T):
        possible = unique(labelings[:,t])
        p = zeros(possible.shape[0])
        for i in range(possible.shape[0]):
            p[i] = sum(exp(lnp)[labelings[:,t]==possible[i]])
        p = p / sum(p)
        l = log2(p)
        l[l==-inf]=0
        ent[t] = -sum(p*l)
    return ent

def compute_kl(all_labels,lnps,samples):
    """Compute KL divergence between the discrete distribution with
    atoms all_labels and (log-)weights lnps, and the equally weighted
    samples in samples."""
    p1 = exp(lnps)
    # use small data type for efficiency
    all_labels = array(all_labels,dtype=uint8)
    samples = array(samples,dtype=uint8)
    for i in range(samples.shape[0]):
        samples[i,:] = analysis.map_labels(samples[i,:])
    samples = array(samples,dtype=uint8)

    p2 = zeros_like(p1)
    N = p1.shape[0]
    kl1 = 0.
    kl2 = 0.
    for i in range(N):
        p2[i] = sum(all(samples==all_labels[i,:],1))/float(samples.shape[0])
    return (p2,cross_entropy(p2,p1)-cross_entropy(p2,p2))

def plot_probs(labelings,probs,num=10):
    idx = argsort(probs)
    mat = labelings[idx[-num:],:]
    ax = subplot(1,2,1)
    #axis('image')
    pcolor(mat,cmap=cm.binary)
    grid()
    setp(gca(), yticklabels=[])
    title('Labelings')
    ylabel('Labeling')
    xlabel('Time step')
    subplot(1,2,2,sharey=ax)
    barh(arange(num),probs[idx[-num:]])
    grid()
    setp(gca(), yticklabels=[])
    title('Prior probability')
    xlabel('p(labeling)')
    F = gcf()
    F.set_size_inches(6,3)
    subplots_adjust(0.1,0.15,0.95,0.9,0.1,0.2)

def cross_entropy(p1,p2):
    l2 = log2(p2)
    l2[l2==-inf] = 0
    return -sum(p1*l2)

def main():
    labels = loadtxt('labelings.txt')

if __name__ == "__main__":
    main()


from AddBook import *
from DeleteBooks import *
from ViewBooks import *
from IssueBook import *
from ReturnBook import *

app = customtkinter.CTk()
app.title("Library")
app.minsize(width=400, height=400)
app.geometry("600x500")
app.resizable(FALSE, FALSE)
app.config(bg = "#4682A9")

font1= ("Arial", 25, "bold")
font2 = ("Arial", 20, "bold")

id_label = customtkinter.CTkLabel(app, font=font1, text = "Welcome to Library", text_color= "#fff", bg_color="#4682A9")
id_label.place(x=180, y=100)

add_button = customtkinter.CTkButton(app, command = addBook, font = font2, text_color="#fff", text = "Add Book details", fg_color= "#164B60", hover_color= "#749BC2", bg_color="#4682A9", cursor ="hand2", corner_radius=15, width=200)
add_button.place(x=180, y=180)

delete_book = customtkinter.CTkButton(app,command=deleteBook, font = font2, text_color="#fff", text = "Delete Book", fg_color= "#164B60", hover_color= "#749BC2", bg_color="#4682A9", cursor ="hand2", corner_radius=15, width=200)
delete_book.place(x=180, y=230)

view_book = customtkinter.CTkButton(app, command=View, font = font2, text_color="#fff", text = "View Book List", fg_color= "#164B60", hover_color= "#749BC2", bg_color="#4682A9", cursor ="hand2", corner_radius=15, width=200)
view_book.place(x=180, y=280)

issue_book = customtkinter.CTkButton(app, command=issueBook, font = font2, text_color="#fff", text = "Issue Book", fg_color= "#164B60", hover_color= "#749BC2", bg_color="#4682A9", cursor ="hand2", corner_radius=15, width=200)
issue_book.place(x=180, y=320)

return_book = customtkinter.CTkButton(app, command = returnBook, font = font2, text_color="#fff", text = "Return Book", fg_color= "#164B60", hover_color= "#749BC2", bg_color="#4682A9", cursor ="hand2", corner_radius=15, width=200)
return_book.place(x=180, y=370)

app.mainloop()


from rest_framework import serializers
from usermedia.models import UserMedia
from account.serializers.profile import UserProfileSerializer

class UserImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserMedia
        fields = [
            'id',
            'image',
            'title',
            'is_main',
            'get_small_image_url'
        ]


# Solution
def bfs_search(root_node, search_value):
    visited = set()                           # Sets are faster while lookup. Lists are faster to iterate.
    queue = [root_node]

    while len(queue) > 0:
        current_node = queue.pop(0)
        visited.add(current_node)

        if current_node.value == search_value:
            return current_node

        for child in current_node.children:
            if child not in visited:          # Lookup
                queue.append(child)


import mimetypes
from uuid import uuid4

import magic
from azure.storage.blob import BlobClient, ContentSettings
from fastapi import APIRouter, Depends, File, UploadFile, status
from pydantic import HttpUrl

from app import models
from app.api import deps
from app.api.api_v1.exceptions import ForbiddenFiletypeException
from app.core.config import settings

router = APIRouter()

@router.post(
    "/upload",
    name="Upload media",
    response_model=HttpUrl,
    status_code=status.HTTP_200_OK,
)
def upload(
    file: UploadFile = File(...),
    current_user: models.User = Depends(deps.get_current_user),
):
    """
    Upload a video or image as a BLOB and return the URL of the uploaded file.

    - `file`: the file to be uploaded
    """
    # get true mimetype of file
    mime = magic.from_buffer(file.file.read(2048), mime=True)
    file.file.seek(0)

    # pick correct storage container
    if mime.startswith("image"):
        container = "images"
    elif file.content_type.startswith("video"):
        container = "videos"
    else:
        raise ForbiddenFiletypeException

    # upload file with a generated filename and the proper file extension
    blob = BlobClient.from_connection_string(
        conn_str=settings.AZURE_STORAGE_CREDENTIALS,
        container_name=container,
        blob_name=uuid4().hex + mimetypes.guess_extension(mime),
    )
    metadata = {"user_uid": current_user.uid}
    content_settings = ContentSettings(content_type=mime)
    blob.upload_blob(file.file, metadata=metadata, content_settings=content_settings)

    return blob.url


import unittest
import numpy as np

from taxonomy import Taxonomy

class TestTaxonomy(unittest.TestCase):
    def test_make_taxonomy(self):
        """
        Test that it can make a taxonomy."
        """
        tax = Taxonomy("fixtures/taxonomy_fixture.csv")
        self.assertIsNotNone(tax)

    def test_taxonomy_grafts_life(self):
        """
        Test that the taxonomy grafts the life node and that
        the life node has 5 children.
        """
        tax = Taxonomy("fixtures/taxonomy_fixture.csv")
        self.assertIs(len(tax.life.children), 5)

    def test_taxonomy_human_branch(self):
        """
        Test that the taxonomy has a human node, and that the
        human branch has the expected taxonomy. Note this test
        may fail if the provided taxonomy drifts.
        """
        tax = Taxonomy("fixtures/taxonomy_fixture.csv")
        human_node = tax.nodes_by_taxon_id[43584]
        self.assertIsNotNone(human_node)

        human_ancestry = []

        node_id = human_node.taxon_id
        node = human_node
        while node is not tax.life:
            human_ancestry.append(node_id)

            node_id = node.parent
            node = tax.nodes_by_taxon_id[node_id]
        human_ancestry = list(reversed(human_ancestry))

        self.assertListEqual(
            human_ancestry,
            [
                1,
                2,
                355675,
                40151,
                848317,
                848320,
                848323,
                43367,
                786045,
                936377,
                936369,
                1036675,
                43575,
                846252,
                43583,
                43584,
            ],
        )

    def test_taxonomy_leaf_node_count(self):
        tax = Taxonomy("fixtures/taxonomy_fixture.csv")
        self.assertEqual(len(tax.nodes_by_leaf_class_id.keys()), 502)

    def test_taxonomy_agg_sum_to_one(self):
        tax = Taxonomy("fixtures/taxonomy_fixture.csv")
        flat_scores = [1 / 502] * 502
        agg_scores = tax.aggregate_scores(flat_scores, tax.life)
        self.assertAlmostEqual(agg_scores[tax.life.taxon_id], 1.0)

    def test_taxonomy_flat_best_branch(self):
        tax = Taxonomy("fixtures/taxonomy_fixture.csv")
        flat_scores = [1 / 502] * 502
        agg_scores = tax.aggregate_scores(flat_scores, tax.life)
        best_branch = tax.best_branch_from_scores(agg_scores)
        bb_taxon_ids = [bb_node.taxon_id for bb_node, score in best_branch]
        self.assertListEqual(
            bb_taxon_ids,
            [
                48460,
                1,
                47120,
                372739,
                47158,
                184884,
                47157,
                47224,
                47922,
                202067,
                202066,
                50392,
                54064,
            ],
        )

if __name__ == "__main__":
    unittest.main()


#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""Simulates right censoring of the data."""

import sys
sys.path.append("../")

import argparse
import numpy
import random

import pandas as pd
from aux.events_io import load_events, store_file_events, store_events

import logging

INF = float("inf")

def move_censoring2(df, args):
    print("updating %i/%i actions" %
          (sum(df.loc[df["type"]=="action", "time"]>=args.max),
           len(df.loc[df["type"]=="action", "time"]) ))
    df.loc[df["type"]=="action", "time"] = df.loc[df["type"]=="action", "time"].apply(lambda v: v if v<=args.max else float("inf"))
    print(df.head())

    if not args.keep_inf:
        print("removing inf from %i actions" % sum(df["type"]=="action"))
        df = df[(df["type"]!="action") | ((df["type"]=="action") & (df["time"]!=float("inf")))]
        print("%i actions left" % sum(df["type"]=="action"))

    print("updating max_time")
    df.loc[df["type"]=="max_time", "time"] = df.loc[df["type"]=="max_time", "time"].apply(lambda v: min(v,args.max))
    print(df.head())

    ###########################################################################

    print("filtering out start_time>args.max")
    id2events = {}
    for i, events in load_events(df).items():
        if events["start_time"][0]>args.max:
            continue
        id2events[i] = events

    ###########################################################################

    print("storing to %s" % args.output)
    store_file_events(args.output, id2events)

def move_censoring(df, mint=-INF, maxt=+INF, keep_inf=True):
    logging.info("censoring: mint=%f maxt=%f keep_inf=%s" % (mint, maxt, keep_inf))
    valid_ids = set(i for i, tp, t in zip(df["id"], df["type"], df["time"])
                        if tp=="start_time" and t>=mint and t<=maxt)
    logging.info("%i valid ids selected out of %i" % (len(valid_ids), len(df["id"].unique())))

    ids, types, times = [], [], []
    for i, tp, t in zip(df["id"], df["type"], df["time"]):
        if i not in valid_ids: continue
        if tp=="max_time":  t = min(t, maxt)
        elif tp!="kernel_time" and tp!="kernel_progress":
            t = t if t<=maxt else INF
        if t==INF and not keep_inf: continue

        ids.append(i)
        types.append(tp)
        times.append(t)

    logging.info("%i rows kept out of %i" % (len(ids), len(df)))
    df = pd.DataFrame({"id": ids, "time": times, "type": types})

    logging.info("dealing 1with types: kernel_time and kernel_progess")
    id2events = load_events(df)
    counter = 0
    for i, events in id2events.items():
        if "kernel_time" not in events: continue
        times, progress = [], []
        for t, p in zip(events["kernel_time"], events["kernel_progress"]):
            if t>maxt: continue
            times.append(t)
            progress.append(p)
        if counter<10:
            logging.debug(" max progress: old=%f new=%f" % (max(events["kernel_progress"]), max(progress+[-INF])))
            counter += 1
        events["kernel_time"], events["kernel_progress"] = times, progress

    df = store_events(id2events)
    return df[ ["id", "time", "type"] ]

def move_censoring1(df, args):
    return move_censoring(df, mint=args.min, maxt=args.max, keep_inf=args.keep_inf)

def main(argv):
    parser = argparse.ArgumentParser(description="Filters a data subset fitting into time window.")

    parser.add_argument("-i", "--input", dest='input',
                        help="a list of input TSV files with samples (three cols: id, time, type).",
                        required=True)

    parser.add_argument("-min", "--min_time", dest='min',
                        help="min start time",
                        required=False, type=float, default=-INF)

    parser.add_argument("-max", "--max_time", dest='max',
                        help="new censoring",
                        required=False, type=float, default=+INF)

    parser.add_argument("-a", "--action", "--skip_inf", dest='keep_inf',
                        help="set this flag to skip actions with time==inf",
                        required=False, action='store_false', default=True)

    parser.add_argument("-o", "--output", dest='output',
                        help="output TSV file",
                        required=True)

    args = parser.parse_args(argv)
    print("Parsed args: %s" % args)

    ###########################################################################

    random.seed(123)
    numpy.random.seed(123)

    ###########################################################################

    print("reading data from %s" % args.input)
    df = pd.read_csv(args.input, sep="\t")
    print(df.head())

    ###########################################################################

    df = move_censoring1(df, args)

    print("writing to %s" % args.output)
    df.to_csv(args.output, sep="\t", index=False, header=True)

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


def __get_rev(self, key, version, **kwa):
    '''Obtain particular version of the doc at key.'''
    if '_doc' in kwa:
      doc = kwa['_doc']
    else:
      if type(version) is int:
        if version == 0:
          order = pymongo.ASCENDING
        elif version == -1:
          order = pymongo.DESCENDING
        doc = self._collection.find_one({'k': key}, sort=[['d', order]])
      elif type(version) is datetime:
        ver = self.__round_time(version)
        doc = self._collection.find_one({'k': key, 'd': ver})

    if doc is None:
      raise KeyError('Supplied key `{0}` or version `{1}` does not exist'
          .format(key, str(version)))

    coded_val = doc['v']
    return pickle.loads(coded_val)


def worker_make_arrays(data, sidx, hslice, optim, maxlen):
    """
    Parallelized worker to build array chunks for output files. One main
    goal here is to keep seqarr to less than ~1GB RAM.
    """

    ## big data arrays
    io5 = h5py.File(data.clust_database, 'r')
    co5 = h5py.File(data.database, 'r')

    ## temporary storage until writing to h5 array
    maxsnp = co5["snps"][hslice:hslice+optim].sum()         ## concat later
    maparr = np.zeros((maxsnp, 4), dtype=np.uint32)
    snparr = np.zeros((sum(sidx), maxsnp), dtype="S1")
    bisarr = np.zeros((sum(sidx), maxsnp), dtype="S1")
    seqarr = np.zeros((sum(sidx), maxlen*optim), dtype="S1")

    ## apply all filters and write loci data
    seqleft = 0
    snpleft = 0
    bis = 0

    ## edge filter has already been applied to snps, but has not yet been
    ## applied to seqs. The locus filters have not been applied to either yet.
    mapsnp = 0
    totloc = 0

    afilt = co5["filters"][hslice:hslice+optim, :]
    aedge = co5["edges"][hslice:hslice+optim, :]
    asnps = co5["snps"][hslice:hslice+optim, :]
    #aseqs = io5["seqs"][hslice:hslice+optim, sidx, :]
    ## have to run upper on seqs b/c they have lowercase storage of alleles
    aseqs = np.char.upper(io5["seqs"][hslice:hslice+optim, sidx, :])

    ## which loci passed all filters
    keep = np.where(np.sum(afilt, axis=1) == 0)[0]

    ## write loci that passed after trimming edges, then write snp string
    for iloc in keep:
        ## grab r1 seqs between edges
        edg = aedge[iloc]

        ## grab SNPs from seqs already sidx subsampled and edg masked.
        ## needs to be done here before seqs are edgetrimmed.
        getsnps = asnps[iloc].sum(axis=1).astype(np.bool)
        snps = aseqs[iloc, :, getsnps].T

        ## trim edges and split from seqs and concatenate for pairs.
        ## this seq array will be the phy output.
        if not "pair" in data.paramsdict["datatype"]:
            seq = aseqs[iloc, :, edg[0]:edg[1]+1]
        else:
            seq = np.concatenate([aseqs[iloc, :, edg[0]:edg[1]+1],
                                  aseqs[iloc, :, edg[2]:edg[3]+1]], axis=1)

        ## remove cols from seq (phy) array that are all N-
        lcopy = seq
        lcopy[lcopy == "-"] = "N"
        bcols = np.all(lcopy == "N", axis=0)
        seq = seq[:, ~bcols]

        ## put into large array (could put right into h5?)
        seqarr[:, seqleft:seqleft+seq.shape[1]] = seq
        seqleft += seq.shape[1]

        ## subsample all SNPs into an array
        snparr[:, snpleft:snpleft+snps.shape[1]] = snps
        snpleft += snps.shape[1]

        ## Enter each snp into the map file
        for i in xrange(snps.shape[1]):
            ## 1-indexed loci in first column
            ## actual locus number in second column
            ## counter for this locus in third column
            ## snp counter total in fourth column
            maparr[mapsnp, :] = [totloc+1, hslice+iloc, i, mapsnp+1]
            mapsnp += 1

        ## subsample one SNP into an array
        if snps.shape[1]:
            samp = np.random.randint(snps.shape[1])
            bisarr[:, bis] = snps[:, samp]
            bis += 1
            totloc += 1

    ## clean up
    io5.close()
    co5.close()

    ## trim trailing edges b/c we made the array bigger than needed.
    ridx = np.all(seqarr == "", axis=0)
    seqarr = seqarr[:, ~ridx]
    ridx = np.all(snparr == "", axis=0)
    snparr = snparr[:, ~ridx]
    ridx = np.all(bisarr == "", axis=0)
    bisarr = bisarr[:, ~ridx]
    ridx = np.all(maparr == 0, axis=1)
    maparr = maparr[~ridx, :]

    ## return these three arrays which are pretty small
    ## catg array gets to be pretty huge, so we return only
    return seqarr, snparr, bisarr, maparr


import os

from gcloud._helpers import _LocalStack
from gcloud._helpers import _determine_default_project as _base_default_project
from gcloud.client import _ClientProjectMixin
from gcloud.client import Client as _BaseClient
from gcloud.datastore import helpers
from gcloud.datastore.connection import Connection
from gcloud.datastore.batch import Batch
from gcloud.datastore.entity import Entity
from gcloud.datastore.key import Key
from gcloud.datastore.query import Query
from gcloud.datastore.transaction import Transaction
from gcloud.environment_vars import GCD_DATASET

_MAX_LOOPS = 128
"""Maximum number of iterations to wait for deferred keys."""

def _get_gcd_project():
    """Gets the GCD application ID if it can be inferred."""
    return os.getenv(GCD_DATASET)

def _determine_default_project(project=None):
    """Determine default project explicitly or implicitly as fall-back.

    In implicit case, supports four environments. In order of precedence, the
    implicit environments are:

    * DATASTORE_DATASET environment variable (for ``gcd`` / emulator testing)
    * GCLOUD_PROJECT environment variable
    * Google App Engine application ID
    * Google Compute Engine project ID (from metadata server)

    :type project: string
    :param project: Optional. The project to use as default.

    :rtype: string or ``NoneType``
    :returns: Default project if it can be determined.
    """
    if project is None:
        project = _get_gcd_project()

    if project is None:
        project = _base_default_project(project=project)

    return project

def _extended_lookup(connection, project, key_pbs,
                     missing=None, deferred=None,
                     eventual=False, transaction_id=None):
    """Repeat lookup until all keys found (unless stop requested).

    Helper function for :meth:`Client.get_multi`.

    :type connection: :class:`gcloud.datastore.connection.Connection`
    :param connection: The connection used to connect to datastore.

    :type project: string
    :param project: The project to make the request for.

    :type key_pbs: list of :class:`gcloud.datastore._generated.entity_pb2.Key`
    :param key_pbs: The keys to retrieve from the datastore.

    :type missing: list
    :param missing: (Optional) If a list is passed, the key-only entity
                    protobufs returned by the backend as "missing" will be
                    copied into it.

    :type deferred: list
    :param deferred: (Optional) If a list is passed, the key protobufs returned
                     by the backend as "deferred" will be copied into it.

    :type eventual: bool
    :param eventual: If False (the default), request ``STRONG`` read
                     consistency.  If True, request ``EVENTUAL`` read
                     consistency.

    :type transaction_id: string
    :param transaction_id: If passed, make the request in the scope of
                           the given transaction.  Incompatible with
                           ``eventual==True``.

    :rtype: list of :class:`gcloud.datastore._generated.entity_pb2.Entity`
    :returns: The requested entities.
    :raises: :class:`ValueError` if missing / deferred are not null or
             empty list.
    """
    if missing is not None and missing != []:
        raise ValueError('missing must be None or an empty list')

    if deferred is not None and deferred != []:
        raise ValueError('deferred must be None or an empty list')

    results = []

    loop_num = 0
    while loop_num < _MAX_LOOPS:  # loop against possible deferred.
        loop_num += 1

        results_found, missing_found, deferred_found = connection.lookup(
            project=project,
            key_pbs=key_pbs,
            eventual=eventual,
            transaction_id=transaction_id,
        )

        results.extend(results_found)

        if missing is not None:
            missing.extend(missing_found)

        if deferred is not None:
            deferred.extend(deferred_found)
            break

        if len(deferred_found) == 0:
            break

        # We have deferred keys, and the user didn't ask to know about
        # them, so retry (but only with the deferred ones).
        key_pbs = deferred_found

    return results

class Client(_BaseClient, _ClientProjectMixin):
    """Convenience wrapper for invoking APIs/factories w/ a project.

    :type project: string
    :param project: (optional) The project to pass to proxied API methods.

    :type namespace: string
    :param namespace: (optional) namespace to pass to proxied API methods.

    :type credentials: :class:`oauth2client.client.OAuth2Credentials` or
                       :class:`NoneType`
    :param credentials: The OAuth2 Credentials to use for the connection
                        owned by this client. If not passed (and if no ``http``
                        object is passed), falls back to the default inferred
                        from the environment.

    :type http: :class:`httplib2.Http` or class that defines ``request()``.
    :param http: An optional HTTP object to make requests. If not passed, an
                 ``http`` object is created that is bound to the
                 ``credentials`` for the current object.
    """
    _connection_class = Connection

    def __init__(self, project=None, namespace=None,
                 credentials=None, http=None):
        _ClientProjectMixin.__init__(self, project=project)
        self.namespace = namespace
        self._batch_stack = _LocalStack()
        super(Client, self).__init__(credentials, http)

    @staticmethod
    def _determine_default(project):
        """Helper:  override default project detection."""
        return _determine_default_project(project)

    def _push_batch(self, batch):
        """Push a batch/transaction onto our stack.

        "Protected", intended for use by batch / transaction context mgrs.

        :type batch: :class:`gcloud.datastore.batch.Batch`, or an object
                     implementing its API.
        :param batch: newly-active batch/transaction.
        """
        self._batch_stack.push(batch)

    def _pop_batch(self):
        """Pop a batch/transaction from our stack.

        "Protected", intended for use by batch / transaction context mgrs.

        :raises: IndexError if the stack is empty.
        :rtype: :class:`gcloud.datastore.batch.Batch`, or an object
                 implementing its API.
        :returns: the top-most batch/transaction, after removing it.
        """
        return self._batch_stack.pop()

    @property
    def current_batch(self):
        """Currently-active batch.

        :rtype: :class:`gcloud.datastore.batch.Batch`, or an object
                implementing its API, or ``NoneType`` (if no batch is active).
        :returns: The batch/transaction at the top of the batch stack.
        """
        return self._batch_stack.top

    @property
    def current_transaction(self):
        """Currently-active transaction.

        :rtype: :class:`gcloud.datastore.transaction.Transaction`, or an object
                implementing its API, or ``NoneType`` (if no transaction is
                active).
        :returns: The transaction at the top of the batch stack.
        """
        transaction = self.current_batch
        if isinstance(transaction, Transaction):
            return transaction

    def get(self, key, missing=None, deferred=None, transaction=None):
        """Retrieve an entity from a single key (if it exists).

        .. note::

           This is just a thin wrapper over :meth:`get_multi`.
           The backend API does not make a distinction between a single key or
           multiple keys in a lookup request.

        :type key: :class:`gcloud.datastore.key.Key`
        :param key: The key to be retrieved from the datastore.

        :type missing: list
        :param missing: (Optional) If a list is passed, the key-only entities
                        returned by the backend as "missing" will be copied
                        into it.

        :type deferred: list
        :param deferred: (Optional) If a list is passed, the keys returned
                         by the backend as "deferred" will be copied into it.

        :type transaction: :class:`gcloud.datastore.transaction.Transaction`
        :param transaction: (Optional) Transaction to use for read consistency.
                            If not passed, uses current transaction, if set.

        :rtype: :class:`gcloud.datastore.entity.Entity` or ``NoneType``
        :returns: The requested entity if it exists.
        """
        entities = self.get_multi(keys=[key], missing=missing,
                                  deferred=deferred, transaction=transaction)
        if entities:
            return entities[0]

    def get_multi(self, keys, missing=None, deferred=None, transaction=None):
        """Retrieve entities, along with their attributes.

        :type keys: list of :class:`gcloud.datastore.key.Key`
        :param keys: The keys to be retrieved from the datastore.

        :type missing: list
        :param missing: (Optional) If a list is passed, the key-only entities
                        returned by the backend as "missing" will be copied
                        into it. If the list is not empty, an error will occur.

        :type deferred: list
        :param deferred: (Optional) If a list is passed, the keys returned
                         by the backend as "deferred" will be copied into it.
                         If the list is not empty, an error will occur.

        :type transaction: :class:`gcloud.datastore.transaction.Transaction`
        :param transaction: (Optional) Transaction to use for read consistency.
                            If not passed, uses current transaction, if set.

        :rtype: list of :class:`gcloud.datastore.entity.Entity`
        :returns: The requested entities.
        :raises: :class:`ValueError` if one or more of ``keys`` has a project
                 which does not match our project.
        """
        if not keys:
            return []

        ids = set(key.project for key in keys)
        for current_id in ids:
            if current_id != self.project:
                raise ValueError('Keys do not match project')

        if transaction is None:
            transaction = self.current_transaction

        entity_pbs = _extended_lookup(
            connection=self.connection,
            project=self.project,
            key_pbs=[k.to_protobuf() for k in keys],
            missing=missing,
            deferred=deferred,
            transaction_id=transaction and transaction.id,
        )

        if missing is not None:
            missing[:] = [
                helpers.entity_from_protobuf(missed_pb)
                for missed_pb in missing]

        if deferred is not None:
            deferred[:] = [
                helpers.key_from_protobuf(deferred_pb)
                for deferred_pb in deferred]

        return [helpers.entity_from_protobuf(entity_pb)
                for entity_pb in entity_pbs]

    def put(self, entity):
        """Save an entity in the Cloud Datastore.

        .. note::

           This is just a thin wrapper over :meth:`put_multi`.
           The backend API does not make a distinction between a single
           entity or multiple entities in a commit request.

        :type entity: :class:`gcloud.datastore.entity.Entity`
        :param entity: The entity to be saved to the datastore.
        """
        self.put_multi(entities=[entity])

    def put_multi(self, entities):
        """Save entities in the Cloud Datastore.

        :type entities: list of :class:`gcloud.datastore.entity.Entity`
        :param entities: The entities to be saved to the datastore.

        :raises: :class:`ValueError` if ``entities`` is a single entity.
        """
        if isinstance(entities, Entity):
            raise ValueError("Pass a sequence of entities")

        if not entities:
            return

        current = self.current_batch
        in_batch = current is not None

        if not in_batch:
            current = self.batch()

        for entity in entities:
            current.put(entity)

        if not in_batch:
            current.commit()

    def delete(self, key):
        """Delete the key in the Cloud Datastore.

        .. note::

           This is just a thin wrapper over :meth:`delete_multi`.
           The backend API does not make a distinction between a single key or
           multiple keys in a commit request.

        :type key: :class:`gcloud.datastore.key.Key`
        :param key: The key to be deleted from the datastore.
        """
        return self.delete_multi(keys=[key])

    def delete_multi(self, keys):
        """Delete keys from the Cloud Datastore.

        :type keys: list of :class:`gcloud.datastore.key.Key`
        :param keys: The keys to be deleted from the datastore.
        """
        if not keys:
            return

        # We allow partial keys to attempt a delete, the backend will fail.
        current = self.current_batch
        in_batch = current is not None

        if not in_batch:
            current = self.batch()

        for key in keys:
            current.delete(key)

        if not in_batch:
            current.commit()

    def allocate_ids(self, incomplete_key, num_ids):
        """Allocate a list of IDs from a partial key.

        :type incomplete_key: :class:`gcloud.datastore.key.Key`
        :param incomplete_key: Partial key to use as base for allocated IDs.

        :type num_ids: int
        :param num_ids: The number of IDs to allocate.

        :rtype: list of :class:`gcloud.datastore.key.Key`
        :returns: The (complete) keys allocated with ``incomplete_key`` as
                  root.
        :raises: :class:`ValueError` if ``incomplete_key`` is not a
                 partial key.
        """
        if not incomplete_key.is_partial:
            raise ValueError(('Key is not partial.', incomplete_key))

        incomplete_key_pb = incomplete_key.to_protobuf()
        incomplete_key_pbs = [incomplete_key_pb] * num_ids

        conn = self.connection
        allocated_key_pbs = conn.allocate_ids(incomplete_key.project,
                                              incomplete_key_pbs)
        allocated_ids = [allocated_key_pb.path[-1].id
                         for allocated_key_pb in allocated_key_pbs]
        return [incomplete_key.completed_key(allocated_id)
                for allocated_id in allocated_ids]

    def key(self, *path_args, **kwargs):
        """Proxy to :class:`gcloud.datastore.key.Key`.

        Passes our ``project``.
        """
        if 'project' in kwargs:
            raise TypeError('Cannot pass project')
        kwargs['project'] = self.project
        if 'namespace' not in kwargs:
            kwargs['namespace'] = self.namespace
        return Key(*path_args, **kwargs)

    def batch(self):
        """Proxy to :class:`gcloud.datastore.batch.Batch`."""
        return Batch(self)

    def transaction(self):
        """Proxy to :class:`gcloud.datastore.transaction.Transaction`."""
        return Transaction(self)

    def query(self, **kwargs):
        """Proxy to :class:`gcloud.datastore.query.Query`.

        Passes our ``project``.
        """
        if 'client' in kwargs:
            raise TypeError('Cannot pass client')
        if 'project' in kwargs:
            raise TypeError('Cannot pass project')
        kwargs['project'] = self.project
        if 'namespace' not in kwargs:
            kwargs['namespace'] = self.namespace
        return Query(self, **kwargs)


def ActivitySelection(Activities):
    selected=[]
    selected.append(Activities[0])
    k=0
    for i in range(1,len(Activities)):
        if Activities[i][0]>Activities[k][1]:
            selected.append(Activities[i])
            k=i

    return selected

s = list(map(int,input("Enter the the start times: ").split()))
f = list(map(int,input("Enter the the end times: ").split()))
Activities = []
for i in range(len(s)):
    data = [s[i],f[i]]
    Activities.append(data)
Activities.sort(key=lambda x: x[1])
print(Activities)
selected = ActivitySelection(Activities)
print("Selected Activities are:",selected)


def transform_grid_to_reference_frame(self, grid):
        """Transform a grid of (y,x) coordinates to the reference frame of the profile, including a translation to \
        its centre and a rotation to it orientation.

        Parameters
        ----------
        grid : ndarray
            The (y, x) coordinates in the original reference frame of the grid.
        """
        if self.__class__.__name__.startswith("Spherical"):
            return super().transform_grid_to_reference_frame(grid)
        shifted_coordinates = np.subtract(grid, self.centre)
        radius = np.sqrt(np.sum(shifted_coordinates ** 2.0, 1))
        theta_coordinate_to_profile = np.arctan2(shifted_coordinates[:, 0],
                                                 shifted_coordinates[:, 1]) - self.phi_radians
        transformed = np.vstack(
            (radius * np.sin(theta_coordinate_to_profile), radius * np.cos(theta_coordinate_to_profile))).T
        return transformed.view(TransformedGrid)


#!/usr/bin/python
import sys
import os
import re

sys.path = ["../"] + sys.path

import CppHeaderParser3 as CppHeaderParser
import common_functions as gen
import converter_object_templates as objt

#TODO converter templates

# from argparse import ArgumentParser
# parser = ArgumentParser()
# parser.add_argument("-b", "--build-dir", dest="build_dir",
#                     help="set CMAKE_BINARY_DIR value here")
# args = parser.parse_args()
# buildDir = args["build_dir"]

# ------------

def outputWriteHeader(file):
    file.write("#include \"Wrapper.hpp\"\n\n")
    # for filename in os.listdir("../to_wrap/"):
    for fullFileName in gen.getHeaderFilesFullPath():
        # if filename.endswith(".hpp") or filename.endswith(".h"):
        file.write("#include \""+fullFileName+"\"\n")

    file.write("extern \"C\"{\n");
    file.write("void setup(){\n\n")

# ------------

outputFile = open("../generated/generated.cpp","w+")

outputWriteHeader(outputFile)

# for filename in gen.getHeaderFiles(): #os.listdir("../to_wrap/"):
for fullFileName in gen.getHeaderFilesFullPath():
    # if filename.endswith(".hpp") or filename.endswith(".h"):
    if True:
        outputFile.write("// {0}\n".format(os.path.basename(fullFileName)))

        try:
            print ("converting: {0}".format(fullFileName))
            cppHeader = CppHeaderParser.CppHeader(fullFileName)#"../to_wrap/"+filename)
        except CppHeaderParser.CppParseError as e:
            print(e)
            sys.exit(1)

# debug:
#        print("CppHeaderParser view of %s"%cppHeader)

        methodIndex = 0

        # ----------
        # plain functions

        for f in cppHeader.functions:
            functionName = f["name"]
            nameSpace = f["namespace"]

            m = f
            if m["template"] != False:
                continue

            methodName = f["name"]

            #todo: add & for references
            methodType = [t["type"] for t in m["parameters"]]
            methodReturn = m["rtnType"]

            # exclude operators now:
            if methodName.startswith("operator"):
                continue

            if m["static"] == True:
                methodReturn = methodReturn.replace('static ','')

            if m["inline"] == True:
                methodReturn = methodReturn.replace('inline ','')

            toWrite = objt.genFunc(nameSpace, methodName, methodIndex, methodReturn, ",".join(methodType))

            outputFile.write(toWrite)

            methodIndex+=1

        # -----------------

        for c in cppHeader.classes:

            className = c
            nameSpace = cppHeader.classes[c]["namespace"]

            # todo: clean up
            justClassName = c

            nameCXX = gen.getClassNameCXX(nameSpace, className)
            namePD = gen.getClassNamePD(nameSpace, className)

            hasDefaultConstructor = False
            hasConstructor = False
            for m in cppHeader.classes[c]["methods"]["public"]:

                if m["constructor"]:
                    hasConstructor = True
                    methodType = [t["type"] for t in m["parameters"]]
                    if methodType == "":
                        hasDefaultConstructor = True
                        continue
            #implicit
            if (not hasConstructor) and (not hasDefaultConstructor):
                hasDefaultConstructor = True

            #####
            if hasDefaultConstructor:
                outputFile.write(objt.genClass(nameSpace, className))

            methodIndex = 0

            # fix:
            nameSpace = nameSpace.lstrip(':')

            if len(nameSpace) > 0:
                className = nameSpace+"::"+c

            # ----------
            # fields

            for m in cppHeader.classes[c]["properties"]["public"]:
                methodName = m["name"]

                #todo: add & for references
                methodType = [t["type"] for t in m["parameters"]]
                methodReturn = m["rtnType"]

                wrapName = "WRAP_FIELD"

                lastClassName = className.split("::")[-1]

                if m["const"] == True:
                    wrapName = "WRAP_CONST_FIELD"

                if m["static"] == True:
                    methodReturn = methodReturn.replace('static ','')

                if m["inline"] == True:
                    methodReturn = methodReturn.replace('inline ','')

                nameSpaceDivider = ''
                if len(nameSpace) > 0:
                    nameSpaceDivider = "::"
                methodPointerName = nameSpace + nameSpaceDivider+ "_M"+justClassName+"__"+methodName+"__"+str(methodIndex)  #"_".join(methodTypeRaw)+"__"+methodReturnRaw
                methodPointerNameWithoutNS = justClassName+"__"+methodName+"__"+str(methodIndex)+"_M"
                # another fix:
                methodPointerNameWithoutNS = methodPointerNameWithoutNS.replace(":","_")
                methodIndex+=1

                # todo
                # outputFile.write(objt.genField(nameSpace, className, methodIndex, methodName, methodReturn))

            # ----------
            # methods

            for m in cppHeader.classes[c]["methods"]["public"]:
                if m["template"] != False:
                    continue

                methodName = m["name"]

                #todo: add & for references
                methodType = [t["type"] for t in m["parameters"]]
                methodReturn = m["rtnType"]

                customConstructor = False

                lastClassName = className.split("::")[-1]

                # custom constructor
                if methodName == lastClassName:
                    #exclude default
                    if methodType == "":
                        continue
                    wrapName = "WRAP_CUSTOM_CLASS"
                    customConstructor = True

                # exclude operators now:
                if methodName.startswith("operator"):
                    continue

                if m["const"] == True:
                    continue

                if m["static"] == True:
                    methodReturn = methodReturn.replace('static ','')

                if m["inline"] == True:
                    methodReturn = methodReturn.replace('inline ','')

                methodIndex += 1

                if m["static"] == True:
                    className = c
                    nameSpace = cppHeader.classes[c]["namespace"]
                    methodArgs = ",".join(methodType)
                    outputFile.write(objt.genClassStaticMethod(nameSpace, className, methodIndex, methodName, methodReturn, methodArgs))
                else:
                    methodArgs = ",".join(methodType)
                    if customConstructor == True :
                        className = c
                        nameSpace = cppHeader.classes[c]["namespace"]

                        outputFile.write(objt.genCustomClass(nameSpace, className, methodIndex, methodArgs))
                    else:
                        className = c
                        nameSpace = cppHeader.classes[c]["namespace"]
                        outputFile.write(objt.genClassMethod(nameSpace, className, methodIndex, methodName, methodReturn, methodArgs))

            outputFile.write("\n")

        continue
    else:
        continue

outputFile.write("}\n")
outputFile.write("}")


# Задача 20: В настольной игре Скрабл (Scrabble) каждая буква имеет определенную
# ценность. В случае с английским алфавитом очки распределяются так:
# ● A, E, I, O, U, L, N, S, T, R – 1 очко;
# ● D, G – 2 очка;
# ● B, C, M, P – 3 очка;
# ● F, H, V, W, Y – 4 очка;
# ● K – 5 очков;
# ● J, X – 8 очков;
# ● Q, Z – 10 очков.
# А русские буквы оцениваются так:
# ● А, В, Е, И, Н, О, Р, С, Т – 1 очко;
# ● Д, К, Л, М, П, У – 2 очка;
# ● Б, Г, Ё, Ь, Я – 3 очка;
# ● Й, Ы – 4 очка;
# ● Ж, З, Х, Ц, Ч – 5 очков;
# ● Ш, Э, Ю – 8 очков;
# ● Ф, Щ, Ъ – 10 очков.
# Напишите программу, которая вычисляет стоимость введенного пользователем слова.
# Будем считать, что на вход подается только одно слово, которое содержит либо только
# английские, либо только русские буквы.

# letter_score = {
#     "AEIOULNSTR": 1,
#     "DG": 2,
#     "BCM": 3,
#     "PFHVWY": 4,
#     "K": 5,
#     "JX": 8,
#     "QZ": 10,
# }

# word = input ("Введите слово: ")
# score = 0

# for letter in word.upper():
#     for letters in letter_score:
#         if letter in letters:
#             score += letter_score.get(letters)

# print(f"Стоимость слова {word}: {score} очков.")

letter_score = {
    "A": 1,
    "E": 1,
    "I": 1,
    "O": 1,
    "U": 1,
    "L": 1,
    "N": 1,
    "S": 1,
    "T": 1,
    "R": 1,
    "D": 2,
    "G": 2,
    "B": 3,
    "C": 3,
    "M": 3,
    "P": 4,
    "F": 4,
    "H": 4,
    "V": 4,
    "W": 4,
    "Y": 4,
    "K": 5,
    "J": 8,
    "X": 8,
    "Q": 10,
    "Z": 10,
}

# Принимаем слово от пользователя, делая все буквы заглавными для поиска по списку
word = input("Введите слово на английском: ").upper()

# Проходим по буквам в слове циклом for, используя каждую букву как ключ, для получения значений из списка. Найденные значения складываем sum()
score = sum(letter_score.get(letter, 0) for letter in word)

print(f"Стоимость слова {word}: {score} очков.")


import toga
from toga.style import Pack
from toga.style.pack import COLUMN
from kink import inject

from helloworld.services.router import Router, Routes

class PlansAdd:
    def addExercise(self, widget):
        self.chosen.append(
            {
                "id": self.selected_item.id,
                "name": self.selected_item.name,
                "reps": -1
                if not self.selected_item.is_repeatable
                else self.weightValue.value,
                "weight": -1
                if not self.selected_item.use_weights
                else self.weightValue.value,
            }
        )
        print(self.chosen)
        self.router.go(Routes.PLANS_CREATE, self.chosen)

    def cancel(self, widget):
        self.router.go(Routes.PLANS_CREATE, self.chosen)

    @inject
    def __init__(self, router_service: Router, exercise, chosen) -> None:
        self.selected_item = exercise
        self.chosen = chosen
        self.router = router_service

    def getContent(self) -> toga.Box:
        self.main_box = toga.Box(style=Pack(direction=COLUMN))
        self.main_box.add(
            toga.Label(text=f"Adding Exercise: {self.selected_item.name}")
        )
        self.weightValue = toga.NumberInput()
        self.repValue = toga.NumberInput()
        if self.selected_item.use_weights:
            self.main_box.add(toga.Label(text="How much weight?"))
            self.main_box.add(self.weightValue)
        if self.selected_item.is_repeatable:
            self.main_box.add(toga.Label(text="How many repetitions?"))
            self.main_box.add(self.repValue)

        self.main_box.add(toga.Button(text="Add", on_press=self.addExercise))
        self.main_box.add(toga.Button(text="Cancel", on_press=self.cancel))
        return self.main_box

    def getName(self) -> str:
        return "Plan Add"


import copy
import simple_algorithm as sa

from tkinter import messagebox

IS_RECTANGLE_SET = False

def clear_canvas(canvas, lines, rectangle):
    canvas.delete("all")

    lines.clear()
    lines.append([])

    for i in range(4):
        rectangle[i] = -1

def set_pixel(canvas, x, y, color):
    canvas.create_line(x, y, x + 1, y, fill=color)

def draw_lines(canvas, lines):
    for line in lines:
        if len(line) != 0:
            try:
                canvas.create_line(line[0], line[1], fill=line[2])
            except IndexError:
                pass

def rgb(color):
    return (int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16))

def get_color(color_var):
    col_var = color_var.get()

    if col_var == 0:
        color = "#000000"
    elif col_var == 1:
        color = "#ff0000"
    elif col_var == 2:
        color = "#0000ff"
    elif col_var == 3:
        color = "#3ebd33"
    elif col_var == 4:
        color = "#ffa600"
    else:
        color = "#bd08fc"

    return color

def click_left(event):
    global IS_RECTANGLE_SET

    IS_RECTANGLE_SET = False

def click_left_motion(event, rectangle, lines, canvas, color_var):
    global IS_RECTANGLE_SET

    color = get_color(color_var)

    if IS_RECTANGLE_SET == False:
        rectangle[0] = event.x
        rectangle[1] = event.y

        IS_RECTANGLE_SET = True
    else:
        x = event.x
        y = event.y

        canvas.delete("all")
        draw_lines(canvas, lines)
        canvas.create_rectangle(rectangle[0], rectangle[1], x, y, outline=color)

        rectangle[2] = x
        rectangle[3] = y

def click_right(event, lines, canvas, color_var):
    x = event.x
    y = event.y

    color = get_color(color_var)
    set_pixel(canvas, x, y, color)

    lines[-1].append([x, y])

    if len(lines[-1]) == 2:
        canvas.create_line(lines[-1][0], lines[-1][1], fill=color)

        lines[-1].append(color)
        lines.append([])

def add_line(lines, canvas, color_var, xb_entry, yb_entry, xe_entry, ye_entry):
    if len(lines[-1]) != 0:
        messagebox.showerror("Ошибка!",
                             "Предыдущий отрезок не был достроен.")
        return

    try:
        xb = int(xb_entry.get())
        yb = int(yb_entry.get())
        xe = int(xe_entry.get())
        ye = int(ye_entry.get())
    except:
        messagebox.showerror("Ошибка!",
                             "Координаты отрезка должны быть целыми числами.")
        return

    color = get_color(color_var)

    canvas.create_line([xb, yb], [xe, ye], fill=color)

    lines[-1].append([xb, yb])
    lines[-1].append([xe, ye])
    lines[-1].append(color)

    lines.append([])

def draw_rectangle(rectangle, lines, canvas, color_var, x_top_left_entry, y_top_left_entry,
                   x_lower_right_entry, y_lower_right_entry):
    try:
        xl = int(x_top_left_entry.get())
        yl = int(y_top_left_entry.get())
        xr = int(x_lower_right_entry.get())
        yr = int(y_lower_right_entry.get())
    except:
        messagebox.showerror("Ошибка!",
                             "Координаты вершин прямоугольника должны быть целыми числами.")
        return

    color = get_color(color_var)

    canvas.delete("all")
    draw_lines(canvas, lines)
    canvas.create_rectangle(xl, yl, xr, yr, outline=color)

    rectangle[0] = xl
    rectangle[1] = yl
    rectangle[2] = xr
    rectangle[3] = yr

def add_horizontal_and_vertical_lines(rectangle, lines, canvas, color_var):
    if rectangle[0] == -1:
        messagebox.showerror("Ошибка!", "Отсутствует отсекатель.")
        return

    color = get_color(color_var)

    x1 = rectangle[0]
    y1 = rectangle[1]
    x2 = rectangle[2]
    y2 = rectangle[3]

    dx = x2 - x1
    dy = y2 - y1

    if lines[-1] == []:
        lines.pop()

    lines.append([[x1 + 0.1 * dx, y1], [x2 - 0.1 * dx, y1], color])
    lines.append([[x1 + 0.1 * dx, y2], [x2 - 0.1 * dx, y2], color])
    lines.append([[x1, y1 + 0.1 * dy], [x1, y2 - 0.1 * dy], color])
    lines.append([[x2, y1 + 0.1 * dy], [x2, y2 - 0.1 * dy], color])

    canvas.create_line(x1, y1 + 0.1 * dy, x1, y2 - 0.1 * dy, fill=color)
    canvas.create_line(x2, y1 + 0.1 * dy, x2, y2 - 0.1 * dy, fill=color)
    canvas.create_line(x1 + 0.1 * dx, y1, x2 - 0.1 * dx, y1, fill=color)
    canvas.create_line(x1 + 0.1 * dx, y2, x2 - 0.1 * dx, y2, fill=color)

    lines.append([])

def draw_visible_lines(result_list, color, canvas):
    for line in result_list:
        canvas.create_line(line[1][0], line[1][1], line[0][0], line[0][1], fill=color)

def clip(rectangle, lines, canvas, color_var):
    if rectangle[0] == -1:
        messagebox.showerror("Ошибка!", "Отсутствует отсекатель.")
        return

    color = get_color(color_var)

    result_list = []

    if rectangle[0] < rectangle[2]:
        left_side = rectangle[0]
        right_side = rectangle[2]
    else:
        right_side = rectangle[0]
        left_side = rectangle[2]

    if rectangle[1] < rectangle[3]:
        top_side = rectangle[1]
        bottom_side = rectangle[3]
    else:
        bottom_side = rectangle[1]
        top_side = rectangle[3]

    tmp_list = copy.deepcopy(lines)

    for i in range(len(tmp_list) - 1):
        tmp_list[i].pop()

    for line in range(len(tmp_list) - 1):
        result = sa.simple_algorithm(tmp_list, line, left_side, right_side, bottom_side, top_side)

        if result:
            result_list.append(result)

    draw_visible_lines(result_list, color, canvas)


#!/usr/bin/env python3

import rospy
import actionlib
from math import sin, cos, pi
from actionlib_msgs.msg import GoalStatus
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal

rospy.init_node('go_to_point')

move_base_client = actionlib.SimpleActionClient('move_base', MoveBaseAction)
move_base_client.wait_for_server()

goals = [
    (1.95, 8.65),
    (5.7, 2.3)
]

while True:
    for target_pos in goals:
        goal = MoveBaseGoal()
        goal.target_pose.header.stamp = rospy.get_rostime()
        goal.target_pose.header.frame_id = 'map'

        goal.target_pose.pose.position.x = target_pos[0]
        goal.target_pose.pose.position.y = target_pos[1]
        goal.target_pose.pose.position.z = 0

        goal.target_pose.pose.orientation.x = 0
        goal.target_pose.pose.orientation.y = 0
        goal.target_pose.pose.orientation.z = sin(- pi / 4)
        goal.target_pose.pose.orientation.w = cos(- pi / 4)

        move_base_client.send_goal(goal)
        move_base_client.wait_for_result()

        status = move_base_client.get_state()
        if status == GoalStatus.SUCCEEDED:
            print("Successfully reached point.")
        else:
            print("Failed to reach point.")


'''
number	k	return
1924	2	94
1231234	3	3234
4177252841	4	775841
'''

def solution(number, k):
    collection = [number[0]]
    for num in number[1:] :
        while collection and collection[-1] < num and k > 0 :
            collection.pop()
            k-=1
        collection.append(num)

    if k != 0 :
        collection = collection[:-k]

    return ''.join(collection)

print(solution('999',2))

''' 58.3 / 100.0 -> 2,3,4,9,10 실패 (1~12)
def solution(number, k):
    answer = ''
    numList = list(map(int,number))

    idx = 0

    while k != 0 :
        test = numList[idx:idx + 3]
        print(test,numList)
        if numList[idx] == numList[idx+1] :
            idx+=1
            continue
        elif numList[idx] != numList[idx+1] :
            numList.pop(numList.index(min(test)))
            k-=1

    return "".join([str(i) for i in numList])
'''