"""Color base."""
from abc import ABCMeta
from .. import util
from . import _parse

# Technically this form can handle any number of channels as long as any
# extra are thrown away. We only support 6 currently. If we ever support
# colors with more channels, we can bump this.
RE_DEFAULT_MATCH = r"""(?xi)
color\(\s*
(?:({{color_space}})\s+)?
((?:{percent}|{float})(?:{space}(?:{percent}|{float})){{{{,{{channels:d}}}}}}(?:{slash}(?:{percent}|{float}))?)
\s*\)
""".format(
    **_parse.COLOR_PARTS
)

WHITES = {
    "A": [1.09850, 1.00000, 0.35585],
    "B": [0.99072, 1.00000, 0.85223],
    "C": [0.98074, 1.00000, 1.18232],
    "D50": [0.96422, 1.00000, 0.82521],
    "D55": [0.95682, 1.00000, 0.92149],
    "D65": [0.95047, 1.00000, 1.08883],
    "D75": [0.94972, 1.00000, 1.22638],
    "E": [1.00000, 1.00000, 1.00000],
    "F2": [0.99186, 1.00000, 0.67393],
    "F7": [0.95041, 1.00000, 1.08747],
    "F11": [1.00962, 1.00000, 0.64350]
}

class Angle(float):
    """Angle type."""

class Percent(float):
    """Percent type."""

class OptionalPercent(float):
    """Optional percent type."""

class GamutBound(tuple):
    """Bounded gamut value."""

class GamutUnbound(tuple):
    """Unbounded gamut value."""

class Cylindrical:
    """Cylindrical space."""

    def hue_name(self):
        """Hue channel name."""

        return "hue"

class Space(
    metaclass=ABCMeta
):
    """Base color space object."""

    # Color space name
    SPACE = ""
    # Serialized name
    SERIALIZE = None
    # Number of channels
    NUM_COLOR_CHANNELS = 3
    # Channel names
    CHANNEL_NAMES = ("alpha",)
    # For matching the default form of `color(space coords+ / alpha)`.
    # Classes should define this if they want to use the default match.
    DEFAULT_MATCH = ""
    # Match pattern variable for classes to override so we can also
    # maintain the default and other alternatives.
    MATCH = ""
    # Should this color also be checked in a different color space? Only when set to a string (specifying a color space)
    # will the default gamut checking also check the specified space as well as the current.
    #
    # Gamut checking:
    #   The specified color space will be checked first followed by the original. Assuming the parent color space fits,
    #   the original should fit as well, but there are some cases when a parent color space that is slightly out of
    #   gamut, when evaluated with a threshold, may appear to be in gamut enough, but when checking the original color
    #   space, the values can be greatly out of specification (looking at you HSL).
    GAMUT_CHECK = None
    # White point
    WHITE = "D50"

    def __init__(self, color, alpha=None):
        """Initialize."""

        self._alpha = util.NaN
        self._coords = [util.NaN] * self.NUM_COLOR_CHANNELS

        if isinstance(color, Space):
            for index, channel in enumerate(color.coords()):
                self.set(self.CHANNEL_NAMES[index], channel)
            self.alpha = color.alpha
        elif isinstance(color, (list, tuple)):
            if len(color) != self.NUM_COLOR_CHANNELS:  # pragma: no cover
                # Only likely to happen with direct usage internally.
                raise ValueError(
                    "A list of channel values should be at a minimum of {}.".format(self.NUM_COLOR_CHANNELS)
                )
            for index in range(self.NUM_COLOR_CHANNELS):
                self.set(self.CHANNEL_NAMES[index], color[index])
            self.alpha = 1.0 if alpha is None else alpha
        else:  # pragma: no cover
            # Only likely to happen with direct usage internally.
            raise TypeError("Unexpected type '{}' received".format(type(color)))

    def __repr__(self):
        """Representation."""

        gamut = self.RANGE
        values = []
        for i, coord in enumerate(util.no_nan(self.coords())):
            value = util.fmt_float(coord, util.DEF_PREC)
            if isinstance(gamut[i][0], Percent):
                value += '%'
            values.append(value)

        return 'color({} {} / {})'.format(
            self._serialize()[0],
            ' '.join(values),
            util.fmt_float(util.no_nan(self.alpha), util.DEF_PREC)
        )

    __str__ = __repr__

    def _handle_input(self, value):
        """Handle numerical input."""

        if not util.is_number(value):
            raise TypeError("Value should be a number not type '{}'".format(type(value)))
        return float(value) if not util.is_nan(value) else value

    def coords(self):
        """Coordinates."""

        return self._coords[:]

    @classmethod
    def space(cls):
        """Get the color space."""

        return cls.SPACE

    @classmethod
    def _serialize(cls):
        """Get the serialized name."""

        return (cls.space(),) if cls.SERIALIZE is None else cls.SERIALIZE

    @classmethod
    def white(cls):
        """Get the white color for this color space."""

        return WHITES[cls.WHITE]

    @property
    def alpha(self):
        """Alpha channel."""

        return self._alpha

    @alpha.setter
    def alpha(self, value):
        """Adjust alpha."""

        self._alpha = util.clamp(self._handle_input(value), 0.0, 1.0)

    def set(self, name, value):  # noqa: A003
        """Set the given channel."""

        if name not in self.CHANNEL_NAMES:
            raise ValueError("'{}' is an invalid channel name".format(name))

        setattr(self, name, value)
        return self

    def get(self, name):
        """Get the given channel's value."""

        if name not in self.CHANNEL_NAMES:
            raise ValueError("'{}' is an invalid channel name".format(name))
        return getattr(self, name)

    def to_string(
        self, parent, *, alpha=None, precision=None, fit=True, **kwargs
    ):
        """Convert to CSS 'color' string: `color(space coords+ / alpha)`."""

        if precision is None:
            precision = parent.PRECISION

        a = util.no_nan(self.alpha)
        alpha = alpha is not False and (alpha is True or a < 1.0)

        method = None if not isinstance(fit, str) else fit
        coords = util.no_nan(parent.fit(method=method).coords() if fit else self.coords())
        gamut = self.RANGE
        template = "color({} {} / {})" if alpha else "color({} {})"

        values = []
        for i, coord in enumerate(coords):
            value = util.fmt_float(coord, precision)
            if isinstance(gamut[i][0], Percent):
                value += '%'
            values.append(value)

        if alpha:
            return template.format(
                self._serialize()[0], ' '.join(values), util.fmt_float(a, max(precision, util.DEF_PREC))
            )
        else:
            return template.format(self._serialize()[0], ' '.join(values))

    @classmethod
    def null_adjust(cls, coords, alpha):
        """Process coordinates and adjust any channels to null/NaN if required."""

        return coords, alpha

    @classmethod
    def match(cls, string, start=0, fullmatch=True):
        """Match a color by string."""

        m = cls.DEFAULT_MATCH.match(string, start)
        if (
            m is not None and
            (
                (m.group(1) and m.group(1).lower() in cls._serialize())
            ) and (not fullmatch or m.end(0) == len(string))
        ):

            # Break channels up into a list
            split = _parse.RE_SLASH_SPLIT.split(m.group(2).strip(), maxsplit=1)

            # Get alpha channel
            alpha = _parse.norm_alpha_channel(split[-1]) if len(split) > 1 else 1.0

            # Parse color channels
            channels = []
            for i, c in enumerate(_parse.RE_CHAN_SPLIT.split(split[0]), 0):
                if c and i < cls.NUM_COLOR_CHANNELS:
                    is_percent = isinstance(cls.RANGE[i][0], Percent)
                    is_optional_percent = isinstance(cls.RANGE[i][0], OptionalPercent)
                    has_percent = c.endswith('%')
                    if is_percent and not has_percent:
                        # We have an invalid percentage channel
                        return None, None
                    elif (not is_percent and not is_optional_percent) and has_percent:
                        # Percents are not allowed for this channel.
                        return None, None
                    channels.append(_parse.norm_color_channel(c, not is_percent))

            # Missing channels are filled with zeros
            if len(channels) < cls.NUM_COLOR_CHANNELS:
                diff = cls.NUM_COLOR_CHANNELS - len(channels)
                channels.extend([0.0] * diff)

            # Apply null adjustments (null hues) if applicable
            return cls.null_adjust(channels, alpha), m.end(0)

        return None, None


def solve(s):

    dic = {}
    ll = 'qwertasdfgzxcvb'
    rr = 'yuiophjklnm'

    for l_i in list(ll):
        dic[l_i] = -1

    for r_i in list(rr):
        dic[r_i] = 1

    ans = 0
    prev = 0

    for s_i in s:
        current = dic[s_i]
        if current != prev:
            if abs(current - prev) == 2:
                ans += 1

        prev = current

    return ans

while 1:
    s = raw_input()
    if s == '#':
        break

    print(solve(s))


from flask import render_template, jsonify, json, request, current_app
from ..models import Queries
from . import deposits

@deposits.route('/deposits/edit/deposits_edit_submit', methods=['POST'])
def deposits_edit_submit():

    deposit_id = request.json['deposit_id']
    deposit_name = request.json['deposit_name']
    aliases = request.json['aliases']
    latitude = request.json['latitude']
    longitude = request.json['longitude']
    database_name = request.json['database_name']
    production = request.json['production']
    grade = request.json['grade']
    geologic_unit = request.json['geologic_unit']
    ore_type = request.json['ore_type']
    discovery_year = request.json['discovery_year']

    ref_ids = request.json['ref_ids']
    mine_type = request.json['mine_type']
    commodities = request.json['commodities']

    district_ids = request.json['district_ids']
    country_id = request.json['country_id']
    state_id = request.json['state_id']
    county_id = request.json['county_id']

    #Query to get the inputs from referenc table
    Queries().deposits_edit_submit(deposit_id, deposit_name, aliases, latitude, longitude, database_name, production, grade, geologic_unit, ore_type, discovery_year, country_id, state_id, county_id, ref_ids, mine_type, commodities)

    Queries().deposits_edit_submit_districts(deposit_id, district_ids)

    return '0'

@deposits.route('/deposits/edit/deposit_SJM_new', methods=['POST'])
def deposits_new():

    #deposit_id = request.json['deposit_id']
    deposit_name = request.json['deposit_name']
    aliases = request.json['aliases']
    latitude = request.json['latitude']
    longitude = request.json['longitude']
    database_name = request.json['database_name']
    production = request.json['production']
    grade = request.json['grade']
    geologic_unit = request.json['geologic_unit']
    ore_type = request.json['ore_type']
    discovery_year = request.json['discovery_year']
    country_id = request.json['country_id']
    state_id = request.json['state_id']
    county_id = request.json['county_id']
    ref_ids = request.json['ref_ids']
    mine_type = request.json['mine_type']
    commodities = request.json['commodities']

    district_ids = request.json['district_ids']

    #Query to get the inputs from referenc table
    #deposit_id_new = Queries().deposits_edit_new(deposit, source, filename, url, yn)
    rows = Queries().deposits_edit_sjmNew(deposit_name, aliases, latitude, longitude, database_name, production, grade, geologic_unit, ore_type, discovery_year, country_id, state_id, county_id, ref_ids, mine_type, commodities, district_ids)

    #deposit_id = '36669'
    #rows = {'deposit_id':deposit_id}
    jsonStr = json.dumps(rows)
    j = jsonify(myData=jsonStr)
    return j
    #return '0'

@deposits.route('/deposits/edit/deposits_delete', methods=['POST'])
def deposits_delete():

    deposit_id = request.json['deposit_id']
    #print("deposit_id ", deposit_id)

    #Query to delete the current reference
    Queries().deposits_edit_delete(deposit_id)
    return '0'

@deposits.route('/deposits/edit/deposits_edit_load_districts/<deposit_id>')
def deposits_edit_load_districts(deposit_id):
    #Query to get the inputs from deposit table
    rows = Queries().districts_by_deposit(deposit_id)
    jsonStr = json.dumps(rows)
    j = jsonify(Load=jsonStr)
    return j

