import uuid
import queue

from rnnvis.utils.tree import TreeNode, Tree

class XTree(object):
    """"This class is just a wrap of class SuffixTree which provide both prefix and suffix
    """
    def __init__(self, data, sentence_delimiter='\n'):
        self._data = data
        self._prefix_data, self._suffix_data = self.data_preprocessing(
            self._data, sentence_delimiter)

        self._prefix_tree = SuffixTree(self._prefix_data)
        self._suffix_tree = SuffixTree(self._suffix_data)

    def fetch_prefix_suffix(self, gram):
        if isinstance(gram, str):
            gram = gram.split()
        prefix_result = self._prefix_tree.search_suffix(list(reversed(gram)))
        suffix_result = self._suffix_tree.search_suffix(gram)

        q = queue.Queue()
        q.put(prefix_result)
        while not q.empty():
            node = q.get()
            prefix_position = (node['position'][0],
                               len(self._prefix_data[node['position'][0]]) -
                               node['position'][1] - len(node['data']))
            node['position'] = prefix_position
            node['data'] = ' '.join(list(reversed(node['data'])))
            for child in node['children']:
                q.put(child)

        q.put(suffix_result)
        while not q.empty():
            node = q.get()
            node['data'] = ' '.join(node['data'])
            for child in node['children']:
                q.put(child)

        return prefix_result, suffix_result

    def data_preprocessing(self, data, sentence_delimiter='\n'):
        """ Preprocess the raw data to produce prefix and suffix data
        """
        lines = data.split(sentence_delimiter)
        prefix_data = []
        for i, line in enumerate(lines):
            words = line.split()
            words = list(reversed(words))
            words.append('<bos_' + str(i) + '>')
            prefix_data.append(words)
        suffix_data = []
        for i, line in enumerate(lines):
            words = line.split()
            words.append('<eos_' + str(i) + '>')
            suffix_data.append(words)

        return prefix_data, suffix_data

class SuffixTree(Tree):
    """This class is used to construct suffix tree
    """

    def __init__(self, data):
        Tree.__init__(self)
        root_node = SuffixTreeNode(data=[], position=(-1, -1))
        self.add_node(root_node)
        self._root = self.get_root()
        self._data = data

        self._leaves = set()
        self._status = None
        self._remainder = 0
        self._previous_node_added = None
        self._reverse_suffix_links = {}
        self._tmp_str = None

        self._words = None
        self._sentence_num = -1

        self.construct(self._data)
        self._tree_dict = self.to_dict(self.get_root())

    def construct(self, data):
        for i, line in enumerate(data):
            self._status = {'active_node': self._root,
                            'active_edge': None,
                            'active_length': 0
                            }
            self._leaves = set()
            self._remainder = 0
            self._words = line
            self._sentence_num = i

            for j, word in enumerate(line):
                for leaf in self._leaves:
                    self.get_node(leaf).append_suffix(word)
                self._remainder += 1
                self.add_to_tree(j)
                self._previous_node_added = None
                # self._tmp_str = self.tree_str(self.get_root())
            # print(self.to_dict(self.get_root()))

    def search_suffix(self, gram):
        if isinstance(gram, str):
            gram = gram.split()
        gram_node, position = self.find_node(self.get_root(), gram)
        if position < 0:
            return None
        tree_dict = self.to_dict(gram_node)
        tree_dict['data'] = ' '.join(gram_node.data[position:])
        return tree_dict

    def to_dict(self, node):
        node_info = {}
        node_info['data'] = node.data if not node.is_root() else ['#root#']
        node_info['position'] = node.position
        node_info['children'] = []
        for child_id in node.children_id:
            child_node = self.get_node(child_id)
            node_info['children'].append(self.to_dict(child_node))
        return node_info

    def find_node(self, start_node, gram):
        if not start_node.children_prefix(gram[0]):
            return start_node, -1

        edge = self.get_node(start_node.children_prefix(gram[0]))
        for i in range(min(len(gram), len(edge.data))):
            if gram[i] != edge.data[i]:
                return start_node, -1
        i += 1
        if i == len(gram):
            return edge, i
        elif i == len(edge.data):
            return self.find_node(edge, gram[i:])

    def tree_str(self, node):
        if len(node.children_id) < 1:
            return ' '.join(node.data)
        strs = []
        for child_id in node.children_id:
            strs.append(self.tree_str(self.get_node(child_id)))
        key_ = ' '.join(node.data) if not node.is_root() else 'root'
        return {key_: strs}

    def add_node(self, node, parent=None):
        if not isinstance(node, TreeNode):
            raise TypeError("arg node should be of type TreeNode, but it's of type {:s}".format(type(node)))
        if node.id in self._dict:
            raise ValueError("node with id {:s} already exists!".format(node.id))
        if parent is None:
            if self.root_id is not None:
                raise ValueError("Attempt to add a multiple root! The tree already has a root.")
            self.root_id = node.id
        else:
            parent = self.get_node(parent)
            if parent is None:
                raise ValueError("the given parent is not in the tree!")
            parent.children_id.add(node.id)
            parent.add_child(node)
            node.parent_id = parent.id
        self._dict[node.id] = node

    def add_to_tree(self, i):
        if self._remainder == 0:
            return

        # word = words[i]
        # if self._status['active_node'].is_root():
        #     tmp_word = words[i - self._remainder + 1]
        # else:
        #     tmp_word = words[i - self._status['active_length']]
        # word = self._words[i - self._remainder + 1] if self._status['active_node'].is_root() else \
        #     self._words[i - self._status['active_length']]
        word_pos = i - self._remainder + 1 if self._status['active_node'].is_root() else \
            i - self._status['active_length']
        word = self._words[word_pos]
        if self._status['active_edge'] is None:
            if not self._status['active_node'].children_prefix(word):
                node = SuffixTreeNode(data=[word], position=(self._sentence_num, word_pos))
                self.add_node(node, parent=self._status['active_node'])
                self._leaves.add(node.id)
                self._remainder -= 1
                if not self._status['active_node'].is_root():
                    self._status['active_node'] = self.get_node(
                        self._status['active_node'].suffix_link) if \
                        self._status['active_node'].suffix_link else self.get_root()
                    # if self._previous_node_added is not None:
                    #     self._previous_node_added.suffix_link = node.id
                    # self._previous_node_added = node
                    self._previous_node_added = None
                    self.add_to_tree(i)

            else:
                edge_node_id = self._status['active_node'].children_prefix(word)
                edge_node = self.get_node(edge_node_id)
                self._status['active_edge'] = edge_node
                self._status['active_length'] = 0
                counter = 0
                while counter+1 <= self._remainder and self._status['active_edge'] and self._status['active_edge'].data[
                    self._status['active_length']] == self._words[i - self._remainder + counter + 1]:

                    self._status['active_length'] += 1
                    counter += 1
                    if len(self._status['active_edge'].data) == self._status['active_length']:
                        self._status['active_node'] = self._status['active_edge']
                        self._status['active_edge'] = self._status['active_node'].children_prefix(
                            self._words[i - self._remainder + counter + 2]) if counter+2 <= self._remainder else None
                        self._status['active_length'] = 0

                if counter == self._remainder:
                    # contain all infomation
                    return
                self.add_to_tree(i)

        elif self._status['active_edge'].data[self._status['active_length']] == self._words[i]:
            self._status['active_length'] += 1
            if len(self._status['active_edge'].data) == self._status['active_length']:
                self._status['active_node'] = self._status['active_edge']
                self._status['active_edge'] = None
                self._status['active_length'] = 0

        elif self._status['active_edge'].data[self._status['active_length']] != self._words[i]:
            new_node = SuffixTreeNode(data=[self._words[i]], position=(self._sentence_num, i))
            other_node = self.split_node(self._status['active_edge'], self._status['active_length'])
            self.add_node(new_node, self._status['active_edge'])
            self.add_node(other_node, self._status['active_edge'])
            self._leaves.add(new_node.id)

            if self._previous_node_added is not None:
                self._previous_node_added.suffix_link = self._status['active_edge'].id
            self._previous_node_added = self._status['active_edge']

            self._remainder -= 1

            # update active node and active edge
            if self._status['active_node'].is_root():
                self._status['active_length'] -= 1
                edge_node_id = self._status['active_node'].children_prefix(self._words[i - self._status['active_length']])
                self._status['active_edge'] = self.get_node(edge_node_id) if edge_node_id else None
                while self._status['active_edge'] and self._status['active_length'] >= len(self._status['active_edge'].data):
                    self._status['active_node'] = self._status['active_edge']
                    self._status['active_length'] -= len(self._status['active_edge'].data)
                    edge_node_id = self._status['active_node'].children_prefix(self._words[i - self._status['active_length']])
                    self._status['active_edge'] = self.get_node(edge_node_id) if edge_node_id else None

                self.add_to_tree(i)
            elif self._status['active_node'].suffix_link:
                self._status['active_node'] = self.get_node(
                    self._status['active_node'].suffix_link)
                edge_node_id = self._status['active_node'].children_prefix(self._words[i - self._status['active_length']])
                self._status['active_edge'] = self.get_node(edge_node_id)
                self.add_to_tree(i)
            else:
                self._status['active_node'] = self.get_root()
                self._status['active_edge'] = None
                self.add_to_tree(i)

    def split_node(self, node, position_):
        new_node = SuffixTreeNode(data=node.data[position_:],
                                  position=(node.position[0], node.position[1]+position_))
        node.data = node.data[:position_]
        for child_id in node.children_id:
            child_node = self.get_node(child_id)
            child_node.parent_id = new_node.id
        new_node.children_id = node.children_id
        new_node.child_prefix_dict = node.child_prefix_dict
        node.delete_all_children()
        if node.id in self._leaves:
            self._leaves.remove(node.id)
            self._leaves.add(new_node.id)
        return new_node

