# Write a function, pair_sum, that takes in a list and a target sum
# as arguments. The function should return a tuple containing
# a pair of indices whose elements sum to the givien target. The
# indices returned must be unique.

# Be sure to return the indices, not the elements themselves.
# There is guaranteed to be one such pair that sums to the target.

def pair_sum(numbers, target_sum):
    nums = {}
    for i, num in enumerate(numbers):
        difference = target_sum - num
        if difference in nums:
            return (nums[difference], i)
        else:
            nums[num] = i
    return -1

print(pair_sum([3, 2, 5, 4, 1], 8)) # -> (0, 2)
print(pair_sum([4, 7, 9, 2, 5, 1], 5)) # -> (0, 5)
print(pair_sum([4, 7, 9, 2, 5, 1], 3)) # -> (3, 5)
print(pair_sum([1, 6, 7, 2], 13)) # -> (1, 2)
print(pair_sum([9, 9], 18)) # -> (0, 1)
print(pair_sum([6, 4, 2, 8 ], 12)) # -> (1, 3)


from __future__ import print_function

from gi.repository import IBus
from gi.repository import GLib
from gi.repository import GObject

import os
import re
import sys
import json
import getopt
import locale
import codecs
from collections import Counter, defaultdict

from difflib import SequenceMatcher

try:
    import Levenshtein
except ImportError:
    Levenshtein = None

try:
    import xdg
except ImportError:
    xdg = None
else:
    import xdg.BaseDirectory

debug_on = True
def debug(*a, **kw):
    if debug_on:
        print(*a, **kw)

# gee thank you IBus :-)
num_keys = []
for n in range(10):
    num_keys.append(getattr(IBus, str(n)))
del n

__base_dir__ = os.path.dirname(__file__)

VALID_CATEGORIES = (
    'Sm', # Symbol, math
    'So', # Symbol, other
    'Pd', # Punctuation, dash
    'Po', # Punctuation, other
)

VALID_RANGES = (
    (0x2000, 0x206f), # General Punctuation, Layout Controls, Invisible Operators
    (0x2070, 0x209f), # Superscripts and Subscripts
    (0x20a0, 0x20cf), # Currency Symbols
    (0x20ac, 0x20ac), # Euro Sign
    (0x20d0, 0x20ff), # Combining Diacritical Marks for Symbols
    (0x2100, 0x214f), # Additional Squared Symbols, Letterlike Symbols
    (0x2150, 0x218f), # Number Forms
    (0x2190, 0x21ff), # Arrows
    (0x2200, 0x22ff), # Mathematical Operators
    (0x2300, 0x23ff), # Miscellaneous Technical, Floors and Ceilings
    (0x2336, 0x237a), # APL symbols
    (0x2400, 0x243f), # Control Pictures
    (0x2440, 0x245f), # Optical Character Recognition (OCR)
    (0x2460, 0x24ff), # Enclosed Alphanumerics
    (0x2500, 0x257f), # Box Drawing
    (0x2580, 0x259f), # Block Elements
    (0x25a0, 0x25ff), # Geometric Shapes
    (0x2600, 0x26ff), # Miscellaneous Symbols
    (0x2616, 0x2617), # Japanese Chess
    (0x2654, 0x265f), # Chess
    (0x2660, 0x2667), # Card suits
    (0x2630, 0x2637), # Yijing Trigrams
    (0x268a, 0x268f), # Yijing Monograms and Digrams
    (0x26c0, 0x26c3), # Checkers/Draughts
    (0x2700, 0x27bf), # Dingbats
    (0x27c0, 0x27ef), # Miscellaneous Mathematical Symbols-A
    (0x27f0, 0x27ff), # Supplemental Arrows-A
    (0x2800, 0x28ff), # Braille Patterns
    (0x2900, 0x297f), # Supplemental Arrows-B
    (0x2980, 0x29ff), # Miscellaneous Mathematical Symbols-B
    (0x2a00, 0x2aff), # Supplemental Mathematical Operators
    (0x2b00, 0x2bff), # Additional Shapes, Miscellaneous Symbols and Arrows
    (0x1f300, 0x1f5ff), # Miscellaneous Symbols and Pictographs
    (0x1f600, 0x1f64f), # Emoticons
    (0x1f650, 0x1f67f), # Ornamental Dingbats
    (0x1f680, 0x1f6ff), # Transport and Map Symbols
    (0x1f900, 0x1f9ff), # Supplemental Symbols and Pictographs
)

def in_range(code):
    return any(x <= code <= y for x,y in VALID_RANGES)

MATCH_LIMIT = 100

if xdg:
    SETTINGS_DIRS = list(xdg.BaseDirectory.load_config_paths('uniemoji'))
else:
    SETTINGS_DIRS = [d for d in [os.path.expanduser('~/.config/uniemoji'), '/etc/xdg/uniemoji']
                     if os.path.isdir(d)]

###########################################################################
CANDIDATE_UNICODE = 0
CANDIDATE_ALIAS = 1

class UniEmojiChar(object):
    def __init__(self, unicode_str=None, is_emojione=False, is_custom=False):
        self.unicode_str = unicode_str
        self.aliasing = []
        self.is_emojione = is_emojione
        self.is_custom = is_custom

    def __repr__(self):
        return 'UniEmojiChar(unicode_str={}, is_emojione={}, is_custom={}, aliasing={})'.format(
            self.unicode_str,
            self.is_emojione,
            self.is_custom,
            self.aliasing)