@deposits.route('/deposits/edit/deposits_edit_load_country/<deposit_id>')
def deposits_edit_load_country(deposit_id):
    #Query to get the inputs from deposit table
    rows = Queries().country_by_deposit(deposit_id)
    jsonStr = json.dumps(rows)
    j = jsonify(Load=jsonStr)
    return j

@deposits.route('/deposits/edit/deposits_edit_load/<deposit_id>')
def deposits_edit_load(deposit_id):
    #Query to get the inputs from referenc table
    rows = Queries().deposits_edit_load(deposit_id)
    #print('In edit load view2 rows', rows)
    jsonStr = json.dumps(rows)
    j = jsonify(Load=jsonStr)
    return j

@deposits.route('/deposits/deposits_edit/<deposit_id>')
def deposits_edit(deposit_id):
    return render_template('deposits/edit.html', deposit_id=deposit_id)

@deposits.route('/deposits/deposits_by_database/<string:database_name>')
def deposits_by_database(database_name):
    rows = Queries().deposits_by_database(database_name)
    jsonStr = json.dumps(rows)
    j = jsonify(Deposits=jsonStr)
    return j

@deposits.route('/deposits/deposits_by_district/<district_id>')
def deposits_by_district(district_id):
    rows = Queries().deposits_by_district(district_id)
    jsonStr = json.dumps(rows)
    j = jsonify(Deposits=jsonStr)
    return j

@deposits.route('/deposits/deposits_search/<id>')
def deposits_search(id):
    #print('In deposits_search', id)
    rows = Queries().deposits_search(id)
    jsonStr = json.dumps(rows)
    j = jsonify(Deposits=jsonStr)
    return j

# PUT THIS AT BOTTOM!
@deposits.route('/deposits_home')
def deposits_home():
    return render_template('deposits/deposits_home.html')


import db

def addToPot(gameId, player, chips, action):
    _,_,_,_,_,pot,betToMatch,_,_,_,_ = db.getGame(gameId)
    playerTuple = db.getPlayer(gameId, player)
    _,_,address,name,stack,_,_,_,_,amountPutInPot,_,amountPutInPotThisRound = playerTuple
    logStatement = ""
    chipsPutIn = chips

    if stack <= chips:
        logStatement += "Player " + name + " is all in! "
        chipsPutIn = stack
        db.updatePlayer(gameId, player, "isAllIn = 1")
    logStatement += "Player " + name + " "
    if action == "sb": # small blind
        logStatement += "posted the small blind of " + str(chipsPutIn) + " chips."
    elif action == "bb": # big blind
        logStatement += "posted the big blind of " + str(chipsPutIn) + " chips."
    elif action == "call":
        logStatement += "calls " + str(chipsPutIn) + " chips."
    elif action == "raise":
        # check if amount put in actually makes it a raise (i.e. with all in less than btm)
        if chipsPutIn > betToMatch:
            db.updateGame(gameId, "betToMatch = " + str(amountPutInPotThisRound + chipsPutIn))
            logStatement += "raises to " + str(amountPutInPotThisRound + chipsPutIn) + " chips."
        # otherwise betToMatch is not increased and no raise has been made

    elif action == "check":
        logStatement += "checks."

    #update player stack
    db.updatePlayer(gameId, player, "stack = " + str(stack - chipsPutIn)
        + ", amountPutInPot = " + str(amountPutInPot + chipsPutIn) +
        ", amountPutInPotThisRound = " + str(amountPutInPotThisRound + chipsPutIn))

    #update pot
    db.updateGame(gameId, "pot = " + str(pot + chipsPutIn))
    return logStatement

def takeFromPot(gameId, player, chips):
    _,_,_,_,_,pot,_,_,_,_,_ = db.getGame(gameId)
    playerTuple = db.getPlayer(gameId, player)
    _,_,address,name,stack,_,_,_,_,amountPutInPot,_,amountPutInPotThisRound = playerTuple
    logStatement = ""

    logStatement = "Player " + name + " takes " + str(chips) + " chips from the pot."

    #update player stack
    db.updatePlayer(gameId, player, "stack = " + str(stack + chips))

    #update pot
    db.updateGame(gameId, "pot = " + str(pot - chips))
    return logStatement

def fold(gameId, playerTuple):
    _,_,_,_,_,pot,betToMatch,handLog,_,_,_ = db.getGame(gameId)
    _,playerId,address,name,stack,_,_,_,_,amountPutInPot,_,amountPutInPotThisRound = playerTuple

    db.updatePlayer(gameId, playerId, "folded = 1")
    db.updateGame(gameId, "handLog = \"" + handLog + "\r\nPlayer " + name + " folds.\"")

def call(gameId, playerTuple):
    _,_,_,_,_,pot,betToMatch,handLog,_,_,_ = db.getGame(gameId)
    _,playerId,address,name,stack,_,_,_,_,amountPutInPot,_,amountPutInPotThisRound = playerTuple

    chipsToPutIn = betToMatch - amountPutInPotThisRound

    logStatement = ""
    if chipsToPutIn == 0:
        #Check
        logStatement = handLog + "\r\n" + addToPot(gameId, playerId, chipsToPutIn, "check")
    else:
        logStatement = handLog + "\r\n" + addToPot(gameId, playerId, chipsToPutIn, "call")

    #update player stack
    db.updatePlayer(gameId, playerId, "isChecked = 1")
    db.updateGame(gameId, "handLog = \"" + logStatement + "\"")

def raiseTo(gameId, playerTuple, raiseToChips):
    _,_,_,_,_,pot,betToMatch,handLog,_,_,_ = db.getGame(gameId)
    _,playerId,address,name,stack,_,_,_,_,amountPutInPot,_,amountPutInPotThisRound = playerTuple

    if betToMatch > raiseToChips:
        return False
    elif betToMatch == raiseToChips:
        call(gameId, playerTuple)
        return True
    else:

        chipsToPutIn = raiseToChips - amountPutInPotThisRound

        logStatement = handLog + "\r\n" + addToPot(gameId, playerId, chipsToPutIn, "raise")

        numberOfPlayers = db.numberOfPlayersInGame(gameId)
        for i in range(numberOfPlayers):
            _,_,_,_,_,_,isAllIn,folded,eliminated,_,isChecked,_ = db.getPlayer(gameId, i)
            if not bool(folded) and not bool(eliminated) and not bool(isAllIn):
                db.updatePlayer(gameId, i, "isChecked = 0")

        # Raiser is checked
        db.updatePlayer(gameId, playerId, "isChecked = 1")

        db.updateGame(gameId, "handLog = \"" + logStatement + "\"")
        return True

def allIn(gameId, playerTuple):
    _,_,_,_,_,pot,betToMatch,handLog,_,_,_ = db.getGame(gameId)
    _,playerId,address,name,stack,_,_,_,_,amountPutInPot,_,amountPutInPotThisRound = playerTuple

    return raiseTo(gameId, playerTuple, stack+amountPutInPotThisRound)


import unittest

import numpy as np

from components.prob_conway_to_binary_conway_fn import ProbConwayToBinaryConwayFn

class TestProbConwayToBinaryConwayFn(unittest.TestCase):

    def test_call(self):
        for _ in range(100):
            test_input = np.random.random((10, 10))
            fn = ProbConwayToBinaryConwayFn(threshold=0.5)
            test_output = fn(test_input).numpy()
            expected_output = test_input >= 0.5
            self.assertTrue(np.array_equal(expected_output, test_output))

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


"""
写一个Glass(玻璃杯)类,有fill(注水)方法,
调用时显示当前水量(当前水量为ml):
1. fill(ml) 表示注水
"""

# 玻璃杯类
class Glass:
    def __init__(self, color, volume, quality):
        self.color = color
        self.volume = volume
        self.quality = quality
        self.density = quality / volume

    def show_glass_type(self):
        if self.density > 4:
            print(f"This is a {self.color} high quality glass")
        else:
            print(f"Don't buy this {self.color} glass")

if __name__ == "__main__":
    test_glass = Glass(input("what's the color of this glass"), int(input("what's the volume of the glass (ml)")),
                       int(input("what's the quality of the glass (g)")))
    test_glass.show_glass_type()


from asimov.extension import Extension
from asimov import event_dispatch
from asimov.event import AsimovEvent
from asimov import extension
from cmd2 import Cmd
import time
import ctypes
import sys, platform, psutil, threading
def hello(self, hoi):
  self.poutput("Hi!")

class AsiCli(extension.Extension):
  listeners = {"/asimov/extension/cli/add_command": "add_command", "/asimov/boot/finished": "start_cli", "/asimov/boot/lifecycle": "lifecycle"}
  def __init__(self):
    event_dispatch.add_event_listener("BOOT-FINISHED", self.start_cli)
    #self.messages.asimov.extension.cli.add_command(hello)

  def lifecycle(self, ev):
    if ev == "start":
      event_dispatch.dispatch_event(AsimovEvent("/asimov/extension/cli/prerun_hook", None))
      pass
  def add_command(self, command_func, command_string, help_text):
    setattr(AsiCliInterpreter, "help_%s" % (command_string), lambda x: x.poutput(help_text))
    setattr(AsiCliInterpreter,"do_%s" % (command_string), command_func)

  def start_cli(self):
    #hello.__doc__ = "This is a test"

    #AsiCliInterpreter.__dict__.update({"do_hello": hello})
    #self.logger.debug("Starting CLI")
    a = AsiCliInterpreter()
    #a = Cmd()
    threading.Thread(target=a.cmdloop).start()

class AsiCliInterpreter(Cmd):

  def __init__(self):
    Cmd.__init__(self, use_ipython = True)
    self.intro = self.get_logo() + self.colorize("""

    Welcome to the AsimovOS shell!
    Type help for information on available commands.
    """, "cyan")
    self.prompt = self.colorize("AsimovOS>", "yellow")
    self.allow_cli_args = False

  def do_exit(self, arg):
    """
    Shutdown system immediately
    """
    self.do_quit(arg)

  def do_quit(self, arg):
    """
    Shutdown system immediately
    """
    event_dispatch.dispatch_event(AsimovEvent("/asimov/system/shutdown", []))

  def do_server(self, arg):
    """
    Control the AsimovOS server. Available commands are start, stop, and kill. Stop and kill are synonymous.
    """
    if "kill" in arg or "stop" in arg:
      event_dispatch.dispatch_event(AsimovEvent("/asimov/extension/server/kill", []))
    elif "start" in arg:
      event_dispatch.dispatch_event(AsimovEvent("/asimov/extension/server/start", []))

  def do_dispatch(self, arg):
    """
    Usage: dispatch {topic} {arg1} {arg2}...
    Due to limitations in the CLI, all args are converted to strings, thus topics expecting other types will fail
    """
    args = arg.split(" ")
    topic = args[0]
    event_dispatch.dispatch_event(AsimovEvent(topic, args[1:]))

  def do_enable(self, arg):
    """
    Allows control over Enabler
    """
    extension.enabler.overrides.update({arg: True})
    extension.enabler.resolve_enable()

  def do_subps(self, arg):
    """
    Enumerate subprocesses
    """
    current_process = psutil.Process()
    children = current_process.children(recursive=True)
    self.poutput(str(children))

  def do_threads(self, arg):
    """
    List running threads
    """
    self.poutput(str(threading.enumerate()))

  def do_sys_info(self, arg):
    """
    Usage: sys_info

    Prints system information
    """
    def linux_distribution():
      try:
        return platform.linux_distribution()
      except:
        return "N/A"
    self.poutput("""Python version: %s
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
mac_ver: %s
""" % (
  sys.version.split('\n'),
  str(platform.dist()),
  linux_distribution(),
  platform.system(),
  platform.machine(),
  platform.platform(),
  platform.uname(),
  platform.version(),
  platform.mac_ver(),
  ))

  def get_logo(self):
    """Asimov logo translated to ANSI art"""
    return """

            ########
              ######
        ##############
        ######  ########
      ######      ######
    #######       ########
    #######         ######
  ########          ######
  ######              ##
  ############################
   ###  ####################
          ################   """