class SuffixTreeNode(TreeNode):
    '''Suffix tree node class, inherit from TreeNode
    '''

    def __init__(self, data, position, id_=None, parent_id=None):
        if id_ is None:
            id_ = uuid.uuid1().hex
        TreeNode.__init__(self, id_=id_, parent_id=parent_id)
        self._data = data
        self._child_prefix_dict = {}
        self._suffix_link = None
        self._position = position

    def first_element(self):
        """Return the first element of node data
        """
        if not isinstance(self._data, list):
            raise ValueError('The node data should be a list of words')
        if len(self._data) < 1:
            raise ValueError('The length of node data should at least be 1')
        return self._data[0]

    def children_prefix(self, word):
        return self._child_prefix_dict.get(word)

    def append_suffix(self, word):
        self._data.append(word)

    def add_child(self, child_node):
        self._child_prefix_dict[child_node.first_element()] = child_node.id
        self._children_id.add(child_node.id)

    def delete_all_children(self):
        self._child_prefix_dict = {}
        self._children_id = set()

    @property
    def position(self):
        return self._position

    @position.setter
    def position(self, new_position):
        self._position = new_position

    @property
    def child_prefix_dict(self):
        return self._child_prefix_dict

    @child_prefix_dict.setter
    def child_prefix_dict(self, dict_):
        self._child_prefix_dict = dict_

    @property
    def children_id(self):
        return self._children_id

    @children_id.setter
    def children_id(self, children_id_):
        self._children_id = children_id_

    @property
    def child_prefix(self):
        return self._child_prefix_dict

    @property
    def suffix_link(self):
        '''Suffix link getter
        '''
        return self._suffix_link

    @suffix_link.setter
    def suffix_link(self, node_id):
        '''Suffix link setter
        '''
        self._suffix_link = node_id

    @property
    def data(self):
        '''Node data getter
        '''
        return self._data

    @data.setter
    def data(self, data_):
        '''Node data setter
        '''
        self._data = data_