# the engine
class UniEmoji(IBus.Engine):
    __gtype_name__ = 'UniEmoji'

    def __init__(self):
        super(UniEmoji, self).__init__()
        self.is_invalidate = False
        self.preedit_string = u""
        self.lookup_table = IBus.LookupTable.new(10, 0, True, True)
        self.prop_list = IBus.PropList()
        self.table = defaultdict(UniEmojiChar)
        self.unicode_chars_to_names = {}
        self.unicode_chars_to_shortnames = {}
        self.ascii_table = {}
        self.reverse_ascii_table = {}
        self.alias_table = {}
        with codecs.open(os.path.join(__base_dir__, 'UnicodeData.txt'), encoding='utf-8') as unicodedata:
            for line in unicodedata.readlines():
                if not line.strip(): continue
                code, name, category, _ = line.split(';', 3)
                code = int(code, 16)
                if category not in VALID_CATEGORIES:
                    continue
                if not in_range(code):
                    continue
                name = name.lower()
                unicode_char = unichr(code)
                self.table[name] = UniEmojiChar(unicode_char)
                self.unicode_chars_to_names[unicode_char] = name

        # Load emojione file
        alias_counter = Counter()
        temp_alias_table = defaultdict(set)

        emojione = json.load(codecs.open(os.path.join(__base_dir__, 'emojione.json'), encoding='utf-8'))
        for emoji_shortname, info in emojione.iteritems():

            # ZWJ emojis such as 'family', 'couple', and 'kiss' appear in an
            # alternate field
            alternate_form = info.get('unicode_alternates')
            if alternate_form and '200d' in alternate_form:
                print('found alternate', alternate_form)
                chars = alternate_form
            else:
                chars = info['unicode']

            unicode_str = u''.join(unichr(int(codepoint, 16)) for codepoint in chars.split('-'))
            self.unicode_chars_to_shortnames[unicode_str] = emoji_shortname

            emoji_shortname = emoji_shortname.replace('_', ' ')

            if emoji_shortname in self.table:
                # Check for clashes between emojione's names and the existing unicode name.
                # Clashes turn into aliases.
                if unicode_str != self.table[emoji_shortname].unicode_str:
                    self.table[emoji_shortname].aliasing.append(unicode_str)
            elif info['category'] == 'flags':
                flag_name = 'flag of ' + info['name']
                self.table[flag_name] = UniEmojiChar(unicode_str, is_emojione=True)
                self.unicode_chars_to_names[unicode_str] = flag_name
            else:
                self.table[emoji_shortname] = UniEmojiChar(unicode_str, is_emojione=True)

            # When the string defined by emojione isn't in Unicode
            # (because it's a combination of characters), use emojione's
            # descriptive name, and set the shortname as an alias
            if unicode_str not in self.unicode_chars_to_names:
                long_name = info['name']
                self.unicode_chars_to_names[unicode_str] = long_name
                if long_name not in self.table:
                    self.table[long_name] = UniEmojiChar(unicode_str)

            # EmojiOne has duplicate entries in the keywords array
            keywords = set(info.get('keywords', []))
            for alias in keywords:
                alias_counter[alias] += 1
                temp_alias_table[alias].add(unicode_str)

            for ascii_aliases in info.get('aliases_ascii', []):
                self.ascii_table[ascii_aliases] = unicode_str
                self.reverse_ascii_table[unicode_str] = info['name']

        # Load less-frequent aliases from emojione file
        for alias, n in alias_counter.most_common():
            if n >= 20:
                continue
            self.table[alias].aliasing.extend(temp_alias_table[alias])

        # Load custom file(s)
        for d in reversed(SETTINGS_DIRS):
            custom_filename = os.path.join(d, 'custom.json')
            debug('Loading custom emoji from {}'.format(custom_filename))
            if os.path.isfile(custom_filename):
                custom_table = None
                try:
                    with codecs.open(custom_filename, encoding='utf-8') as f:
                        custom_table = json.loads(f.read())
                except:
                    error = sys.exc_info()[1]
                    debug(error)
                    self.table = {
                        u'Failed to load custom file {}: {}'.format(custom_filename, error): u'ERROR'
                    }
                    break
                else:
                    debug(custom_table)
                    for k, v in custom_table.iteritems():
                        self.table[k] = UniEmojiChar(v, is_custom=True)

        debug("Create UniEmoji engine OK")

    def do_process_key_event(self, keyval, keycode, state):
        debug("process_key_event(%04x, %04x, %04x)" % (keyval, keycode, state))

        # ignore key release events
        is_press = ((state & IBus.ModifierType.RELEASE_MASK) == 0)
        if not is_press:
            return False

        if self.preedit_string:
            if keyval == IBus.Return:
                if self.lookup_table.get_number_of_candidates() > 0:
                    self.commit_candidate()
                else:
                    self.commit_string(self.preedit_string)
                return True
            elif keyval == IBus.Escape:
                self.preedit_string = u""
                self.update_candidates()
                return True
            elif keyval == IBus.BackSpace:
                self.preedit_string = self.preedit_string[:-1]
                self.invalidate()
                return True
            elif keyval in num_keys[1:]:
                index = num_keys.index(keyval) - 1
                page_size = self.lookup_table.get_page_size()
                if index > page_size:
                    return False
                page, pos_in_page = divmod(self.lookup_table.get_cursor_pos(),
                                           page_size)
                new_pos = page * page_size + index
                if new_pos > self.lookup_table.get_number_of_candidates():
                    return False
                self.lookup_table.set_cursor_pos(new_pos)
                self.commit_candidate()
                return True
            elif keyval == IBus.Page_Up or keyval == IBus.KP_Page_Up:
                self.page_up()
                return True
            elif keyval == IBus.Page_Down or keyval == IBus.KP_Page_Down:
                self.page_down()
                return True
            elif keyval == IBus.Up:
                self.cursor_up()
                return True
            elif keyval == IBus.Down:
                self.cursor_down()
                return True
            elif keyval == IBus.Left or keyval == IBus.Right:
                return True

        if keyval == IBus.space and len(self.preedit_string) == 0:
            # Insert space if that's all you typed (so you can more easily
            # type a bunch of emoji separated by spaces)
            return False

        # Allow typing all ASCII letters and punctuation, except digits
        if ord(' ') <= keyval < ord('0') or \
           ord('9') < keyval <= ord('~'):
            if state & (IBus.ModifierType.CONTROL_MASK | IBus.ModifierType.MOD1_MASK) == 0:
                self.preedit_string += unichr(keyval)
                self.invalidate()
                return True
        else:
            if keyval < 128 and self.preedit_string:
                self.commit_string(self.preedit_string)

        return False

    def invalidate(self):
        if self.is_invalidate:
            return
        self.is_invalidate = True
        GLib.idle_add(self.update_candidates)

    def page_up(self):
        if self.lookup_table.page_up():
            self._update_lookup_table()
            return True
        return False

    def page_down(self):
        if self.lookup_table.page_down():
            self._update_lookup_table()
            return True
        return False

    def cursor_up(self):
        if self.lookup_table.cursor_up():
            self._update_lookup_table()
            return True
        return False

    def cursor_down(self):
        if self.lookup_table.cursor_down():
            self._update_lookup_table()
            return True
        return False

    def commit_string(self, text):
        self.commit_text(IBus.Text.new_from_string(text))
        self.preedit_string = u""
        self.update_candidates()

    def commit_candidate(self):
        self.commit_string(self.candidates[self.lookup_table.get_cursor_pos()])

    def filter(self, query, candidates = None):
        if len(self.table) <= 10:
            # this only happens if something went wrong; it's our cheap way of displaying errors
            return [[0, 0, message] for message in self.table]

        if candidates is None: candidates = self.table

        # Replace '_' in query with ' ' since that's how emojione names are stored
        query = query.replace('_', ' ')

        query_words = []
        for w in query.split():
            escaped_w = re.escape(w)
            query_words.append((
                w,
                re.compile(r'\b' + escaped_w + r'\b'),
                re.compile(r'\b' + escaped_w),
            ))

        # Matches are tuples of the form:
        # (match_type, score, name)
        # Match types are:
        # * 20 - exact
        # * 10 - substring
        # * 5 - substring of alias
        # * 0 - levenshtein distance
        matched = []

        for candidate, candidate_info in candidates.iteritems():
            if len(query) > len(candidate): continue

            if query == candidate:
                # Exact match
                if candidate_info.unicode_str:
                    matched.append((20, 0, candidate, CANDIDATE_UNICODE))
                if candidate_info.aliasing:
                    matched.append((5, 0, candidate, CANDIDATE_ALIAS))
            else:
                # Substring match
                word_ixs = []
                substring_found = False
                exact_word_match = 0
                prefix_match = 0
                for w, exact_regex, prefix_regex in query_words:
                    ix = candidate.find(w)
                    if ix == -1:
                        word_ixs.append(100)
                    else:
                        substring_found = True
                        word_ixs.append(ix)

                        # Check if an exact word match or a prefix match
                        if exact_regex.search(candidate):
                            exact_word_match += 1
                        elif prefix_regex.search(candidate):
                            prefix_match += 1

                if substring_found and all(ix >= 0 for ix in word_ixs):
                    # For substrings, the closer to the origin, the better
                    score = -(float(sum(word_ixs)) / len(word_ixs))

                    # Receive a boost if the substring matches a word or a prefix
                    score += 20 * exact_word_match + 10 * prefix_match

                    if candidate_info.unicode_str:
                        matched.append((10, score, candidate, CANDIDATE_UNICODE))
                    if candidate_info.aliasing:
                        matched.append((5, score, candidate, CANDIDATE_ALIAS))
                else:
                    # Levenshtein distance
                    score = 0
                    if Levenshtein is None:
                        opcodes = SequenceMatcher(None, query, candidate,
                            autojunk=False).get_opcodes()
                    else:
                        opcodes = Levenshtein.opcodes(query, candidate)
                    for (tag, i1, i2, j1, j2) in opcodes:
                        if tag in ('replace', 'delete'):
                            score = 0
                            break
                        if tag == 'insert':
                            score -= 1
                        if tag == 'equal':
                            score += i2 - i1
                            # favor word boundaries
                            if j1 == 0:
                                score += 2
                            elif candidate[j1 - 1] == ' ':
                                score += 1
                            if j2 == len(candidate):
                                score += 2
                            elif [j2] == ' ':
                                score += 1
                    if score > 0:
                        if candidate_info.unicode_str:
                            matched.append((0, score, candidate, CANDIDATE_UNICODE))
                        if candidate_info.aliasing:
                            matched.append((0, score, candidate, CANDIDATE_ALIAS))

        # The first two fields are sorted in reverse.
        # The third text field is sorted by the length of the string, then alphabetically.
        matched.sort(key=lambda x: (len(x[2]), x[2]))
        matched.sort(key=lambda x: (x[0], x[1]), reverse=True)
        return matched[:MATCH_LIMIT]

    def update_candidates(self):
        preedit_len = len(self.preedit_string)
        attrs = IBus.AttrList()
        self.lookup_table.clear()
        self.candidates = []
        candidate_strings = set()

        if preedit_len > 0:
            # Look for an ASCII alias that matches exactly
            ascii_match = self.ascii_table.get(self.preedit_string)
            if ascii_match:
                unicode_name = self.reverse_ascii_table[ascii_match]
                display_str = u'{}: {} [{}]'.format(ascii_match, unicode_name, self.preedit_string)
                candidate = IBus.Text.new_from_string(display_str)
                self.candidates.append(ascii_match)
                self.lookup_table.append_candidate(candidate)

            # Look for a fuzzy match against a description
            for level, score, name, candidate_type in self.filter(self.preedit_string.lower()):
                uniemoji_char = self.table[name]

                # Since we have several source (UnicodeData.txt, EmojiOne),
                # make sure we don't output multiple identical candidates
                if candidate_type == CANDIDATE_UNICODE:
                    if uniemoji_char.unicode_str in candidate_strings:
                        continue
                    candidate_strings.add(uniemoji_char.unicode_str)

                    display_str = None
                    if uniemoji_char.is_emojione:
                        unicode_name = self.unicode_chars_to_names.get(uniemoji_char.unicode_str)
                        if unicode_name and unicode_name != name:
                            display_str = u'{}: :{}: {}'.format(
                                uniemoji_char.unicode_str,
                                name.replace(' ', '_'),
                                unicode_name)
                    if display_str is None:
                        shortname = self.unicode_chars_to_shortnames.get(uniemoji_char.unicode_str, '')
                        if shortname:
                            shortname = ':' + shortname + ': '
                        display_str = u'{}: {}{}'.format(
                            uniemoji_char.unicode_str,
                            shortname,
                            name)

                    candidate = IBus.Text.new_from_string(display_str)
                    self.candidates.append(uniemoji_char.unicode_str)
                    self.lookup_table.append_candidate(candidate)

                # Aliases expand into several candidates
                for unicode_str in uniemoji_char.aliasing:
                    if unicode_str in candidate_strings:
                        continue
                    candidate_strings.add(unicode_str)
                    unicode_name = self.unicode_chars_to_names.get(unicode_str)
                    shortname = self.unicode_chars_to_shortnames.get(unicode_str, '')
                    if shortname:
                        shortname = ':' + shortname + ': '
                    display_str = u'{}: {}{} [{}]'.format(
                        unicode_str,
                        shortname,
                        unicode_name,
                        name)
                    candidate = IBus.Text.new_from_string(display_str)
                    self.candidates.append(unicode_str)
                    self.lookup_table.append_candidate(candidate)

        text = IBus.Text.new_from_string(self.preedit_string)
        text.set_attributes(attrs)
        self.update_auxiliary_text(text, preedit_len > 0)

        attrs.append(IBus.Attribute.new(IBus.AttrType.UNDERLINE,
                IBus.AttrUnderline.SINGLE, 0, preedit_len))
        text = IBus.Text.new_from_string(self.preedit_string)
        text.set_attributes(attrs)
        self.update_preedit_text(text, preedit_len, preedit_len > 0)
        self._update_lookup_table()
        self.is_invalidate = False

    def _update_lookup_table(self):
        visible = self.lookup_table.get_number_of_candidates() > 0
        self.update_lookup_table(self.lookup_table, visible)

    def do_focus_in(self):
        debug("focus_in")
        self.register_properties(self.prop_list)

    def do_focus_out(self):
        debug("focus_out")
        self.do_reset()

    def do_reset(self):
        debug("reset")
        self.preedit_string = u""

    def do_property_activate(self, prop_name):
        debug("PropertyActivate(%s)" % prop_name)

###########################################################################
# the app (main interface to ibus)
class IMApp:
    def __init__(self, exec_by_ibus):
        if not exec_by_ibus:
            global debug_on
            debug_on = True
        self.mainloop = GLib.MainLoop()
        self.bus = IBus.Bus()
        self.bus.connect("disconnected", self.bus_disconnected_cb)
        self.factory = IBus.Factory.new(self.bus.get_connection())
        self.factory.add_engine("uniemoji", GObject.type_from_name("UniEmoji"))
        if exec_by_ibus:
            self.bus.request_name("org.freedesktop.IBus.UniEmoji", 0)
        else:
            xml_path = os.path.join(__base_dir__, 'uniemoji.xml')
            if os.path.exists(xml_path):
                component = IBus.Component.new_from_file(xml_path)
            else:
                xml_path = os.path.join(os.path.dirname(__base_dir__),
                                        'ibus', 'component', 'uniemoji.xml')
                component = IBus.Component.new_from_file(xml_path)
            self.bus.register_component(component)

    def run(self):
        self.mainloop.run()

    def bus_disconnected_cb(self, bus):
        self.mainloop.quit()

def launch_engine(exec_by_ibus):
    IBus.init()
    IMApp(exec_by_ibus).run()

def print_help(out, v = 0):
    print("-i, --ibus             executed by IBus.", file=out)
    print("-h, --help             show this message.", file=out)
    print("-d, --daemonize        daemonize ibus", file=out)
    sys.exit(v)

def main():
    try:
        locale.setlocale(locale.LC_ALL, "")
    except:
        pass

    exec_by_ibus = False
    daemonize = False

    shortopt = "ihd"
    longopt = ["ibus", "help", "daemonize"]

    try:
        opts, args = getopt.getopt(sys.argv[1:], shortopt, longopt)
    except getopt.GetoptError:
        print_help(sys.stderr, 1)

    for o, a in opts:
        if o in ("-h", "--help"):
            print_help(sys.stdout)
        elif o in ("-d", "--daemonize"):
            daemonize = True
        elif o in ("-i", "--ibus"):
            exec_by_ibus = True
        else:
            print("Unknown argument: %s" % o, file=sys.stderr)
            print_help(sys.stderr, 1)

    if daemonize:
        if os.fork():
            sys.exit()

    launch_engine(exec_by_ibus)

if __name__ == "__main__":
    main()


class Search:
    def __init__(self, filename):
        self.filename = filename
        self.countries = []
        self.file = None

        with open(self.filename, "rt") as myfile:
            for myline in myfile:
                self.countries.append(myline.rstrip('\n'))

    def validate(self, soal):
        result = ''
        for count in self.countries:
            if soal in count.lower():
                result +=  count + '--'
        return result.rstrip('--')


def helper(arr): #conquer
    n = len(arr)
    ans = {0}
    for mask in range(1, 1 << n):
        ss = 0
        for i, val in enumerate(arr):
            if (1 << i) & mask:
                    ss += val
        ans.add(ss)
    return list(ans)
def minAbsDifference(nums, target):
    n = len(nums)
    n_2 = n // 2
    s1, s2 = helper(nums[:n_2]), helper(nums[n_2 :]) #divide
    s1.sort()
    s2.sort()
    ans = abs(target)
    i1, i2 = 0, len(s2) - 1
    while i1 < len(s1) and i2 >= 0: #combine
        cur = s1[i1] + s2[i2]
        ans = min(ans, abs(cur - target))
        if cur == target:
            return 0
        elif cur > target:
            i2 -= 1
        else:
            i1 += 1
    return ans