"""From https://github.com/tf-encrypted/tf-encrypted/blob/master/examples/logistic/common.py"""

"""Provide classes to perform private training and private predictionn"""
import tensorflow as tf
import tf_encrypted as tfe

class DataOwner:
    """Contains code meant to be executed by a data owner Player."""

    def __init__(
        self, player_name, num_features, training_set_size, test_set_size, batch_size
    ):
        self.player_name = player_name
        self.num_features = num_features
        self.training_set_size = training_set_size
        self.test_set_size = test_set_size
        self.batch_size = batch_size
        self.train_initializer = None
        self.test_initializer = None

    @property
    def initializer(self):
        return tf.group(self.train_initializer, self.test_initializer)

    @tfe.local_computation
    def provide_training_data(self,x,y):
        """Preprocess training dataset

    Return single batch of training dataset
    """

        def norm(x, y):
            return tf.cast(x, tf.float32), tf.expand_dims(y, 0)

        train_set = (
            tf.data.Dataset.from_tensor_slices((x, y))
            .map(norm)
            .repeat()
            .shuffle(buffer_size=self.batch_size)
            .batch(self.batch_size)
        )

        train_set_iterator = train_set.make_initializable_iterator()
        self.train_initializer = train_set_iterator.initializer

        x, y = train_set_iterator.get_next()
        x = tf.reshape(x, [self.batch_size, self.num_features])
        y = tf.reshape(y, [self.batch_size, 1])

        return x, y

    @tfe.local_computation
    def provide_testing_data(self,x,y):
        """Preprocess testing dataset

    Return single batch of testing dataset
    """

        def norm(x, y):
            return tf.cast(x, tf.float32), tf.expand_dims(y, 0)

        test_set = (
            tf.data.Dataset.from_tensor_slices((x, y))
            .map(norm)
            .batch(self.test_set_size)
        )

        test_set_iterator = test_set.make_initializable_iterator()
        self.test_initializer = test_set_iterator.initializer

        x, y = test_set_iterator.get_next()
        x = tf.reshape(x, [self.test_set_size, self.num_features])
        y = tf.reshape(y, [self.test_set_size, 1])

        return x, y

class PredictionClient:
    """Contains methods meant to be executed by a prediction client."""

    def __init__(self, player_name, num_features):
        self.player_name = player_name
        self.num_features = num_features

    @tfe.local_computation
    def provide_input(self):
        return tf.random.uniform(
            minval=-0.5, maxval=0.5, dtype=tf.float32, shape=[1, self.num_features]
        )

    @tfe.local_computation
    def receive_output(self, result):
        return tf.print("Result on {}:".format(self.player_name), result)

Preparation/AI/Secure and Privacy-preserving Machine Learning/lib/common.py


from segmentation import Segmentation
def Normalization(dataFrame):

    from sklearn.preprocessing import MinMaxScaler
    import pandas as pd

    novos_dados = dados.drop(['Unnamed: 0','Unnamed: 0.1','classe','imagem'], axis=1)

    dados_normalizados = MinMaxScaler().fit(novos_dados)
    normalizados = dados_normalizados.transform(novos_dados)
    df_normalizado = pd.DataFrame(normalizados)
    df_normalizado["classe"] = dados["classe"]
    df_normalizado["imagem"] = dados["imagem"]
    df_normalizado.columns = ['Area','Perimetro','m00','m10','m01','m20','m11','m02','m30','m21','m12','m03','mu20','mu11','mu02','mu30','mu21','mu12','mu03','nu20','nu11','nu02','nu30','nu21','nu12','nu03','cx','cy','B','G','R','H','S','V','L','A','D','LBP','I1','I2','I3','b','g','r','h','s','v','l','a','d','lbp','i1','i2','i3','classe','imagem']

    return df_normalizado


# -*- coding: utf-8 -*-
__author__ = 'boonya'

import json
from flask import make_response

class Response(object):
    """Response wrapper helper."""

    @staticmethod
    def success(data, code=200, serializer=None):
        """Returns successful response.

        :param str body:
        :param int code:
        :return ResponseBase:
        """

        if serializer:
            data = json.dumps(data, cls=serializer)
        else:
            data = json.dumps(data)

        response = make_response(data, code)
        response.headers['Content-Type'] = 'application/json'
        return response

    @staticmethod
    def failure(reason, code=400, **kwargs):
        """Returns response with serialized json string about error reason.

        :param str reason:
        :param int code:
        :param kwargs:
        :return ResponseBase:
        """
        response = make_response(json.dumps({"reason": reason}), code)
        response.headers['Content-Type'] = 'application/json'
        return response


#!/usr/bin/python3
import time

from rgbmatrix import graphics,  RGBMatrix, RGBMatrixOptions

options = RGBMatrixOptions()
#options.hardware_mapping = self.args.led_gpio_mapping
options.rows = 16
options.cols = 32
options.chain_length = 3
options.parallel = 3
#options.row_address_type = self.args.led_row_addr_type
options.multiplexing = 4
options.pwm_bits = 11
options.brightness = 10
#options.pwm_lsb_nanoseconds = self.args.led_pwm_lsb_nanoseconds
#options.led_rgb_sequence = self.args.led_rgb_sequence
#options.pixel_mapper_config = self.args.led_pixel_mapper
#options.show_refresh_rate = 1
options.gpio_slowdown = 4
#options.disable_hardware_pulsing = True
matrix = RGBMatrix(options = options)

offscreen_canvas = matrix.CreateFrameCanvas()
font = graphics.Font()
font.LoadFont("fonts/7x13.bdf")
yellow = graphics.Color(255, 255, 0)
white = graphics.Color(255, 255, 255)
blue = graphics.Color(0, 0, 255)
pink = graphics.Color(255,192,203)
black = graphics.Color(0,0,0)
pos = offscreen_canvas.width
my_text = 'default'

print('AA Env display start...')

def DrawRectangle(canvas,x1,y1,x2,y2,color):
    graphics.DrawLine(canvas,x1,y1,x2,y1, color)
    graphics.DrawLine(canvas,x2,y1,x2,y2, color)
    graphics.DrawLine(canvas,x1,y2,x2,y2, color)
    graphics.DrawLine(canvas,x1,y1,x1,y2, color)

def DrawFillRectangle(canvas,x1,y1,x2,y2,color):
    for y in range(y1,y2+1):
        for x in range(x1,x2):
            graphics.DrawLine(canvas,x1,y,x2,y,color)

while True:
    offscreen_canvas.Clear()
    DrawFillRectangle(offscreen_canvas,0,0,95,47,blue)
    #DrawFillRectangle(offscreen_canvas,0,0,95,15,pink)
    DrawRectangle(offscreen_canvas,0,32,95,47,white)
    len = graphics.DrawText(offscreen_canvas, font, pos, 10, black, my_text)
    pos -= 1
    if (pos + len < 0):
       pos = offscreen_canvas.width
    time.sleep(0.5)
    offscreen_canvas = matrix.SwapOnVSync(offscreen_canvas)


'''
Paramteres to modify for testing.
'''
import numpy as np

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

# Frams to save after

frames_to_save_after = 500

# Training Data file names.

#save_training_data_file = 'TrainingData/' + 'training_data.npy'
save_training_data_file = 'TrainingData/' + 'nurburgring_without_green_line.npy'
normalized_training_data_file = save_training_data_file + '_normalized.npy'

# Training Parameters

training_epochs = 10
lr = 1e-5

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

# WARNING DONT TOUCH THIS BLOCK UNLESS REQUIRED

# The screen part to capture
monitor = {"top": 40, "left": 40, "width": 700, "height": 550}

# Decreases the monitor window size by this factor
monitor_reduction_factor = 10

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

# Analysis with ModifyCapture

# Region of intrest in the window

roi_box_height_from_bottom = 200

roi_vertices = [
	np.array([
		[0,monitor['height']],
		[0,roi_box_height_from_bottom],
		[monitor['width'],roi_box_height_from_bottom],
		[monitor['width'],monitor['height']]
	], np.int32)]

# Canny thresholds

canny_threshold1 = 200
canny_threshold2 = 300

# Dawn lines parameters

minimum_lenth = 180
maximum_gap = 20

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


from state import State

"""
This module contains two utility functions for reading and writing files.
"""

def read_input_file(filename):
    """
    This function reads a problem file and returns two State objects, one for the initial
    state and one for the goal state.
    """
    with open('problems/' + filename) as f:
        lines = [line.split() for line in f]     #Read the file by line and split it.

        blocks_names = lines[0][1:]     #Get the blocks names.
        blocks_names[-1] = blocks_names[-1][:-1]     #Remove the parenthesis from the last block name.

        initial = lines[1][1:-1]     #Get the initial state.
        initial = [i.replace('(', '') for i in initial]     #Remove the parentheses.
        initial = [i.replace(')', '') for i in initial]

        goal = lines[2][2:]     #Get the goal state.
        goal = [i.replace('(', '') for i in goal]     #Remove the parentheses.
        goal = [i.replace(')', '') for i in goal]

        initial_layout = {key: ['-', 'c'] for key in blocks_names}     #Construct the inital layout.
        goal_layout = {key: ['-', 'c'] for key in blocks_names}     #Construct the goal layout.

        for i in range(len(initial)):
            if initial[i] == 'ON':
                initial_layout[initial[i + 1]][0] = initial[i + 2]
                initial_layout[initial[i + 2]][1] = 'u'

        for i in range(len(goal)):
            if goal[i] == 'ON':
                goal_layout[goal[i + 1]][0] = goal[i + 2]
                goal_layout[goal[i + 2]][1] = 'u'

    return State(layout = initial_layout), State(layout = goal_layout)     #Return two state objects.

def write_output_file(solution, filename):
    """
    This function is taking as arguments a State object which is a solution of the problem,
    and a filename to write the steps towards the solution.
    """
    current_state = solution     #The state we start, which is the last i.e. the solution.
    path = []     #The path from the solution towards the intial state.
    i = 1

    while True:
        path.append(current_state)     #Add the current state i.e. solution, in the list.

        current_state = current_state.parent     #The current state now becomes the parent of it.

        if current_state.parent == None:     #If the current state has no parent...
            path.append(current_state)     #Add the current state in the list.
            break

    path.reverse()     #Reverse the list.

    with open(filename, 'w') as f:     #Open the output file.
        for state in path[1:]:     #For every state in the path, except the first one which is the initial state that has no previous move...
            move = state.move     #Get the move.

            f.write(str(i) + '. Move(' + move[0] + ', ' + move[1] + ', ' + move[2] + ')\n')     #Write the move.
            i += 1     #Increment the counter.

    return len(path[1:])     #Return the number of steps.


import vk_api
import datetime
import time
import setings
import requests
from vk_api.longpoll import VkLongPoll, VkEventType
from vk_api.keyboard import VkKeyboard, VkKeyboardColor
from vk_api.utils import get_random_id
from vk_api import VkUpload
from PIL import Image, ImageDraw, ImageFont

# vk token
vk_session = vk_api.VkApi(token = setings.vkMTFapi)
longpoll = VkLongPoll(vk_session)
vk = vk_session.get_api()

# Настройка шрифтов
font = ImageFont.truetype('9622.ttf', size = 30)
fontWeek = ImageFont.truetype('ArialRoundedMTProCyr-Bold.otf', size = 35)