n = int(input())
a = list(map(int, input().split()))
a.sort()
answer = 0
tmp = a[0]

if n <= 2:
    if n == 1:
        print(tmp)
    else:
        if a[0] + 1 == a[1]:
            print(a[0])
        else:
            print(a[0] + a[1])
    exit(0)

for i in range(n - 1):
    if a[i] + 1 == a[i + 1]:
        continue
    else:
        answer += tmp
        tmp = a[i + 1]
answer += tmp

print(answer)


import pandas as pd

def get_average(data):
    total = 0
    for x in data:
        total += x
    average = total / len(data)
    return average

def read_data(path):
    data_path = path
    sales = pd.read_csv(data_path)
    return sales

def get_total_sales(monthly):
    monthly_sales = monthly
    total_sales = 0
    for x in monthly_sales:
        total_sales += x
    return total_sales

def get_highest(data):
    high = 0
    for x in data:
        if x > high:
            high = x
    return high

def get_lowest(data):
    low = 10000
    for x in data:
        if x < low:
            low = x
    return low

def get_monthly_dictionary(data, months):
    monthly_dictionary = {}
    for i in range(len(data)):
        monthly_dictionary[data[i]] = months[i]
    return monthly_dictionary

def calculate_percentage_change(a, b):
    change = b - a
    percentage_change = change / a * 100
    return percentage_change

def get_monthly_change(data, months):
    change_dictionary = {}
    for i in range(len(data)):
        if i < len(data) - 1:
            p_change = calculate_percentage_change(data[i], data[i+1])
            change_dictionary[months[i]] = str(round(p_change, 2)) + '%'
    return change_dictionary

def get_highest_lowest(monthly_sales, months):
    highest = get_highest(monthly_sales)
    lowest = get_lowest(monthly_sales)
    # print("Highest: {}, Lowest: {}".format(highest, lowest))
    monthly_dictionary = get_monthly_dictionary(monthly_sales, months)
    print(monthly_dictionary)
    highest_month = monthly_dictionary[highest]
    lowest_month = monthly_dictionary[lowest]
    print("Highest month: {}, Lowest month: {}".format(highest_month, lowest_month))

def is_seasonal_product(profits):
    winter = profits[11] + profits[0] + profits[1]
    spring = profits[2] + profits[3] + profits[4]
    summer = profits[5] + profits[6] + profits[7]
    autumn = profits[8] + profits[9] + profits[10]
    return winter + summer > spring + autumn

#Work out total expenditure
def get_total_expenditure(monthly):
    monthly_expenditure = monthly
    total_expenditure = 0
    for x in monthly_expenditure:
        total_expenditure += x
    return total_expenditure

if __name__ == '__main__':
    # MUST
    # read sales.csv data
    data = read_data('sales.csv')
    # get monthly sales
    monthly_sales = data['sales'].values
    print(monthly_sales)
    # get total sales across all months
    total_sales = get_total_sales(monthly_sales)
    print("Total sales: {}".format(total_sales))
    # SHOULD
    # get average sales over months
    avg = get_average(monthly_sales)
    avg = round(avg, 3)
    print('Average sales: {}'.format(avg))
    # get highest and lowest monthly sales
    months = data['month'].values
    get_highest_lowest(monthly_sales, months)
    # create dictionary that shows percentage change as a percentage
    percentage_change_dictionary = get_monthly_change(monthly_sales, months)
    print(percentage_change_dictionary)
    # COULD #
    # calculate highest expenditure and lowest expenditure
    expenditure = data['expenditure'].values
    get_highest_lowest(expenditure, months)
    # calculate monthly profit
    profit = monthly_sales - expenditure
    print('Monthly profits: {}'.format(profit))
    # calculate monthly changes in expenditure
    monthly_expenditure_change = get_monthly_change(expenditure, months)
    print(monthly_expenditure_change)
    #  calculate seasonal profits
    print(is_seasonal_product(profit))
    # add profit to the original csv file and export it
    data['profit'] = profit
    new_data = pd.DataFrame(data)
    new_data.to_csv('new_sales.csv')
    # get monthly expenditure
    monthly_expenditure = data['expenditure'].values
    print(monthly_expenditure)
    # get total expenditure across all months
    total_expenditure = get_total_expenditure(monthly_expenditure)
    print("Total expenditure: {}".format(total_expenditure))
    # get total profit across all months
    total_profit = total_sales - total_expenditure
    print("Total profit: {}".format(total_profit))


import sys

# sys.exit()

nt = type(None)
I = lambda x: x

class Error:
    def __init__(self, msg, origin, expr, name):
        self.msg = msg
        self.origin = origin
        self.expr = expr
        self.name = name
    def display(self):
        print(str(self))
    def __repr__(self):
        return 'Unhandled exception: {}\n{}\n{}\n{}'.format(self.name, self.expr,(' ' * self.origin + '^\n') if self.origin else '\b', self.msg)
        #return f'Unhandled exception: {self.name}\n' + (f'{self.expr}\n{' ' * self.origin + '^\n' if self.expr else '\n'}' + f'{self.msg}'

def parse_error(origin_buffer, origin, errmsg, errname):
    n = Node(None, 'Value', origin_buffer)
    n.value = lambda a, e, _: Error(errmsg, origin_buffer +  origin, e, errname)
    return [n]

def cls_stringify(cls):
    return str(cls)[8:-2] # Removes the "<class '" and "'>" part from string (e.g. "<class 'object'>")
def lst_stringify(lst):
    return ', '.join([cls_stringify(j) for j in lst])

class Value:
    valid = [chr(x)for x in range(97, 123)]+[chr(x)for x in range(65, 91)]+['_']+[str(s)for s in range(0, 10)]