string = input()
target = int(input())

arr = []
i = 0
tem = ""
while i < len(string):
    if string[i] == '-':
        tem += string[i]
        i += 1
    elif string[i].isdigit():
        tem += string[i]
        i += 1
    else:
        if tem != "":
            arr.append(int(tem))
        i += 1
        tem = ""
print(minAbsDifference(arr, target))


from spacy import Language
from atis.intent import *
from atis.entities import *
from atis.actions import *

def parse(nlp: Language, utterance: str) -> dict:
    doc = nlp(utterance)
    result = {}

    result['utterance'] = utterance

    intent = detect_intent(nlp, doc)
    if intent:
        result['intent'] = detect_intent(nlp, doc)

    result['entities'] = {}

    locations = extract_locations(nlp, doc)
    if locations:
        result['entities']['locations'] = locations

    airports = extract_airports(nlp, doc)
    if airports:
        result['entities']['airports'] = airports

    gpe_entity_filter = filter(lambda ent: ent.label_ == 'GPE', list(doc.ents))
    gpe_entities = list(gpe_entity_filter)
    if gpe_entities:
        gpe_entity_map = map(lambda ent: ent.text, gpe_entities)
        result['entities']['geopolitical'] = list(gpe_entity_map)

    return result


import discord
import asyncio
import bot_token
from discord.ext import commands

class MyClient(discord.Client):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # create the background task and run it in the background
        self.bg_task = self.loop.create_task(self.my_background_task())

    description = '''Test bot'''
    bot = commands.Bot(command_prefix='!', description=description)

    async def on_ready(self):
        print('Logged in as')
        print(self.user.name)
        print(self.user.id)
        print('------')

    async def my_background_task(self):
        await self.wait_until_ready()
        counter = 0
        channel = self.get_channel(395078356703510541) # channel ID goes here
        while not self.is_closed():
            counter += 1
            await channel.send(counter)
            print(counter)
            await asyncio.sleep(10) # task runs every 10 seconds

    async def testcommand(ctx):
        await ctx.send('test command with background action')

client = MyClient()
client.run(bot_token.TOKEN)


"""
Test sending custom attributes

http://www.growlforwindows.com/gfw/help/gntp.aspx#custom
"""

from gntp.test import GNTPTestCase

class TestCustom(GNTPTestCase):
	def test_custom_values(self):
		self._notify(title='Custom Attributes', custom={
				'X-Custom1': 'Some Value',
				'X-Custom2': 'Some other value',
			})


from sagemaker.spark.processing import PySparkProcessor

processor = PySparkProcessor(
    base_job_name='spark-amazon-reviews-processor',
    role=role,
    framework_version='3.2.1',  # Spark version
    instance_count=2,
    instance_type='ml.r5.xlarge',
    max_runtime_in_seconds=7200)
root_path = f's3://{bucket}/{prefix}/output/bert'
train_data_bert_output = f'{root_path}-train'
validation_data_bert_output = f'{root_path}-validation'
test_data_bert_output = f'{root_path}-test'

processor.run(
    submit_app='proprocessor-spark-text-to-bert.py',
    arguments=[
        's3_input_data', s3_input_data,
        's3_output_train_data', train_data_bert_output,
        's3_output_validation_data', validation_data_bert_output,
        's3_output_test_data', test_data_bert_output,
        'train_split_percentage', str(train_split_percentage),
        'validation_split_percentage', str(validation_split_percentage),
        'test_split_percentage', str(test_split_percentage),
        'max_seq_length', str(max_seq_length)],
    outputs=[
        ProcessingOutput(
            s3_upload_mode='EndOfJob',
            output_name='bert-train',
            source='/opt/ml/processing/output/bert/train'),
        ProcessingOutput(
            s3_upload_mode='EndOfJob',
            output_name='bert-validation',
            source='/opt/ml/processing/output/bert/validation'),
        ProcessingOutput(
            s3_upload_mode='EndOfJob',
            output_name='bert-test',
            source='/opt/ml/processing/output/bert/test')],
    logs=True,
    wait=False)


# The input to the program is a line of text.
# Write a program that determines whether the shade of the text is good or not.
# The text has a good shade if it contains the substring "good" in all possible cases.
#
# Input data format
# The input to the program is a line of text.
#
# Output data format
# The program should print "YES" if the text has a good shade and "NO" otherwise.

string = input().lower()
a = 'хорош'
print('YES' if a in string else 'NO')


from django import forms

from shortener.validators import validate_url, validate_desired_shortcode

class SubmitForm(forms.Form):
    url = forms.CharField(
        label='',
        validators=[validate_url],
        widget=forms.TextInput(attrs={
            "placeholder": "Long URL",
            "class": "form-control form-control-lg"
            }
        )
    )

    short_url = forms.CharField(
        required=False,
        label='',
        # label_suffix='/+',
        validators=[validate_desired_shortcode],
        widget=forms.TextInput(attrs={
            "placeholder": "Type the shortcode (host will be added)",
            "class": "form-control form-control-sm",
            "id": "toggle",
            "style": "display: none",
            },
        ),

    )


#sanmanasullavar errors fix akki tharanam 🙂

import pyrogram
from asyncio import sleep
from pyrogram import Client, filters
from pyrogram.types import User, Message
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup

from info import API_ID
from info import API_HASH
from info import BOT_TOKEN
from OMDB import get_movie_info
#=======================================================================

START_MSG = f"Hii , \n I'm a Simple Telegram Bot To Get Movie Info Using OMDb \n \nSend Me The **Movie Name** To Get Info About It"

STICKER = 'CAACAgUAAxkDAALjS2F9dI-C4OaXKkSgsAxjX1mkofkKAAJXBAAC6aXoV2X6ud6KqXzUHgQ'

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

Sam = Client(
    session_name="OMDb-Bot",
    api_id=API_ID,
    api_hash=API_HASH,
    bot_token=BOT_TOKEN
)

print("Starting Bot..")

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

@Sam.on_message(filters.command(['start']) & filters.private)
def start(client, cmd):
         cmd.reply_sticker(STICKER)
         cmd.reply_text(START_MSG)

@Sam.on_message(filters.text)
async def imdbcmd(client, message):
    movie_name = message.text
    movie_info = get_movie_info(movie_name)
    if movie_info:
                  poster = movie_info["pimage"]
                  urlid = movie_info['imdb_id']
                  buttons=[[InlineKeyboardButton('🎟 IMDb', url=f"https://www.imdb.com/title/{urlid}")]]

                  text=f"""📀 Title : {movie_info['title']}

⏱ Runtime : {movie_info['duration']}
🌟 Rating : {movie_info['imdb_rating']}/10
🗳 Votes : {movie_info['votes']}

📆 Release : {movie_info['release']}
🎭 Genre : {movie_info['genre']}
🎙 Language : {movie_info['language']}
🌐 Country : {movie_info['country']}

🎥 Director : {movie_info['director']}
📝 Writer's : {movie_info['writer']}
🔆 Star's : {movie_info['actors']}

🗒 Plot : {movie_info['plot']}"""

                  if poster.startswith("https"):
                                                m = await message.reply_text("Finding Details..")
                                                await message.reply_photo(photo=poster.replace("_SX300","_"), caption=text, reply_markup=InlineKeyboardMarkup(buttons))
                                                await m.delete()
                  else:
                       m = await message.reply_text("Sorry,\nI Can't Find Posters.\nSending Available Details..")
                       await message.reply_text(text=text, reply_markup=InlineKeyboardMarkup(buttons))
                       await sleep(4)
                       await m.delete()
    else:
        omdbbuttons=[[InlineKeyboardButton('🔍 Search On Google.', url=f'https://google.com/search?q={movie_name.replace(" ","+")}')]]
        await message.reply_text(text="Couldn't Fetch Details\nTry To Check Your Spelling.", reply_markup=InlineKeyboardMarkup(omdbbuttons))

#=======================================================================
print("Bot Started!")
#=======================================================================

Sam.run()

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


class CustomException(Exception):
    status = None

    def __init__(self, message, details=None, err=None, log=False):
        self.message = message
        self.details = details
        self.err = err
        self.log = log

    def form_response(self):
        if not self.message or not self.status:
            return None

        response_body = {
            "message": self.message
        }

        if self.details:
            response_body["details"] = self.details

        return response_body, self.status


"""Schemas for dif presentation exchange attachment."""
from typing import Mapping, Optional, Sequence

from marshmallow import (
    EXCLUDE,
    INCLUDE,
    ValidationError,
    fields,
    post_dump,
    pre_load,
    validate,
)

from ....messaging.models.base import BaseModel, BaseModelSchema
from ....messaging.valid import StrOrNumberField, UUID4_EXAMPLE, UUID4_VALIDATE
from ....vc.vc_ld.models.presentation import (
    VerifiablePresentation,
    VerifiablePresentationSchema,
)

class ClaimFormat(BaseModel):
    """Defines Claim field."""

    class Meta:
        """ClaimFormat metadata."""

        schema_class = "ClaimFormatSchema"

    def __init__(
        self,
        *,
        jwt: Mapping = None,
        jwt_vc: Mapping = None,
        jwt_vp: Mapping = None,
        ldp: Mapping = None,
        ldp_vc: Mapping = None,
        ldp_vp: Mapping = None,
    ):
        """Initialize format."""
        self.jwt = jwt
        self.jwt_vc = jwt_vc
        self.jwt_vp = jwt_vp
        self.ldp = ldp
        self.ldp_vc = ldp_vc
        self.ldp_vp = ldp_vp

class ClaimFormatSchema(BaseModelSchema):
    """Single ClaimFormat Schema."""

    class Meta:
        """ClaimFormatSchema metadata."""

        model_class = ClaimFormat
        unknown = EXCLUDE

    jwt = fields.Dict(required=False)
    jwt_vc = fields.Dict(required=False)
    jwt_vp = fields.Dict(required=False)
    ldp = fields.Dict(required=False)
    ldp_vc = fields.Dict(required=False)
    ldp_vp = fields.Dict(required=False)

class SubmissionRequirements(BaseModel):
    """describes input to be submitted via a presentation submission."""

    class Meta:
        """SubmissionRequirements metadata."""

        schema_class = "SubmissionRequirementsSchema"

    def __init__(
        self,
        *,
        _name: str = None,
        purpose: str = None,
        rule: str = None,
        count: int = None,
        minimum: int = None,
        maximum: int = None,
        _from: str = None,
        # Self_reference
        from_nested: Sequence = None,
    ):
        """Initialize SubmissionRequirement."""
        self._name = _name
        self.purpose = purpose
        self.rule = rule
        self.count = count
        self.minimum = minimum
        self.maximum = maximum
        self._from = _from
        self.from_nested = from_nested

class SubmissionRequirementsSchema(BaseModelSchema):
    """Single Presentation Definition Schema."""

    class Meta:
        """SubmissionRequirementsSchema metadata."""

        model_class = SubmissionRequirements
        unknown = EXCLUDE

    _name = fields.Str(
        required=False, data_key="name", metadata={"description": "Name"}
    )
    purpose = fields.Str(required=False, metadata={"description": "Purpose"})
    rule = fields.Str(
        required=False,
        validate=validate.OneOf(["all", "pick"]),
        metadata={"description": "Selection"},
    )
    count = fields.Int(
        required=False,
        metadata={"description": "Count Value", "example": 1234, "strict": True},
    )
    minimum = fields.Int(
        required=False,
        data_key="min",
        metadata={"description": "Min Value", "example": 1234, "strict": True},
    )
    maximum = fields.Int(
        required=False,
        data_key="max",
        metadata={"description": "Max Value", "example": 1234, "strict": True},
    )
    _from = fields.Str(
        required=False, data_key="from", metadata={"description": "From"}
    )
    # Self References
    from_nested = fields.List(
        fields.Nested(lambda: SubmissionRequirementsSchema()), required=False
    )

    @pre_load
    def validate_from(self, data, **kwargs):
        """Support validation of from and from_nested."""
        if "from" in data and "from_nested" in data:
            raise ValidationError(
                "Both from and from_nested cannot be "
                "specified in the submission requirement"
            )
        if "from" not in data and "from_nested" not in data:
            raise ValidationError(
                "Either from or from_nested needs to be "
                "specified in the submission requirement"
            )
        return data