while True:
    # Настройка счетчика
    dateNow = datetime.datetime.now()
    dateThen = datetime.datetime(2020, 10, 30, 0, 00, 0)
    timer = dateThen - dateNow
    timerSecond = timer.total_seconds()
    timerMinute = (timerSecond % 3600) // 60
    timerHour = (timerSecond % 86400) // 3600
    parityWeek = "Числитель" if datetime.datetime.now().isocalendar()[1] % 2 == 0 else "Знаменатель"
    getTimer = "{}д.  {}ч.  {}мин.".format(timer.days, round(timerHour), round(timerMinute))

    im = Image.open('/Users/igorgerasimov/Desktop/Python/DdKGTA/Cover/coverMTF.jpg')
    draw_text = ImageDraw.Draw(im)

    draw_text.text(
        (196, 321),
        'До стипендии осталось :',
        # Добавляем шрифт к изображению
        font = font,
        fill = (255,255,255,128))

    draw_text.text(
        (1038, 321),
        getTimer,
        font = font,
        fill = (255,255,255,128))

    draw_text.text(
        (549, 142),
        'Эта неделя : ',
        font = font,
        fill = (255,255,255,128))

    draw_text.text(
        (550, 200),
        parityWeek,
        font = fontWeek,
        fill = (255,255,255,128))

    im.save('coverMTF2.jpg')
    print("Сохранение фото")
    # a = vk.photos.getOwnerCoverPhotoUploadServer(photo = 'coverMTF2.jpg', # DdKGTA group
    #                                              group_id = 194390511,
    #                                              crop_x = 1,
    #                                              crop_y = 1,
    #                                              crop_x2 = 1499,
    #                                              crop_y2 = 378)
    a = vk.photos.getOwnerCoverPhotoUploadServer(photo = 'coverMTF2.jpg',
                                                group_id = 16035652, # MTF group
                                                crop_x = 1,
                                                crop_y = 1,
                                                crop_x2 = 1499,
                                                crop_y2 = 378)
    print ('Получение ссылки ...')

    img = {'photo': ('coverMTF2.jpg', open(r'coverMTF2.jpg', 'rb'))}
    print("Получение положения фото")

    reg = requests.post(a['upload_url'], files = img)
    v = reg.json()

    print ("Загрузка фото")
    a = vk.photos.saveOwnerCoverPhoto(hash = v['hash'], photo = v['photo'])
    time.sleep(90)
    # im.show()


from .explainer_interface import ExplainerInterface
from collections import Counter
from gensim.utils import simple_preprocess
from wordcloud import STOPWORDS

class CountExplainer(ExplainerInterface):
    """
    Explainer based on counted tokens.
    """

    def initialize(self, options):
        """
        Initializes reader with options in dictionary.

        Options:
        'max_results': Number of max results to be retruned by get_token_dict
        """
        self.max_results = options['max_results']
        print('CountExplainer max_results:', self.max_results)

    def get_token_dict(self, item_ids_a, item_ids_b, reader):
        """
        Compares items of distribution A with items of distribution B.
        Returns a dictionary of words and scores for tokens.
        """

        # Collect texts
        texts_a = []
        for item_id in item_ids_a:
            texts_a.append(reader.get_text(item_id))
        texts_b = []
        for item_id in item_ids_b:
            texts_b.append(reader.get_text(item_id))

        # Get tokens from texts
        tokens_a = self.get_tokens(texts_a)
        tokens_b = self.get_tokens(texts_b)

        if(False):
            # Remove tokens which occur often in both distributions
            tokens = self.remove_tokens(tokens_a, tokens_b)
        else:
            # Difference of relative counts
            tokens = self.relative_counts(tokens_a, tokens_b)

        # Sort by value
        sorted_tuples = sorted(tokens.items(), key=lambda item: item[1], reverse=True)
        sorted_dict = {k: v for k, v in sorted_tuples}

        # Return top values
        max_items = self.max_results
        token_weights = {}
        for item in sorted_dict.items():
            token_weights[item[0]] = item[1]
            max_items -= 1
            if(max_items == 0):
                break
        return token_weights

    # https://radimrehurek.com/gensim/utils.html#gensim.utils.simple_preprocess
    def get_tokens(self, texts, stopwords=STOPWORDS, min_len=2, max_len=15):
        tokens = []
        for text in texts:
            tokens += simple_preprocess(text, min_len=min_len, max_len=max_len)
        tokens = [w for w in tokens if w not in stopwords]
        return Counter(tokens)

    def remove_tokens(self, counter, counter_remove, factor=2):
        dict_ = {}
        for token in counter.keys():
            if(token in counter_remove):
                if(counter[token] >= counter_remove[token] * factor):
                    dict_[token] = counter[token]
        return Counter(dict_)

    def relative_counts(self, counter_a, counter_b):
        # Counter A to relative
        dic = {}
        for key in counter_a.keys():
            dic[key] = counter_a[key] / len(counter_a)
        a = Counter(dic)
        # Counter B to relative
        dic = {}
        for key in counter_b.keys():
            dic[key] = counter_b[key] / len(counter_b)
        b = Counter(dic)
        # Difference
        dic = {}
        for token in set(counter_a.keys()).union(set(counter_b.keys())):
            dic[token] = b[token] - a[token]
        return Counter(dic)


from src.Models.BaseModels import ModelBase

class SECRD(ModelBase):
    def __init__(self, a, b, gamma1, gamma2, mu):
        self.gamma1 = gamma1
        self.gamma2 = gamma2
        self.mu = mu
        self.a = a
        self.b = b

    def equation(self, S, I, C, M, RD, RI, t):
        # S susceptibles
        # I Infectadxs que no estan en cuarentena
        # C Infectadxs Detectadxs
        # M Muertxs
        # RD Recuperadxs detectadxs
        # RI Recuperadxs bo detectadxs

        # if t < 28:
        #     R = R0
        # if t >= 28:
        #     R = k * R0
        #     if t >= 40:
        #         R = R0
        # b = R / Tinc

        dS = -self.b * S * I
        dI = self.b * S * I - (self.a + self.gamma2) * I
        dC = self.a * I - self.mu * C - self.gamma1 * C
        dM = self.mu * C
        dRD = self.gamma1 * C
        dRI = self.gamma2 * I

        return dS, dI, dC, dM, dRD, dRI


from cubicweb_frarchives_edition.hooks import files_query_from_content
from rql import RQLSyntaxError

def update_editorials(cnx):
    """
    update content field of editoral etypes
    """
    etypes = (
        "Card",
        "NewsContent",
        "Map",
        "Section",
        "CommemorationItem",
        "CommemoCollection",
        "ExternRef",
        "BaseContent",
        "Map",
    )
    query = "Any X WHERE X is IN (%(etypes)s)"
    for entity in cnx.execute(query % {"etypes": ", ".join(etypes)}).entities():
        already_linked = {e.eid for e in entity.referenced_files}
        uischema = entity.cw_adapt_to("IJsonFormEditable").ui_schema()
        files = set()
        for attr, descr in uischema.items():
            if descr.get("ui:widget") == "wysiwygEditor":
                value = getattr(entity, attr)
                if not value or not value.strip():
                    continue
                queries = files_query_from_content(value)
                if not queries:
                    continue
                query = " UNION ".join("(%s)" % q for q in queries)
                try:
                    files |= {eid for eid, in cnx.execute(query)}
                except RQLSyntaxError:
                    print('fail to execute query "%r"', query)
        if not already_linked and not files:
            continue
        to_remove = already_linked - files
        if to_remove:
            print("TO REMOVE", entity, to_remove)
            cnx.execute(
                "DELETE X referenced_files Y WHERE X eid %(e)s, Y eid IN ({})".format(
                    ",".join(str(e) for e in to_remove)
                ),
                {"e": entity.eid},
            )
        to_add = files - already_linked
        if to_add:
            print("TO ADD", entity, to_add)
            cnx.execute(
                "SET X referenced_files Y WHERE X eid %(e)s, Y eid IN ({})".format(
                    ",".join(str(e) for e in to_add)
                ),
                {"e": entity.eid},
            )

update_editorials(cnx)  # noqa


# (c) 2012, Jan-Piet Mens <jpmens(at)gmail.com>
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

DOCUMENTATION = """
    lookup: redis_kv
    author: Jan-Piet Mens <jpmens(at)gmail.com>
    version_added: "0.9"
    short_description: fetch data from Redis
    deprecated:
        why: This lookup uses options intermingled with terms which blurs the interface between settings and data
        version: '2.9'
        alternative: new 'redis' lookup
    description:
      - this lookup returns a list of items given to it, if any of the top level items is also a list it will flatten it, but it will not recurse
    requirements:
      - redis (python library https://github.com/andymccurdy/redis-py/)
    options:
      _terms:
        description: Two element comma separated strings composed of url of the Redis server and key to query
        options:
          _url:
            description: location of redis host in url format
            default: 'redis://localhost:6379'
          _key:
            description: key to query
            required: True
"""

EXAMPLES = """
- name: query redis for somekey
  debug: msg="{{ lookup('redis_kv', 'redis://localhost:6379,somekey') }} is value in Redis for somekey"
"""

RETURN = """
_raw:
  description: values stored in Redis
"""
import os
import re

HAVE_REDIS = False
try:
    import redis
    HAVE_REDIS = True
except ImportError:
    pass

from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase

# ==============================================================
# REDISGET: Obtain value from a GET on a Redis key. Terms
# expected: 0 = URL, 1 = Key
# URL may be empty, in which case redis://localhost:6379 assumed
# --------------------------------------------------------------
class LookupModule(LookupBase):

    def run(self, terms, variables, **kwargs):

        if not HAVE_REDIS:
            raise AnsibleError("Can't LOOKUP(redis_kv): module redis is not installed")

        ret = []
        for term in terms:
            (url, key) = term.split(',')
            if url == "":
                url = 'redis://localhost:6379'

            # urlsplit on Python 2.6.1 is broken. Hmm. Probably also the reason
            # Redis' from_url() doesn't work here.

            p = '(?P<scheme>[^:]+)://?(?P<host>[^:/ ]+).?(?P<port>[0-9]*).*'

            try:
                m = re.search(p, url)
                host = m.group('host')
                port = int(m.group('port'))
            except AttributeError:
                raise AnsibleError("Bad URI in redis lookup")

            try:
                conn = redis.Redis(host=host, port=port)
                res = conn.get(key)
                if res is None:
                    res = ""
                ret.append(res)
            except:
                ret.append("")  # connection failed or key not found
        return ret


"""
Задание №5

Напишите программу, которая выводит на экран числа от 1 до 100.

При этом вместо чисел, кратных трём, программа должна выводить
слово "Fizz".

Вместо чисел, кратных пяти - слово "Buzz".

Если число кратно и 3, и 5, программа должна выводить
слово "FizzBuzz".

*Превратите решение в генераторное выражение.
"""

# mav
def func(num_):
    if num_ % 3 == 0 and num_ % 5 == 0:
        yield 'FizzBuzz'
    elif num_ % 3 == 0:
        yield 'Fizz'
    elif num_ % 5 == 0:
        yield 'Buzz'
    else:
        yield num_

# result = (num for num in range(0, 100 + 1, 2) if num // 10 + num % 10 != 8)
for num in range(1, 100 + 1):
    print(*func(num), end=' ')
# print()

print('*' * 80)

# Khalil Batkaev
result = ('FizzBuzz' if num % 3 == 0 and num % 5 == 0
          else 'Fizz' if num % 3 == 0
          else 'Buzz' if num % 5 == 0
          else num
          for num in range(1, 100 + 1))
print(*result)

print('*' * 80)

# Dmitry Voytic - вариант хуже, т.к. создаётся ГЕНЕРАТОР ИЗ ГЕНЕРАТОРА !
nums = (i for i in range(1, 100+1))
res = ('FizzBuzz' if j % 3 == 0 and j % 5 == 0 else
       'Fizz' if j % 3 == 0 else
       'Buzz' if j % 5 == 0 else
       j for j in nums)
print(*res)