class Operation:
    class Unary:
        class Boolean:
            class Negation:
                valid = [bool]
                @staticmethod
                def function(p, c):
                    return not p
    class Binary:
        class Boolean:
            @staticmethod
            def excl_disjunction(p, q, c):
                return (p or q) and not (p and q)
        class Arithmetic:
            class Addition:
                valid = [[int, int], [float, int], [int, float], [float, float], [str, str]]
                @staticmethod
                def function(a, b, c):
                    return a + b

            class Subtraction:
                valid = [[int, int], [float, int], [int, float], [float, float]]
                @staticmethod
                def function(a, b, c):
                    return a - b

            class Multiplaction:
                valid = [[int, int], [float, int], [int, float], [float, float], [str, int]]
                @staticmethod
                def function(a, b, c):
                    return a * b

            class Division:
                valid = [[int, int], [float, int], [int, float], [float, float]]
                @staticmethod
                def function(a, b, c):
                    if b == 0:
                        return Error('Cannot divide by zero!', c["self"].origin, c["expr"], 'DivideByZeroError')
                    return a / b

class Operators:
    Unary = {
        "name": "Unary functions",
        "tags": ["unary"],
        "ops": {
            "~": { # Negation
                "funct": lambda a, _: not a,
                "supported": [bool]
                }
            },
            "!": { # Negation
                "funct": lambda a, _: not a,
                "supported": [bool]
            }

        }
    Binary = [
        # Boolean Functions
        { # And
            "name": "And",
            "category": "boolean-functions",
            "tags": [],
            "ops": {
                '∧': {
                    "funct": lambda a, b, _: a and b,
                    "supported": [[bool, bool]]
                    }
                }
            },
        { # Or
            "name": "Or",
            "category": "boolean-functions",
            "tags": [],
            "ops": {
                '∨': {
                    "funct": lambda a, b, _: a or b,
                    "supported": [[bool, bool]]
                    }
                }
            },
        # Mathmatical Functions
        { # Add, Sub
            "name": "Add-Sub",
            "category": "Mathmatical-functions",
            "tags": [],
            "ops": {
                '+': {
                    "funct": Operation.Binary.Arithmetic.Addition.function,
                    "supported": Operation.Binary.Arithmetic.Addition.valid
                    },
                '-': {
                    "funct": Operation.Binary.Arithmetic.Subtraction.function,
                    "supported": Operation.Binary.Arithmetic.Subtraction.valid
                    }
                }
            },
        { # Mult, Div
            "name": "Mult-Div",
            "category": "Mathmatical-functions",
            "tags": [],
            "ops": {
                    '*': { # Mult
                        "funct": Operation.Binary.Arithmetic.Multiplaction.function,
                        "supported": Operation.Binary.Arithmetic.Multiplaction.valid
                        },
                    '/': { # Div
                        "funct": Operation.Binary.Arithmetic.Division.function,
                        "supported": Operation.Binary.Arithmetic.Division.valid
                        }
                }
            },
        # Turnary Operators
        { # ?, :
            "name": "Turnary Operations",
            "category": None,
            "tags": [],
            "ops": {
                '?': { # If-Clause
                    "funct": lambda b, o, c: [b] + ([c["r"].value(c["vars"], c["expr"], c)] if b else []),
                    "supported": [[bool, object]],
                    "ignores": ["r"]
                    },
                ':': { # Else-clause
                    "funct": lambda l, o, c: (l[1] if l[0] else c["r"].value(c["vars"], c["expr"], c)),
                    "supported": [[list, object]],
                    "ignores": ["r"]
                    }
                }
            },
        # Eval function
        {
            "name": "Eval-function",
            "category": "Meta-functions",
            "tags": ["meta"],
            "ops": {
                '#': {
                    "funct": lambda v, e, c: expr_parse(e, v, 0, 0, c["show_steps"])[0].value(c["vars"], e, c),
                    "supported": [[dict, str]]
                    },
                }
            },
        {
            "name": "Application",
            "category": "Lambda-Calculus",
            "tags": [],
            "ops": {
                "<=": {
                    "funct": lambda a, b, c: a(b),
                    "supported": [[type(I), object]]
                }
            }
        }
    ]

class Node:
    def __init__(self, info, _type, origin):
        self.info = info
        self.type = _type
        self.origin = origin
        self.left = None
        self.riht = None
        self.is_operation = False
        self.is_unary = False

    def __repr__(self):
        return 'Node: {0}, Type: {1}, Origin: {2}, Is_op: {3}.'.format(self.info, self.type, self.origin, self.is_operation)

    def value(self, _vars, expr, _context):
        if not self.is_operation and not self.is_unary:
            if self.info in list(_vars.keys()):
                return _vars[self.info]
            if self.info == 'Y':
                return Error('This is an error.\nDo not use this.', self.origin, expr, "YError")
            try:
                return eval(self.info)
            except NameError as e:
                return Error('{0}'.format('{0}.'.format(e)[5:]), self.origin, expr, 'UndefinedVariableError')
            except SyntaxError as e:
                return Error('Invalid syntax? {0}'.format(e), self.origin, expr, 'InvalidSyntaxError')

        elif self.is_unary:
            assert(False)
        elif self.is_operation:
            for priority in Operators.Binary:
                l = None
                tl = nt
                r = None
                tr = nt

                if self.info not in list(priority["ops"].keys()):
                    continue

                ignores = []
                try:
                    ignores = priority["ops"][self.info]["ignores"]
                except KeyError:
                    pass

                context = {"l": self.left, "r": self.riht, "expr": expr, "vars": _vars, "show_steps": _context["show_steps"], "self": self, "tl": nt, "tr": nt}
                if "l" not in ignores:
                    l = self.left.value(_vars, expr, context)
                    tl = type(l)
                    context["tl"] = tl
                    if tl == Error:
                        return l

                if self.info not in list(priority["ops"].keys()):
                    return Error('\'' + self.info + '\' isn\'t a valid operator!', self.origin, expr, 'InvalidOperatorError')

                if "r" not in ignores:
                    r = self.riht.value(_vars, expr, context)
                    tr = type(r)
                    context["tr"] = tr
                    if tr == Error:
                        return r
                for types in priority["ops"][self.info]["supported"]:
                    if (("l" in ignores) or issubclass(tl, types[0])) and (("r" in ignores) or issubclass(tr, types[1])):
                        break
                else:
                    return Error('Unsupported operand type(s) for the \'{0}\' operator: {1}, {2}.'.format(self.info, cls_stringify(tl), cls_stringify(tr)), self.origin, expr, 'UnsupportedOperandTypesError')
                try:
                    return priority["ops"][self.info]["funct"](l, r, context)
                except TypeError as e:
                   return Error('The operands given to the \'{0}\' operator resulted in an error. {1}.'.format(self.info, e), self.origin, expr, 'InternalErrorInOperationError')
            else:
                return Error('\'' + self.info + '\' isn\'t a valid operator!', self.origin, expr, 'InvalidOperatorError')
        else:
            return Error('Invalid node type!', None)

    def to_tuple(self):
        return (self.info, self.type, self.origin)

    def visualise(self, depth=0, buffer=0):
        print(' ' * buffer * 3 + (' ' * (depth-1) * 3 + '|- ' if depth!= 0 else '') + str(self))
        if self.left:
            self.left.visualise(depth + 1, buffer)
        if self.riht:
            self.riht.visualise(depth + 1, buffer)