class SchemaInputDescriptor(BaseModel):
    """SchemaInputDescriptor."""

    class Meta:
        """SchemaInputDescriptor metadata."""

        schema_class = "SchemaInputDescriptorSchema"

    def __init__(
        self,
        *,
        uri: str = None,
        required: bool = None,
    ):
        """Initialize SchemaInputDescriptor."""
        self.uri = uri
        self.required = required

class SchemaInputDescriptorSchema(BaseModelSchema):
    """Single SchemaField Schema."""

    class Meta:
        """SchemaInputDescriptorSchema metadata."""

        model_class = SchemaInputDescriptor
        unknown = EXCLUDE

    uri = fields.Str(required=False, metadata={"description": "URI"})
    required = fields.Bool(required=False, metadata={"description": "Required"})

class SchemasInputDescriptorFilter(BaseModel):
    """SchemasInputDescriptorFilter."""

    class Meta:
        """InputDescriptor Schemas filter metadata."""

        schema_class = "SchemasInputDescriptorFilterSchema"

    def __init__(
        self,
        *,
        oneof_filter: bool = False,
        uri_groups: Sequence[Sequence[SchemaInputDescriptor]] = None,
    ):
        """Initialize SchemasInputDescriptorFilter."""
        self.oneof_filter = oneof_filter
        self.uri_groups = uri_groups

class SchemasInputDescriptorFilterSchema(BaseModelSchema):
    """Single SchemasInputDescriptorFilterSchema Schema."""

    class Meta:
        """SchemasInputDescriptorFilterSchema metadata."""

        model_class = SchemasInputDescriptorFilter
        unknown = EXCLUDE

    uri_groups = fields.List(fields.List(fields.Nested(SchemaInputDescriptorSchema)))
    oneof_filter = fields.Bool(metadata={"description": "oneOf"})

    @pre_load
    def extract_info(self, data, **kwargs):
        """deserialize."""
        new_data = {}
        if isinstance(data, dict):
            if "uri_groups" in data:
                return data
            elif "oneof_filter" in data and isinstance(data["oneof_filter"], list):
                new_data["oneof_filter"] = True
                uri_group_list_of_list = []
                uri_group_list = data.get("oneof_filter")
                for uri_group in uri_group_list:
                    if isinstance(uri_group, list):
                        uri_group_list_of_list.append(uri_group)
                    else:
                        uri_group_list_of_list.append([uri_group])
                new_data["uri_groups"] = uri_group_list_of_list
        elif isinstance(data, list):
            new_data["oneof_filter"] = False
            new_data["uri_groups"] = [data]
        data = new_data
        return data

class DIFHolder(BaseModel):
    """Single Holder object for Constraints."""

    class Meta:
        """Holder metadata."""

        schema_class = "DIFHolderSchema"

    def __init__(
        self,
        *,
        field_ids: Sequence[str] = None,
        directive: str = None,
    ):
        """Initialize Holder."""
        self.field_ids = field_ids
        self.directive = directive

class DIFHolderSchema(BaseModelSchema):
    """Single Holder Schema."""

    class Meta:
        """DIFHolderSchema metadata."""

        model_class = DIFHolder
        unknown = EXCLUDE

    field_ids = fields.List(
        fields.Str(
            required=False,
            validate=UUID4_VALIDATE,
            metadata={"description": "FieldID", "example": UUID4_EXAMPLE},
        ),
        required=False,
        data_key="field_id",
    )
    directive = fields.Str(
        required=False,
        validate=validate.OneOf(["required", "preferred"]),
        metadata={"description": "Preference"},
    )

class Filter(BaseModel):
    """Single Filter for the Constraint object."""

    class Meta:
        """Filter metadata."""

        schema_class = "FilterSchema"

    def __init__(
        self,
        *,
        _not: bool = False,
        _type: str = None,
        fmt: str = None,
        pattern: str = None,
        minimum: str = None,
        maximum: str = None,
        min_length: int = None,
        max_length: int = None,
        exclusive_min: str = None,
        exclusive_max: str = None,
        const: str = None,
        enums: Sequence[str] = None,
    ):
        """Initialize Filter."""
        self._type = _type
        self.fmt = fmt
        self.pattern = pattern
        self.minimum = minimum
        self.maximum = maximum
        self.min_length = min_length
        self.max_length = max_length
        self.exclusive_min = exclusive_min
        self.exclusive_max = exclusive_max
        self.const = const
        self.enums = enums
        self._not = _not

class FilterSchema(BaseModelSchema):
    """Single Filter Schema."""

    class Meta:
        """FilterSchema metadata."""

        model_class = Filter
        unknown = EXCLUDE

    _type = fields.Str(
        required=False, data_key="type", metadata={"description": "Type"}
    )
    fmt = fields.Str(
        required=False, data_key="format", metadata={"description": "Format"}
    )
    pattern = fields.Str(required=False, metadata={"description": "Pattern"})
    minimum = StrOrNumberField(required=False, metadata={"description": "Minimum"})
    maximum = StrOrNumberField(required=False, metadata={"description": "Maximum"})
    min_length = fields.Int(
        required=False,
        data_key="minLength",
        metadata={"description": "Min Length", "example": 1234, "strict": True},
    )
    max_length = fields.Int(
        required=False,
        data_key="maxLength",
        metadata={"description": "Max Length", "example": 1234, "strict": True},
    )
    exclusive_min = StrOrNumberField(
        required=False,
        data_key="exclusiveMinimum",
        metadata={"description": "ExclusiveMinimum"},
    )
    exclusive_max = StrOrNumberField(
        required=False,
        data_key="exclusiveMaximum",
        metadata={"description": "ExclusiveMaximum"},
    )
    const = StrOrNumberField(required=False, metadata={"description": "Const"})
    enums = fields.List(
        StrOrNumberField(required=False, metadata={"description": "Enum"}),
        required=False,
        data_key="enum",
    )
    _not = fields.Boolean(
        required=False,
        data_key="not",
        metadata={"description": "Not", "example": False},
    )

    @pre_load
    def extract_info(self, data, **kwargs):
        """Enum validation and not filter logic."""
        if "not" in data:
            new_data = {"not": True}
            for key, value in data.get("not").items():
                new_data[key] = value
            data = new_data
        if "enum" in data:
            if not isinstance(data.get("enum"), list):
                raise ValidationError("enum is not specified as a list")
        return data

    @post_dump
    def serialize_reformat(self, data, **kwargs):
        """Support serialization of not filter according to DIF spec."""
        if data.pop("not", False):
            return {"not": data}

        return data

class DIFField(BaseModel):
    """Single Field object for the Constraint."""

    class Meta:
        """Field metadata."""

        schema_class = "DIFFieldSchema"

    def __init__(
        self,
        *,
        id: str = None,
        paths: Sequence[str] = None,
        purpose: str = None,
        predicate: str = None,
        _filter: Filter = None,
    ):
        """Initialize Field."""
        self.paths = paths
        self.purpose = purpose
        self.predicate = predicate
        self._filter = _filter
        self.id = id

class DIFFieldSchema(BaseModelSchema):
    """Single Field Schema."""

    class Meta:
        """DIFFieldSchema metadata."""

        model_class = DIFField
        unknown = EXCLUDE

    id = fields.Str(required=False, metadata={"description": "ID"})
    paths = fields.List(
        fields.Str(required=False, metadata={"description": "Path"}),
        required=False,
        data_key="path",
    )
    purpose = fields.Str(required=False, metadata={"description": "Purpose"})
    predicate = fields.Str(
        required=False,
        validate=validate.OneOf(["required", "preferred"]),
        metadata={"description": "Preference"},
    )
    _filter = fields.Nested(FilterSchema, data_key="filter")

class Constraints(BaseModel):
    """Single Constraints which describes InputDescriptor's Contraint field."""

    class Meta:
        """Constraints metadata."""

        schema_class = "ConstraintsSchema"

    def __init__(
        self,
        *,
        subject_issuer: str = None,
        limit_disclosure: bool = None,
        holders: Sequence[DIFHolder] = None,
        _fields: Sequence[DIFField] = None,
        status_active: str = None,
        status_suspended: str = None,
        status_revoked: str = None,
    ):
        """Initialize Constraints for Input Descriptor."""
        self.subject_issuer = subject_issuer
        self.limit_disclosure = limit_disclosure
        self.holders = holders
        self._fields = _fields
        self.status_active = status_active
        self.status_suspended = status_suspended
        self.status_revoked = status_revoked

class ConstraintsSchema(BaseModelSchema):
    """Single Constraints Schema."""

    class Meta:
        """ConstraintsSchema metadata."""

        model_class = Constraints
        unknown = EXCLUDE

    subject_issuer = fields.Str(
        required=False,
        validate=validate.OneOf(["required", "preferred"]),
        data_key="subject_is_issuer",
        metadata={"description": "SubjectIsIssuer"},
    )
    limit_disclosure = fields.Str(
        required=False, metadata={"description": "LimitDisclosure"}
    )
    holders = fields.List(
        fields.Nested(DIFHolderSchema), required=False, data_key="is_holder"
    )
    _fields = fields.List(
        fields.Nested(DIFFieldSchema), required=False, data_key="fields"
    )
    status_active = fields.Str(
        required=False, validate=validate.OneOf(["required", "allowed", "disallowed"])
    )
    status_suspended = fields.Str(
        required=False, validate=validate.OneOf(["required", "allowed", "disallowed"])
    )
    status_revoked = fields.Str(
        required=False, validate=validate.OneOf(["required", "allowed", "disallowed"])
    )

    @pre_load
    def extract_info(self, data, **kwargs):
        """Support deserialization of statuses according to DIF spec."""
        if "statuses" in data:
            if "active" in data.get("statuses"):
                if "directive" in data.get("statuses").get("active"):
                    data["status_active"] = data["statuses"]["active"]["directive"]
            if "suspended" in data.get("statuses"):
                if "directive" in data.get("statuses").get("suspended"):
                    data["status_suspended"] = data["statuses"]["suspended"][
                        "directive"
                    ]
            if "revoked" in data.get("statuses"):
                if "directive" in data.get("statuses").get("revoked"):
                    data["status_revoked"] = data["statuses"]["revoked"]["directive"]
        return data

    @post_dump
    def reformat_data(self, data, **kwargs):
        """Support serialization of statuses according to DIF spec."""
        if "status_active" in data:
            statuses = data.get("statuses", {})
            statuses["active"] = {"directive": data.get("status_active")}
            data["statuses"] = statuses
            del data["status_active"]
        if "status_suspended" in data:
            statuses = data.get("statuses", {})
            statuses["suspended"] = {"directive": data.get("status_suspended")}
            data["statuses"] = statuses
            del data["status_suspended"]
        if "status_revoked" in data:
            statuses = data.get("statuses", {})
            statuses["revoked"] = {"directive": data.get("status_revoked")}
            data["statuses"] = statuses
            del data["status_revoked"]
        return data