import itertools
import json
import os
from os import listdir
from os import path

import cairo
import drawSvg as draw
import numpy as np
import svg_stack as ss
from numpy import random
import svgutils as su

from vectorizer.png2svg import parse_svg_paths, vectorize
from .colors import Palette

# Load All elements
RESOURCES_DIRECTORY = os.environ.get("RESOURCES_DIR",
                                     r"resources")
elements_directory_name = os.environ.get("ELEMENTS_DIR", "")
fonts_file_name = os.environ.get("FONTS_TXT_FILE", "installed_fonts.txt")
palettes_file_name = os.environ.get("PALETTES_JSON_FILE", "palettes.json")
gradients_file_name = os.environ.get("GRADIENTS_JSON_FILE", "gradients.json")
with open(path.join(RESOURCES_DIRECTORY, fonts_file_name)) as fonts_file:
    FONTS = tuple(filter(lambda x: x.strip() != '', fonts_file.read().split('\n')))
with open(path.join(RESOURCES_DIRECTORY, palettes_file_name)) as palettes_file:
    PALETTES = json.load(palettes_file)
with open(path.join(RESOURCES_DIRECTORY, gradients_file_name)) as gradients_file:
    GRADIENTS = json.load(gradients_file)["gradients"]
elements_path = path.join(RESOURCES_DIRECTORY, elements_directory_name)
ELEMENTS = [f for f in listdir(elements_path) if path.isfile(path.join(elements_path, f))]

class LogoData:
    def __init__(self, **kwargs):
        self.seed = kwargs.get("seed", 0)
        self.text_color = kwargs.get("text_color", (0, 0, 0))
        self.text_font = kwargs.get("text_font", "Dela Gothic One")

    def jsonify(self):
        return {"text_font": self.text_font,
                "text_color": self.text_color,
                "seed": self.seed}

    def __call__(self, *args, **kwargs):
        self.jsonify()

class Style(draw.DrawingDef):
    TAG_NAME = "style"

    def __init__(self, import_statement, **kwargs):
        self.import_statement = import_statement
        super().__init__(**kwargs, type="text/css")

    def writeSvgElement(self, idGen, isDuplicate, outputFile, dryRun, forceDup=False):
        outputFile.write(f'<style type="text/css">{self.import_statement}</style>')

class SVG(draw.DrawingDef):
    TAG_NAME = "svg"

    def __init__(self, svg, **kwargs):
        self.svg = svg
        super().__init__(**kwargs)

    def writeSvgElement(self, idGen, isDuplicate, outputFile, dryRun, forceDup=False):
        outputFile.write(self.svg)

class ImportStatement(draw.DrawingBasicElement):
    pass

def get_recolored_element(element_name, color):
    with open(element_name) as f:
        data = f.read()
        data.replace("black", color)
        return None