def class_of(char):
    return "Value" if char in Value.valid else "Operation"

# Value:
    # Boolean
    # Integer
    # Number
    # String

def current_node(current, _type, origin):
    return [Node(current, _type, origin)] if current != '' else []

def expr_parse(expr, given={}, depth=0, origin_buffer=0, show_steps=False):
    if expr == '':
        return parse_error(origin_buffer, 0, 'Empty expression given.', 'EmptyExpressionError')

    if show_steps:
        print(depth * '  ' + 'Evaluating {0}, Buffer: {1}'.format(expr, origin_buffer))

    # Step one: Lex
    current = ''
    on_new = True
    origin = 0
    parsed = []
    current_class = ''
    prev_class = ''

    in_sub_expr = False
    sub_expr = ''
    sub_origin = 0
    indent = 0

    in_list = False
    sub_list = []

    in_string = False
    temp_ignore_escp = False

    in_infix = False

    for i, char in enumerate(list(expr + ' ')):
        if in_sub_expr:
            if char == '(':
                indent += 1
                sub_expr += '('
            elif char == ')':
                if indent == 0:
                    in_sub_expr = False
                    on_new = True
                    current = ''
                    parsed += expr_parse(sub_expr, given, depth+1, origin_buffer+sub_origin+1, show_steps)
                    sub_expr = ''
                else:
                    indent -= 1
                    sub_expr += ')'
            else:
                sub_expr += char
                if i == len(expr):
                    return parse_error(origin_buffer, sub_origin, 'Mismatching left parenthesis.', 'MismatchingLeftParenError')

        elif in_string:
            if char == '\'' and not temp_ignore_escp:
                parsed += current_node(current + '\'', 'Value', origin+origin_buffer)
                current = ''
                on_new = True
                in_string = False
                prev_class = 'Value'

            elif char == '\\':
                temp_ignore_escp = True
            else:
                if i == len(expr) - 1:
                    return parse_error(origin_buffer, i + 1, 'Unexpected EOL while reading string literal.', 'UnexpectedEndOfLineError')
                current += char
                temp_ignore_escp = False

        elif in_infix:
            if char == '`':
                in_infix = False
                parsed += current_node(current, 'Operation', origin+origin_buffer)
                current = ''
                on_new = True
                prev_class = 'Operation'
            else:
                current += char
        else:
            if char == ' ':
                parsed += current_node(current, prev_class, origin+origin_buffer)
                current = ''
                on_new = True
            elif char == '(':
                in_sub_expr = True
                sub_origin = i
                parsed += current_node(current, prev_class, origin+origin_buffer)
                current = ''
                on_new = True
            elif char == ')':
                return parse_error(origin_buffer, i, 'Mismatching right parenthesis.', 'MismatchingRightParenError')
            elif char == '\'':
                in_string = True
                parsed += current_node(current, prev_class, origin+origin_buffer)
                current = '\''
            elif char == '`': # Infix notation
                in_infix = True
                origin = i
            elif on_new:
                current = char
                prev_class = class_of(char)
                if in_infix:
                    prev_class = 'Operation'
                on_new = False
                origin = i
            else:
                current_class = class_of(char)
                if in_infix:
                    current_class = 'Operation'
                    prev_class = 'Operation'
                if prev_class != current_class:
                    parsed += current_node(current, prev_class, origin+origin_buffer)
                    current = char
                    origin = i
                else:
                    current += char
                on_new = False
                prev_class = current_class

    if show_steps:
        print(' ' * 3 * depth +  'Given:')
        for i in parsed:
            i.visualise(buffer=depth)
        print()

    # AST

    # Step two: Unary Operations
        # Todo:
            # Detect Unaries. Use pattern ..OOV.. (Op, Op, Val).
            # Resolve Unaries. Implement ..OOV.. -> ..Ov[V].. (Op, Op, Val -> Op, Val [Val]).

    # Step two_two: value application, and unexpected operation check

    parsed_new = []
    prev_type = 'Operation'
    for k, n in enumerate(parsed):
        parsed_new += [n]
        current_type = n.type
        if prev_type == current_type:
            if current_type == 'Operation':
                return parse_error(origin_buffer, n.origin, 'Unexpected operator', 'UnexpectedOperatorError')
            elif current_type == 'Value':
                parsed_new += [Node('<=', 'Operation', n.origin - 1), parsed_new.pop()]
            else:
                return parse_error(origin_buffer, n.origin, 'Invalid node type! {0}'.format(current_type), 'InvalidNodeTypeError')
        prev_type = current_type
    parsed = parsed_new

    if show_steps:
        print(' ' * 3 * depth +  'Insert Application:')
        for i in parsed:
            i.visualise(buffer=depth)
        print()

    if parsed[-1].type != 'Value':
        return parse_error(origin_buffer, parsed[-1].origin + len(parsed[-1].info) + 1, 'Missing value after operator.', 'MissingValueError')

    # Step three: Known Binary Operations.
        # Todo: Use order of Operations

    # Check single: Is the pattern a single node?
    if len(parsed) == 1:
        return parsed
    if len(parsed) == 2:
        raise EnvironmentError('Check single; 2')

    # Step four: Unknown Binary Operations.

    while len(parsed) != 1:
        parsed[1].left = parsed[0]
        parsed[1].riht = parsed[2]

        parsed.pop(0)
        parsed.pop(1)
        parsed[0].type = 'Value'
        parsed[0].is_operation = True

    # Assert single: Is the pattern a single node?
    if len(parsed) != 1:
        raise EnvironmentError('Assert single node')

    if show_steps:
        print(' ' * 3 * depth +  'Result:')
        [p.visualise(buffer=depth) for p in parsed]
        print()

    return parsed