class InputDescriptors(BaseModel):
    """Input Descriptors."""

    class Meta:
        """InputDescriptors metadata."""

        schema_class = "InputDescriptorsSchema"

    def __init__(
        self,
        *,
        id: str = None,
        groups: Sequence[str] = None,
        name: str = None,
        purpose: str = None,
        metadata: dict = None,
        constraint: Constraints = None,
        schemas: SchemasInputDescriptorFilter = None,
    ):
        """Initialize InputDescriptors."""
        self.id = id
        self.groups = groups
        self.name = name
        self.purpose = purpose
        self.metadata = metadata
        self.constraint = constraint
        self.schemas = schemas

class InputDescriptorsSchema(BaseModelSchema):
    """Single InputDescriptors Schema."""

    class Meta:
        """InputDescriptorsSchema metadata."""

        model_class = InputDescriptors
        unknown = EXCLUDE

    id = fields.Str(required=False, metadata={"description": "ID"})
    groups = fields.List(
        fields.Str(required=False, metadata={"description": "Group"}),
        required=False,
        data_key="group",
    )
    name = fields.Str(required=False, metadata={"description": "Name"})
    purpose = fields.Str(required=False, metadata={"description": "Purpose"})
    metadata = fields.Dict(
        required=False, metadata={"description": "Metadata dictionary"}
    )
    constraint = fields.Nested(
        ConstraintsSchema, required=False, data_key="constraints"
    )
    schemas = fields.Nested(
        SchemasInputDescriptorFilterSchema,
        required=False,
        data_key="schema",
        metadata={
            "description": (
                "Accepts a list of schema or a dict containing filters like"
                " oneof_filter."
            ),
            "example": {
                "oneof_filter": [
                    [
                        {"uri": "https://www.w3.org/Test1#Test1"},
                        {"uri": "https://www.w3.org/Test2#Test2"},
                    ],
                    {
                        "oneof_filter": [
                            [{"uri": "https://www.w3.org/Test1#Test1"}],
                            [{"uri": "https://www.w3.org/Test2#Test2"}],
                        ]
                    },
                ]
            },
        },
    )

class Requirement(BaseModel):
    """Single Requirement generated from toRequirement function."""

    class Meta:
        """Requirement metadata."""

        schema_class = "RequirementSchema"

    def __init__(
        self,
        *,
        count: int = None,
        maximum: int = None,
        minimum: int = None,
        input_descriptors: Sequence[InputDescriptors] = None,
        nested_req: Sequence = None,
    ):
        """Initialize Requirement."""
        self.count = count
        self.maximum = maximum
        self.minimum = minimum
        self.input_descriptors = input_descriptors
        self.nested_req = nested_req

class RequirementSchema(BaseModelSchema):
    """Single Requirement Schema."""

    class Meta:
        """RequirementSchema metadata."""

        model_class = Requirement
        unknown = EXCLUDE

    count = fields.Int(
        required=False,
        metadata={"description": "Count Value", "example": 1234, "strict": True},
    )
    maximum = fields.Int(
        required=False,
        metadata={"description": "Max Value", "example": 1234, "strict": True},
    )
    minimum = fields.Int(
        required=False,
        metadata={"description": "Min Value", "example": 1234, "strict": True},
    )
    input_descriptors = fields.List(
        fields.Nested(InputDescriptorsSchema), required=False
    )
    # Self References
    nested_req = fields.List(
        fields.Nested(lambda: RequirementSchema(exclude=("_nested_req",))),
        required=False,
    )

class PresentationDefinition(BaseModel):
    """https://identity.foundation/presentation-exchange/."""

    class Meta:
        """PresentationDefinition metadata."""

        schema_class = "PresentationDefinitionSchema"

    def __init__(
        self,
        *,
        id: str = None,
        name: str = None,
        purpose: str = None,
        fmt: ClaimFormat = None,
        submission_requirements: Sequence[SubmissionRequirements] = None,
        input_descriptors: Sequence[InputDescriptors] = None,
        **kwargs,
    ):
        """Initialize flattened single-JWS to include in attach decorator data."""
        super().__init__(**kwargs)
        self.id = id
        self.name = name
        self.purpose = purpose
        self.fmt = fmt
        self.submission_requirements = submission_requirements
        self.input_descriptors = input_descriptors

class PresentationDefinitionSchema(BaseModelSchema):
    """Single Presentation Definition Schema."""

    class Meta:
        """PresentationDefinitionSchema metadata."""

        model_class = PresentationDefinition
        unknown = EXCLUDE

    id = fields.Str(
        required=False,
        validate=UUID4_VALIDATE,
        metadata={
            "description": "Unique Resource Identifier",
            "example": UUID4_EXAMPLE,
        },
    )
    name = fields.Str(
        required=False,
        metadata={
            "description": (
                "Human-friendly name that describes what the presentation definition"
                " pertains to"
            )
        },
    )
    purpose = fields.Str(
        required=False,
        metadata={
            "description": (
                "Describes the purpose for which the Presentation Definition's inputs"
                " are being requested"
            )
        },
    )
    fmt = fields.Nested(ClaimFormatSchema, required=False, data_key="format")
    submission_requirements = fields.List(
        fields.Nested(SubmissionRequirementsSchema), required=False
    )
    input_descriptors = fields.List(
        fields.Nested(InputDescriptorsSchema), required=False
    )

class InputDescriptorMapping(BaseModel):
    """Single InputDescriptorMapping object."""

    class Meta:
        """InputDescriptorMapping metadata."""

        schema_class = "InputDescriptorMappingSchema"

    def __init__(
        self,
        *,
        id: str = None,
        fmt: str = None,
        path: str = None,
    ):
        """Initialize InputDescriptorMapping."""
        self.id = id
        self.fmt = fmt
        self.path = path

class InputDescriptorMappingSchema(BaseModelSchema):
    """Single InputDescriptorMapping Schema."""

    class Meta:
        """InputDescriptorMappingSchema metadata."""

        model_class = InputDescriptorMapping
        unknown = EXCLUDE

    id = fields.Str(required=False, metadata={"description": "ID"})
    fmt = fields.Str(
        required=False,
        dump_default="ldp_vc",
        data_key="format",
        metadata={"description": "Format"},
    )
    path = fields.Str(required=False, metadata={"description": "Path"})

class PresentationSubmission(BaseModel):
    """Single PresentationSubmission object."""

    class Meta:
        """PresentationSubmission metadata."""

        schema_class = "PresentationSubmissionSchema"

    def __init__(
        self,
        *,
        id: str = None,
        definition_id: str = None,
        descriptor_maps: Sequence[InputDescriptorMapping] = None,
    ):
        """Initialize InputDescriptorMapping."""
        self.id = id
        self.definition_id = definition_id
        self.descriptor_maps = descriptor_maps

class PresentationSubmissionSchema(BaseModelSchema):
    """Single PresentationSubmission Schema."""

    class Meta:
        """PresentationSubmissionSchema metadata."""

        model_class = PresentationSubmission
        unknown = EXCLUDE

    id = fields.Str(
        required=False,
        validate=UUID4_VALIDATE,
        metadata={"description": "ID", "example": UUID4_EXAMPLE},
    )
    definition_id = fields.Str(
        required=False,
        validate=UUID4_VALIDATE,
        metadata={"description": "DefinitionID", "example": UUID4_EXAMPLE},
    )
    descriptor_maps = fields.List(
        fields.Nested(InputDescriptorMappingSchema),
        required=False,
        data_key="descriptor_map",
    )

class VPWithSubmission(VerifiablePresentation):
    """Single VerifiablePresentation object."""

    class Meta:
        """VerifiablePresentation metadata."""

        schema_class = "VPWithSubmissionSchema"

    def __init__(
        self,
        *,
        presentation_submission: Optional[PresentationSubmission] = None,
        **kwargs,
    ):
        """Initialize VerifiablePresentation."""
        super().__init__(**kwargs)
        self.presentation_submission = presentation_submission

class VPWithSubmissionSchema(VerifiablePresentationSchema):
    """Single Verifiable Presentation Schema."""

    class Meta:
        """VerifiablePresentationSchema metadata."""

        model_class = VPWithSubmission
        unknown = INCLUDE

    presentation_submission = fields.Nested(PresentationSubmissionSchema)

class DIFOptions(BaseModel):
    """Single DIFOptions object."""

    class Meta:
        """DIFOptions metadata."""

        schema_class = "DIFOptionsSchema"

    def __init__(
        self,
        *,
        challenge: str = None,
        domain: str = None,
    ):
        """Initialize DIFOptions."""
        self.challenge = challenge
        self.domain = domain

class DIFOptionsSchema(BaseModelSchema):
    """Schema for options required for the Prover to fulfill the Verifier's request."""

    class Meta:
        """DIFOptionsSchema metadata."""

        model_class = DIFOptions
        unknown = EXCLUDE

    challenge = fields.String(
        required=False,
        validate=UUID4_VALIDATE,
        metadata={
            "description": "Challenge protect against replay attack",
            "example": UUID4_EXAMPLE,
        },
    )
    domain = fields.String(
        required=False,
        metadata={
            "description": "Domain protect against replay attack",
            "example": "4jt78h47fh47",
        },
    )


import sys
input = sys.stdin.readline

def GCD(n,m):
    while(m > 0):
        n,m = m, n%m
    return n
def LCM(n,m):
    return ((n*m)/GCD(n,m))

answer = []

for i in range(int(input())):
    n,m = map(int, input().split())
    answer.append(LCM(n,m))
for i in answer:
    print(int(i))


import re
import multiprocessing

from flask import Flask
from flask import request
from flask import redirect
from flask import url_for
from flask import render_template

import predictionio

TITLE = 'gitcha'

USER_PATTERN = r'(\w|-)+'
REPO_PATTERN = r'{user}/(\w|-|\.)+'.format(user=USER_PATTERN)

app = Flask(__name__)
user_re = re.compile(r'^' + USER_PATTERN + r'$')
repo_re = re.compile(r'^' + REPO_PATTERN + r'$')

engine_client = predictionio.EngineClient(url="https://localhost:8000")

@app.route('/')
def index():
    query = request.args.get('query', '')

    output = None
    if query:
        output = request_to_engine(query)

    return render_template('index.html', title=TITLE, output=output)

def request_to_engine(query):
    if user_re.match(query):
        rep = engine_client.send_query({"user": query})
        return rep_to_output(rep)
    elif repo_re.match(query):
        rep = engine_client.send_query({"item": query})
        return rep_to_output(rep)
    else:
        return []

def rep_to_output(rep):
    return [ item_dict['item'] for item_dict in rep['itemScores']]

if __name__ == "__main__":
    app.run(host='0.0.0.0')


from django.contrib.auth.backends import ModelBackend
from .models import User

class DiscordAuthenticationBackend(ModelBackend):
    def authenticate(self, request, user):
        find_user = User.objects.filter(id=user['id'])
        if len(find_user) == 0:
            new_user = User.objects.create_user(user)
            return new_user

        find_user.update(
            discord_tag=f"{user['username']}#{user['discriminator']}",
            avatar=user['avatar'],
            public_flags=user['public_flags'],
            flags=user['flags'],
            locale=user['locale'],
            mfa_enabled=user['mfa_enabled'],
        )

        return list(find_user).pop()

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None


# Списки

students = ['Ivan', 'Masha', 'Sasha']
students2 = ['Dasha', 'Oleg']

students[1] = 'Sergey'
print(students)

students3 = students + students2
print(students3)

students3.append('Alexey')
students3 += ['Kseniya']
students3.insert(1, 'Gena')
print(students3)

for student in students3:
    print(f'Hello, {student}!')

students3.remove('Sasha') #Удаляет элемент из списка по первому вхождению
del students3[1]  #Удаляет элемент из списка по индексу
print(students3)

if 'Oleg' in students3:     #Проверка есть ли элемент в списке
    print('Oleg is here')