# deprecated def
def draw_logo_legacy(palette: Palette,
                     file_name: str = 'example.png',
                     add_svg_elements: bool = False,
                     rects_max_n: int = 2,
                     poly_max_n: int = 4,
                     color_style: str = 'smooth',
                     sharpen: float = 0.5,
                     image_size: tuple = (512, 512)):
    # Create svg surface
    with cairo.SVGSurface(file_name, image_size[0], image_size[1]) as surface:

        ctx = cairo.Context(surface)
        ctx.scale(image_size[0], image_size[1])

        """ctx.rectangle(0, 0, 1, 1)
        c = palette.next()
        bg = c
        ctx.set_source_rgb(*c)
        ctx.fill()"""

        r = [cairo.LINE_JOIN_MITER, cairo.LINE_JOIN_BEVEL, cairo.LINE_JOIN_ROUND]
        ctx.set_line_join(random.choice(r))

        for _ in range(rects_max_n):
            x, y = random.random(), random.random()
            ctx.rectangle(x, y, random.random(), random.random())
            c = palette.next()
            ctx.set_source_rgb(*c)
            ctx.fill()

        #
        for _ in range(random.randint(poly_max_n // 2, poly_max_n)):
            points = [(random.random(), random.random()) for _ in range(random.randint(3, 5))]

            if random.random() < 0.5:
                ctx.curve_to(*np.array(points[:3]).flatten())
            else:
                ctx.move_to(*points[0])
                for point in points[1:]:
                    ctx.line_to(*point)

            ctx.close_path()
            if random.random() < 0.7:
                ctx.set_source_rgb(*palette.next())
            else:
                gr = GRADIENTS[random.randint(0, len(GRADIENTS))]
                lg1 = cairo.LinearGradient(*points[0], *points[-1])
                lg1.add_color_stop_rgb(0, *map(lambda x: x / 255, gr[0]))
                lg1.add_color_stop_rgb(0.5, *map(lambda x: x / 255, gr[1]))
                ctx.set_source(lg1)

            ctx.set_line_width(random.randint(1, 10) / 100)
            if random.random() < 0.6:
                ctx.stroke()
            else:
                ctx.fill()

        Context = cairo.Context(surface)
        Context.set_font_size(100)
        Context.select_font_face(random.choice(FONTS), cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
        text_x, text_y = random.randint(0, image_size[0] // 4), random.randint(0 + 200, image_size[1] - 200)
        Context.move_to(text_x, text_y)

        Context.set_source_rgb(0, 0, 0)
        Context.text_path("NTI")

        svg = vectorize(public_id='yd0cnq0dxzgjscg1afct')
        path = parse_svg_paths(svg)[-1][9:-3]

        Context.append_path(cairo.Path(path))
        Context.stroke()

        # Fill text
        if random.random() > 0.7:
            gr = GRADIENTS[random.randint(0, len(GRADIENTS))]
            lg1 = cairo.LinearGradient(text_x, text_y, 500, 500)
            lg1.add_color_stop_rgb(0, *map(lambda x: x / 255, gr[0]))
            lg1.add_color_stop_rgb(0.5, *map(lambda x: x / 255, gr[1]))
            Context.set_source(lg1)
        else:
            Context.set_source_rgb(0, 0, 0)

        if random.random() < 0.6:
            Context.fill()
        else:
            Context.stroke()
    if add_svg_elements:
        doc = ss.Document()

        layout1 = ss.HBoxLayout()
        layout1.setSpacing(-image_size[0])
        layout1.addSVG(file_name, alignment=ss.AlignHCenter | ss.AlignVCenter)
        for _ in range(1):
            el = random.choice(ELEMENTS)
            layout1.addSVG(el, alignment=ss.AlignHCenter | ss.AlignVCenter)
        doc.setLayout(layout1)
        doc.save(file_name)

def draw_svg_design(file_name: str = 'example.png',
                    text="Template",
                    add_svg_elements: bool = False,
                    rects_max_n: int = 2,
                    poly_max_n: int = 2,
                    circles_max_n: int = 2,
                    poly_max_n_points: int = 4,
                    color_style: str = 'epic',
                    font_color: tuple = (0, 0, 0),
                    sharpen: float = 0.5,
                    font_family: str or None = None,
                    image_size: tuple = (512, 512),
                    margin: tuple = (50, 50),
                    seed=None) -> tuple:
    if seed is not None:
        random.seed(seed)
    if font_family is None:
        font_family = random.choice(FONTS)

    p = Palette(color_style)
    d = draw.Drawing(image_size[0], image_size[1], displayInline=False)

    import_statement = Style('@import url(http://fonts.googleapis.com/css?family=Dela+Gothic+One);')
    d.append(import_statement)

    poly_max_n += int(poly_max_n * sharpen)

    # Drawing polygons
    for _ in range(0, poly_max_n):
        # Generating points for polygon
        points_ = [(random.randint(0 + margin[0], image_size[0] - margin[0]),
                    random.randint(0 + margin[1], image_size[1] - margin[1]))
                   for _ in range(random.randint(3, poly_max_n_points))]

        # Concatenating all coordinates
        points = list(itertools.chain(*points_))

        poly_params = {}
        if random.random() < 0.6:
            poly_params["fill"] = p.next_rgb()
        else:
            poly_params["stroke"] = p.next_rgb()
            poly_params["stroke_width"] = random.randint(3, 10)
            poly_params["fill"] = "rgba(0, 0, 0, 0.001)"
        if sharpen < 0:
            poly_params['stroke-linejoin'] = "round"
        elif sharpen > 0:
            poly_params['stroke-linejoin'] = "miter"
        else:
            poly_params['stroke-linejoin'] = "round" if random.random() > 0.5 else "miter"
        # Drawing
        d.append(draw.Lines(*points,
                            close=True,
                            **poly_params))

    circles_max_n += int(circles_max_n * -sharpen)

    for _ in range(circles_max_n):

        circle_params = {}
        if random.random() < 0.6:
            circle_params["fill"] = p.next_rgb()
        else:
            circle_params["stroke"] = p.next_rgb()
            circle_params["stroke_width"] = random.randint(3, 6)
            circle_params["fill"] = "rgba(0, 0, 0, 0.001)"

        s = random.randint(30, 100)
        cx, cy = random.randint(margin[0], image_size[0] - s // 2), random.randint(margin[1], image_size[1] - s // 2)
        circle = draw.Circle(cx, cy, s, **circle_params)
        d.append(circle)

    # Draw text
    r, g, b = font_color
    font_size = random.randint(70, 150)
    x, y = random.randint(margin[0], image_size[0] // 2), random.randint(margin[1] * 2, image_size[1] - margin[1] * 2)
    d.append(draw.Text(text, font_size, x, y, fill=f'rgb({r}, {g}, {b})', font_family=font_family))

    """icon_d = draw.Drawing(image_size[0], image_size[1], displayInline=False)
    svg_icon = vectorize(public_id="sgtb7y5h12lg3xwdgyct")
    path = parse_svg_paths(svg_icon)[-1][9:-3]
    icon_d.append(draw.Path(path, stroke="black", fill=p.next_rgb(), transform='rotate(180 0 0)'))
    d.append(SVG(icon_d.asSvg()))"""

    ret_params = {'font_color': font_color,
                  'font_family': font_family,
                  'seed': seed,
                  'circles_n': circles_max_n,
                  'poly_n': poly_max_n,
                  'sharpen': sharpen,
                  'font_size': font_size}

    """ # Draw a rectangle

    # Draw a circle
    d.append(draw.Circle(-40, -10, 30,
                         fill='red', stroke_width=2, stroke='black'))

    # Draw an arbitrary path (a triangle in this case)
    p = draw.Path(stroke_width=2, stroke='lime',
                  fill='black', fill_opacity=0.2)
    p.M(-10, 20)  # Start path at point (-10, 20)
    p.C(30, -10, 30, 50, 70, 20)  # Draw a curve to (70, 20)
    d.append(p)

    d.append(draw.Text('Path text', 8, path=p, text_anchor='start', valign='middle'))
    d.append(draw.Text(['Multi-line', 'text'], 8, path=p, text_anchor='end'))

    # Draw multiple circular arcs
    d.append(draw.ArcLine(60, -20, 20, 60, 270,
                          stroke='red', stroke_width=5, fill='red', fill_opacity=0.2))
    d.append(draw.Arc(60, -20, 20, 60, 270, cw=False,
                      stroke='green', stroke_width=3, fill='none'))
    d.append(draw.Arc(60, -20, 20, 270, 60, cw=True,
                      stroke='blue', stroke_width=1, fill='black', fill_opacity=0.3))

    # Draw arrows
    arrow = draw.Marker(-0.1, -0.5, 0.9, 0.5, scale=4, orient='auto')
    arrow.append(draw.Lines(-0.1, -0.5, -0.1, 0.5, 0.9, 0, fill='red', close=True))
    p = draw.Path(stroke='red', stroke_width=2, fill='none',
                  marker_end=arrow)  # Add an arrow to the end of a path
    p.M(20, -40).L(20, -27).L(0, -20)  # Chain multiple path operations
    d.append(p)
    d.append(draw.Line(30, -20, 0, -10,
                       stroke='red', stroke_width=2, fill='none',
                       marker_end=arrow))  # Add an arrow to the end of a line

    d.setPixelScale(2)  # Set number of pixels per geometry unit
    # d.setRenderSize(400,200)  # Alternative to setPixelScale"""
    return ret_params, d.asSvg()

def generate_variations(p, n=10):
    for i in range(n):
        draw_logo_legacy(p, file_name=f'images/{i}.svg', rects_max_n=3, poly_max_n=4)
        p.change_palette()


from flask import Flask,request
import json
from enum import Enum

app = Flask(__name__)

@app.route('/app',methods=['POST'])
def handler():
    if request.data:
        data = request.get_json()
        print(data)

        return calculate(data)
    return app.response_class(
        status=400,
    )

def calculate(data):
    try:
        x = data['x']
        y = data['y']
        operation_type = data['operation_type'].lower()
        operator = Operation[operation_type].value
        print(type(Operation[operation_type]))
        if (operator =="*"):
            result = x * y
        elif (operator == "+"):
            result = x + y
        else:
            result = x - y
            z = Operation.subtraction
        response_data = json.dumps(
        {"slackUsername": "Wamuyu",
        "result": result,
        "operation_type": data['operation_type']
        # "operation_type": Operation[operation_type].value
        }
    )
    except KeyError:

        return app.response_class(
            status=400,
            response={
                "operation_type[multiplication or addition or subtraction], x and y are required"
            }
        )
    else:

        response = app.response_class(
        response = response_data,
        status = 200,
        mimetype='application/json'
        )
        return response

class Operation(str,Enum):
    multiplication = "*"
    addition = "+"
    subtraction = "-"

if __name__=='__main__':
    app.run()


from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, LSTM, Conv1D, Flatten
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical
import gym
import numpy as np
import requests
from bs4 import BeautifulSoup
import nltk
import string
from sklearn.model_selection import train_test_split
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords

nltk.download('punkt')
nltk.download('wordnet')
nltk.download('stopwords')

lemmatizer = WordNetLemmatizer()
stopwords = set(stopwords.words('english'))

def create_model(input_shape, num_classes):
    """
    Creates a keras Model with Conv1D, LSTM, and Dense layers.
    """
    try:
        input_layer = Input(shape=(input_shape,))
        conv_layer = Conv1D(filters=32, kernel_size=5, activation='relu')(input_layer)
        flat_layer = Flatten()(conv_layer)
        rnn_layer = LSTM(32)(flat_layer)
        output_layer = Dense(num_classes, activation='softmax')(rnn_layer)
        model = Model(inputs=input_layer, outputs=output_layer)
        model.compile(loss='categorical_crossentropy', optimizer=Adam(), metrics=['accuracy'])
        return model
    except Exception as e:
        print(f"Error creating model: {e}")
        return None

def q_learning_with_table(env, num_episodes=50000, learning_rate=0.1, discount_factor=0.9):
    """
    Performs Q-learning on the provided Gym environment.
    """
    try:
        Q_table = np.zeros([env.observation_space.n, env.action_space.n])
        for i_episode in range(num_episodes):
            state = env.reset()
            for t in range(100):
                action = np.argmax(Q_table[state])
                next_state, reward, done, _ = env.step(action)
                old_value = Q_table[state, action]
                next_max = np.max(Q_table[next_state])
                new_value = (1 - learning_rate) * old_value + learning_rate * (reward + discount_factor * next_max)
                Q_table[state, action] = new_value
                state = next_state
                if done:
                    break
        return Q_table
    except Exception as e:
        print(f"Error during Q-learning: {e}")
        return None

def scrape_website(url):
    """
    Scrapes the provided website URL using BeautifulSoup.
    """
    try:
        page = requests.get(url)
        soup = BeautifulSoup(page.content, "html.parser")
        return soup.get_text()
    except Exception as e:
        print(f"Error scraping website: {e}")
        return None

def preprocess_text(text):
    """
    Preprocesses the provided text using NLTK.
    """
    try:
        words = word_tokenize(text)
        words = [word.lower() for word in words if word not in stopwords and word not in string.punctuation]
        words = [lemmatizer.lemmatize(word) for word in words]
        return words
    except Exception as e:
        print(f"Error preprocessing text: {e}")
        return None

if __name__ == "__main__":
    url = "https://www.nist.gov/topics/cybersecurity"
    scraped_text = scrape_website(url)
    if scraped_text is not None:
        words = preprocess_text(scraped_text)
        if words is not None:
            print(words)

    # Assume that dialogues is a list of cybersecurity dialogues and labels is their corresponding labels
    dialogues = words  # Replace this with your list
    labels = []  # Replace this with your labels

    # Convert text to sequences for training
    tokenizer = Tokenizer()
    tokenizer.fit_on_texts(dialogues)
    sequences = tokenizer.texts_to_sequences(dialogues)
    X = pad_sequences(sequences)
    y = to_categorical(labels)

    # Split the data into training and testing set
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

    # Create the model
    model = create_model((X_train.shape[1],), y_train.shape[1])
    if model is not None:
        print(model.summary())
        # Train the model
        model.fit(X_train, y_train, epochs=5, batch_size=32, validation_data=(X_test, y_test))

        # Save the model
        model.save("chatbot_model.h5")

    # Q-learning
    env = gym.make('FrozenLake-v0')
    q_table = q_learning_with_table(env, num_episodes=5000, learning_rate=0.1, discount_factor=0.9)
    if q_table is not None:
        print(q_table)


class Solution:
    def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
        answer = 0
        dic = dict()
        for i in nums1:
            for j in nums2:
                if dic.get(i+j) is None:
                    dic[i+j] = 1
                else:
                    dic[i+j] = dic[i+j] + 1

        for k in nums3:
            for l in nums4:
                if dic.get(-(k+l)) is not None:
                    answer = answer+dic[-(k+l)]
        return answer


#!/usr/bin/env python3

import contextlib
import json

from pathlib import Path
from typing import Dict
from AoC.util import show

CWD = Path(__file__).parent

def read_input(filename: str="input.txt") -> Dict:
    input_file = CWD.joinpath(filename)
    with open(input_file, "r") as reader:
        return json.load(reader)

def json_sum(data, ignore_red=False) -> int:
    if isinstance(data, str):
        return 0
    elif isinstance(data, list):
        return sum([v if isinstance(v, int) else json_sum(v, ignore_red) for v in data])
    else: # dict
        if ignore_red and "red" in data.values():
            return 0
        return sum([v if isinstance(v, int) else json_sum(v, ignore_red) for v in data.values()])

@show
def first(data: Dict) -> int:
    return json_sum(data)

@show
def second(data: Dict) -> int:
    return json_sum(data, True)

def test_example() -> None:
    with contextlib.redirect_stdout(None):
        assert first(json.loads('[1,2,3]')) == first(json.loads('{"a":2,"b":4}')) == 6
        assert first(json.loads('[[[3]]]')) == first(json.loads('{"a":{"b":4},"c":-1}')) == 3
        assert first(json.loads('{"a":[-1,1]}')) == first(json.loads('[-1,{"a":1}]')) == 0
        assert first(json.loads('[]')) == first(json.loads('{}')) == 0
        assert second(json.loads('[1,2,3]')) == 6
        assert second(json.loads('[1,{"c":"red","b":2},3]')) == 4
        assert second(json.loads('{"d":"red","e":[1,2,3,4],"f":5}')) == 0
        assert second(json.loads('[1,"red",5]')) == 6

test_example()
data = read_input()
first(data) # 119433
second(data) # 68466


"""
Напишите программу которая будет спрашивать пользователя ввод имени пока пользователь не введет off.
Программа должна используя lambda-функцию добавлять к каждому имени надпись "гений".
"""
while True:
    # lambda_name = lambda x: x + "гений"
    name = input("Введите Ваше имя: / Или off для завершения программы. \n")
    if name == "off":
        break
    else:
        new_name = lambda x: x + "гений"
        print(new_name(name))


import mydefs
import os
import pyocr
from multiprocessing import Process

dir = '2022-12-30_15-51-09'

if(__name__ == '__main__'):
    file_count = mydefs.countFiles(dir)
    cpus = os.cpu_count()
    block_size = int(file_count / cpus)
    start = 0
    end = block_size
    process_list = []

    for i in range(cpus-1):
        print("process " + str(i) + " launched")
        process = Process(target=mydefs.slaveOCR, args=(dir, start, end))
        process.start()
        process_list.append(process)
        start = end + 1
        end = end + block_size

    print("process " + str(cpus-1) + " launched")
    process = Process(target=mydefs.slaveOCR, args=(dir, start, file_count))
    process.start()
    process_list.append(process)

    for process in process_list:
        process.join()


import json
import uuid
import os, shutil
from uuid import uuid4
from flask import current_app, g, Blueprint, make_response, request, jsonify, send_file
from karmalegoweb.src.negative_mining.negativeConnector import run_cpp_program
from karmalegoweb.src.preprocessing.negative_proccessing import negative_preprocessing

from karmalegoweb.src.preprocessing.results import preprocessins_results
from karmalegoweb.src.preprocessing.preproccessing import preprocessing

from karmalegoweb.src.views.error_handlers import validate_args
from karmalegoweb.src.views.auth import login_required
from karmalegoweb.src.db import get_db
from karmalegoweb.src import models, tasks, utils

from karmalegoweb.KarmaLego_Framework import RunKarmaLego

bp = Blueprint("data_mining", __name__, "/")

@bp.route("/addTIM", methods=["POST"])
@login_required
@validate_args(
    [
        "DiscretizationId",
        "Epsilon",
        "Max Gap",
        "min_ver_support",
        "num_relations",
        "max Tirp Length",
        "index_same",
        "negative_mining",
        "maximum_negatives",
		"ofo",
		"as",
		"bc",
    ]
)
def add_tim():
    """
    This function handles a new KarmaLego run attempt.
    :param current_user: The user which is currently logged in.
    param - epsilon - the value of epsilon, int
    param - max gap- int, the max_gap between the intervals for creating the index
    :param min_ver_support: float, the minimum vertical support value
    :param num_relations: int, number of relations
    :param index_same: Boolean, index same symbols or not
    :return:
    if it was a sussess run it returns status 200
    if there is already a karma lego like the user wants now it returns status 400
    """
    # makes all the validations e making any write to the database
    data = request.form

    # if check_if_not_int_but_0(data['Epsilon']):
    #     return jsonify({'message': 'you did not give me an integer but a float'}), 404
    # if check_if_not_int(data['max Tirp Length']) or check_if_not_int(
    #         data['Max Gap']) or check_if_not_int(data['min_ver_support']):
    #     return jsonify({'message': 'you did not give me an integer but a float or a number less then 1'}), 404
    # if int(data['min_ver_support']) > 100:
    #     return jsonify({'message': 'minimum vertical support cant be greater then 100'}), 404
    # discretization_id = str(data['DiscretizationId'])
    # if 'Epsilon' not in data:
    #     epsilon = int(0.0000)
    # else:
    #     epsilon = int(data['Epsilon'])
    # saves all the parameters that the user passed me
    discretization_id = data["DiscretizationId"]
    epsilon = int(data["Epsilon"])
    max_gap = int(data["Max Gap"])
    vertical_support = int(data["min_ver_support"]) / 100
    num_relations = int(data["num_relations"])
    max_tirp_length = int(data["max Tirp Length"])
    index_same = str(data["index_same"])
    negative_mining = str(data["negative_mining"])
    maximum_negatives = int(data["maximum_negatives"])
    ofo = str(data["ofo"])
    as1 = str(data["as"])
    bc = str(data["bc"])
    class_name = str(data["class_name"])
    second_class_name = str(data["second_class_name"])
    timestamp = str(data["timestamp"])
    comments = str(data["comments"])
    to_visualize = data["to_visualize"]

    if negative_mining == "true":
        ofo = (ofo == "true")
        as1 = (as1 == "true")
        bc = (bc == "true")

        models.get_db().create_all()

        disc = models.discretization.query.filter_by(id=discretization_id).first()
        email = g.user.Email
        dataset_name = get_dataset_name(disc)
        KL_id = str(uuid.uuid4())
        create_directory(dataset_name, discretization_id, KL_id)
        directory_path = dataset_name + "\\" + discretization_id

        print("directory_path" + directory_path)
        # saves the data to the database
        KL = models.negative_karma_lego(
            discretization=disc,
            id=KL_id,
            max_gap=max_gap,
            min_ver_support=vertical_support,
            maximum_negatives=maximum_negatives,
            ofo = ofo,
            a_s = as1,
            bc=bc
        )
        status = models.negative_karmalego_status(karmalego_id=KL_id)
        db = get_db()
        db.session.add(KL)
        db.session.add(status)
        db.session.commit()

        #run negative sequential mining algo
        command = __create_negative_mining_command(vertical_support, max_gap, maximum_negatives, ofo, as1, bc, dataset_name, discretization_id, KL_id)
        run_algo = run_cpp_program(command)
        if run_algo == 0:
            _fix_outputfile(dataset_name, discretization_id, KL_id)
            status.finished = True
            status.success = True
            db.session.commit()
        if run_algo == 1:
            status.finished = True
            status.success = False
            db.session.commit()
            return jsonify({"message": "A problem as occurred with karmalego, try different parameters"}), 500

        if to_visualize == "true":
                print("finished KL, starting Guy's preprocess")
                # call Guy's and Tali's preprocessing
                process = negative_preprocessing(KL_id)
                result, _vis_id = process.start_negative()
                if result != preprocessins_results.GOOD:
                    tasks.send_email(
                        message=f"Subject: problem with preprocessing", receiver_email=email
                    )
                    return jsonify({"message": "A problem as occurred with preprocessing"}), 500

                print("finished Guy's and Tali's preprocess")

        return jsonify({"message": "karmalego created!", "KL_id": KL_id}), 200

    if negative_mining == "false":
        if index_same == "true":
            index_same = True
        else:
            index_same = False
        disc = models.discretization.query.filter_by(id=discretization_id).first()
        email = g.user.Email
        # checking if the current discretization already exists
        if check_exists(
            disc, epsilon, max_gap, vertical_support, num_relations, index_same, max_tirp_length
        ):
            return (
                jsonify(
                    {
                        "message": "Time interval mining file for this dataset with the same parameters already exist"
                    }
                ),
                409,
            )
        dataset_name = get_dataset_name(disc)
        # dataset_name ='Gradient'
        KL_id = str(uuid.uuid4())
        create_directory(dataset_name, discretization_id, KL_id)
        directory_path = dataset_name + "\\" + discretization_id
        # saves the data to the dataset
        KL = models.karma_lego(
            discretization=disc,
            epsilon=epsilon,
            id=KL_id,
            index_same=index_same,
            max_gap=max_gap,
            max_tirp_length=max_tirp_length,
            min_ver_support=vertical_support,
            num_relations=num_relations,
        )
        status = models.karmalego_status(karmalego_id=KL_id)
        db = get_db()
        db.session.add(KL)
        db.session.add(status)
        db.session.commit()

        # after creating the directory, creating by karma lego 3 files: kl, kl0, kl1
        try:
            for filename in os.listdir(current_app.config["DATASETS_ROOT"] + "\\" + directory_path):
                if filename.endswith(".txt"):
                    path = current_app.config["DATASETS_ROOT"] + "\\" + directory_path + "\\" + filename

                    out_path = (
                        current_app.config["DATASETS_ROOT"]
                        + "\\"
                        + directory_path
                        + "\\"
                        + KL_id
                        + "\\"
                        + filename[:-4]  # Removes the .txt
                    )

                    os.mkdir(out_path)

                    # calling the actual karma lego algorithm
                    _lego_0, _karma_0 = RunKarmaLego.runKarmaLego(
                        time_intervals_path=path,
                        output_path=out_path,
                        processes_num=10,
                        calc_offsets=True,
                        entity_ids_num=2,
                        epsilon=epsilon,
                        incremental_output=True,
                        index_same=index_same,
                        label=0,
                        max_gap=max_gap,
                        max_tirp_length=max_tirp_length,
                        min_ver_support=vertical_support,
                        need_one_sized=True,
                        num_comma=2,
                        num_relations=num_relations,
                        print_params=True,
                        semicolon_end=True,
                        skip_followers=False,
                    )
                else:
                    continue
        except Exception as e:
            current_app.log_exception(e)
            status.finished = True
            status.success = False
            db.session.commit()

            tasks.send_email(message=f"Subject: problem with creating karmalego", receiver_email=email)

            return jsonify({"message": "A problem as occurred with karmalego"}), 500
        # checks if the creation of the file of the karma lego was successful and if not it deletes the record from the db
        if (
            (
                os.path.exists(
                    current_app.config["DATASETS_ROOT"]
                    + "/"
                    + directory_path
                    + "/"
                    + KL_id
                    + "/"
                    + "KL"
                )
            )
            or (
                os.path.exists(
                    current_app.config["DATASETS_ROOT"]
                    + "/"
                    + directory_path
                    + "/"
                    + KL_id
                    + "/"
                    + "KL-class-0.0"
                )
            )
            or (
                os.path.exists(
                    current_app.config["DATASETS_ROOT"]
                    + "/"
                    + directory_path
                    + "/"
                    + KL_id
                    + "/"
                    + "KL-class-1.0"
                )
            )
        ):
            status.finished = True
            status.success = True
            db.session.commit()
            tasks.send_email(message=f"Subject: karmalego successfully created", receiver_email=email)
            if to_visualize == "true":
                print("finished KL, starting Guy's preprocess")
                # call Guy's and Tali's preprocessing
                process = preprocessing(KL_id)
                result, _vis_id = process.start()
                if result != preprocessins_results.GOOD:
                    tasks.send_email(
                        message=f"Subject: problem with preprocessing", receiver_email=email
                    )
                    return jsonify({"message": "A problem as occurred with preprocessing"}), 500

                print("finished Guy's and Tali's preprocess")

            return jsonify({"message": "karmalego created!", "KL_id": KL_id}), 200
        else:
            status.finished = True
            status.success = False
            db.session.commit()

            tasks.send_email(message=f"Subject: problem with creating karmalego", receiver_email=email)

            return jsonify({"message": "A problem as occurred with karmalego"}), 500

@bp.route("/deleteKarmaLego", methods=["POST"])
@login_required
@validate_args(["karma_id", "disc_id", "datasetName"])
def deleteKarmaLego():
    karmalego = models.karma_lego.query.filter_by(id=request.form["karma_id"]).first()
    if karmalego is None:
        karmalego = models.negative_karma_lego.query.filter_by(id=request.form["karma_id"]).first()
    if karmalego is None:
        return "Could not found requested karmalego", 400
    path = os.path.join(
        current_app.config["DATASETS_ROOT"],
        request.form["datasetName"],
        request.form["disc_id"],
        request.form["karma_id"],
    )
    if os.path.exists(path):
        shutil.rmtree(path)

    karmalego_status = models.karmalego_status.query.filter_by(
        karmalego_id=request.form["karma_id"]
    ).first()
    negative_karmalego_status = models.negative_karmalego_status.query.filter_by(
        karmalego_id=request.form["karma_id"]
    ).first()
    visualizations = models.Visualization.query.filter_by(KL_id=request.form["karma_id"])
    neg_visualizations = models.Negative_Visualization.query.filter_by(KL_id=request.form["karma_id"])
    visualizations_paths = []
    for visualization in visualizations:
        visualization_path = os.path.join(
            current_app.config["DATASETS_ROOT"],
            request.form["datasetName"],
            "visualizations",
            visualization.id,
        )
        visualizations_paths.append(visualization_path)

    for visualization in neg_visualizations:
        visualization_path = os.path.join(
            current_app.config["DATASETS_ROOT"],
            request.form["datasetName"],
            "visualizations",
            visualization.id,
        )
        visualizations_paths.append(visualization_path)

    db = get_db()
    for visualization in visualizations:
        db.session.delete(visualization)
    for visual_path in visualizations_paths:
        if os.path.exists(visual_path):
            shutil.rmtree(visual_path)

    db.session.delete(karmalego)
    db.session.delete(karmalego_status)
    db.session.delete(negative_karmalego_status)
    db.session.commit()

    return "Deleted karmalego successfully"

@bp.route("/getTIM", methods=["POST"])
@login_required
def get_tim():
    """
    This function handles a request to download a zip of all the karma lego files.
    :return:
    200 (OK) if all files have been found, sends a zipped folder of all the KarmaLego framework's outputs.
    """
    data = request.form
    kl_id = data["kl_id"]
    karma = models.karma_lego.query.filter_by(id=kl_id).first()
    disc = karma.discretization.id
    dataset = karma.discretization.dataset.Name

    kl_path = os.path.join(current_app.config["DATASETS_ROOT"], dataset, disc, kl_id)

    kl_zip_name = "karma_lego.zip"

    files_to_send = ["KL.txt"]

    if os.path.exists(os.path.join(kl_path, "KL-class-0.0.txt")):
        files_to_send.append("KL-class-0.0.txt")

    if os.path.exists(os.path.join(kl_path, "KL-class-1.0.txt")):
        files_to_send.append("KL-class-1.0.txt")

    utils.create_disc_zip(kl_path, kl_zip_name, files_to_send)

    return send_file(os.path.join(kl_path, kl_zip_name))

@bp.route("/getNegativeTIM", methods=["POST"])
@login_required
def get_negative_tim():
    """
    This function handles a request to download a zip of all the karma lego files.
    :return:
    200 (OK) if all files have been found, sends a zipped folder of all the KarmaLego framework's outputs.
    """
    data = request.form
    kl_id = data["kl_id"]
    karma = models.negative_karma_lego.query.filter_by(id=kl_id).first()
    disc = karma.discretization.id
    dataset = karma.discretization.dataset.Name

    kl_path = os.path.join(current_app.config["DATASETS_ROOT"], dataset, disc,kl_id,  "negative_output.json")

    with open(kl_path, 'r') as f:
        data = json.load(f)

    data_str = json.dumps(data)
    response = make_response(data_str)
    response.headers['Content-Disposition'] = 'attachment; filename=negative_output.json'
    response.headers['Content-type'] = 'application/json'

    return response

def check_exists(
    disc, epsilon, max_gap, vertical_support, num_relations, index_same, max_tirp_length
):
    """
    This function checks if a KL run already exists in the DB
    param - epsilon - the value of epsilon, int
    param - max gap- int, the max_gap between the intervals for creating the index
    :param min_ver_support: float, the minimum vertical support value
    :param num_relations: int, number of relations
    :param index_same: Boolean, index same symbols or not
    :return:
    if there is already a kl with that caracteristics
    """
    exists = models.karma_lego.query.filter_by(
        discretization=disc,
        epsilon=epsilon,
        index_same=index_same,
        max_gap=max_gap,
        max_tirp_length=max_tirp_length,
        min_ver_support=vertical_support,
        num_relations=num_relations,
    ).first()
    if exists is None:
        return False
    return True

def get_dataset_name(disc):
    """
    This function returns the dataset name for a given discretization.
    :param disc: the id of the discretization
    :return:
    the name of the dataset related to the discretization
    """
    dataset = disc.dataset
    dataset_name = dataset.Name
    return dataset_name

def create_directory(dataset_name, discretization_id, kl_id):
    """
    This function creates a directory for a KarmaLego run inside its parent discretization folder.
    :param dataset_name: the name of the datset
    :param discretization_id: the id of the discretization
    :param kl_id: the id of the karma lego run
    :return:
    """
    path = (
        current_app.config["DATASETS_ROOT"]
        + "/"
        + dataset_name
        + "/"
        + discretization_id
        + "/"
        + kl_id
    )
    try:
        os.mkdir(path)
    except OSError as e:
        current_app.log_exception(e)
    else:
        current_app.logger.info("Successfully created the directory %s " % path)
    return path

def __create_negative_mining_command(vertical_support, max_gap, maximum_negatives, ofo, as1, bc, name, discretization_id, kl_id):
    path = (
        current_app.config["DATASETS_ROOT"]
        + "\\"
        + name
        + "\\"
        + discretization_id
    )

    options = [("ofo", ofo), ("as", as1), ("bc", bc)]

    command_parts = ["./NegativeRanges", "-i", path + "\\negative.ascii" , "-o", path + "\\"+ kl_id + "\\negative_output.json" , "-ms", str(vertical_support), "-mg", str(max_gap), "-mn", str(maximum_negatives)]
    command_parts += [f"-{option}" for option, value in options if value == True]

    return " ".join(command_parts)

def _fix_outputfile(name, discretization_id, KL_id):
    path = (
        current_app.config["DATASETS_ROOT"]
        + "\\"
        + name
        + "\\"
        + discretization_id
        + "\\"
        + KL_id
        + "\\negative_output.json"
    )

    with open(path, 'r') as file:
        lines = file.readlines()

    with open(path, 'w') as file:
        file.write('[')
        for i, line in enumerate(lines):
            if i == len(lines) - 1:
                file.write(line.rstrip('\n'))
            else:
                file.write(line.rstrip('\n') + ',\n')
        file.write(']')

@bp.route("/addSequentialTIM", methods=["POST"])
@login_required
@validate_args(
    [
        "Max Gap",
        "min_ver_support",
        "negative_mining",
        "maximum_negatives",
		"ofo",
		"as",
		"bc",
    ]
)
def add_sequential_tim():
    """
    This function handles a new KarmaLego run attempt.
    :param current_user: The user which is currently logged in.
    param - epsilon - the value of epsilon, int
    param - max gap- int, the max_gap between the intervals for creating the index
    :param min_ver_support: float, the minimum vertical support value
    :param num_relations: int, number of relations
    :param index_same: Boolean, index same symbols or not
    :return:
    if it was a sussess run it returns status 200
    if there is already a karma lego like the user wants now it returns status 400
    """
    # makes all the validations e making any write to the database
    data = request.form

    max_gap = int(data["Max Gap"])
    vertical_support = int(data["min_ver_support"]) / 100
    negative_mining = str(data["negative_mining"])
    maximum_negatives = int(data["maximum_negatives"])
    ofo = str(data["ofo"])
    as1 = str(data["as"])
    bc = str(data["bc"])
    to_visualize = data["to_visualize"]
    datasetName = data["datasetName"]

    ofo = (ofo == "true")
    as1 = (as1 == "true")
    bc = (bc == "true")

    models.get_db().create_all()
    exist = models.discretization.query.filter_by(dataset_Name=datasetName).first()
    if exist is None:
        disc = models.discretization(
                id=str(uuid4()),
                dataset=models.info_about_datasets.query.filter_by(Name=datasetName).first(),
                AbMethod="-",
                InterpolationGap=None,
                NumStates=0,
                PAA=None,
                GradientWindowSize=0,
                GradientFile_name=None,
                KnowledgeBasedFile_name=None,
            )
        run = models.discretization_status(discretization_id=disc.id)
        db = get_db()
        db.session.add(disc)
        db.session.add(run)
        db.session.commit()

    disc = models.discretization.query.filter_by(dataset_Name=datasetName).first()
    discretization_id = disc.id
    create_disc_directory(datasetName, discretization_id)

    original_path = (
        current_app.config["DATASETS_ROOT"]
        + "\\"
        + datasetName
    )

    path = (
        current_app.config["DATASETS_ROOT"]
        + "\\"
        + datasetName
        + "\\"
        + discretization_id
    )
    copy_file(original_path, path, datasetName)

    email = g.user.Email
    dataset_name = get_dataset_name(disc)
    KL_id = str(uuid.uuid4())
    create_directory(dataset_name, discretization_id, KL_id)

    # saves the data to the database
    KL = models.negative_karma_lego(
        discretization=disc,
        id=KL_id,
        max_gap=max_gap,
        min_ver_support=vertical_support,
        maximum_negatives=maximum_negatives,
        ofo = ofo,
        a_s = as1,
        bc=bc
    )
    status = models.negative_karmalego_status(karmalego_id=KL_id)
    db = get_db()
    db.session.add(KL)
    db.session.add(status)
    db.session.commit()

    #run negative sequential mining algo
    command = __create_negative_mining_command(vertical_support, max_gap, maximum_negatives, ofo, as1, bc, dataset_name, discretization_id, KL_id)
    run_algo = run_cpp_program(command)
    if run_algo == 0:
        _fix_outputfile(dataset_name, discretization_id, KL_id)
        status.finished = True
        status.success = True
        db.session.commit()
    if run_algo == 1:
        status.finished = True
        status.success = False
        db.session.commit()
        return jsonify({"message": "A problem as occurred with karmalego, try different parameters"}), 500

    if to_visualize == "true":
            print("finished KL, starting Guy's preprocess")
            # call Guy's and Tali's preprocessing
            process = negative_preprocessing(KL_id)
            result, _vis_id = process.start()
            if result != preprocessins_results.GOOD:
                tasks.send_email(
                    message=f"Subject: problem with preprocessing", receiver_email=email
                )
                return jsonify({"message": "A problem as occurred with preprocessing"}), 500

            print("finished Guy's and Tali's preprocess")

    return jsonify({"message": "karmalego created!", "KL_id": KL_id}), 200

def copy_file(source_dir, destination_dir, datasetName):
    file_name = datasetName + ".ascii"
    output_name = "negative.ascii"
    source_file = os.path.join(source_dir, file_name)
    destination_file = os.path.join(destination_dir, output_name)

    try:
        shutil.copy(source_file, destination_file)
        current_app.logger.info("File copied successfully!")
    except IOError as e:
        current_app.logger.info(f"Unable to copy file: {e}")

def create_disc_directory(dataset_name, discretization_id):
    """
    This function creates a directory for a KarmaLego run inside its parent discretization folder.
    :param dataset_name: the name of the datset
    :param discretization_id: the id of the discretization
    :param kl_id: the id of the karma lego run
    :return:
    """
    path = (
        current_app.config["DATASETS_ROOT"]
        + "/"
        + dataset_name
        + "/"
        + discretization_id
    )

    if os.path.exists(path):
        current_app.logger.info("Discretization folder already exist!")
        return path
    try:
        os.mkdir(path)
    except OSError as e:
        current_app.log_exception(e)
    else:
        current_app.logger.info("Successfully created the directory %s " % path)
    return path


import sys

if(sys.version_info[0] < 3):
    print("This program is written with Python 3.x")
    print("Run \'Python3 filename.py\' to propperly run the program")
    sys.exit(1)

else:
    import os
    import tkinter as tk
    from tkinter import *
    from zipfile import ZipFile
    from tkinter import messagebox, filedialog

    def CreateWidgets():
        selectlabel = Label(root, text = "SELECT FILE TO ZIP : ", bg = "steelblue", font=('', 10, 'bold'))
        selectlabel.grid(row = 0, column = 0, padx = 5, pady = 5)

        root.zipSelectEntry = Text(root, height = 4, width = 45, font = ('Arial', 10))
        root.zipSelectEntry.grid(row = 0, column = 1, columnspan = 2, padx = 5, pady = 5)

        zipBrowserButton = Button(root, text = "BROWSER", width = 20, height = 2, command = ZipBrowse)
        zipBrowserButton.grid(row = 0, column = 3, padx = 5, pady = 5)

        zipNamelabel = Label(root, text = "NAME OF ZIPPED FILE : ", bg = "steelblue", font = ('', 9, 'bold'))
        zipNamelabel.grid(row = 1, column = 0, padx = 5, pady = 5)

        root.zipNameEntry = Entry(root, width = 45, textvariable = zipName, font = ('Arial', 10))
        root.zipNameEntry.grid(row = 1, column = 1, columnspan = 2, padx = 5, pady = 5)

        zipButton = Button(root, text = "ZIP", width = 20, command = ZipFiles)
        zipButton.grid(row = 1, column = 3, padx = 5, pady = 5)

        unzipFilelabel = Label(root, text = "SELECT FILE TO UNZIP : ", bg = "steelblue", font=('', 10, 'bold'))
        unzipFilelabel.grid(row = 2, column = 0, padx = 5, pady = 5)

        root.unzipSelectEntry = Text(root, height = 4, width = 45, font = ('Arial', 10))
        root.unzipSelectEntry.grid(row = 2, column = 1, columnspan = 2, padx = 5, pady = 5)

        unZipBrowserButton = Button(root, text = "BROWSER", width = 20, height = 2, command = unZipBrowse)
        unZipBrowserButton.grid(row = 2, column = 3, padx = 5, pady = 5)

        unzipFileNamelabel = Label(root, text = "NAME FOR UNZIPPED FILE : ", bg = "steelblue", font = ('', 9, 'bold'))
        unzipFileNamelabel.grid(row = 3, column = 0, padx = 5, pady = 5)

        root.unzipNameEntry = Entry(root, width = 45, textvariable = foldername, font = ('Arial', 10))
        root.unzipNameEntry.grid(row = 3, column = 1, columnspan = 2, padx = 5, pady = 5)

        unZipButton = Button(root, text = "UnZIP", width = 20, command = unZipFiles)
        unZipButton.grid(row = 3, column = 3, padx = 5, pady = 5)

    def ZipBrowse():
        root.zipFileList = filedialog.askopenfilenames(initialdir = "~/Desktop/2019\ Projects/Python/Day-03/")
        root.zipSelectEntry.insert('1.0', "FOLOOWING FILES WILL BE ZIPPED\n")
        for files in root.zipFileList:
            root.files = os.path.basename(files)
            root.zipSelectEntry.insert('2.0',root.files+"\n")
        root.zipSelectEntry.config(state=DISABLED)
    def unZipBrowse():
        root.unzipFileList = filedialog.askopenfilenames(initialdir = "~/Desktop/2019\ Projects/Python/Day-03/")
        root.zipSelectEntry.insert('1.0', "FOLOOWING FILES WILL BE UNZIPPED\n")
        root.files = os.path.basename(root.unzipFileList)
        root.unzipSelectEntry.insert('2.0', root.files+"\n")
        root.unzipSelectEntry.config(state=DISABLED)

    def ZipFiles():
        with ZipFile(zipName.get(), 'w') as zip1:
            for files1 in root.zipFileList:
                zip1.write(files1, os.path.basename(files1))

        messagebox.showinfo("SUCCESS", "FILES ZIPPED SUCCESSFULLY")

    def unZipFiles():
        os.makedirs(foldername.get())
        with ZipFile(root.unzipFileList, 'r') as UNzip1:
            UNzip1.extractall(foldername.get())

        messagebox.showinfo("SUCCESS", "FILES UNZIPPED SUCCESSFULLY")

    if __name__ == '__main__':
        root = tk.Tk()

        root.title("ZipUnzip")
        root.config(background = "steelblue")

        zipName = StringVar()
        foldername = StringVar()

        CreateWidgets()

        root.mainloop()


import turtle
import random
chin = turtle.Turtle()
chin.shape("arrow")
colours = ["lime green", "aquamarine", "plum", "cyan", "dark orchid", "yellow", "red"]
d = 10
def black_hole():
    chin.color(random.choice(colours))
    chin.pensize(2)
    chin.circle(d)
    chin.speed(10)
    chin.left(20)
while True:
    for i in range(0, 11):
        black_hole()
        d = d + 4