_vars = {
    'T': True,
    'F': False,
    'X': {},
    'I': lambda x: x,
    'M': lambda x: x(x),
    'K': eval('lambda a: lambda b: a')
}

def resolve(fn, text):
    e = expr_parse(text, show_steps=False)
    result = e[0].value(_vars, text, {"show_steps": False})
    if type(result) == Error:
        return None, result
    return result, None


import cv2

#设置高低阈值
lowThreshold = 0
max_lowThreshold = 100
ratio = 3
kernel_size = 3

img = cv2.imread('lenna.png')
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

def Canny(lowThreshold,ratio,img_gray):
    detected_edges = cv2.GaussianBlur(img_gray,(3,3),0) #高斯滤波处理
    detected_edges = cv2.Canny(detected_edges,
                               lowThreshold,
                               lowThreshold * ratio,
                               apertureSize=kernel_size)  # 边缘检测
    cv2.imshow('canny demo', detected_edges)
    cv2.waitKey()

Canny(0,ratio,img_gray)


from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

def AddDisplayNameFlag(parser, required=True):
  """Adds a --display-name flag to the given parser."""
  help_text = """Friendly name for the stream."""
  parser.add_argument('--display-name', help=help_text, required=required)

def AddUpdateMaskFlag(parser):
  """Adds a --update-mask flag to the given parser."""
  help_text = """Used to specify the fields to be overwritten in the stream resource by the update.
  If the update mask is used, then a field will be overwritten only if it is in the mask. If the user does not provide a mask then all fields will be overwritten.
  This is a comma-separated list of fully qualified names of fields, written as snake_case or camelCase. Example: "display_name, source_config.oracle_source_config"."""
  parser.add_argument('--update-mask', help=help_text)

def AddStateFlag(parser):
  """Adds a --state flag to the given parser."""
  help_text = """Stream state, can be set to: "RUNNING" or "PAUSED"."""
  parser.add_argument('--state', help=help_text)

def AddValidationGroup(parser, verb):
  """Adds a --validate-only or --force flag to the given parser."""
  validation_group = parser.add_group(mutex=True)
  validation_group.add_argument(
      '--validate-only',
      help="""Only validate the stream, but do not %s any resources.
      The default is false.""" % verb.lower(),
      action='store_true',
      default=False)
  validation_group.add_argument(
      '--force',
      help="""%s the stream without validating it.""" % verb,
      action='store_true',
      default=False)

def AddBackfillStrategyGroup(parser, required=True):
  """Adds a --backfiill-all or --backfill-none flag to the given parser."""
  backfill_group = parser.add_group(required=required, mutex=True)
  backfill_group.add_argument(
      '--backfill-none',
      help="""Do not automatically backfill any objects.""",
      action='store_true')
  backfill_all_group = backfill_group.add_group()
  backfill_all_group.add_argument(
      '--backfill-all',
      help="""Automatically backfill objects included in the stream source
      configuration. Specific objects can be excluded.""",
      action='store_true')
  backfill_all_excluded_objects = backfill_all_group.add_group(mutex=True)
  backfill_all_excluded_objects.add_argument(
      '--oracle-excluded-objects',
      help="""Oracle data source objects to avoid backfilling.""")
  backfill_all_excluded_objects.add_argument(
      '--mysql-excluded-objects',
      help="""MySQL data source objects to avoid backfilling.""")
  backfill_all_excluded_objects.add_argument(
      '--postgresql-excluded-objects',
      help="""PostgreSQL data source objects to avoid backfilling.""")


# 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.

import uuid

from openstack.load_balancer.v2 import l7_rule
from openstack.tests.unit import base

EXAMPLE = {
    'admin_state_up': True,
    'compare_type': 'REGEX',
    'created_at': '2017-08-17T12:14:57.233772',
    'id': uuid.uuid4(),
    'invert': False,
    'key': 'my_cookie',
    'l7_policy_id': uuid.uuid4(),
    'operating_status': 'ONLINE',
    'project_id': uuid.uuid4(),
    'provisioning_status': 'ACTIVE',
    'type': 'COOKIE',
    'updated_at': '2017-08-17T12:16:57.233772',
    'value': 'chocolate',
}