ind = students3.index('Oleg')   #Возвращяет позицию элемента в списке
print(ind)

ordered_students = sorted(students3)    #Выводит элементы списка по алфавиту, но не меняет сам список
print(ordered_students)

students3.sort()
print(students3)    #Сортирует список по алфавиту, если список цифр то по возростанию

# Генерация списков

a = [0]*5
print(a)

a = [0 for i in range(5)]
print(a)

a = [i * i for i in range(5)]
print(a)

a = [int(i) for i in input('Введите числа через пробел: ').split()]
print(a)

# Двумерные списки

n = 3
a = [[0] * n for i in range(n)]
print(a)
a = [[0 for j in range(n)] for i in range(n)]
print(' '.join(map(str, a)))

# Поиск минимума в списке

a = [int(i) for i in input().split()]
m = a[0]
for x in a:
    if m > x:
        m = x
print(m)

Программирование на Python/Task21(list).py


import re
from re import search

value = input()

print(len(value))

array = []

def has_chars(input):
    chars = []
    nums = []
    for char in input:
        if char.isalpha():
            chars.append(char)
        elif char.isdigit():
            nums.append(char)

    total = []
    total.append(chars)
    total.append(nums)
    return total

re.compile(r"[a-zA-Z0-9]*")
#patrn = re.compile(value)

operators = ['/', '-', '+', '^']

regex = r'\d{2}'

patr = re.compile(regex)

x = re.findall("[-, /, *, +]", value)
y = re.search("[-, /, *, +]", value).span()
print('equis', x)
print('ygriega', y)

for m in re.finditer("[-, /, *, +]", value):
    print('match stack')
    #print('re.match', m)
    print('operator in regex version', m.group())
    print('operator', value[m.start()])
    print(m.start(0))
    #print(m.end(0))

#for o in operators:
    #m = patr.search(value).span()
    #if m:
        #m.span()
        #print(m)

        #print('m found')

for i in range(len(value)):
    #print(value[i])
    array.append(value[i])
    if value[i] == '*' or value[i] == '/' or value[i] == '+' or value[i] == '-' or value[i] == '^':
        if value[i] =='*': #or value[i] == '/':
            print('isMultiplication', i)
        elif value[i] == '/':
            print('isDivision', i)
        elif value[i] == '-':
            print('isSubstraction', i)
        elif value[i] == '+':
            print('isSum', i)
        elif value[i] == '^':
            print('isElev', i)

print(value[0:2])
print(array)
print(has_chars(value))


import BLAST_alignments_parser as parser
import os

def last_index(string, char):
	index = None
	for i, ch in enumerate(string[-1::-1]):
		if char == ch:
			index = i
			break
	assert index is not None

	return len(string) - index - 1

def batch(count=0):
	folder_path = input("\tPath to text file folder: ")
	print()

	if not folder_path.endswith("/"):
		folder_path += "/"

	files = []
	for filename in os.listdir(folder_path):
		if filename.endswith(".txt"):
			files.append(filename)

	content = []
	for file in files:
		with open(folder_path + file) as infile:
			content.append(infile.readlines())

	outfile = f"Batch {count}.xlsx"
	parser.parse_batch(files, content, outfile)

def single():
	path = input("\tPath to text file: ")
	assert os.path.exists(path)
	print()

	filename = path
	if "/" in filename:
		filename = filename[last_index(filename, "/")+1:-4]

	with open(path) as infile:
		content = infile.readlines()

	parser.parse(filename, content)

def main():

	batch_count = 0
	while True:
		selection = input("Single or Batch Parse? (s/b) ").strip().lower()
		print()

		if selection == "b" or selection == "s":
			if selection == "b":
				batch_count += 1
				batch(batch_count)
			else:
				single()

			if input("Parse Again? (y/n) ").strip().lower() != "y":
				break
			print()
		else:
			print("ERROR: Invalid Selection\n")

main()


import oauth2client.client
import oauth2client.file

__author__ = 'elon'

def consolecallback(authorize_url):
    print("\n" * 5)
    print("Please navigate to {authorize_url} and authorize this application".format(authorize_url=authorize_url))
    code = input("Code: ")
    return code

class OAuth:
    REDIRECT_URL = 'urn:ietf:wg:oauth:2.0:oob'

    def __init__(self, client_id, client_secret, storage_path, callback=consolecallback):
        self.client_id = client_id
        self.client_secret = client_secret
        self.storage = oauth2client.file.Storage(storage_path)
        self.callback = callback

    def get(self, scopes):
        self.storage.acquire_lock()
        credentials = self.storage.locked_get()

        if credentials is None or not credentials.has_scopes(scopes):
            try:
                new_scopes = credentials.scopes + scopes
            except AttributeError:
                new_scopes = scopes

            credentials = self._generate_credentials(new_scopes)
            credentials.set_store(self.storage)
            self.storage.locked_put(credentials)

        self.storage.release_lock()
        return credentials

    def _generate_credentials(self, scopes):
        flow = oauth2client.client.OAuth2WebServerFlow(self.client_id, self.client_secret, scope=scopes,
                                                       redirect_uri=self.REDIRECT_URL)
        authorize_url = flow.step1_get_authorize_url()
        code = self.callback(authorize_url)
        credentials = flow.step2_exchange(code)
        return credentials


# coding: utf-8

from typing import Any, Literal, cast

import aiohttp
from loguru import logger
from pydantic import SecretStr

from services.vk.exceptions import (AccessDeniedException,
                                    AccountDeactivatedException,
                                    BaseVKAPIException, CaptchaException,
                                    TokenRevokedException, TooManyRequestsException)
from services.vk.utils import random_id

ALL_USER_FIELDS = "activities, about, blacklisted, blacklisted_by_me, books, bdate, can_be_invited_group, can_post, can_see_all_posts, can_see_audio, can_send_friend_request, can_write_private_message, career, common_count, connections, contacts, city, country, crop_photo, domain, education, exports, followers_count, friend_status, has_photo, has_mobile, home_town, photo_100, photo_200, photo_200_orig, photo_400_orig, photo_50, sex, site, schools, screen_name, status, verified, games, interests, is_favorite, is_friend, is_hidden_from_feed, last_seen, maiden_name, military, movies, music, nickname, occupation, online, personal, photo_id, photo_max, photo_max_orig, quotes, relation, relatives, timezone, tv, universities"
ALL_GROUP_FIELDS = "activity, ban_info, can_post, can_see_all_posts, city, contacts, counters, country, cover, description, finish_date, fixed_post, links, market, members_count, place, site, start_date, status, verified, photo_100, photo_200, photo_200_orig, photo_400_orig, photo_50"