class TestL7Rule(base.TestCase):
    def test_basic(self):
        test_l7rule = l7_rule.L7Rule()
        self.assertEqual('rule', test_l7rule.resource_key)
        self.assertEqual('rules', test_l7rule.resources_key)
        self.assertEqual(
            '/lbaas/l7policies/%(l7policy_id)s/rules', test_l7rule.base_path
        )
        self.assertTrue(test_l7rule.allow_create)
        self.assertTrue(test_l7rule.allow_fetch)
        self.assertTrue(test_l7rule.allow_commit)
        self.assertTrue(test_l7rule.allow_delete)
        self.assertTrue(test_l7rule.allow_list)

    def test_make_it(self):
        test_l7rule = l7_rule.L7Rule(**EXAMPLE)
        self.assertTrue(test_l7rule.is_admin_state_up)
        self.assertEqual(EXAMPLE['compare_type'], test_l7rule.compare_type)
        self.assertEqual(EXAMPLE['created_at'], test_l7rule.created_at)
        self.assertEqual(EXAMPLE['id'], test_l7rule.id)
        self.assertEqual(EXAMPLE['invert'], test_l7rule.invert)
        self.assertEqual(EXAMPLE['key'], test_l7rule.key)
        self.assertEqual(EXAMPLE['l7_policy_id'], test_l7rule.l7_policy_id)
        self.assertEqual(
            EXAMPLE['operating_status'], test_l7rule.operating_status
        )
        self.assertEqual(EXAMPLE['project_id'], test_l7rule.project_id)
        self.assertEqual(
            EXAMPLE['provisioning_status'], test_l7rule.provisioning_status
        )
        self.assertEqual(EXAMPLE['type'], test_l7rule.type)
        self.assertEqual(EXAMPLE['updated_at'], test_l7rule.updated_at)
        self.assertEqual(EXAMPLE['value'], test_l7rule.rule_value)

        self.assertDictEqual(
            {
                'limit': 'limit',
                'marker': 'marker',
                'created_at': 'created_at',
                'updated_at': 'updated_at',
                'project_id': 'project_id',
                'tags': 'tags',
                'any_tags': 'tags-any',
                'not_tags': 'not-tags',
                'not_any_tags': 'not-tags-any',
                'operating_status': 'operating_status',
                'provisioning_status': 'provisioning_status',
                'is_admin_state_up': 'admin_state_up',
                'compare_type': 'compare_type',
                'invert': 'invert',
                'key': 'key',
                'type': 'type',
                'rule_value': 'rule_value',
                'l7_policy_id': 'l7policy_id',
            },
            test_l7rule._query_mapping._mapping,
        )


#
# def change(A):
#     for k in range(0,len(A)):
#         if A[k]=="0":
#             A[k]="1"
#         else:
#             A[k]= "0"
#     return 1
# for i in range(int(input())):
#     A = list(input())
#     count = 0
#     p = 0
#     for j in range(len(A)):
#         if A[j]=="0":
#             p+=change(A)
#     print(p)

for i in range(int(input())):
    A = list(input())
    p = "1"
    count = 0
    for j in range(len(A)):
        if p!=A[j]:
            p = A[j]
            count+=1
    print(count)


#! python3
'''Autom8r: log all inputs to a log file (possibly stderr) before echoing them to stdout'''
import sys
import time

try:
    logname = time.strftime(sys.argv[1])    # treat filename as pattern for strftime (%Y, %m, %d, etc.)
    logfile = open(logname, "a")            # open file for over-writing
except IndexError:
    logfile = sys.stderr

# For each line of input...
for line in sys.stdin:
    # ...strip newline...
    line = line.rstrip('\n')

    # ...and print them to BOTH stdout AND our logfile
    print(line)
    print(line, file=logfile)

# For legibility, print a divider bar of '-'s to stderr here (if we are logging to stderr)
if logfile is sys.stderr:
    print('-'*60, file=logfile)
else:
    logfile.close()


# Даны два файла,
# в каждом из которых находится запись многочлена.
#  Задача - сформировать файл, содержащий сумму многочленов.
#  2*x² + 4*x + 5 3*x² +10*x + 6 Вывод: 5*x² + 14*x + 11

import sympy

with open('C:/GB_1/lecture_Py/file5.1DZ.txt', 'r') as file:
   list1 = file.read()
   print(list1)
with open('C:/GB_1/lecture_Py/file5.2DZ.txt', 'r') as file:
   list2 = file.read()
   print(list2)
sum = sympy.simplify(list1+ '+' + list2)
print(sum)
with open('C:/GB_1/lecture_Py/file5.3DZ.txt', 'w', encoding='utf-8') as file:
   file.write(str(sum))


import pygame
from snakeplayer import *
from scene import *
from Apple import *
import time

def display_info():

    """ Print out information about the"""
    """display driver and video information."""
    print('The display is using the "{}" driver.'.format(pygame.display.get_driver()))
    print('Video Info:')
    print(pygame.display.Info())

def main():

    print('hello world!')
    pygame.init()
    display_info()
    window_size = (800, 800)

    screen = pygame.display.set_mode(window_size)
    title = 'Snake++'
    pygame.display.set_caption(title)
    snake = SnakePlayer(screen)
    apple = Apple(screen, snake)
    scene_list = [TitleScene(screen, title, rgbcolors.green, 72),enterNameScreen(screen, title, rgbcolors.purple, 72), InstructionScene(screen, title,rgbcolors.grey, 72), GameLevel(screen, snake, apple)
    , GameOverScreen(screen,'Game Over',rgbcolors.red, 72), highScores(screen, title, 60)]
    #scene_list = [highScores(screen, title, 60)]

    for scene in scene_list:
        scene.play_music()
        while scene.is_valid():
            for e in pygame.event.get():
                scene.process_event(e)
            scene.update()
            scene.draw()
            pygame.display.update()
        scene.stop_music()
    pygame.quit()


#!/usr/bin/env python

# Title			: 	samplesSheetCreater.py
# Created by	: 	Marissa Dubbelaar
# Created on	: 	26-05-2016
# Purpose		:	Create a samples sheet which can be used within the RNA sequencing pipeline of Calculon.

import os

class CreateSampleSheet():
	def __init__(self, pathwayFastQ, outputFile):
		'''
			As input the pathway to the FastQ files and the output file are given.
			The init calls the necessary functions to obtain the names of the files and
			to create and close the file where the information is written.
		'''
		self.pathwayFastQ = pathwayFastQ
		self.outputFile = outputFile
		# A count is made to write the index of the file.
		self.count = 1
		# The file is made
		self.createCSV()
		# The names of the files within the pathwayFastQ are obtained
		self.readFiles()
		# CSV files is closed again.
		self.closeCSV()

	def readFiles(self):
		'''
			This function obtains all of the known fastq files within the given pathway.
		'''
		# The root and file names are obtained that are available in the self.pathwayFastQ
		for root, directories, files in os.walk(self.pathwayFastQ):
			# The root is splitted to make sure that the ensemble id is obtained for further use.
			root = root.split("/")
			# For every filename in the pathway.
			for f in files:
				# Make sure that the files end with .fastq or .fastq.gz
				if f.endswith(".fastq") or f.endswith(".fastq.gz"):
					# The file name is splitted on the dot, resulting in the SRA number and the extention.
					f= f.split(".")
					# The SRA number and the ensemble id is used with the function "writeCSV"
					self.writeCSV(f[0], root[-2])

	def createCSV(self):
		'''
			Creates a csv where all of the necessary information for the RNA sequencing pipeline needs to be stored.
		'''
		self.csv = open(self.outputFile, 'w')
		self.csv.write("internalId,project,sampleName,reads1FqGz,reads2FqGz,sortedBamFile\n")

	def closeCSV(self):
		'''
			The CSV file is closed.
		'''
		self.csv.close()

	def writeCSV(self, SRANumber, EGEODNumber):
		'''
			All of the necessary information will be written into the file with the use of the function writeCSV.
		'''
		# If the fastq file is part of a pairwise sequencing.
		if "_" in SRANumber and SRANumber.endswith("_1"):
			# The SRNA number splitted and used to be written into the file and the column "reads2FqGz" is filled in as well.
			SRANumber, addition = SRANumber.split("_")
			self.csv.write(str(self.count)+",EGEOD_"+EGEODNumber+","+SRANumber+",/groups/umcg-gcc/tmp04/umcg-mdubbelaar/GOAD/"
				+EGEODNumber+"/"+SRANumber+"_1.fastq,/groups/umcg-gcc/tmp04/umcg-mdubbelaar/GOAD/"
				+EGEODNumber+"/"+SRANumber+"_2.fastq,/groups/umcg-gcc/tmp04/umcg-mdubbelaar/tryKallisto/miceData/EGEOD_"
				+EGEODNumber+"/run01/results/sortedBam/"+SRANumber+"_"+str(self.count)+".bam\n")
			self.count += 1
		# If the fastq file is sequenced singlewise
		elif "_" not in SRANumber:
			# The SRA number is used and the column "reads2FqGz" remains empty.
			self.csv.write(str(self.count)+",EGEOD_"+EGEODNumber+","+SRANumber+",/groups/umcg-gcc/tmp04/umcg-mdubbelaar/GOAD/"
				+EGEODNumber+"/"+SRANumber+".fastq,,/groups/umcg-gcc/tmp04/umcg-mdubbelaar/tryKallisto/miceData/EGEOD_"
				+EGEODNumber+"/run01/results/sortedBam/"+SRANumber+"_"+str(self.count)+".bam\n")
			self.count += 1

css = CreateSampleSheet("/Volumes/Elements/School/Afstuderen/GOAD3/Data/53737/", "/Users/marissa/Desktop/samplesSheet53737.csv")


"""
1200. Minimum Absolute Difference
https://leetcode.com/problems/minimum-absolute-difference/

Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.

Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows

a, b are from arr
a < b
b - a equals to the minimum absolute difference of any two elements in arr

Example:
Input: arr = [4,2,1,3]
Output: [[1,2],[2,3],[3,4]]
Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.

Input: arr = [3,8,-10,23,19,-4,-14,27]
Output: [[-14,-10],[19,23],[23,27]]
"""

# Runtime: 328ms (82.02%)
class Solution:
    def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:

        arr.sort()
        curr_min = float('inf')
        output = []

        for i in range(0, len(arr)-1):
            # check the curr_min
            temp_min = abs(arr[i+1] - arr[i])
            if temp_min < curr_min:
                curr_min = temp_min
                output = [[arr[i], arr[i+1]]]
            elif temp_min == curr_min:
                output.append([arr[i], arr[i+1]])

        return output


"""
Tests: Restore a trained model and re-evaluate
"""
import tensorflow as tf
from rnnvis.procedures import build_model, init_tf_environ, pour_data

flags = tf.flags
flags.DEFINE_string("config_path", None, "The path of the model configuration file")
flags.DEFINE_integer('gpu_num', 0, "The number of the gpu to use, 0 to use no gpu.")
FLAGS = flags.FLAGS

def config_path():
    return FLAGS.config_path

if __name__ == '__main__':
    init_tf_environ(FLAGS.gpu_num)
    # datasets = get_datasets_by_name('ptb', ['test'])
    # test_data = datasets['test']

    model, train_config = build_model(config_path(), True)

    model.add_evaluator(10, 1, 1, True, False, False, False, log_gates=True)
    model.restore()

    print('Preparing data')
    producers = pour_data(train_config.dataset, ['test'], train_config.batch_size, train_config.num_steps)
    inputs, targets, epoch_size = producers[0]
    print('Re-Testing...')
    model.validate(inputs, targets, epoch_size)


import numpy as np
import math

# 问题1计算出Wn
def calculate_Wn_1(y_position):
    theta = math.radians(120)
    alpha = math.radians(1.5)
    Depth = 2 * 1852 * math.tan(math.radians(1.5)) + 110 - y_position * math.tan(math.radians(1.5))
    # print(Depth)
    W = math.sin(theta) * math.cos(alpha)**2 * Depth / (math.cos(theta/2-alpha) * math.cos(theta/2+alpha))
    return W

# print(calculate_Wn_1(2*1852))

#记录每单位的移动对应的测量数量
# def detect_array():
#     detect_array = []
#     for i in range(0,L,step):
#         detect_array.append((i,detect_width(i)))
#     return detect_array