class VKAPI:
	"""
	API для использования методов ВКонтакте.

	Данный класс предоставляет низкоуровневый доступ к определённым API-запросам ВКонтакте.
	"""

	token: SecretStr
	version: str

	def __init__(self, token: SecretStr, api_version: str = "5.131") -> None:
		"""
		Инициализация API.

		:param token: Токен для доступа к API ВКонтакте.
		"""

		self.token = token
		self.version = api_version

	@staticmethod
	def _parse_response(response: dict, method: str) -> dict:
		"""
		Парсит ответ от ВКонтакте.
		"""

		logger.debug(f"[VK] {method} response: {response}")

		if response.get("error"):
			error: dict | str = response["error"]
			code = error["error_code"] if isinstance(error, dict) else -1
			message = error["error_msg"] if isinstance(error, dict) else error

			if code in [3610, 17, 18]:
				raise AccountDeactivatedException(message=message)
			elif code == 5:
				raise TokenRevokedException(message=message)
			elif code == 6:
				raise TooManyRequestsException(message=message)
			elif code == 14:
				raise CaptchaException(message=message)
			elif code == 15:
				raise AccessDeniedException(message=message)
			else:
				raise BaseVKAPIException(
					error_code=code,
					message=message
				)

		if "response" in response:
			return response["response"]

		return response

	@staticmethod
	def _cleanup_none(data: dict) -> dict:
		"""
		Очищает словарь `data` от ключей None.

		:param data: Словарь, который необходимо очистить.
		"""

		return {key: value for key, value in data.items() if value is not None}

	async def _get_(self, method: str, params: dict[str, str | int | bool | float | None] | None = None) -> dict:
		"""
		Выполняет GET-запрос к API ВКонтакте.

		:param method: Метод API.
		:param params: Параметры запроса.
		"""

		if params is None:
			params = {}

		params["access_token"] = self.token.get_secret_value()
		params["v"] = self.version

		async with aiohttp.ClientSession() as session:
			async with session.get(f"https://api.vk.com/method/{method}", headers={"User-Agent": ""}, params=self._cleanup_none(params)) as response:
				return self._parse_response(await response.json(), method)

	async def _post_(self, method: str, params: dict[str, str | int | bool | float | None] | None = None) -> dict:
		"""
		Выполняет POST-запрос к API ВКонтакте.

		:param method: Метод API.
		:param params: Параметры запроса.
		"""

		if params is None:
			params = {}

		params["access_token"] = self.token.get_secret_value()
		params["v"] = self.version

		async with aiohttp.ClientSession() as session:
			async with session.post(f"https://api.vk.com/method/{method}", headers={"User-Agent": ""}, params=self._cleanup_none(params)) as response:
				return self._parse_response(await response.json(), method)

	async def account_setOnline(self) -> dict:
		"""
		Включает режим "онлайн" в текущем аккаунте на 5 минут. API: `account.setOnline`.
		"""

		return await self._post_("account.setOnline")

	async def account_getProfileInfo(self) -> dict:
		"""
		Получает информацию об аккаунте. API: `account.getProfileInfo`.
		"""

		return await self._post_("account.getProfileInfo")

	async def users_get(self, user_ids: list[int] | None = None) -> dict:
		"""
		Получает информацию о пользователях. API: `users.get`.
		В данном методе извлекается вся доступная информация о пользователе (все возможные значения для `fields`).

		:param user_ids: Список ID пользователей. Если не указано, то будет использован ID текущего пользователя.
		"""

		data: dict[str, Any] = {"fields": ALL_USER_FIELDS}
		if user_ids:
			data["user_ids"] = ",".join(map(str, user_ids))

		return await self._post_("users.get", data)

	async def get_self_info(self, user_id: int | None = None) -> dict:
		"""
		Получает информацию о данном аккаунте ВКонтаке (с которым ассоциирован данный токен). API: `users.get`.

		:param user_id: ID пользователя, информацию о котором необходимо получить. Если не указано, то будет использован ID текущего пользователя.
		"""

		return (await self.users_get([user_id] if user_id else []))[0]

	async def messages_send(self, peer_id: int, message: str, reply_to: int | None = None, attachment: list[str] | str | None = None, lat: float | None = None, long: float | None = None) -> int:
		"""
		Отправляет сообщение пользователю. API: `messages.send`.

		:param peer_id: ID пользователя/группы/беседы, в которую будет отправлено сообщение.
		:param message: Текст сообщения.
		:param reply_to: ID сообщения, на которое будет дан ответ.
		:param attachment: Вложения к сообщению.
		:param lat: Широта местоположения.
		:param long: Долгота местоположения.
		"""

		if not isinstance(attachment, str):
			attachment = ",".join(attachment or [])

		return cast(int, await self._post_("messages.send", {
			"peer_id": peer_id,
			"message": message,
			"random_id": random_id(),
			"reply_to": reply_to,
			"attachment": attachment,
			"lat": lat,
			"long": long
		}))

	async def messages_getLongPollServer(self) -> dict:
		"""
		Выдаёт информацию о longpoll-сервере. API: `messages.getLongPollServer`.
		"""

		return await self._post_("messages.getLongPollServer")

	async def messages_getConversations(self, offset: int = 0, count: int = 200, extended: bool = True) -> dict:
		"""
		Выдаёт список из бесед пользователя. API: `messages.getConversations`.

		:param offset: Смещение относительно начала списка.
		:param count: Количество бесед, которое необходимо получить.
		:param extended: Нужно ли получить расширенную информацию о беседах.
		"""

		return await self._post_("messages.getConversations", {
			"offset": offset,
			"count": count,
			"extended": 1 if extended else 0,
			"fields": ALL_USER_FIELDS
		})

	async def messages_getByConversationMessageId(self, peer_id: int, conversation_message_ids: int | list[int]) -> dict:
		"""
		Возвращает сообщения по их conversation_message_id. API: `messages.getByConversationMessageId`.

		:param peer_id: ID пользователя/группы/беседы, в которой находится сообщение.
		:param conversation_message_ids: ID сообщения(-й).
		"""

		if isinstance(conversation_message_ids, int):
			conversation_message_ids = [conversation_message_ids]

		return await self._post_("messages.getByConversationMessageId", {
			"peer_id": peer_id,
			"conversation_message_ids": ",".join(map(str, conversation_message_ids))
		})

	async def messages_getById(self, message_ids: int | list[int]) -> dict:
		"""
		Возвращает сообщения по их ID. API: `messages.getById`.

		:param message_ids: ID сообщения(-й).
		"""

		if isinstance(message_ids, int):
			message_ids = [message_ids]

		return await self._post_("messages.getById", {
			"message_ids": ",".join(map(str, message_ids))
		})

	async def photos_getById(self, photos: str | list[str]) -> dict:
		"""
		Возвращает информацию о фотографиях. API: `photos.getById`.

		:param photos: Список фотографий.
		"""

		if isinstance(photos, str):
			photos = [photos]

		return await self._post_("photos.getById", {
			"photos": ",".join(photos)
		})

	async def video_get(self, videos: list[str] | str) -> dict:
		"""
		Возвращает информацию о видео. API: `video.get`.

		:param videos: Список видео.
		"""

		if isinstance(videos, str):
			videos = [videos]

		return await self._post_("video.get", {
			"videos": ",".join(videos)
		})

	async def audio_getById(self, audios: list[str] | str) -> dict:
		"""
		Возвращает информацию о аудиозаписях. API: `audio.getById`.

		:param audios: Список аудиозаписей.
		"""

		if isinstance(audios, str):
			audios = [audios]

		return await self._post_("audio.getById", {
			"audios": ",".join(audios)
		})

	async def messages_delete(self, message_ids: int | list[int], delete_for_all: bool = True) -> dict:
		"""
		Удаляет сообщение по его ID. API: `messages.delete`.

		:param message_ids: ID сообщения(-й).
		:param delete_for_all: Удалить ли сообщение для всех пользователей. Работает только если сообщение было отправлено не более 24 часов назад.
		"""

		if isinstance(message_ids, int):
			message_ids = [message_ids]

		return await self._post_("messages.delete", {
			"message_ids": ",".join(map(str, message_ids)),
			"delete_for_all": 1 if delete_for_all else 0
		})

	async def messages_edit(self, peer_id: int, message_id: int, message: str, keep_forward_messages: bool = True, keep_snippets = True) -> dict:
		"""
		Редактирует сообщение по его ID. API: `messages.edit`.

		:param peer_id: ID пользователя/группы/беседы, в которой находится сообщение.
		:param message_id: ID сообщения.
		:param message: Новый текст сообщения.
		:param keep_forward_messages: Оставить ли пересланные сообщения.
		:param keep_snippets: Оставить ли прикреплённые в сообщении ссылки.
		"""

		return await self._post_("messages.edit", {
			"peer_id": peer_id,
			"message_id": message_id,
			"message": message,
			"keep_forward_messages": 1 if keep_forward_messages else 0,
			"keep_snippets": 1 if keep_snippets else 0
		})

	async def messages_setActivity(self, peer_id: int, type: Literal["typing", "audiomessage"] = "typing") -> dict:
		"""
		Начинает действие печати либо записи голосового сообщения в указанном диалоге. API: `messages.setActivity`.

		:param peer_id: ID пользователя/группы/беседы, в котором будет начато действие.
		:param type: Тип действия. Может быть либо `typing`, либо `audiomessage`.
		"""

		return await self._post_("messages.setActivity", {
			"peer_id": peer_id,
			"type": type
		})

	async def messages_markAsRead(self, peer_id: int, start_message_id: int | None = None, mark_conversation_as_read: bool = True) -> dict:
		"""
		Помечает сообщения как прочитанные. API: `messages.markAsRead`.

		:param peer_id: ID пользователя/группы/беседы, в которой находится сообщение.
		:param start_message_id: ID сообщения, начиная с которого нужно пометить сообщения как прочитанные.
		:param mark_conversation_as_read: Пометить ли беседу как прочитанную.
		"""

		return await self._post_("messages.markAsRead", {
			"peer_id": peer_id,
			"start_message_id": start_message_id,
			"mark_conversation_as_read": 1 if mark_conversation_as_read else 0
		})

	async def photos_getMessagesUploadServer(self, peer_id: int) -> dict:
		"""
		Возвращает ссылку для загрузки голосовых сообщений. API: `messages.getMessagesUploadServer`.

		:param peer_id: ID пользователя/группы/беседы, в которую будет отправлено сообщение.
		"""

		return await self._post_("photos.getMessagesUploadServer", {
			"peer_id": peer_id,
			"type": "audio_message"
		})

	async def photos_saveMessagesPhoto(self, photo: str, server: int, hash: str) -> dict:
		"""
		Сохраняет фотографию после успешной загрузки методом `photos.getMessagesUploadServer`. API: `photos.saveMessagesPhoto`.

		:param photo: Фотография.
		:param server: Сервер.
		:param hash: Хэш.
		"""

		return await self._post_("photos.saveMessagesPhoto", {
			"photo": photo,
			"server": server,
			"hash": hash
		})

	async def docs_getMessagesUploadServer(self, peer_id: int, type: Literal["doc", "audio_message", "graffiti"] = "doc") -> dict:
		"""
		Возвращает ссылку для загрузки документов. API: `docs.getMessagesUploadServer`.

		:param peer_id: ID пользователя/группы/беседы, в которую будет отправлено сообщение.
		:param type: Тип документа. Может быть либо `doc`, либо `audio_message`.
		"""

		return await self._post_("docs.getMessagesUploadServer", {
			"peer_id": peer_id,
			"type": type
		})

	async def docs_save(self, file: str, title: str | None = None, tags: str | list[str] | None = None) -> dict:
		"""
		Сохраняет документ после успешной загрузки. API: `docs.save`.

		:param file: Поле `file` из ответа API-метода `docs.getMessagesUploadServer`.
		:param title: Название.
		:param tags: Теги.
		"""

		if not isinstance(tags, str):
			tags = ",".join(tags or [])

		return await self._post_("docs.save", {
			"file": file,
			"title": title,
			"tags": tags
		})

	async def video_save(self, name: str | None = None, description: str | None = None, wallpost: bool = False, link: str | None = None, group_id: int | None = None, album_id: int | None = None, is_private: bool = False, no_comments: bool = False, repeat: bool = False, compression: bool = False) -> dict:
		"""
		Сохраняет видео после успешной загрузки. API: `video.save`.

		:param name: Название.
		:param description: Описание.
		:param wallpost: Опубликовать ли на стене.
		:param link: Ссылка на видео.
		:param group_id: ID группы, в которой будет опубликовано видео.
		:param album_id: ID альбома, в котором будет опубликовано видео.
		:param is_private: Приватность видео.
		:param no_comments: Запретить ли комментарии.
		:param repeat: Зациклить ли видео.
		:param compression: Сжать ли видео.
		"""

		return await self._post_("video.save", {
			"name": name,
			"description": description,
			"wallpost": 1 if wallpost else 0,
			"link": link,
			"group_id": group_id,
			"album_id": album_id,
			"is_private": 1 if is_private else 0,
			"no_comments": 1 if no_comments else 0,
			"repeat": 1 if repeat else 0,
			"compression": 1 if compression else 0
		})

	async def groups_getByID(self, user_ids: list[int] | None = None) -> dict:
		"""
		Получает информацию о группах с указанными ID. API: `groups.getById`.

		:param user_ids: Список ID пользователей. Если не указано, то будет использован ID текущего пользователя.
		"""

		data: dict[str, Any] = {"fields": ALL_GROUP_FIELDS}
		if user_ids:
			data["group_ids"] = ",".join(map(str, user_ids))

		return await self._post_("groups.getById", data)


import sys
fichier = str(sys.argv[1])

grid = []
with open(fichier) as sudoku:
    lignes = sudoku.readlines()
    for line in lignes:
        grid.append(line)

lines = []
columns = []
for i in range(11):
    lines.append(grid[i])

for i in range(11):
    column = ""
    for line in lines:
        column += line[i]
    columns.append(column)

def grid_solver(x,y):
    for index in range(1,10):
        if lines[x].count(str(index)) == 0 and columns[y].count(str(index)) == 0:
            grid[x] = grid[x][:y] + str(index) + grid[x][y+1:]
            break
        else:
            continue
    #print(grid[x][y])

print("SOLUTION:\n")

for line in range(len(lines)):
    for column in range(len(columns)):
        if grid[line][column] == "_" :
            grid_solver(line,column)
        else:
            continue
    print(grid[line])


import os.path
import re
import sys
from xml.etree import ElementTree

from alff.errors import *
from alff.utils import *

DEFAULT_CONFIG_DIR = "/etc/alff/default"
CONFIG_DIRS = ( 'plugin.d', 'rules.d', 'services.d' )
CONFIG_FILE_NAME = "alff.conf"

CACHE_BASE_DIR = "/var/cache/alff"

class Config (object):

	def __init__ (self, config_dir = DEFAULT_CONFIG_DIR):
		# Remeber which config dir was used for the current run
		self.config_dir = config_dir

		# We have to cache the generated rules for pushing them later.
		# Therefore we use a separate rules directory for every config directory and site
		# we were called with to maintain the principle of least surprise for the user,
		# who may even use the same site and firewall names in the different configurations.
		self.rules_base_dir = "%s/%s/rules/" % (CACHE_BASE_DIR, config_dir.replace ("/", "_"))

		self._check_config_dir (config_dir)

		self.config = Parser (self.config_file).get_config ()

		self._get_security_classes ()

	def _check_config_dir (self, dir):
		if not os.path.isdir (dir):
			raise ConfigError ("Directory '%s' does not exist." % dir)

		self.config_dir = dir

		# Check subdirs
		for subdir in CONFIG_DIRS:
			if not os.path.isdir (os.path.join (dir, subdir)):
				raise ConfigError ("Directory '%s' missing in '%s'" % (subdir, dir))

		self.config_file = os.path.join (dir, CONFIG_FILE_NAME)

		if not os.path.isfile (self.config_file):
			raise ConfigError ("No '%s' found in '%s'." % (CONFIG_FILE_NAME, dir))

	def _get_security_classes (self):
		all_sec_classes = {
			'filtered' : 1,
			'trusted' : 1,
		}

		for network_id in self.config['networks'].keys ():
			network = self.config['networks'][network_id]

			for sec_class in network['security_class']:
				all_sec_classes[sec_class] = 1

			for magic_class in ('filtered', 'trusted'):
				if magic_class in network and re.search ('yes|true', network[magic_class], re.I):
					network['security_class'].append (magic_class)

		self.security_classes = all_sec_classes.keys ()

	########################################
	# global stuff
	########################################

	def get_config_dir (self):
		return self.config_dir

	def get_rules_base_dir (self):
		return self.rules_base_dir

	def get_option (self, option, default = None):
		if option in self.config['options']:
			return self.config['options'][option]

		if default != None:
			return default

		raise ConfigError ("Unknown option '%s'" % option)

	""" Get a list of all DHCP servers found in the configuration file """
	def get_dhcp_servers (self):
		return self.config['options']['dhcp_server']

	def get_security_classes (self):
		return self.security_classes

	def is_valid_security_class (self, sec_class):
		return sec_class in self.security_classes

	########################################
	# site handling
	########################################

	def get_sites (self):
		return self.config['sites'].keys ()

	def is_valid_site (self, site_id):
		return site_id in self.config['sites']

	def get_default_interface (self, site):
		if not self.is_valid_site (site):
			raise RuntimeError ("Invalid site id '%s'." % site)

		def_int = self.config['sites'][site]['interface_map'].get ('default')

		return def_int['interface'] if def_int else None

	########################################
	# network handling
	########################################

	def get_vlans (self):
		AlffDeprecated ("get_vlans()", "get_networks()")
		return self.get_networks ()
	def get_networks (self):
		return self.config['networks'].keys ()

	def is_valid_vlan (self, vlan):
		AlffDeprecated ("is_valid_vlan()", "is_valid_network()")
		return self.is_valid_network (vlan)
	def is_valid_network (self, network):
		return network in self.config['networks']

	def get_vlans_of_security_class (self, sec_class):
		AlffDeprecated ("get_vlans_of_security_class()", "get_networks_of_security_class()")
		return self.get_networks_of_security_class (sec_class)
	def get_networks_of_security_class (self, sec_class):
		return [network for network in self.config['networks'].keys () if sec_class in self.config['networks'][network]['security_class']]

	def get_filtered_vlans (self):
		AlffDeprecated ("get_filtered_vlans()", "get_filtered_networks()")
		return self.get_filtered_networks ()
	def get_filtered_networks (self):
		return self.get_networks_of_security_class ("filtered")

	def get_trusted_vlans (self):
		AlffDeprecated ("get_trusted_vlans()", "get_trusted_networks()")
		return self.get_trusted_networks ()
	def get_trusted_networks (self):
		return self.get_networks_of_security_class ("trusted")

	def is_filtered_vlan (self, vlan):
		AlffDeprecated ("is_filtered_vlan()", "is_filtered_network()")
		return self.is_filtered_network (vlan)
	def is_filtered_network (self, network):
		if not self.is_valid_network (network):
			raise RuntimeError ("Invalid network id '%s'." % network)

		return "filtered" in self.config['networks'][network]['security_class']

	def get_vlan_interface (self, vlan, site, use_default = False):
		AlffDeprecated ("get_vlan_interface()", "get_network_interface()")
		return self.get_network_interface (vlan, site, use_default)
	def get_network_interface (self, network, site, use_default = False):
		if not self.is_valid_network (network):
			raise RuntimeError ("Invalid network id '%s'." % network)

		if not self.is_valid_site (site):
			raise RuntimeError ("Invalid site id '%s'." % site)

		iface = self.config['sites'][site]['interface_map'].get (network)

		if iface is None:
			if use_default:
				return self.get_default_interface (site)
			else:
				return None

		return iface['interface']

	def get_vlan_networks (self, vlan):
		AlffDeprecated ("get_vlan_networks()", "get_network_prefixes()")
		return self.get_network_prefixes (vlan)
	def get_network_prefixes (self, network):
		if not self.is_valid_network (network):
			raise RuntimeError ("Invalid network id '%s'." % network)

		return self.config['networks'][network]['prefix']

	def get_security_classes_of_vlan (self, vlan):
		AlffDeprecated ("get_security_classes_of_vlan()", "get_security_classes_of_network()")
		return self.get_security_classes_of_network (vlan)
	def get_security_classes_of_network (self, network):
		if not self.is_valid_network (network):
			raise RuntimeError ("Invalid network id '%s'." % network)

		return self.config['networks'][network]['security_class']

	########################################
	# Machine handling
	########################################

	def get_machine_ids (self, site):
		if not self.is_valid_site (site):
			raise RuntimeError ("Invalid site id '%s'!" % site)

		return self.config['sites'][site]['machines'].keys ()

	def is_valid_machine_id (self, machine, site):
		if not self.is_valid_site (site):
			raise RuntimeError ("Invalid site id '%s'!" % site)

		return machine in self.config['sites'][site]['machines']

	def get_machine_hostname (self, machine, site):
		if not self.is_valid_machine_id (machine, site):
			raise RuntimeError ("Invalid machine id '%s' in site '%s'!" %  (machine, site))

		return self.config['sites'][site]['machines'][machine].get ('hostname')

	def get_machine_ip (self, machine, site):
		if not self.is_valid_machine_id (machine, site):
			raise RuntimeError ("Invalid machine id '%s' in site '%s'!" %  (machine, site))

		return self.config['sites'][site]['machines'][machine].get ('ip')

	def get_machine_ip6 (self, machine, site):
		if not self.is_valid_machine_id (machine, site):
			raise RuntimeError ("Invalid machine id '%s' in site '%s'!" %  (machine, site))

		return self.config['sites'][site]['machines'][machine].get ('ip6')

	########################################
	# Plugin configuration
	########################################

	def get_plugin_option (self, plugin, option, default = None):
		if plugin not in self.config['plugins']:
			return None

		return self.config['plugins'][plugin].get (option, default)

################################################################################
#                          XML config file parser                              #
################################################################################

class Parser (object):
	default_options = {
		'fw_type' : 'router',
		'allow_icmp' : 'all',
		'allow_traceroute_udp' : False,
		'support_ipv6_nat': False,
		'suppress_empty_chains' : False,
		'suppress_unreferenced_chains' : False,
		'dhcp_server' : [],
	}

	multi_opt = ('dhcp_server')

	def __init__ (self, config_file):
		try:
			tree = ElementTree.parse (config_file)
			self.root = tree.getroot ()
		except Exception as e:
			raise ConfigError (e)

	def get_config (self):
		config = {
			'options'  : self._get_options (),
			'plugins'  : self._get_plugin_options (),
			'networks' : self._get_networks (),
			'sites'    : self._get_sites (),
		}

		return config

	""" Parse global options """
	def _get_options (self):
		# Get default options and get out if there is no options section in the config
		options = Parser.default_options

		opts_elem = self.root.find ('options')
		if opts_elem is not None:
			for opt_elem in opts_elem:
				if opt_elem.tag in Parser.multi_opt:
					options[opt_elem.tag].append (opt_elem.text.strip ())
				else:
					# If we have a default value and it's a boolean, except value to be boolean
					if opt_elem.tag in options and type (options[opt_elem.tag]) == bool:
						options[opt_elem.tag] = self.__get_true_false (opt_elem.text)
					else:
						options[opt_elem.tag] = opt_elem.text.strip ()
		return options

	""" Parse plugin options """
	def _get_plugin_options (self):
		plugins = {}

		plugins_tree = self.root.find ('plugins')
		if plugins_tree is not None:
			for p_elem in plugins_tree:
				plugins[p_elem.tag] = {}
				self.__get_text_elements (p_elem, plugins[p_elem.tag])

		return plugins

	""" Parse network list """
	def _get_networks (self):
		networks = {}

		xml_networks = self.root.findall ('network')

		vlans = self.root.findall ('vlan')
		if len (vlans):
			xml_networks.extend (vlans)
			AlffDeprecated ("Config tag <vlan>", "<network>")

		for network in xml_networks:
			network_dict = {
				'network' : [],
				'prefix' : [],
				'security_class' : [],
			}

			# Fetch network elements
			for elem in list (network):
				if elem.tag in ('network', 'prefix', 'security_class'):
					network_dict[elem.tag].append (elem.text.strip ())
				else:
					network_dict[elem.tag] = elem.text.strip ()

			if len (network_dict['network']):
				AlffDeprecated ("Old <vlan> element <network>", "<prefix>")
				network_dict['prefix'].extend (network_dict['network'])

			del network_dict['network']

			# Fetch network attributes (if any)
			self.__get_attributes (network, network_dict)

			if 'id' not in network_dict:
				raise ConfigError ("No ID found for network!")

			networks[network_dict['id']] = network_dict

		return networks

	""" Parse sites """
	def _get_sites (self):
		sites = {}

		sites_tree = self.root.find ('sites')
		if sites_tree is None:
			raise ConfigError ("No sites found in configuration!")

		for site in list (sites_tree):
			site_dict = {
				'machines' : {},
				'interface_map' : {},
			}

			# Fetch attributes (if any)
			self.__get_attributes (site, site_dict)

			# Get id (if not given as attribute)
			id_elem = site.find ('id')
			if id_elem is not None:
				site_dict['id'] = id_elem.text.strip ()

			if 'id' not in site_dict:
				raise ConfigError ("Site with no 'id' found!")

			site_id = site_dict['id']

			# Get machine information
			machines = site.findall ("machines/machine")
			if len (machines) == 0:
				raise ConfigError ("No machines defined in site %s!" % site_id)

			for machine in machines:
				machine_dict = {}

				self.__get_attributes (machine, machine_dict)
				self.__get_text_elements (machine, machine_dict)

				if 'id' not in machine_dict:
					raise ConfigError ("Machine without 'id' found in site '%s'!" % site_id)

				machine_id = machine_dict['id']

				if machine_id in machines:
					raise ConfigError ("Duplicate machine id '%s' found in site '%s'" % (machine_id, site_id))

				site_dict['machines'][machine_id] = machine_dict

			# Get interface_map
			int_map = site_dict['interface_map']
			networks = site.findall ("interface_map/network")
			# Compatibility glue
			vlan_networks = site.findall ("interface_map/vlan")
			if len (vlan_networks):
				networks.extend (vlan_networks)
				AlffDeprecated ("<vlan>", "<network>")

			if len (networks) == 0:
				raise ConfigError ("Empty interface map for site %s!" % site_id)

			for network in networks:
				network_dict = {}

				self.__get_attributes (network, network_dict)
				self.__get_text_elements (network, network_dict)

				if 'id' not in network_dict:
					raise ConfigError ("Network without 'id' found in site '%s'!" % site_id)

				network_id = network_dict['id']

				if 'interface' not in network_dict:
					raise ConfigError ("No 'interface' specified for network '%s' at site '%s'!" % (network_id, site_id))

				if network_id in int_map:
					raise ConfigError ("Duplicate network id '%s' found in interface map for site '%s'!" (network_id, site_id))

				int_map[network_id] = network_dict

				# Default interace found?
				if 'default' in network_dict:
					if 'default' in int_map:
						raise ConfigError ("Duplicate default interface found: '%s' vs. '%s'!" % (int_map['default']['interface'], network_dict['interface']))

					int_map['default'] = {
						'id' : 'default',
						'interface' : network_dict['interface'],
						'orig_network' : network_dict['id'],
					}

			# Store this site
			sites[site_dict['id']] = site_dict

		return sites

	def __get_attributes (self, elem, dst_dict):
		for attr in elem.attrib.keys ():
			dst_dict[attr] = elem.attrib[attr].strip ()

	def __get_text_elements (self, elem, dst_dict):
		for subelem in list (elem):
			if subelem.text is not None:
				# Try to convert boolean text value into real boolean (if any)
				dst_dict[subelem.tag] = self.__get_true_false (subelem.text, noerror = True)
			else:
				# If there is no text value we assume that it's a boolean
				dst_dict[subelem.tag] = True

	def __get_true_false (self, string, noerror = False):
		match = string.strip ()

		if re.search ("^(yes|true)$", match, re.I):
			return True
		elif re.search ("^(no|false)$", match, re.I):
			return False

		if noerror:
			return match

		raise ConfigError ("Expected boolean value ('yes', 'no'), got '%s'" % string)